Programs & Examples On #Pulsar

Which Eclipse version should I use for an Android app?

Eclipse 3.5 for Java Developer is the best option for you and 3.6 version is good but not at all because of compatibility issues.

How can I add a vertical scrollbar to my div automatically?

I'm not quite sure what you're attempting to use the div for, but this is an example with some random text.

Mr_Green gave the correct instructions when he said to add overflow-y: auto as that restricts it to vertical scrolling. This is a JSFiddle example:

JSFiddle

How do I rename a column in a SQLite database table?

While it is true that there is no ALTER COLUMN, if you only want to rename the column, drop the NOT NULL constraint, or change the data type, you can use the following set of commands:

Note: These commands have the potential to corrupt your database, so make sure you have a backup

PRAGMA writable_schema = 1;
UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';
PRAGMA writable_schema = 0;

You will need to either close and reopen your connection or vacuum the database to reload the changes into the schema.

For example:

Y:\> sqlite3 booktest  
SQLite version 3.7.4  
Enter ".help" for instructions  
Enter SQL statements terminated with a ";"  
sqlite> create table BOOKS ( title TEXT NOT NULL, publication_date TEXT NOT NULL);  
sqlite> insert into BOOKS VALUES ("NULLTEST",null);  
Error: BOOKS.publication_date may not be NULL  
sqlite> PRAGMA writable_schema = 1; 
sqlite> UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';  
sqlite> PRAGMA writable_schema = 0;  
sqlite> .q  

Y:\> sqlite3 booktest  
SQLite version 3.7.4  
Enter ".help" for instructions  
Enter SQL statements terminated with a ";"  
sqlite> insert into BOOKS VALUES ("NULLTEST",null);  
sqlite> .q  

REFERENCES FOLLOW:


pragma writable_schema
When this pragma is on, the SQLITE_MASTER tables in which database can be changed using ordinary UPDATE, INSERT, and DELETE statements. Warning: misuse of this pragma can easily result in a corrupt database file.

alter table
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

ALTER TABLE SYNTAX

nginx - client_max_body_size has no effect

Assuming you have already set the client_max_body_size and various PHP settings (upload_max_filesize / post_max_size , etc) in the other answers, then restarted or reloaded NGINX and PHP without any result, run this...

nginx -T

This will give you any unresolved errors in your NGINX configs. In my case, I struggled with the 413 error for a whole day before I realized there were some other unresolved SSL errors in the NGINX config (wrong pathing for certs) that needed to be corrected. Once I fixed the unresolved issues I got from 'nginx -T', reloaded NGINX, and EUREKA!! That fixed it.

python setup.py uninstall

It might be better to remove related files by using bash to read commands, like the following:

sudo python setup.py install --record files.txt
sudo bash -c "cat files.txt | xargs rm -rf"

Connecting PostgreSQL 9.2.1 with Hibernate

Yes by using spring-boot with hibernate configuration files we can persist the data to the database. keep hibernating .cfg.xml in your src/main/resources folder for reading the configurations related to database.

enter image description here

How to align a div to the top of its parent but keeping its inline-block behaviour?

As others have said, vertical-align: top is your friend.

As a bonus here is a forked fiddle with added enhancements that make it work in Internet Explorer 6 and Internet Explorer 7 too ;)

Example: here

How do I fit an image (img) inside a div and keep the aspect ratio?

For me, the following CSS worked (tested in Chrome, Firefox and Safari).

There are multiple things working together:

  • max-height: 100%;, max-width: 100%; and height: auto;, width: auto; make the img scale to whichever dimension first reaches 100% while keeping the aspect ratio
  • position: relative; in the container and position: absolute; in the child together with top: 50%; and left: 50%; center the top left corner of the img in the container
  • transform: translate(-50%, -50%); moves the img back to the left and top by half its size, thus centering the img in the container

CSS:

.container {
    height: 48px;
    width: 48px;

    position: relative;
}

.container > img {
    max-height: 100%;
    max-width: 100%;
    height: auto;
    width: auto;

    position: absolute;
    top: 50%;
    left: 50%;

    transform: translate(-50%, -50%);
}

Sass .scss: Nesting and multiple classes?

Christoph's answer is perfect. Sometimes however you may want to go more classes up than one. In this case you could try the @at-root and #{} css features which would enable two root classes to sit next to each other using &.

This wouldn't work (due to the nothing before & rule):

_x000D_
_x000D_
container {_x000D_
    background:red;_x000D_
    color:white;_x000D_
    _x000D_
    .desc& {_x000D_
      background: blue;_x000D_
    }_x000D_
_x000D_
    .hello {_x000D_
        padding-left:50px;_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

But this would (using @at-root plus #{&}):

_x000D_
_x000D_
container {_x000D_
    background:red;_x000D_
    color:white;_x000D_
    _x000D_
    @at-root .desc#{&} {_x000D_
      background: blue;_x000D_
    }_x000D_
_x000D_
    .hello {_x000D_
        padding-left:50px;_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Insert picture into Excel cell

Now we can add a picture to Excel directly and easely. Just follow these instructions:

  1. Go to the Insert tab.
  2. Click on the Pictures option (it’s in the illustrations group). image1
  3. In the ‘Insert Picture’ dialog box, locate the pictures that you want to insert into a cell in Excel. image2
  4. Click on the Insert button. image3
  5. Re-size the picture/image so that it can fit perfectly within the cell. image4
  6. Place the picture in the cell. A cool way to do this is to first press the ALT key and then move the picture with the mouse. It will snap and arrange itself with the border of the cell as soon it comes close to it.

If you have multiple images, you can select and insert all the images at once (as shown in step 4).

You can also resize images by selecting it and dragging the edges. In the case of logos or product images, you may want to keep the aspect ratio of the image intact. To keep the aspect ratio intact, use the corners of an image to resize it.


When you place an image within a cell using the steps above, it will not stick with the cell in case you resize, filter, or hide the cells. If you want the image to stick to the cell, you need to lock the image to the cell it’s placed n.

To do this, you need to follow the additional steps as shown below.

  1. Right-click on the picture and select Format Picture. image5
  2. In the Format Picture pane, select Size & Properties and with the options in Properties, select ‘Move and size with cells’. image6

Now you can move cells, filter it, or hide it, and the picture will also move/filter/hide.


NOTE:

This answer was taken from this link: Insert Picture into a Cell in Excel.

Spring Boot - Handle to Hibernate SessionFactory

Another way similar to the yglodt's

In application.properties:

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

And in your configuration class:

@Bean
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
    return hemf.getSessionFactory();
}

Then you can autowire the SessionFactory in your services as usual:

@Autowired
private SessionFactory sessionFactory;

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

If you are using impersonation, be sure to give permissions, including write and modify permission to the relevant user account on the following folder:

C:\Users\[username]\AppData\Local\Temp\Temporary ASP.NET Files

I was missing the modify permission, which was why just adding the default permissions wasn't working for me.

Decompile Python 2.7 .pyc

Decompyle++ (pycdc) appears to work for a range of python versions: https://github.com/zrax/pycdc

For example:

git clone https://github.com/zrax/pycdc   
cd pycdc
make  
./bin/pycdc Example.pyc > Example.py

Insert if not exists Oracle

If you do NOT want to merge in from an other table, but rather insert new data... I came up with this. Is there perhaps a better way to do this?

MERGE INTO TABLE1 a
    USING DUAL
    ON (a.C1_pk= 6)
WHEN NOT MATCHED THEN
    INSERT(C1_pk, C2,C3,C4)
    VALUES (6, 1,0,1);

A reference to the dll could not be added

You can add .dll file manually. For example if you want to add a dll file in your WPF application, and you are unable to refer it in your project

(Getting error :A reference to the "....dll" could not be added.Please make sure that the file is accessible and that it is a valid assembly or COM component) ,

then COPY that dll file and PASTE in the INSTALLER PROJECT (in application folder).

Using Google maps API v3 how do I get LatLng with a given address?

I don't think location.LatLng is working, however this works:

results[0].geometry.location.lat(), results[0].geometry.location.lng()

Found it while exploring Get Lat Lon source code.

What's the difference between next() and nextLine() methods from Scanner class?

In short: if you are inputting a string array of length t, then Scanner#nextLine() expects t lines, each entry in the string array is differentiated from the other by enter key.And Scanner#next() will keep taking inputs till you press enter but stores string(word) inside the array, which is separated by whitespace.

Lets have a look at following snippet of code

    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    String[] s = new String[t];

    for (int i = 0; i < t; i++) {
        s[i] = in.next();
    }

when I run above snippet of code in my IDE (lets say for string length 2),it does not matter whether I enter my string as

Input as :- abcd abcd or

Input as :-

abcd

abcd

Output will be like abcd

abcd

But if in same code we replace next() method by nextLine()

    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    String[] s = new String[t];

    for (int i = 0; i < t; i++) {
        s[i] = in.nextLine();
    }

Then if you enter input on prompt as - abcd abcd

Output is :-

abcd abcd

and if you enter the input on prompt as abcd (and if you press enter to enter next abcd in another line, the input prompt will just exit and you will get the output)

Output is:-

abcd

How to setup FTP on xampp

XAMPP for linux and mac comes with ProFTPD. Make sure to start the service from XAMPP control panel -> manage servers.

Further complete instructions can be found at localhost XAMPP dashboard -> How-to guides -> Configure FTP Access. I have pasted them below :

  1. Open a new Linux terminal and ensure you are logged in as root.

  2. Create a new group named ftp. This group will contain those user accounts allowed to upload files via FTP.

groupadd ftp

  1. Add your account (in this example, susan) to the new group. Add other users if needed.

usermod -a -G ftp susan

  1. Change the ownership and permissions of the htdocs/ subdirectory of the XAMPP installation directory (typically, /opt/lampp) so that it is writable by the the new ftp group.

cd /opt/lampp chown root.ftp htdocs chmod 775 htdocs

  1. Ensure that proFTPD is running in the XAMPP control panel.

You can now transfer files to the XAMPP server using the steps below:

  1. Start an FTP client like winSCP or FileZilla and enter connection details as below.

If you’re connecting to the server from the same system, use "127.0.0.1" as the host address. If you’re connecting from a different system, use the network hostname or IP address of the XAMPP server.

Use "21" as the port.

Enter your Linux username and password as your FTP credentials.

Your FTP client should now connect to the server and enter the /opt/lampp/htdocs/ directory, which is the default Web server document root.

  1. Transfer the file from your home directory to the server using normal FTP transfer conventions. If you’re using a graphical FTP client, you can usually drag and drop the file from one directory to the other. If you’re using a command-line FTP client, you can use the FTP PUT command.

Once the file is successfully transferred, you should be able to see it in action.

(Excel) Conditional Formatting based on Adjacent Cell Value

I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:

Under Conditional Formatting > Manage Rules:

  1. Make a new rule with "Use a formula to determine which cells to format"
  2. Make your rule, but put a dollar sign only in front of the letter: $A2<$B2
  3. Under "Applies to", Manually select the second column (It would not work for me if I changed the value in the box, it just kept snapping back to what was already there), so it looks like $B$2:$B$100 (assuming you have 100 rows)

This worked for me in Excel 2016.

How to handle anchor hash linking in AngularJS

<a href="##faq-1">Question 1</a>
<a href="##faq-2">Question 2</a>
<a href="##faq-3">Question 3</a>

<h3 id="faq-1">Question 1</h3>
<h3 id="faq-2">Question 2</h3>
<h3 id="faq-3">Question 3</h3>

What is the '.well' equivalent class in Bootstrap 4

This worked best for me:

<div class="card bg-light p-3">
 <p class="mb-0">Some text here</p>
</div>

Loop in Jade (currently known as "Pug") template engine

Pug (renamed from 'Jade') is a templating engine for full stack web app development. It provides a neat and clean syntax for writing HTML and maintains strict whitespace indentation (like Python). It has been implemented with JavaScript APIs. The language mainly supports two iteration constructs: each and while. 'for' can be used instead 'each'. Kindly consult the language reference here:

https://pugjs.org/language/iteration.html

Here is one of my snippets: each/for iteration in pug_screenshot

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

For me, the gem lock file was specifying an older version of cocoapods than the one I had installed. I had to re-branch and run bundle exec pod install instead of pod install

PHP array() to javascript array()

To convert you PHP array to JS , you can do it like this :

var js_array = [<?php echo '"'.implode('","',  $disabledDaysRange ).'"' ?>];

or using JSON_ENCODE :

var js_array =<?php echo json_encode($disabledDaysRange );?>;

Example without JSON_ENCODE:

<script type='text/javascript'>
    <?php
    $php_array = array('abc','def','ghi');
    ?>
    var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
    alert(js_array[0]);
</script>

Example with JSON_ENCODE :

<script type='text/javascript'>
    <?php
    $php_array = array('abc','def','ghi');
    ?>
    var js_array =<?php echo json_encode($disabledDaysRange );?>;
    alert(js_array[0]);
</script>

Command to escape a string in bash

You can use perl to replace various characters, for example:

$ echo "Hello\ world" | perl -pe 's/\\/\\\\/g'
Hello\\ world

Depending on the nature of your escape, you can chain multiple calls to escape the proper characters.

What are the different NameID format used for?

About this I think you can reference to http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html.

Here're my understandings about this, with the Identity Federation Use Case to give a details for those concepts:

  • Persistent identifiers-

IdP provides the Persistent identifiers, they are used for linking to the local accounts in SPs, but they identify as the user profile for the specific service each alone. For example, the persistent identifiers are kind of like : johnForAir, jonhForCar, johnForHotel, they all just for one specified service, since it need to link to its local identity in the service.

  • Transient identifiers-

Transient identifiers are what IdP tell the SP that the users in the session have been granted to access the resource on SP, but the identities of users do not offer to SP actually. For example, The assertion just like “Anonymity(Idp doesn’t tell SP who he is) has the permission to access /resource on SP”. SP got it and let browser to access it, but still don’t know Anonymity' real name.

  • unspecified identifiers-

The explanation for it in the spec is "The interpretation of the content of the element is left to individual implementations". Which means IdP defines the real format for it, and it assumes that SP knows how to parse the format data respond from IdP. For example, IdP gives a format data "UserName=XXXXX Country=US", SP get the assertion, and can parse it and extract the UserName is "XXXXX".

What is the difference between an IntentService and a Service?

service: It runs in the background on your system. For example,

  1. If you went to a hotel and you give your order for a soup to a server
  2. The server gets your order and sends to chef
  3. You don't know how the soup is made in the kitchen and what processes are required for making the soup
  4. Once your order is ready, the server brings you the soup.

background process: chef making soup

IntentService:- it's consecutive service.. (i.e) when you order many food items at a time to server but the server delivers those items one by one and not deliver them all at once.

jQuery - Illegal invocation

In my case (using webpack 4) within an anonymous function, that I was using as a callback.

I had to use window.$.ajax() instead of $.ajax() despite having:

import $ from 'jquery';
window.$ = window.jQuery = $;

How to remove only 0 (Zero) values from column in excel 2010

I selected columns that I want to delete 0 values then clicked DATA > FILTER. In column's header there is a filter icon appears. I clicked on that icon and selected only 0 values and clicked OK. Only 0 values becomes selected. Finally clear content OR use DELETE button. Problem Solved!

How to open a new window on form submit

i believe this jquery work for you well please check a code below.

this will make your submit action works and open a link in new tab whether you want to open action url again or a new link

jQuery('form').on('submit',function(e){
setTimeout(function () { window.open('https://www.google.com','_blank');}, 1000);});})

This code works for me perfect..

How to truncate string using SQL server

If you only want to return a few characters of your long string, you can use:

select 
  left(col, 15) + '...' col
from yourtable

See SQL Fiddle with Demo.

This will return the first 15 characters of the string and then concatenates the ... to the end of it.

If you want to to make sure than strings less than 15 do not get the ... then you can use:

select 
  case 
    when len(col)>=15
    then left(col, 15) + '...' 
    else col end col
from yourtable

See SQL Fiddle with Demo

Can't operator == be applied to generic types in C#?

So many answers, and not a single one explains the WHY? (which Giovanni explicitly asked)...

.NET generics do not act like C++ templates. In C++ templates, overload resolution occurs after the actual template parameters are known.

In .NET generics (including C#), overload resolution occurs without knowing the actual generic parameters. The only information the compiler can use to choose the function to call comes from type constraints on the generic parameters.

R plot: size and resolution

A reproducible example:

the_plot <- function()
{
  x <- seq(0, 1, length.out = 100)
  y <- pbeta(x, 1, 10)
  plot(
    x,
    y,
    xlab = "False Positive Rate",
    ylab = "Average true positive rate",
    type = "l"
  )
}

James's suggestion of using pointsize, in combination with the various cex parameters, can produce reasonable results.

png(
  "test.png",
  width     = 3.25,
  height    = 3.25,
  units     = "in",
  res       = 1200,
  pointsize = 4
)
par(
  mar      = c(5, 5, 2, 2),
  xaxs     = "i",
  yaxs     = "i",
  cex.axis = 2,
  cex.lab  = 2
)
the_plot()
dev.off()

Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,

library(ggplot2)

ggplot_alternative <- function()
{
  the_data <- data.frame(
    x <- seq(0, 1, length.out = 100),
    y = pbeta(x, 1, 10)
  )

ggplot(the_data, aes(x, y)) +
    geom_line() +
    xlab("False Positive Rate") +
    ylab("Average true positive rate") +
    coord_cartesian(0:1, 0:1)
}

ggsave(
  "ggtest.png",
  ggplot_alternative(),
  width = 3.25,
  height = 3.25,
  dpi = 1200
)

What are .dex files in Android?

.dex file

Compiled Android application code file.

Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.

Differences between utf8 and latin1

UTF-8 is prepared for world domination, Latin1 isn't.

If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).

Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4.

Cannot push to GitHub - keeps saying need merge

Have you updated your code before pushing?

Use git pull origin master before you push anything.

I assume that you are using origin as a name for your remote.

You need to pull before push, to make your local repository up-to-date before you push something (just in case someone else has already updated code on github.com). This helps in resolving conflicts locally.

Importing a CSV file into a sqlite3 database table using Python

Many thanks for bernie's answer! Had to tweak it a bit - here's what worked for me:

import csv, sqlite3
conn = sqlite3.connect("pcfc.sl3")
curs = conn.cursor()
curs.execute("CREATE TABLE PCFC (id INTEGER PRIMARY KEY, type INTEGER, term TEXT, definition TEXT);")
reader = csv.reader(open('PC.txt', 'r'), delimiter='|')
for row in reader:
    to_db = [unicode(row[0], "utf8"), unicode(row[1], "utf8"), unicode(row[2], "utf8")]
    curs.execute("INSERT INTO PCFC (type, term, definition) VALUES (?, ?, ?);", to_db)
conn.commit()

My text file (PC.txt) looks like this:

1 | Term 1 | Definition 1
2 | Term 2 | Definition 2
3 | Term 3 | Definition 3

ASP.NET MVC - passing parameters to the controller

Your routing needs to be set up along the lines of {controller}/{action}/{firstItem}. If you left the routing as the default {controller}/{action}/{id} in your global.asax.cs file, then you will need to pass in id.

routes.MapRoute(
    "Inventory",
    "Inventory/{action}/{firstItem}",
    new { controller = "Inventory", action = "ListAll", firstItem = "" }
);

... or something close to that.

exclude @Component from @ComponentScan

Another approach is to use new conditional annotations. Since plain Spring 4 you can use @Conditional annotation:

@Component("foo")
@Conditional(FooCondition.class)
class Foo {
    ...
}

and define conditional logic for registering Foo component:

public class FooCondition implements Condition{
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // return [your conditional logic]
    }     
}

Conditional logic can be based on context, because you have access to bean factory. For Example when "Bar" component is not registered as bean:

    return !context.getBeanFactory().containsBean(Bar.class.getSimpleName());

With Spring Boot (should be used for EVERY new Spring project), you can use these conditional annotations:

  • @ConditionalOnBean
  • @ConditionalOnClass
  • @ConditionalOnExpression
  • @ConditionalOnJava
  • @ConditionalOnMissingBean
  • @ConditionalOnMissingClass
  • @ConditionalOnNotWebApplication
  • @ConditionalOnProperty
  • @ConditionalOnResource
  • @ConditionalOnWebApplication

You can avoid Condition class creation this way. Refer to Spring Boot docs for more detail.

Unexpected end of file error

Change the Platform of your C++ project to "x64" (or whichever platform you are targeting) instead of "Win32". This can be found in Visual Studio under Build -> Configuration Manager. Find your project in the list and change the Platform column. Don't forget to do this for all solution configurations.

Extract string between two strings in java

Jlordo approach covers specific situation. If you try to build an abstract method out of it, you can face a difficulty to check if 'textFrom' is before 'textTo'. Otherwise method can return a match for some other occurance of 'textFrom' in text.

Here is a ready-to-go abstract method that covers this disadvantage:

  /**
   * Get text between two strings. Passed limiting strings are not 
   * included into result.
   *
   * @param text     Text to search in.
   * @param textFrom Text to start cutting from (exclusive).
   * @param textTo   Text to stop cuutting at (exclusive).
   */
  public static String getBetweenStrings(
    String text,
    String textFrom,
    String textTo) {

    String result = "";

    // Cut the beginning of the text to not occasionally meet a      
    // 'textTo' value in it:
    result =
      text.substring(
        text.indexOf(textFrom) + textFrom.length(),
        text.length());

    // Cut the excessive ending of the text:
    result =
      result.substring(
        0,
        result.indexOf(textTo));

    return result;
  }

Serialize form data to JSON

My contribution:

function serializeToJson(serializer){
    var _string = '{';
    for(var ix in serializer)
    {
        var row = serializer[ix];
        _string += '"' + row.name + '":"' + row.value + '",';
    }
    var end =_string.length - 1;
    _string = _string.substr(0, end);
    _string += '}';
    console.log('_string: ', _string);
    return JSON.parse(_string);
}

var params = $('#frmPreguntas input').serializeArray();
params = serializeToJson(params);

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

I am using OpsWorks and wanted to register a new existing Linux instance from my Windows machine on AWS Cli.

Frist problem was, that I had to use my Putty generated .pkk file.

Second problem was that I needed to quote the absolute path to that .pkk file like that:

aws opsworks register --infrastructure-class ec2 --ssh-username ec2-user --ssh-private-key "C:\key.ppk"

Conditional formatting based on another cell's value

Basically all you need to do is add $ as prefix at column letter and row number. Please see image below

enter image description here

Does bootstrap 4 have a built in horizontal divider?

For dropdowns, yes:

https://v4-alpha.getbootstrap.com/components/dropdowns/

<div class="dropdown-menu">
  <a class="dropdown-item" href="#">Action</a>
  <a class="dropdown-item" href="#">Another action</a>
  <a class="dropdown-item" href="#">Something else here</a>
  <div class="dropdown-divider"></div>
  <a class="dropdown-item" href="#">Separated link</a>
</div>

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

How to calculate Date difference in Hive

datediff(to_date(String timestamp), to_date(String timestamp))

For example:

SELECT datediff(to_date('2019-08-03'), to_date('2019-08-01')) <= 2;

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

This is the normal behavior, and it's caused by the default <select> style under Firefox : you can't set line-height, then you need to play on padding when you want to have a customized <select>.

Example, with results under Firefox 25 / Chrome 31 / IE 10 :

<select>
  <option>Default</option>
  <option>Default</option>
  <option>Default</option>
</select>

<select class="form-control">
  <option>Bootstrap</option>
  <option>Bootstrap</option>
  <option>Bootstrap</option>
</select>

<select class="form-control custom">
  <option>Custom</option>
  <option>Custom</option>
  <option>Custom</option>
</select>
select.custom {
  padding: 0px;
}

Bootply

enter image description here

Java get String CompareTo as a comparator object

Ok this is a few years later but with java 8 you can use Comparator.naturalOrder():

http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#naturalOrder--

From javadoc:

static <T extends Comparable<? super T>> Comparator<T> naturalOrder()

Returns a comparator that compares Comparable objects in natural order. The returned comparator is serializable and throws NullPointerException when comparing null.

Function not defined javascript

The actual problem is with your

showList function.

There is an extra ')' after 'visible'.

Remove that and it will work fine.

function showList()
{
  if (document.getElementById("favSports").style.visibility == "hidden") 
    {
       // document.getElementById("favSports").style.visibility = "visible");  
       // your code
       document.getElementById("favSports").style.visibility = "visible";
       // corrected code
    }
}

Server.Transfer Vs. Response.Redirect

To be Short: Response.Redirect simply tells the browser to visit another page. Server.Transfer helps reduce server requests, keeps the URL the same and, with a little bug-bashing, allows you to transfer the query string and form variables.

Something I found and agree with (source):

Server.Transfer is similar in that it sends the user to another page with a statement such as Server.Transfer("WebForm2.aspx"). However, the statement has a number of distinct advantages and disadvantages.

Firstly, transferring to another page using Server.Transfer conserves server resources. Instead of telling the browser to redirect, it simply changes the "focus" on the Web server and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.

But watch out: because the "transfer" process can work on only those sites running on the server; you can't use Server.Transfer to send the user to an external site. Only Response.Redirect can do that.

Secondly, Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging.

That's not all: The Server.Transfer method also has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("WebForm2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.

For example, if your WebForm1.aspx has a TextBox control called TextBox1 and you transferred to WebForm2.aspx with the preserveForm parameter set to True, you'd be able to retrieve the value of the original page TextBox control by referencing Request.Form("TextBox1").

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.


EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

Fatal error: Call to a member function query() on null

put this line in parent construct : $this->load->database();

function  __construct() {
    parent::__construct();
    $this->load->library('lib_name');
    $model=array('model_name');
    $this->load->model($model);
    $this->load->database();
}

this way.. it should work..

How to reset the state of a Redux store?

for me what worked the best is to set the initialState instead of state:

  const reducer = createReducer(initialState,
  on(proofActions.cleanAdditionalInsuredState, (state, action) => ({
    ...initialState
  })),

How to change the port of Tomcat from 8080 to 80?

As previous answers didn't work well (it was good, but not enough) for me on a 14.04 Ubuntu Server, I mention these recommendations (this is a quote).

Edit: note that as @jason-faust mentioned it in the comments, on 14.04, the authbind package that ships with it does support IPv6 now, so the prefer IPv4 thing isn't needed any longer.

1) Install authbind
2) Make port 80 available to authbind (you need to be root):

  touch /etc/authbind/byport/80
  chmod 500 /etc/authbind/byport/80
  chown tomcat7 /etc/authbind/byport/80

3) Make IPv4 the default (authbind does not currently support IPv6).
   To do so, create the file TOMCAT/bin/setenv.sh with the following content: 

   CATALINA_OPTS="-Djava.net.preferIPv4Stack=true"

4) Change /usr/share/tomcat7/bin/startup.sh

  exec authbind --deep "$PRGDIR"/"$EXECUTABLE" start "$@"
  # OLD: exec "$PRGDIR"/"$EXECUTABLE" start "$@"

If you already got a setenv.sh file in /usr/share/tomcat7/bin with CATALINA_OPTS, you have to use :

export CATALINA_OPTS="$CATALINA_OPTS -Djava.net.preferIPv4Stack=true"

Now you can change the port to 80 as told in other answers.

Most efficient way to create a zero filled JavaScript array?

function makeArrayOf(value, length) {
  var arr = [], i = length;
  while (i--) {
    arr[i] = value;
  }
  return arr;
}

makeArrayOf(0, 5); // [0, 0, 0, 0, 0]

makeArrayOf('x', 3); // ['x', 'x', 'x']

Note that while is usually more efficient than for-in, forEach, etc.

Convert string to int if string is a number

Try this: currentLoad = ConvertToLongInteger(oXLSheet2.Cells(4, 6).Value) with this function:

Function ConvertToLongInteger(ByVal stValue As String) As Long
 On Error GoTo ConversionFailureHandler
 ConvertToLongInteger = CLng(stValue)  'TRY to convert to an Integer value
 Exit Function           'If we reach this point, then we succeeded so exit

ConversionFailureHandler:
 'IF we've reached this point, then we did not succeed in conversion
 'If the error is type-mismatch, clear the error and return numeric 0 from the function
 'Otherwise, disable the error handler, and re-run the code to allow the system to 
 'display the error
 If Err.Number = 13 Then 'error # 13 is Type mismatch
      Err.Clear
      ConvertToLongInteger = 0
      Exit Function
 Else
      On Error GoTo 0
      Resume
 End If
End Function

I chose Long (Integer) instead of simply Integer because the min/max size of an Integer in VBA is crummy (min: -32768, max:+32767). It's common to have an integer outside of that range in spreadsheet operations.

The above code can be modified to handle conversion from string to-Integers, to-Currency (using CCur() ), to-Decimal (using CDec() ), to-Double (using CDbl() ), etc. Just replace the conversion function itself (CLng). Change the function return type, and rename all occurrences of the function variable to make everything consistent.

Maintain model of scope when changing between views in AngularJS

Angular doesn't really provide what you are looking for out of the box. What i would do to accomplish what you're after is use the following add ons

UI Router & UI Router Extras

These two will provide you with state based routing and sticky states, you can tab between states and all information will be saved as the scope "stays alive" so to speak.

Check the documentation on both as it's pretty straight forward, ui router extras also has a good demonstration of how sticky states works.

How do you access the element HTML from within an Angular attribute directive?

So actually, my comment that you should do a console.log(el.nativeElement) should have pointed you in the right direction, but I didn't expect the output to be just a string representing the DOM Element.

What you have to do to inspect it in the way it helps you with your problem, is to do a console.log(el) in your example, then you'll have access to the nativeElement object and will see a property called innerHTML.

Which will lead to the answer to your original question:

let myCurrentContent:string = el.nativeElement.innerHTML; // get the content of your element
el.nativeElement.innerHTML = 'my new content'; // set content of your element

Update for better approach:

Since it's the accepted answer and web workers are getting more important day to day (and it's considered best practice anyway) I want to add this suggestion by Mark Rajcok here.

The best way to manipulate DOM Elements programmatically is using the Renderer:

constructor(private _elemRef: ElementRef, private _renderer: Renderer) { 
    this._renderer.setElementProperty(this._elemRef.nativeElement, 'innerHTML', 'my new content');
}

Edit

Since Renderer is deprecated now, use Renderer2 instead with setProperty


Update:

This question with its answer explained the console.log behavior.

Which means that console.dir(el.nativeElement) would be the more direct way of accessing the DOM Element as an "inspectable" Object in your console for this situation.


Hope this helped.

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

In C can a long printf statement be broken up into multiple lines?

I don't think using one printf statement to print string literals as seen above is a good programming practice; rather, one can use the piece of code below:

printf("name: %s\t",sp->name);
printf("args: %s\t",sp->args);
printf("value: %s\t",sp->value);
printf("arraysize: %s\t",sp->name); 

HTML: how to force links to open in a new tab, not new window

The way the browser handles new windows vs new tab is set in the browser's options and can only be changed by the user.

Deleting multiple elements from a list

here is another method which removes the elements in place. also if your list is really long, it is faster.

>>> a = range(10)
>>> remove = [0,4,5]
>>> from collections import deque
>>> deque((list.pop(a, i) for i in sorted(remove, reverse=True)), maxlen=0)

>>> timeit.timeit('[i for j, i in enumerate(a) if j not in remove]', setup='import random;remove=[random.randrange(100000) for i in range(100)]; a = range(100000)', number=1)
0.1704120635986328

>>> timeit.timeit('deque((list.pop(a, i) for i in sorted(remove, reverse=True)), maxlen=0)', setup='from collections import deque;import random;remove=[random.randrange(100000) for i in range(100)]; a = range(100000)', number=1)
0.004853963851928711

How to access parent Iframe from JavaScript

Also you can set name and ID to equal values

<iframe id="frame1" name="frame1" src="any.html"></iframe>

so you will be able to use next code inside child page

parent.document.getElementById(window.name);

Must issue a STARTTLS command first

You are probably attempting to use Gmail's servers on port 25 to deliver mail to a third party over an unauthenticated connection. Gmail doesn't let you do this, because then anybody could use Gmail's servers to send mail to anybody else. This is called an open relay and was a common enabler of spam in the early days. Open relays are no longer acceptable on the Internet.

You will need to ask your SMTP client to connect to Gmail using an authenticated connection, probably on port 587.

Duplicate Entire MySQL Database

Here's a windows bat file I wrote which combines Vincent and Pauls suggestions. It prompts the user for source and destination names.

Just modify the variables at the top to set the proper paths to your executables / database ports.

:: Creates a copy of a database with a different name.
:: User is prompted for Src and destination name.
:: Fair Warning: passwords are passed in on the cmd line, modify the script with -p instead if security is an issue.
:: Uncomment the rem'd out lines if you want script to prompt for database username, password, etc.

:: See also: http://stackoverflow.com/questions/1887964/duplicate-entire-mysql-database

@set MYSQL_HOME="C:\sugarcrm\mysql\bin"
@set mysqldump_exec=%MYSQL_HOME%\mysqldump
@set mysql_exec=%MYSQL_HOME%\mysql
@set SRC_PORT=3306
@set DEST_PORT=3306
@set USERNAME=TODO_USERNAME
@set PASSWORD=TODO_PASSWORD

:: COMMENT any of the 4 lines below if you don't want to be prompted for these each time and use defaults above.
@SET /p USERNAME=Enter database username: 
@SET /p PASSWORD=Enter database password: 
@SET /p SRC_PORT=Enter SRC database port (usually 3306): 
@SET /p DEST_PORT=Enter DEST database port: 

%MYSQL_HOME%\mysql --user=%USERNAME% --password=%PASSWORD% --port=%DEST_PORT% --execute="show databases;"
@IF NOT "%ERRORLEVEL%" == "0" GOTO ExitScript

@SET /p SRC_DB=What is the name of the SRC Database:  
@SET /p DEST_DB=What is the name for the destination database (that will be created):  

%mysql_exec% --user=%USERNAME% --password=%PASSWORD% --port=%DEST_PORT% --execute="create database %DEST_DB%;"
%mysqldump_exec% --add-drop-table --user=%USERNAME% --password=%PASSWORD% --port=%SRC_PORT% %SRC_DB% | %mysql_exec% --user=%USERNAME% --password=%PASSWORD% --port=%DEST_PORT% %DEST_DB%
@echo SUCCESSFUL!!!
@GOTO ExitSuccess

:ExitScript
@echo "Failed to copy database"
:ExitSuccess

Sample output:

C:\sugarcrm_backups\SCRIPTS>copy_db.bat
Enter database username: root
Enter database password: MyPassword
Enter SRC database port (usually 3306): 3308
Enter DEST database port: 3308

C:\sugarcrm_backups\SCRIPTS>"C:\sugarcrm\mysql\bin"\mysql --user=root --password=MyPassword --port=3308 --execute="show databases;"
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sugarcrm_550_pro   |
| sugarcrm_550_ce    |
| sugarcrm_640_pro   |
| sugarcrm_640_ce    |
+--------------------+
What is the name of the SRC Database:  sugarcrm
What is the name for the destination database (that will be created):  sugarcrm_640_ce

C:\sugarcrm_backups\SCRIPTS>"C:\sugarcrm\mysql\bin"\mysql --user=root --password=MyPassword --port=3308 --execute="create database sugarcrm_640_ce;"

C:\sugarcrm_backups\SCRIPTS>"C:\sugarcrm\mysql\bin"\mysqldump --add-drop-table --user=root --password=MyPassword --port=3308 sugarcrm   | "C:\sugarcrm\mysql\bin"\mysql --user=root --password=MyPassword --port=3308 sugarcrm_640_ce
SUCCESSFUL!!!

Python constructor and default value

Mutable default arguments don't generally do what you want. Instead, try this:

class Node:
     def __init__(self, wordList=None, adjacencyList=None):
        if wordList is None:
            self.wordList = []
        else:
             self.wordList = wordList 
        if adjacencyList is None:
            self.adjacencyList = []
        else:
             self.adjacencyList = adjacencyList 

how to install apk application from my pc to my mobile android

1) Put the apk on your SDKCard and install file browsers like "Estrongs File Explorer", "Easy Installer", etc...

https://market.android.com/details?id=com.estrongs.android.pop&feature=search_result https://market.android.com/details?id=mobi.infolife.installer&feature=search_result

2) Go to your mobile settings - applications- debuging - and thick "USB debugging" enter image description here

'Static readonly' vs. 'const'

const and readonly are similar, but they are not exactly the same.

A const field is a compile-time constant, meaning that that value can be computed at compile-time. A readonly field enables additional scenarios in which some code must be run during construction of the type. After construction, a readonly field cannot be changed.

For instance, const members can be used to define members like:

struct Test
{
    public const double Pi = 3.14;
    public const int Zero = 0;
}

Since values like 3.14 and 0 are compile-time constants. However, consider the case where you define a type and want to provide some pre-fab instances of it. E.g., you might want to define a Color class and provide "constants" for common colors like Black, White, etc. It isn't possible to do this with const members, as the right hand sides are not compile-time constants. One could do this with regular static members:

public class Color
{
    public static Color Black = new Color(0, 0, 0);
    public static Color White = new Color(255, 255, 255);
    public static Color Red   = new Color(255, 0, 0);
    public static Color Green = new Color(0, 255, 0);
    public static Color Blue  = new Color(0, 0, 255);
    private byte red, green, blue;

    public Color(byte r, byte g, byte b) => (red, green, blue) = (r, g, b);
}

But then there is nothing to keep a client of Color from mucking with it, perhaps by swapping the Black and White values. Needless to say, this would cause consternation for other clients of the Color class. The "readonly" feature addresses this scenario.

By simply introducing the readonly keyword in the declarations, we preserve the flexible initialization while preventing client code from mucking around.

public class Color
{
    public static readonly Color Black = new Color(0, 0, 0);
    public static readonly Color White = new Color(255, 255, 255);
    public static readonly Color Red   = new Color(255, 0, 0);
    public static readonly Color Green = new Color(0, 255, 0);
    public static readonly Color Blue  = new Color(0, 0, 255);
    private byte red, green, blue;

    public Color(byte r, byte g, byte b) => (red, green, blue) = (r, g, b);
}

It is interesting to note that const members are always static, whereas a readonly member can be either static or not, just like a regular field.

It is possible to use a single keyword for these two purposes, but this leads to either versioning problems or performance problems. Assume for a moment that we used a single keyword for this (const) and a developer wrote:

public class A
{
    public static const C = 0;
}

and a different developer wrote code that relied on A:

public class B
{
    static void Main() => Console.WriteLine(A.C);
}

Now, can the code that is generated rely on the fact that A.C is a compile-time constant? I.e., can the use of A.C simply be replaced by the value 0? If you say "yes" to this, then that means that the developer of A cannot change the way that A.C is initialized -- this ties the hands of the developer of A without permission.

If you say "no" to this question then an important optimization is missed. Perhaps the author of A is positive that A.C will always be zero. The use of both const and readonly allows the developer of A to specify the intent. This makes for better versioning behavior and also better performance.

How to append binary data to a buffer in node.js

insert byte to specific place.

insertToArray(arr,index,item) {
   return Buffer.concat([arr.slice(0,index),Buffer.from(item,"utf-8"),arr.slice(index)]);
}

How to write a test which expects an Error to be thrown in Jasmine?

I replace Jasmine's toThrow matcher with the following, which lets you match on the exception's name property or its message property. For me this makes tests easier to write and less brittle, as I can do the following:

throw {
   name: "NoActionProvided",
   message: "Please specify an 'action' property when configuring the action map."
}

and then test with the following:

expect (function () {
   .. do something
}).toThrow ("NoActionProvided");

This lets me tweak the exception message later without breaking tests, when the important thing is that it threw the expected type of exception.

This is the replacement for toThrow that allows this:

jasmine.Matchers.prototype.toThrow = function(expected) {
  var result = false;
  var exception;
  if (typeof this.actual != 'function') {
    throw new Error('Actual is not a function');
  }
  try {
    this.actual();
  } catch (e) {
    exception = e;
  }
  if (exception) {
      result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected) || this.env.equals_(exception.name, expected));
  }

  var not = this.isNot ? "not " : "";

  this.message = function() {
    if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) {
      return ["Expected function " + not + "to throw", expected ? expected.name || expected.message || expected : " an exception", ", but it threw", exception.name || exception.message || exception].join(' ');
    } else {
      return "Expected function to throw an exception.";
    }
  };

  return result;
};

Connect multiple devices to one device via Bluetooth

I think its possible provided if it is a serial data in broadcasting method. but you will not be able to transfer any voice/audio data to the other slave device. As per Bluetooth 4.0, the protocol does not support this. However there is a improvement going on to broadcast the audio/voice data.

Datatable to html Table

The first answer is correct, but if you have a large amount of data (in my project I had 8.000 rows * 8 columns) is tragically slow.... Having a string that becomes that large in c# is why that solution is forbiden

Instead using a large string I used a string array that I join at the end in order to return the string of the html table. Moreover, I used a linq expression ((from o in row.ItemArray select o.ToString()).ToArray()) in order to join each DataRow of the table, instead of looping again, in order to save as much time as possible.

This is my sample code:

private string MakeHtmlTable(DataTable data)
{
            string[] table = new string[data.Rows.Count] ;
            long counter = 1;
            foreach (DataRow row in data.Rows)
            {
                table[counter-1] = "<tr><td>" + String.Join("</td><td>", (from o in row.ItemArray select o.ToString()).ToArray()) + "</td></tr>";

                counter+=1;
            }

            return "</br><table>" + String.Join("", table) + "</table>";
}

How to get multiple select box values using jQuery?

You can also use js map function:

$("#multipleSelect :selected").map(function(i, el) {
    return $(el).val();
}).get();

And then you can get any property of the option element:

return $(el).text();
return $(el).data("mydata");
return $(el).prop("disabled");
etc...

SSIS cannot convert because a potential loss of data

When you first set up this package, I am guessing that either a one or two digit number was the first value in the ShipTo column. Your package reading from the Excel picked a numeric type for that input field and the word "ALL" fails the package since the input spec for that field is numeric. There are several ways to fix this beforehand, but to fix it after the fact, the easiest way is to right click the Excel Source and choose Show Advanced Editor... From there, choose the tab that says Input and Output Properties. In the topmost part of the inputs and outputs section of that dialog box, find the column ShipTo. You will have to drill down to find it. Set the DataType to "string [DT_STR]" and the length to 20.

Click OK then attempt to run your package again.

Why doesn't CSS ellipsis work in table cell?

Leave your tables as they are. Just wrap the content inside the TD's with a span that has the truncation CSS applied.

/* CSS */
.truncate {
    width: 50px; /*your fixed width */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: block; /* this fixes your issue */
}

<!-- HTML -->
<table>
    <tbody>
        <tr>
            <td>
                <span class="truncate">
                    Table data to be truncated if it's too long.
                </span>
            </td>
        </tr>
    </tbody>
</table>

How to convert a Scikit-learn dataset to a Pandas dataset?

Here's another integrated method example maybe helpful.

from sklearn.datasets import load_iris
iris_X, iris_y = load_iris(return_X_y=True, as_frame=True)
type(iris_X), type(iris_y)

The data iris_X are imported as pandas DataFrame and the target iris_y are imported as pandas Series.

How to default to other directory instead of home directory

From a Pinned Start Menu Item in Windows 10

  1. Open the file location of the pinned shortcut
  2. Open the shortcut properties
    1. Remove --cd-to-home arg
    2. Update Start in path
  3. Re-pin to start menu via recently added

open file location screenshot

open shortcut properites screenshot

update shortcut properites screenshot

pin via recently added screnshot


Thanks to all the other answers for how to do this! Wanted to provide Win 10 instructions...

Powershell: count members of a AD group

$users = Get-ADGroupMember -Identity 'Client Services' -Recursive ; $users.count

The above one-liner gives a clean count of recursive members found. Simple, easy, and one line.

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

This single step worked for me... No 2-step verification. As I had created a dummy account for my local development, so I was OK with this setting. Make sure you only do this if your account contains NO personal or any critical data. This is just another way of tackling this error and NOT secure.

I turned ON the setting to alow less secured apps to be allowed access. Form here : https://myaccount.google.com/lesssecureapps

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

A little late, but since I've run into the same problem, in your exact scenario, I figured I'd add my solution.

I have Windows 7 (64-bit) and Office 2010 (32-bit). I tried with the DSN-less connection string:

jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=I:/TeamForge/ORS/CTFORS.accdb

and I tried with the DSN connection, using both the System32 and SysWOW64 versions of the ODBC Admin, and none of that worked.

What finally worked, was to match the bit version of Java with the bit version of Office. Once I did that, I could use either the DSN or DSN less connection mode, without any fuss.

Url to a google maps page to show a pin given a latitude / longitude?

From my notes:

http://maps.google.com/maps?q=37.4185N+122.08774W+(label)&ll=37.419731,-122.088715&spn=0.004250,0.011579&t=h&iwloc=A&hl=en

Which parses like this:

    q=latN+lonW+(label)     location of teardrop

    t=k             keyhole (satelite map)
    t=h             hybrid

    ll=lat,-lon     center of map
    spn=w.w,h.h     span of map, degrees

iwloc has something to do with the info window. hl is obviously language.

See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

How to remove item from array by value?

indexOf is an option, but it's implementation is basically searching the entire array for the value, so execution time grows with array size. (so it is in every browser I guess, I only checked Firefox).

I haven't got an IE6 around to check, but I'd call it a safe bet that you can check at least a million array items per second this way on almost any client machine. If [array size]*[searches per second] may grow bigger than a million you should consider a different implementation.

Basically you can use an object to make an index for your array, like so:

var index={'three':0, 'seven':1, 'eleven':2};

Any sane JavaScript environment will create a searchable index for such objects so that you can quickly translate a key into a value, no matter how many properties the object has.

This is just the basic method, depending on your need you may combine several objects and/or arrays to make the same data quickly searchable for different properties. If you specify your exact needs I can suggest a more specific data structure.

How to implement a material design circular progress bar in android

Was looking for a way to do this using simple xml, but couldn't find any helpful answers, so came up with this.

This works on pre-lollipop versions too, and is pretty close to the material design progress bar. You just need to use this drawable as the indeterminate drawable in the ProgressBar layout.

<?xml version="1.0" encoding="utf-8"?><!--<layer-list>-->
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="360">
    <layer-list>
        <item>
            <rotate xmlns:android="http://schemas.android.com/apk/res/android"
                android:fromDegrees="-90"
                android:toDegrees="-90">
                <shape
                    android:innerRadiusRatio="2.5"
                    android:shape="ring"
                    android:thickness="2dp"
                    android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->

                    <gradient
                        android:angle="0"
                        android:endColor="#007DD6"
                        android:startColor="#007DD6"
                        android:type="sweep"
                        android:useLevel="false" />
                </shape>
            </rotate>
        </item>
        <item>
            <rotate xmlns:android="http://schemas.android.com/apk/res/android"
                android:fromDegrees="0"
                android:toDegrees="270">
                <shape
                    android:innerRadiusRatio="2.6"
                    android:shape="ring"
                    android:thickness="4dp"
                    android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->
                    <gradient
                        android:angle="0"
                        android:centerColor="#FFF"
                        android:endColor="#FFF"
                        android:startColor="#FFF"
                        android:useLevel="false" />
                </shape>
            </rotate>
        </item>
    </layer-list>
</rotate>

set the above drawable in ProgressBar as follows:

  android:indeterminatedrawable="@drawable/above_drawable"

How to capture Enter key press?

Use event.key instead of event.keyCode!

function onEvent(event) {
    if (event.key === "Enter") {
        // Submit form
    }
};

Mozilla Docs

Supported Browsers

Facebook Access Token for Pages

See here if you want to grant a Facebook App permanent access to a page (even when you / the app owner are logged out):

http://developers.facebook.com/docs/opengraph/using-app-tokens/

"An App Access Token does not expire unless you refresh the application secret through your app settings."

Updating to latest version of CocoaPods?

Execute the following on your terminal to get the latest stable version:

sudo gem install cocoapods

Add --pre to get the latest pre release:

sudo gem install cocoapods --pre

If you originally installed the cocoapods gem using sudo, you should use that command again.

Later on, when you're actively using CocoaPods by installing pods, you will be notified when new versions become available with a CocoaPods X.X.X is now available, please update message.

How to connect to remote Oracle DB with PL/SQL Developer?

I am facing to this problem so many times till I have 32bit PL/SQL Developer and 64bit Oracle DB or Oracle Client.

The solution is:

  1. install a 32bit client.
  2. set PLSQL DEV-Tools-Preferencies-Oracle Home to new 32bit client Home
  3. set PLSQL DEV-Tools-Preferencies-OCI to new 32 bit home /bin/oci.dll For example: c:\app\admin\product\11.2.0\client_1\BIN\oci.dll
  4. Save and restart PLSQL DEV.

Edit or create a TNSNAMES.ORA file in c:\app\admin\product\11.2.0\client_1\NETWORK\admin folder like mentioned above.

Try with TNSPING in console like

C:>tnsping ORCL

If still have problem, set the TNS_ADMIN Enviroment properties value pointing to the folder where the TNSNAMES.ORA located, like: c:\app\admin\product\11.2.0\client_1\network\admin

Fine control over the font size in Seaborn plots for academic papers

It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:

sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:

axs.set_ylabel('mylabel',size=6)

you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.

def set_pubfig:
    sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.

Note: If you specify these numbers, specifying font_scale in sns.set_context is ignored for all specified font elements, even if you set it.

Android - Get value from HashMap

Note: If you know Key, use this code

String value=meMap.get(key);

Notepad++ Regular expression find and delete a line

Using the "Replace all" functionality, you can delete a line directly by ending your pattern with:

  • If your file have linux (LF) line ending : $\n?
  • If your file have windows (CRLF) line ending : $(\r\n)?

For instance, in your case :

.*#RedirectMatch Permanent.*$\n?

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.

I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.

# Enable TCP/IP

Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable

# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433

# Modify TCP/IP properties to enable an IP address

$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }

# Restart SQL Server

Restart-Service 'MSSQL$SQLEXPRESS'

How to download file from database/folder using php

You can use html5 tag to download the image directly

<?php
$file = "Bang.png"; //Let say If I put the file name Bang.png
echo "<a href='download.php?nama=".$file."' download>donload</a> ";
?>

For more information, check this link http://www.w3schools.com/tags/att_a_download.asp

React - changing an uncontrolled input

When you use onChange={this.onFieldChange('name').bind(this)} in your input you must declare your state empty string as a value of property field.

incorrect way:

this.state ={
       fields: {},
       errors: {},
       disabled : false
    }

correct way:

this.state ={
       fields: {
         name:'',
         email: '',
         message: ''
       },
       errors: {},
       disabled : false
    }

Git: How do I list only local branches?

git show-ref --heads

The answer by @gertvdijk is the most concise and elegant, but I wanted to leave this here because it helped me grasp the idea that refs/heads/* are equivalent to local branches.

Most of the time the refs/heads/master ref is a file at .git/refs/heads/master that contains a git commit hash that points to the git object that represents the current state of your local master branch, so each file under .git/refs/heads/* represents a local branch.

How to launch an Activity from another Application in Android

Edit depending on comment

In some versions - as suggested in comments - the exception thrown may be different.

Thus the solution below is slightly modified

Intent launchIntent = null;
try{
   launchIntent = getPackageManager().getLaunchIntentForPackage("applicationId");
} catch (Exception ignored) {}

if(launchIntent == null){
    startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "applicationId")));
} else {
    startActivity(launchIntent);
}

Original Answer

Although answered well, there is a pretty simple implementation that handles if the app is not installed. I do it like this

try{
    startActivity(getPackageManager().getLaunchIntentForPackage("applicationId"));
} catch (PackageManager.NameNotFoundException e) {
    startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "applicationId")));
}

Replace "applicationId" with the package that you want to open such as com.google.maps, etc.

How to export and import a .sql file from command line with options?

Type the following command to import sql data file:

$ mysql -u username -p -h localhost DATA-BASE-NAME < data.sql

In this example, import 'data.sql' file into 'blog' database using vivek as username:

$ mysql -u vivek -p -h localhost blog < data.sql

If you have a dedicated database server, replace localhost hostname with with actual server name or IP address as follows:

$ mysql -u username -p -h 202.54.1.10 databasename < data.sql

To export a database, use the following:

mysqldump -u username -p databasename > filename.sql

Note the < and > symbols in each case.

Copy row but with new id

This works in MySQL all versions and Amazon RDS Aurora:

INSERT INTO my_table SELECT 0,tmp.* FROM tmp;

or

Setting the index column to NULL and then doing the INSERT.

But not in MariaDB, I tested version 10.

How to convert std::string to LPCWSTR in C++ (Unicode)

LPCWSTR lpcwName=std::wstring(strname.begin(), strname.end()).c_str()

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

You can use native JS so you don't have to rely on external libraries.

(I will use some ES2015 syntax, a.k.a ES6, modern javascript) What is ES2015?

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    });

You can also capture errors if any:

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    })
    .catch(err => {
        console.error('An error ocurred', err);
    });

By default it uses GET and you don't have to specify headers, but you can do all that if you want. For further reference: Fetch API reference

make arrayList.toArray() return more specific types

A shorter version of converting List to Array of specific type (for example Long):

Long[] myArray = myList.toArray(Long[]::new);

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

I even run the command prompt as Administrator but it didn't work for me with the below error.

'keytool' is not recognized as an internal or external command,
 operable program or batch file.

If the path to the keytool is not in your System paths then you will need to use the full path to use the keytool, which is

C:\Program Files\Java\jre<version>\bin

So, the command should be like

"C:\Program Files\Java\jre<version>\bin\keytool.exe" -importcert -alias certificateFileAlias -file CertificateFileName.cer -keystore cacerts

that worked for me.

How to determine an interface{} value's "real" type?

I'm going to offer up a way to return a boolean based on passing an argument of a reflection Kinds to a local type receiver (because I couldn't find anything like this).

First, we declare our anonymous type of type reflect.Value:

type AnonymousType reflect.Value

Then we add a builder for our local type AnonymousType which can take in any potential type (as an interface):

func ToAnonymousType(obj interface{}) AnonymousType {
    return AnonymousType(reflect.ValueOf(obj))
}

Then we add a function for our AnonymousType struct which asserts against a reflect.Kind:

func (a AnonymousType) IsA(typeToAssert reflect.Kind) bool {
    return typeToAssert == reflect.Value(a).Kind()
}

This allows us to call the following:

var f float64 = 3.4

anon := ToAnonymousType(f)

if anon.IsA(reflect.String) {
    fmt.Println("Its A String!")
} else if anon.IsA(reflect.Float32) {
    fmt.Println("Its A Float32!")
} else if anon.IsA(reflect.Float64) {
    fmt.Println("Its A Float64!")
} else {
    fmt.Println("Failed")
}

Can see a longer, working version here:https://play.golang.org/p/EIAp0z62B7

Sample random rows in dataframe

You could do this:

sample_data = data[sample(nrow(data), sample_size, replace = FALSE), ]

How do you set the startup page for debugging in an ASP.NET MVC application?

Selecting a specific page from Project properties does not solve my problem.

In MVC 4 open App_Start/RouteConfig.cs

For example, if you want to change startup page to Login:

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

How to write a unit test for a Spring Boot Controller endpoint

Adding @WebAppConfiguration (org.springframework.test.context.web.WebAppConfiguration) annotation to your DemoApplicationTests class will work.

Easiest way to convert a Blob into a byte array

The easiest way is this.

byte[] bytes = rs.getBytes("my_field");

Node.js: how to consume SOAP XML web service

I think that an alternative would be to:

Yes, this is a rather dirty and low level approach but it should work without problems

Convert a char to upper case using regular expressions (EditPad Pro)

TextPad will allow you to perform this operation.

example:

test this sentence

Find what: \([^ ]*\) \(.*\) Replace with: \U\1\E \2

the \U will cause all following chars to be upper

the \E will turn off the \U

the result will be:

TEST this sentence

run a python script in terminal without the python command

You need to use a hashbang. Add it to the first line of your python script.

#! <full path of python interpreter>

Then change the file permissions, and add the executing permission.

chmod +x <filename>

And finally execute it using

./<filename>

If its in the current directory,

Can a Byte[] Array be written to a file in C#?

You can do this using System.IO.BinaryWriter which takes a Stream so:

var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate);
bw.Write(byteArray);

Convert List<DerivedClass> to List<BaseClass>

I've read this whole thread, and I just want to point out what seems like an inconsistency to me.

The compiler prevents you from doing the assignment with Lists:

List<Tiger> myTigersList = new List<Tiger>() { new Tiger(), new Tiger(), new Tiger() };
List<Animal> myAnimalsList = myTigersList;    // Compiler error

But the compiler is perfectly fine with arrays:

Tiger[] myTigersArray = new Tiger[3] { new Tiger(), new Tiger(), new Tiger() };
Animal[] myAnimalsArray = myTigersArray;    // No problem

The argument about whether the assignment is known to be safe falls apart here. The assignment I did with the array is not safe. To prove that, if I follow that up with this:

myAnimalsArray[1] = new Giraffe();

I get a runtime exception "ArrayTypeMismatchException". How does one explain this? If the compiler really wants to prevent me from doing something stupid, it should have prevented me from doing the array assignment.

Javascript, Change google map marker color

var map_marker = $(".map-marker").children("img").attr("src") var pinImage = new google.maps.MarkerImage(map_marker);

     var marker = new google.maps.Marker({
      position: uluru,
      map: map,
      icon: pinImage
    });
  }

How do I make a checkbox required on an ASP.NET form?

javascript function for client side validation (using jQuery)...

function CheckBoxRequired_ClientValidate(sender, e)
{
    e.IsValid = jQuery(".AcceptedAgreement input:checkbox").is(':checked');
}

code-behind for server side validation...

protected void CheckBoxRequired_ServerValidate(object sender, ServerValidateEventArgs e)
{
    e.IsValid = MyCheckBox.Checked;
}

ASP.Net code for the checkbox & validator...

<asp:CheckBox runat="server" ID="MyCheckBox" CssClass="AcceptedAgreement" />
<asp:CustomValidator runat="server" ID="CheckBoxRequired" EnableClientScript="true"
    OnServerValidate="CheckBoxRequired_ServerValidate"
    ClientValidationFunction="CheckBoxRequired_ClientValidate">You must select this box to proceed.</asp:CustomValidator>

and finally, in your postback - whether from a button or whatever...

if (Page.IsValid)
{
    // your code here...
}

How to convert a Java 8 Stream to an Array?

import java.util.List;
import java.util.stream.Stream;

class Main {

    public static void main(String[] args) {
        // Create a stream of strings from list of strings
        Stream<String> myStreamOfStrings = List.of("lala", "foo", "bar").stream();

        // Convert stream to array by using toArray method
        String[] myArrayOfStrings = myStreamOfStrings.toArray(String[]::new);

        // Print results
        for (String string : myArrayOfStrings) {
            System.out.println(string);
        }
    }
}

Try it out online: https://repl.it/@SmaMa/Stream-to-array

sh: 0: getcwd() failed: No such file or directory on cited drive

Please check the directory path whether exists or not. This error comes up if the folder doesn't exists from where you are running the command. Probably you have executed a remove command from same path in command line.

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.

What is the difference between exit and return?

In C, there's not much difference when used in the startup function of the program (which can be main(), wmain(), _tmain() or the default name used by your compiler).

If you return in main(), control goes back to the _start() function in the C library which originally started your program, which then calls exit() anyways. So it really doesn't matter which one you use.

How to append the output to a file?

you can append the file with >> sign. It insert the contents at the last of the file which we are using.e.g if file let its name is myfile contains xyz then cat >> myfile abc ctrl d

after the above process the myfile contains xyzabc.

MySQL SELECT only not null values

Select * from your_table 
WHERE col1 and col2 and col3 and col4 and col5 IS NOT NULL;

The only disadvantage of this approach is that you can only compare 5 columns, after that the result will always be false, so I do compare only the fields that can be NULL.

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

It is prohibiting the opening of Eclipse app because it was not registered with Apple by an identified developer. This is a security feature, however, you can override the security setting and open the app by doing the following:

  1. Locate the Eclipse.app (eclipse/Eclipse.app) in Finder. (Make sure you use Finder so that you can perform the subsequent steps.)
  2. Press the Control key and then click the Eclipse.app icon.
  3. Choose Open from the shortcut menu.
  4. Click the Open button when the alert window appears.

The last step will add an exception for Eclipse to your security settings and now you will be able to open it without any warnings.

Note, these steps work for other *.app apps that may encounter the same issue.

How to programmatically send SMS on the iPhone?

//call method with name and number.

-(void)openMessageViewWithName:(NSString*)contactName withPhone:(NSString *)phone{

CTTelephonyNetworkInfo *networkInfo=[[CTTelephonyNetworkInfo alloc]init];

CTCarrier *carrier=networkInfo.subscriberCellularProvider;

NSString *Countrycode = carrier.isoCountryCode;

if ([Countrycode length]>0)     //Check If Sim Inserted
{

    [self sendSMS:msg recipientList:[NSMutableArray arrayWithObject:phone]];
}
else
{

    [AlertHelper showAlert:@"Message" withMessage:@"No sim card inserted"];
}

}

//Method for sending message

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSMutableArray *)recipients{  
 MFMessageComposeViewController *controller1 = [[MFMessageComposeViewController alloc] init] ;
 controller1 = [[MFMessageComposeViewController alloc] init] ;
 if([MFMessageComposeViewController canSendText])
{
    controller1.body = bodyOfMessage;
    controller1.recipients = recipients;
    controller1.messageComposeDelegate = self;
    [self presentViewController:controller1 animated:YES completion:Nil];
 }
}

How do I copy the contents of one ArrayList into another?

to copy one list into the other list, u can use the method called Collection.copy(myObject myTempObject).now after executing these line of code u can see all the list values in the myObject.

.ps1 cannot be loaded because the execution of scripts is disabled on this system

There are certain scenarios in which you can follow the steps suggested in the other answers, verify that Execution Policy is set correctly, and still have your scripts fail. If this happens to you, you are probably on a 64-bit machine with both 32-bit and 64-bit versions of PowerShell, and the failure is happening on the version that doesn't have Execution Policy set. The setting does not apply to both versions, so you have to explicitly set it twice.

Look in your Windows directory for System32 and SysWOW64.

Repeat these steps for each directory:

  1. Navigate to WindowsPowerShell\v1.0 and launch powershell.exe
  2. Check the current setting for ExecutionPolicy:

    Get-ExecutionPolicy -List

  3. Set the ExecutionPolicy for the level and scope you want, for example:

    Set-ExecutionPolicy -Scope LocalMachine Unrestricted

Note that you may need to run PowerShell as administrator depending on the scope you are trying to set the policy for.

You can read a lot more here: Running Windows PowerShell Scripts

Laravel 4: how to run a raw SQL?

The best way to do this I have found so far it to side step Laravel and execute the query directly using the Pdo object.

Example

DB::connection()->getPdo()->exec( $sql );

I usually find it faster and more efficient for a one time query to simply open my database query tool and type the query with full syntax checking then execute it directly.

This becomes essential if you have to work with stored procedures or need to use any database functions

Example 2 setting created_at to a the value you need it to be and side steeping any carbon funkiness

$sql = 'UPDATE my_table SET updated_at = FROM_UNIXTIME(nonce) WHERE id = ' . strval($this->id);
DB::statement($sql);

I found this worked in a controller but not in a migration

Error when using scp command "bash: scp: command not found"

Check if scp is installed or not on from where you want want to copy check using which scp

If it's already installed, it will print you a path like /usr/bin/scp Else, install scp using:

yum -y install openssh-clients

Then copy command

scp -r [email protected]:/var/www/html/database_backup/restore_fullbackup/backup_20140308-023002.sql  /var/www/html/db_bkp/

How to pass optional parameters while omitting some other optional parameters?

You can create a helper method that accept a one object parameter base on error arguments

 error(message: string, title?: string, autoHideAfter?: number){}

 getError(args: { message: string, title?: string, autoHideAfter?: number }) {
    return error(args.message, args.title, args.autoHideAfter);
 }

/lib/ld-linux.so.2: bad ELF interpreter: No such file or directory

These are the installation i had to run in order to make it work on fedora 22 :-

glibc-2.21-7.fc22.i686

alsa-lib-1.0.29-1.fc22.i686

qt3-3.3.8b-64.fc22.i686

libusb-1:0.1.5-5.fc22.i686

To add server using sp_addlinkedserver

-- check if server exists in table sys.server

select * from sys.servers

-- set database security

    EXEC sp_configure 'show advanced options', 1
    RECONFIGURE
    GO

    EXEC sp_configure 'ad hoc distributed queries', 1
    RECONFIGURE
    GO

-- add the external dbserver

EXEC sp_addlinkedserver @server='#servername#'

-- add login on external server

EXEC sp_addlinkedsrvlogin '#Servername#', 'false', NULL, '#username#', '#password@123"'

-- control query on remote table

select top (1000) * from [#server#].[#database#].[#schema#].[#table#]

Adding a JAR to an Eclipse Java library

In Eclipse Ganymede (3.4.0):

  1. Select the library and click "Edit" (left side of the window)
  2. Click "User Libraries"
  3. Select the library again and click "Add JARs"

are there dictionaries in javascript like python?

I realize this is an old question, but it pops up in Google when you search for 'javascript dictionaries', so I'd like to add to the above answers that in ECMAScript 6, the official Map object has been introduced, which is a dictionary implementation:

var dict = new Map();
dict.set("foo", "bar");

//returns "bar"
dict.get("foo");

Unlike javascript's normal objects, it allows any object as a key:

var foo = {};
var bar = {};
var dict = new Map();
dict.set(foo, "Foo");
dict.set(bar, "Bar");

//returns "Bar"
dict.get(bar);

//returns "Foo"
dict.get(foo);

//returns undefined, as {} !== foo and {} !== bar
dict.get({});

SELECT CASE WHEN THEN (SELECT)

For a start the first select has 6 columns and the second has 4 columns. Perhaps make both have the same number of columns (adding nulls?).

bash script read all the files in directory

You can go without the loop:

find /path/to/dir -type f -exec /your/first/command \{\} \; -exec /your/second/command \{\} \; 

HTH

What does the DOCKER_HOST variable do?

Ok, I think I got it.

The client is the docker command installed into OS X.

The host is the Boot2Docker VM.

The daemon is a background service running inside Boot2Docker.

This variable tells the client how to connect to the daemon.

When starting Boot2Docker, the terminal window that pops up already has DOCKER_HOST set, so that's why docker commands work. However, to run Docker commands in other terminal windows, you need to set this variable in those windows.

Failing to set it gives a message like this:

$ docker run hello-world
2014/08/11 11:41:42 Post http:///var/run/docker.sock/v1.13/containers/create: 
dial unix /var/run/docker.sock: no such file or directory

One way to fix that would be to simply do this:

$ export DOCKER_HOST=tcp://192.168.59.103:2375

But, as pointed out by others, it's better to do this:

$ $(boot2docker shellinit)
$ docker run hello-world
Hello from Docker. [...]

To spell out this possibly non-intuitive Bash command, running boot2docker shellinit returns a set of Bash commands that set environment variables:

export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1

Hence running $(boot2docker shellinit) generates those commands, and then runs them.

How can I access each element of a pair in a pair list?

Use tuple unpacking:

>>> pairs = [("a", 1), ("b", 2), ("c", 3)]
>>> for a, b in pairs:
...    print a, b
... 
a 1
b 2
c 3

See also: Tuple unpacking in for loops.

What is the difference between match_parent and fill_parent?

match_parent and fill_parent are same property, used to define width or height of a view in full screen horizontally or vertically.

These properties are used in android xml files like this.

 android:layout_width="match_parent"
 android:layout_height="fill_parent"

or

 android:layout_width="fill_parent"
 android:layout_height="match_parent"

fill_parent was used in previous versions, but now it has been deprecated and replaced by match_parent. I hope it'll help you.

Express.js: how to get remote client address

With could-flare, nginx and x-real-ip support

var user_ip;

    if(req.headers['cf-connecting-ip'] && req.headers['cf-connecting-ip'].split(', ').length) {
      let first = req.headers['cf-connecting-ip'].split(', ');
      user_ip = first[0];
    } else {
      let user_ip = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
    }

Manually highlight selected text in Notepad++

"Select your text, right click, then choose Style Token and then using 1st style (2nd style, etc …). At the moment is not possible to save the style tokens but there is an idea pending on Idea torrent you may vote for if your are interested in that."

It should be default, but it might be hidden.

"It might be that something happened to your contextMenu.xml so that you only get the basic standard. Have a look in NPPs config folder (%appdata%\Notepad++\) if the contextMenu.xml is there. If no: that would be the answer; if yes: it might be defect. Anyway you can grab the original standart contextMenu.xml from here and place it into the config folder (or replace the existing xml). Start NPP and you should have quite a long context menu. Tip: have a look at the contextmenu.xml itself - because you're allowed to change it to your own needs."

See this for more information

Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

You need to change your text to 'Plain text' before pasting into the HTML document. This looks like an error I've had before by pasting straight from MS word.

MS word and other rich text editors often place hidden or invalid chars into your code. Try using &mdash; for your dashes, or &rsquo; for apostrophes (etc), to eliminate the need for relying on your char encoding.

Get current rowIndex of table in jQuery

Try this,

$('td').click(function(){
   var row_index = $(this).parent().index();
   var col_index = $(this).index();
});

If you need the index of table contain td then you can change it to

var row_index = $(this).parent('table').index(); 

Can I access variables from another file?

I may be doing this a little differently. I'm not sure why I use this syntax, copied it from some book a long time ago. But each of my js files defines a variable. The first file, for no reason at all, is called R:

    var R = 
    { 
        somevar: 0,
        othervar: -1,

        init: function() {
          ...
        } // end init function

        somefunction: function(somearg) {
          ...
        }  // end somefunction

        ...

    }; // end variable R definition


    $( window ).load(function() {
       R.init();
    })

And then if I have a big piece of code that I want to segregate, I put it in a separate file and a different variable name, but I can still reference the R variables and functions. I called the new one TD for no good reason at all:

    var TD = 
    { 
        xvar: 0,
        yvar: -1,

        init: function() {
           ...
        } // end init function

        sepfunction: function() {
           ...
           R.somefunction(xvar);
           ...
        }  // end somefunction

        ...

    }; // end variable TD definition


    $( window ).load(function() {
       TD.init();
    })

You can see that where in the TD 'sepfunction' I call the R.somefunction. I realize this doesn't give any runtime efficiencies because both scripts to need to load, but it does help me keep my code organized.

Detecting Browser Autofill

I was looking for a similar thing. Chrome only... In my case the wrapper div needed to know if the input field was autofilled. So I could give it extra css just like Chrome does on the input field when it autofills it. By looking at all the answers above my combined solution was the following:

/* 
 * make a function to use it in multiple places
 */
var checkAutoFill = function(){
    $('input:-webkit-autofill').each(function(){
        $(this).closest('.input-wrapper').addClass('autofilled');
    });
}

/* 
 * Put it on the 'input' event 
 * (happens on every change in an input field)
 */
$('html').on('input', function() {
    $('.input-wrapper').removeClass('autofilled');
    checkAutoFill();
});

/*
 * trigger it also inside a timeOut event 
 * (happens after chrome auto-filled fields on page-load)
 */
setTimeout(function(){ 
    checkAutoFill();
}, 0);

The html for this to work would be

<div class="input-wrapper">
    <input type="text" name="firstname">
</div>

How to style the option of an html "select" element?

Some properties can be styled for<option> tag:

  • font-family
  • color
  • font-*
  • background-color

Also you can use custom font for individual <option> tag, for example any google font, Material Icons or other icon fonts from icomoon or alike. (That may come handy for font selectors etc.)

Considering that, you can create font-family stack and insert icons in <option> tags, eg.

    <select>
        <option style="font-family: 'Icons', 'Roboto', sans-serif;">a    ???</option>
        <option style="font-family: 'Icons', 'Roboto', sans-serif;">b    ????</option>
    </select>

where ? is taken from Icons and the rest is from Roboto.

Note though that custom fonts do not work for mobile select.

Highest Salary in each department

WITH cteRowNum AS (
    SELECT DeptID, EmpName, Salary,
           ROW_NUMBER() OVER(PARTITION BY DeptID ORDER BY Salary DESC) AS RowNum
        FROM EmpDetails
)
SELECT DeptID, EmpName, Salary,Rownum
    FROM cteRowNum
    WHERE RowNum in(1,2);

Delete files older than 3 months old in a directory using .NET

Just create a small delete function which can help you to achieve this task, I have tested this code and it runs perfectly well.

This function deletes files older than 90 days as well as a file with extension .zip to be deleted from a folder.

Private Sub DeleteZip()

    Dim eachFileInMydirectory As New DirectoryInfo("D:\Test\")
    Dim fileName As IO.FileInfo

    Try
        For Each fileName In eachFileInMydirectory.GetFiles
            If fileName.Extension.Equals("*.zip") AndAlso (Now - fileName.CreationTime).Days > 90 Then
                fileName.Delete()
            End If
        Next

    Catch ex As Exception
        WriteToLogFile("No Files older than 90 days exists be deleted " & ex.Message)
    End Try
End Sub

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

The answers provided did not work for me (Chrome or Firefox) while creating PWA for local development and testing. DO NOT USE FOR PRODUCTION! I was able to use the following:

  1. Online certificate tools site with the following options:
    • Common Names: Add both the "localhost" and IP of your system e.g. 192.168.1.12
    • Subject Alternative Names: Add "DNS" = "localhost" and "IP" = <your ip here, e.g. 192.168.1.12>
    • "CRS" drop down options set to "Self Sign"
    • all other options were defaults
  2. Download all links
  3. Import .p7b cert into Windows by double clicking and select "install"/ OSX?/Linux?
  4. Added certs to node app... using Google's PWA example
    • add const https = require('https'); const fs = require('fs'); to the top of the server.js file
    • comment out return app.listen(PORT, () => { ... }); at the bottom of server.js file
    • add below https.createServer({ key: fs.readFileSync('./cert.key','utf8'), cert: fs.readFileSync('./cert.crt','utf8'), requestCert: false, rejectUnauthorized: false }, app).listen(PORT)

I have no more errors in Chrome or Firefox

How to determine whether code is running in DEBUG / RELEASE build?

zitao xiong's answer is pretty close to what I use; I also include the file name (by stripping off the path of FILE).

#ifdef DEBUG
    #define NSLogDebug(format, ...) \
    NSLog(@"<%s:%d> %s, " format, \
    strrchr("/" __FILE__, '/') + 1, __LINE__, __PRETTY_FUNCTION__, ## __VA_ARGS__)
#else
    #define NSLogDebug(format, ...)
#endif

How can I format DateTime to web UTC format?

You want to use DateTimeOffset class.

var date = new DateTimeOffset(2009, 9, 1, 0, 0, 0, 0, new TimeSpan(0L));
var stringDate = date.ToString("u");

sorry I missed your original formatting with the miliseconds

var stringDate = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");

Is HTML considered a programming language?

I think not exactly a programming language, but exactly what its name says: a markup language. We cannot program using just pure, HTML. But just annotate how to present content.

But if you consider programming the act of tell the computer how to present contents, it is a programming language.

Add ArrayList to another ArrayList in java

Wouldn't it just be a case of:

ArrayList<ArrayList<String>> outer = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();

// Fill in nodeList here...

outer.add(nodeList);

Repeat as necesary.

This should return you a list in the format you specified.

Composer could not find a composer.json

If you forget to run:

php artisan key:generate

You would be face this error : Composer could not find a composer.json

Difference between attr_accessor and attr_accessible

Many people on this thread and on google explain very well that attr_accessible specifies a whitelist of attributes that are allowed to be updated in bulk (all the attributes of an object model together at the same time) This is mainly (and only) to protect your application from "Mass assignment" pirate exploit.

This is explained here on the official Rails doc : Mass Assignment

attr_accessor is a ruby code to (quickly) create setter and getter methods in a Class. That's all.

Now, what is missing as an explanation is that when you create somehow a link between a (Rails) model with a database table, you NEVER, NEVER, NEVER need attr_accessor in your model to create setters and getters in order to be able to modify your table's records.

This is because your model inherits all methods from the ActiveRecord::Base Class, which already defines basic CRUD accessors (Create, Read, Update, Delete) for you. This is explained on the offical doc here Rails Model and here Overwriting default accessor (scroll down to the chapter "Overwrite default accessor")

Say for instance that: we have a database table called "users" that contains three columns "firstname", "lastname" and "role" :

SQL instructions :

CREATE TABLE users (
  firstname string,
  lastname string
  role string
);

I assumed that you set the option config.active_record.whitelist_attributes = true in your config/environment/production.rb to protect your application from Mass assignment exploit. This is explained here : Mass Assignment

Your Rails model will perfectly work with the Model here below :

class User < ActiveRecord::Base

end

However you will need to update each attribute of user separately in your controller for your form's View to work :

def update
    @user = User.find_by_id(params[:id])
    @user.firstname = params[:user][:firstname]
    @user.lastname = params[:user][:lastname]

    if @user.save
        # Use of I18 internationalization t method for the flash message
        flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
    end

    respond_with(@user)
end

Now to ease your life, you don't want to make a complicated controller for your User model. So you will use the attr_accessible special method in your Class model :

class User < ActiveRecord::Base

  attr_accessible :firstname, :lastname

end

So you can use the "highway" (mass assignment) to update :

def update
    @user = User.find_by_id(params[:id])

    if @user.update_attributes(params[:user])
        # Use of I18 internationlization t method for the flash message
        flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
    end

    respond_with(@user)
end

You didn't add the "role" attributes to the attr_accessible list because you don't let your users set their role by themselves (like admin). You do this yourself on another special admin View.

Though your user view doesn't show a "role" field, a pirate could easily send a HTTP POST request that include "role" in the params hash. The missing "role" attribute on the attr_accessible is to protect your application from that.

You can still modify your user.role attribute on its own like below, but not with all attributes together.

@user.role = DEFAULT_ROLE

Why the hell would you use the attr_accessor?

Well, this would be in the case that your user-form shows a field that doesn't exist in your users table as a column.

For instance, say your user view shows a "please-tell-the-admin-that-I'm-in-here" field. You don't want to store this info in your table. You just want that Rails send you an e-mail warning you that one "crazy" ;-) user has subscribed.

To be able to make use of this info you need to store it temporarily somewhere. What more easy than recover it in a user.peekaboo attribute ?

So you add this field to your model :

class User < ActiveRecord::Base

  attr_accessible :firstname, :lastname
  attr_accessor :peekaboo

end

So you will be able to make an educated use of the user.peekaboo attribute somewhere in your controller to send an e-mail or do whatever you want.

ActiveRecord will not save the "peekaboo" attribute in your table when you do a user.save because she don't see any column matching this name in her model.

Load resources from relative path using local html in uiwebview

Swift answer 2.

The UIWebView Class Reference advises against using webView.loadRequest(request):

Don’t use this method to load local HTML files; instead, use loadHTMLString:baseURL:.

In this solution, the html is read into a string. The html's url is used to work out the path, and passes that as a base url.

let url = bundle.URLForResource("index", withExtension: "html", subdirectory: "htmlFileFolder")
let html = try String(contentsOfURL: url)
let base = url.URLByDeletingLastPathComponent
webView.loadHTMLString(html, baseURL: base)

PHP Get name of current directory

Actually I found the best solution is the following:

$cur_dir = explode('\\', getcwd());
echo $cur_dir[count($cur_dir)-1];

if your dir is www\var\path\ Current_Path

then this returns Current_path

Sass and combined child selector

Without the combined child selector you would probably do something similar to this:

foo {
  bar {
    baz {
      color: red;
    }
  }
}

If you want to reproduce the same syntax with >, you could to this:

foo {
  > bar {
    > baz {
      color: red;
    }
  }
}

This compiles to this:

foo > bar > baz {
  color: red;
}

Or in sass:

foo
  > bar
    > baz
      color: red

Tomcat request timeout

For anyone who doesn't like none of the solutions posted above like me then you can simply implement a timer yourself and stop the request execution by throwing a runtime exception. Something like below:

                  try 
                 {
                     timer.schedule(new TimerTask() {
                       @Override
                       public void run() {
                         timer.cancel();
                       }
                     }, /* specify time of the requst */ 1000);
                 }
                 catch(Exception e)
                 {
                   throw new RuntimeException("the request is taking longer than usual");
                 }

   

or preferably use the java guava timeLimiter here

Run jar file in command prompt

You can run a JAR file from the command line like this:

java -jar myJARFile.jar

How to make scipy.interpolate give an extrapolated result beyond the input range?

As of SciPy version 0.17.0, there is a new option for scipy.interpolate.interp1d that allows extrapolation. Simply set fill_value='extrapolate' in the call. Modifying your code in this way gives:

import numpy as np
from scipy import interpolate

x = np.arange(0,10)
y = np.exp(-x/3.0)
f = interpolate.interp1d(x, y, fill_value='extrapolate')

print f(9)
print f(11)

and the output is:

0.0497870683679
0.010394302658

Changing git commit message after push (given that no one pulled from remote)

Use these two step in console :

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

and then

git push -f

Done :)

How to add multiple columns to pandas dataframe in one assignment?

I am not comfortable using "Index" and so on...could come up as below

df.columns
Index(['A123', 'B123'], dtype='object')

df=pd.concat([df,pd.DataFrame(columns=list('CDE'))])

df.rename(columns={
    'C':'C123',
    'D':'D123',
    'E':'E123'
},inplace=True)


df.columns
Index(['A123', 'B123', 'C123', 'D123', 'E123'], dtype='object')

How to format code in Xcode?

  1. Select the block of code that you want indented.

  2. Right-click (or, on Mac, Ctrl-click).

  3. Structure → Re-indent

How to serialize object to CSV file?

Worth mentioning that the handlebar library https://github.com/jknack/handlebars.java can trivialize many transformation tasks include toCSV.

How to change the docker image installation directory?

For Those looking in 2020. The following is for Windows 10 Machine:

  1. In the global Actions pane of Hyper-V Manager click Hyper-V Settings…
  2. Under Virtual Hard Disks change the location from the default to your desired location.
  3. Under Virtual Machines change the location from the default to your desired location, and click apply.

enter image description here

  1. Click OK to close the Hyper-V Settings page.

Python naming conventions for modules

From PEP-8: Package and Module Names:

Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability.

Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket).

Cross-Origin Read Blocking (CORB)

It's not clear from the question, but assuming this is something happening on a development or test client, and given that you are already using Fiddler you can have Fiddler respond with an allow response:

  • Select the problem request in Fiddler
  • Open the AutoResponder tab
  • Click Add Rule and edit the rule to:
    • Method:OPTIONS server url here, e.g. Method:OPTIONS http://localhost
    • *CORSPreflightAllow
  • Check Unmatched requests passthrough
  • Check Enable Rules

A couple notes:

  1. Obviously this is only a solution for development/testing where it isn't possible/practical to modify the API service
  2. Check that any agreements you have with the third-party API provider allow you to do this
  3. As others have noted, this is part of how CORS works, and eventually the header will need to be set on the API server. If you control that server, you can set the headers yourself. In this case since it is a third party service, I can only assume they have some mechanism via which you are able to provide them with the URL of the originating site and they will update their service accordingly to respond with the correct headers.

java.net.SocketException: Software caused connection abort: recv failed

If you are using Netbeans to manage Tomcat, try to disable HTTP monitor in Tools - Servers

Peak signal detection in realtime timeseries data

In computational topology the idea of persistent homology leads to an efficient – fast as sorting numbers – solution. It does not only detect peaks, it quantifies the "significance" of the peaks in a natural way that allows you to select the peaks that are significant for you.

Algorithm summary. In a 1-dimensional setting (time series, real-valued signal) the algorithm can be easily described by the following figure:

Most persistent peaks

Think of the function graph (or its sub-level set) as a landscape and consider a decreasing water level starting at level infinity (or 1.8 in this picture). While the level decreases, at local maxima islands pop up. At local minima these islands merge together. One detail in this idea is that the island that appeared later in time is merged into the island that is older. The "persistence" of an island is its birth time minus its death time. The lengths of the blue bars depict the persistence, which is the above mentioned "significance" of a peak.

Efficiency. It is not too hard to find an implementation that runs in linear time – in fact it is a single, simple loop – after the function values were sorted. So this implementation should be fast in practice and is easily implemented, too.

References. A write-up of the entire story and references to the motivation from persistent homology (a field in computatioal algebraic topology) can be found here: https://www.sthu.org/blog/13-perstopology-peakdetection/index.html

Download TS files from video stream

1) Please read instructions by @aalhanane (after "paste URL m3u8" step you have to type name for the file, eg "video" then click on "hand" icon next to "quality" and only after that you should select "one on one" and "download").

2) The stream splits video and audio, so you need to download them separately and then use the same m3u8x to join them https://youtu.be/he-tDNiVl2M (optionally convert to mp4).

3) m3u8x can download video without any issues but in my case it cannot extract audio links. So I simply downloaded the *.m3u8 file and searched for line which contains GROUP-ID="audio-0" and then scroll right and copied the link (!including token!) and paste it straight into "Quality URL" field of m3u8x app. Then "one on one" and download it similar to video stream.

Once I had both video and audio, I joined and success =)

p.s. in case automatic extraction will stop working in the future, you can use the same method to extract video links manually.

Javascript Append Child AFTER Element

You can use:

if (parentGuest.nextSibling) {
  parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
}
else {
  parentGuest.parentNode.appendChild(childGuest);
}

But as Pavel pointed out, the referenceElement can be null/undefined, and if so, insertBefore behaves just like appendChild. So the following is equivalent to the above:

parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);

Oracle query execution time

One can issue the SQL*Plus command SET TIMING ON to get wall-clock times, but one can't take, for example, fetch time out of that trivially.

The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.

Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".

import module from string variable

Apart from using the importlib one can also use exec method to import a module from a string variable.

Here I am showing an example of importing the combinations method from itertools package using the exec method:

MODULES = [
    ['itertools','combinations'],
]

for ITEM in MODULES:
    import_str = "from {0} import {1}".format(ITEM[0],', '.join(str(i) for i in ITEM[1:]))
    exec(import_str)

ar = list(combinations([1, 2, 3, 4], 2))
for elements in ar:
    print(elements)

Output:

(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

wampserver doesn't go green - stays orange

you can run appache:

E:\wamp\bin\apache\apache2.4.9\bin\httpd.exe -d E:/wamp/bin/apache/apache2.4.9

after that see the log of error and solve it.

Python: Get the first character of the first string in a list?

Try mylist[0][0]. This should return the first character.

React Native: Getting the position of an element

If you use function components and don't want to use a forwardRef to measure your component's absolute layout, you can get a reference to it from the LayoutChangeEvent in the onLayout callback.

This way, you can get the absolute position of the element:

<MyFunctionComp
  onLayout={(event) => {
    event.target.measure(
      (x, y, width, height, pageX, pageX) => {
        doSomethingWithAbsolutePosition({
          x: x + pageX, 
          y: y + pageY,
        });
      },
    );
  }}
/>

Tested with React Native 0.63.3.

Get Value of Row in Datatable c#

Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...

for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
    double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}

Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.

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

Using Angular latest version (1.2.1) and track by $index. This issue is fixed

http://jsfiddle.net/rnw3u/53/

<div ng-repeat="(i, name) in names track by $index">
    Value: {{name}}
    <input ng-model="names[i]">                         
</div>

How to change UIButton image in Swift

For anyone using Assets.xcassets and Swift 3, it'd be like this (no need for .png)

let buttonDone  = UIButton(type: .Custom)

if let image = UIImage(named: "Done") {
    self.buttonDone.setImage(image, for: .normal)
}

Bootstrap DatePicker, how to set the start date for tomorrow?

1) use for tommorow's date startDate: '+1d'

2) use for yesterday's date startDate: '-1d'

3) use for today's date startDate: new Date()

C# ListView Column Width Auto

There is another useful method called AutoResizeColumn which allows you to auto size a specific column with the required parameter.

You can call it like this:

listview1.AutoResizeColumn(1, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(2, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(3, ColumnHeaderAutoResizeStyle.HeaderSize);
listview1.AutoResizeColumn(4, ColumnHeaderAutoResizeStyle.HeaderSize);

How to access Anaconda command prompt in Windows 10 (64-bit)

After installing Anaconda3 on your system you need to add Anaconda to the PATH environment variable. This will allow you to access Anaconda with the 'conda' command from cmd.exe or PowerShell.

The link I provided below go through the three major issues with not recognized error. Which are:

  1. Environment PATH for Conda is not set
  2. Environment PATH is incorrectly added
  3. Anaconda version is older than the version of the Anaconda Navigator

LINK: https://appuals.com/fix-conda-is-not-recognized-as-an-internal-or-external-command-operable-program-or-batch-file/

My issue was resolved following the steps for issue #2 Environment PATH is incorrectly added. I did not have all three file paths in my variable environment.

Export Postgresql table data using pgAdmin

  1. Right-click on your table and pick option Backup..
  2. On File Options, set Filepath/Filename and pick PLAIN for Format
  3. Ignore Dump Options #1 tab
  4. In Dump Options #2 tab, check USE INSERT COMMANDS
  5. In Dump Options #2 tab, check Use Column Inserts if you want column names in your inserts.
  6. Hit Backup button

Ruby objects and JSON serialization (without Rails)

Check out Oj. There are gotchas when it comes to converting any old object to JSON, but Oj can do it.

require 'oj'

class A
    def initialize a=[1,2,3], b='hello'
        @a = a
        @b = b
    end
end

a = A.new
puts Oj::dump a, :indent => 2

This outputs:

{
  "^o":"A",
  "a":[
    1,
    2,
    3
  ],
 "b":"hello"
}

Note that ^o is used to designate the object's class, and is there to aid deserialization. To omit ^o, use :compat mode:

puts Oj::dump a, :indent => 2, :mode => :compat

Output:

{
  "a":[
    1,
    2,
    3
  ],
  "b":"hello"
}

Hive Alter table change Column Name

alter table table_name change old_col_name new_col_name new_col_type;

Here is the example

hive> alter table test change userVisit userVisit2 STRING;      
    OK
    Time taken: 0.26 seconds
    hive> describe test;                                      
    OK
    uservisit2              string                                      
    category                string                                      
    uuid                    string                                      
    Time taken: 0.213 seconds, Fetched: 3 row(s)

How to sort an object array by date property?

After correcting the JSON this should work for you now:

var array = [{id: 1, date:'Mar 12 2012 10:00:00 AM'}, {id: 2, date:'Mar 8 2012 08:00:00 AM'}];


array.sort(function(a, b) {
    var c = new Date(a.date);
    var d = new Date(b.date);
    return c-d;
});

Pass variables to Ruby script via command line

tl;dr

I know this is old, but getoptlong wasn't mentioned here and it's probably the best way to parse command line arguments today.


Parsing command line arguments

I strongly recommend getoptlong. It's pretty easy to use and works like a charm. Here is an example extracted from the link above

require 'getoptlong'

opts = GetoptLong.new(
    [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
    [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
    [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
)

dir = nil
name = nil
repetitions = 1
opts.each do |opt, arg|
    case opt
        when '--help'
            puts <<-EOF
hello [OPTION] ... DIR

-h, --help:
     show help

--repeat x, -n x:
     repeat x times

--name [name]:
     greet user by name, if name not supplied default is John

DIR: The directory in which to issue the greeting.
            EOF
        when '--repeat'
            repetitions = arg.to_i
        when '--name'
            if arg == ''
                name = 'John'
            else
                name = arg
            end
    end
end

if ARGV.length != 1
    puts "Missing dir argument (try --help)"
    exit 0
end

dir = ARGV.shift

Dir.chdir(dir)
for i in (1..repetitions)
    print "Hello"
    if name
        print ", #{name}"
    end
    puts
end

You can call it like this ruby hello.rb -n 6 --name -- /tmp

What OP is trying to do

In this case I think the best option is to use YAML files as suggested in this answer

How to escape single quotes within single quoted strings

If you have GNU Parallel installed you can use its internal quoting:

$ parallel --shellquote
L's 12" record
<Ctrl-D>
'L'"'"'s 12" record'
$ echo 'L'"'"'s 12" record'
L's 12" record

From version 20190222 you can even --shellquote multiple times:

$ parallel --shellquote --shellquote --shellquote
L's 12" record
<Ctrl-D>
'"'"'"'"'"'"'L'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'s 12" record'"'"'"'"'"'"'
$ eval eval echo '"'"'"'"'"'"'L'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'"'s 12" record'"'"'"'"'"'"'
L's 12" record

It will quote the string in all supported shells (not only bash).

html/css buttons that scroll down to different div sections on a webpage

There is a much easier way to get the smooth scroll effect without javascript. In your CSS just target the entire html tag and give it scroll-behavior: smooth;

_x000D_
_x000D_
html {_x000D_
  scroll-behavior: smooth;_x000D_
 }_x000D_
 _x000D_
 a {_x000D_
  text-decoration: none;_x000D_
  color: black;_x000D_
 } _x000D_
 _x000D_
 #down {_x000D_
  margin-top: 100%;_x000D_
  padding-bottom: 25%;_x000D_
 } 
_x000D_
<html>_x000D_
  <a href="#down">Click Here to Smoothly Scroll Down</a>_x000D_
  <div id="down">_x000D_
    <h1>You are down!</h1>_x000D_
  </div>_x000D_
</html
_x000D_
_x000D_
_x000D_

The "scroll-behavior" is telling the page how it should scroll and is so much easier than using javascript. Javascript will give you more options on speed and the smoothness but this will deliver without all of the confusing code.

Padding In bootstrap

The suggestion from @Dawood is good if that works for you.

If you need more fine-tuning than that, one option is to use padding on the text elements, here's an example: http://jsfiddle.net/panchroma/FtBwe/

CSS

p, h2 {
    padding-left:10px;
}

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

You have to add reference to

Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll 

It can be found at C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies\ directory (for VS2010 professional or above; .NET Framework 4.0).

or right click on your project and select: Add Reference... > .NET: or click Add Reference... > .NET:

Writing a string to a cell in excel

replace Range("A1") = "Asdf" with Range("A1").value = "Asdf"

JSON encode MySQL results

One more option using FOR loop:

 $sth = mysql_query("SELECT ...");
 for($rows = array(); $row = mysql_fetch_assoc($sth); $rows[] = $row);
 print json_encode($rows);

The only disadvantage is that loop for is slower then e.g. while or especially foreach

Regular expressions inside SQL Server

SQL Wildcards are enough for this purpose. Follow this link: http://www.w3schools.com/SQL/sql_wildcards.asp

you need to use a query like this:

select * from mytable where msisdn like '%7%'

or

select * from mytable where msisdn like '56655%'

Display Yes and No buttons instead of OK and Cancel in Confirm box?

No, it is not possible to change the content of the buttons in the dialog displayed by the confirm function. You can use Javascript to create a dialog that looks similar.

Check if checkbox is NOT checked on click - jQuery

jQuery to check for checked? Really?

if(!this.checked) {

Don't use a bazooka to do a razor's job.

Java Delegates?

Depending precisely what you mean, you can achieve a similar effect (passing around a method) using the Strategy Pattern.

Instead of a line like this declaring a named method signature:

// C#
public delegate void SomeFunction();

declare an interface:

// Java
public interface ISomeBehaviour {
   void SomeFunction();
}

For concrete implementations of the method, define a class that implements the behaviour:

// Java
public class TypeABehaviour implements ISomeBehaviour {
   public void SomeFunction() {
      // TypeA behaviour
   }
}

public class TypeBBehaviour implements ISomeBehaviour {
   public void SomeFunction() {
      // TypeB behaviour
   }
}

Then wherever you would have had a SomeFunction delegate in C#, use an ISomeBehaviour reference instead:

// C#
SomeFunction doSomething = SomeMethod;
doSomething();
doSomething = SomeOtherMethod;
doSomething();

// Java
ISomeBehaviour someBehaviour = new TypeABehaviour();
someBehaviour.SomeFunction();
someBehaviour = new TypeBBehaviour();
someBehaviour.SomeFunction();

With anonymous inner classes, you can even avoid declaring separate named classes and almost treat them like real delegate functions.

// Java
public void SomeMethod(ISomeBehaviour pSomeBehaviour) {
   ...
}

...

SomeMethod(new ISomeBehaviour() { 
   @Override
   public void SomeFunction() {
      // your implementation
   }
});

This should probably only be used when the implementation is very specific to the current context and wouldn't benefit from being reused.

And then of course in Java 8, these do become basically lambda expressions:

// Java 8
SomeMethod(() -> { /* your implementation */ });

How to echo in PHP, HTML tags

Here I have added code, the way you want line by line.

The .= helps you to echo multiple lines of code.

$html = '<div>';
$html .= '<h3><a href="#">First</a></h3>';
$html .= '<div>Lorem ipsum dolor sit amet.</div>';
$html .= '</div>';
$html .= '<div>';
echo $html;

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.

Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).

IN vs OR in the SQL WHERE Clause

I did a SQL query in a large number of OR (350). Postgres do it 437.80ms.

Use OR

Now use IN:

Use IN

23.18ms

Search a whole table in mySQL for a string

Try something like this:

SELECT * FROM clients WHERE CONCAT(field1, '', field2, '', fieldn) LIKE "%Mary%"

You may want to see SQL docs for additional information on string operators and regular expressions.

Edit: There may be some issues with NULL fields, so just in case you may want to use IFNULL(field_i, '') instead of just field_i

Case sensitivity: You can use case insensitive collation or something like this:

... WHERE LOWER(CONCAT(...)) LIKE LOWER("%Mary%")

Just search all field: I believe there is no way to make an SQL-query that will search through all field without explicitly declaring field to search in. The reason is there is a theory of relational databases and strict rules for manipulating relational data (something like relational algebra or codd algebra; these are what SQL is from), and theory doesn't allow things such as "just search all fields". Of course actual behaviour depends on vendor's concrete realisation. But in common case it is not possible. To make sure, check SELECT operator syntax (WHERE section, to be precise).