Programs & Examples On #Self reference

Self-reference is the ability of a program (or logical sentence) to refer to itself, either directly or indirectly.

Self-reference for cell, column and row in worksheet functions

In a VBA worksheet function UDF you use Application.Caller to get the range of cell(s) that contain the formula that called the UDF.

plot data from CSV file with matplotlib

I'm guessing

x= data[:,0]
y= data[:,1]

Center form submit buttons HTML / CSS

One simple solution if only one button needs to be centered is something like:

<input type='submit' style='display:flex; justify-content:center;' value='Submit'>

You can use a similar style to handle several buttons.

Get the current date in java.sql.Date format

new java.sql.Date(Calendar.getInstance().getTimeInMillis());

AngularJS $http, CORS and http authentication

No you don't have to put credentials, You have to put headers on client side eg:

 $http({
        url: 'url of service',
        method: "POST",
        data: {test :  name },
        withCredentials: true,
        headers: {
                    'Content-Type': 'application/json; charset=utf-8'
        }
    });

And and on server side you have to put headers to this is example for nodejs:

/**
 * On all requests add headers
 */
app.all('*', function(req, res,next) {


    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

Find running median from a stream of integers

If the variance of the input is statistically distributed (e.g. normal, log-normal, etc.) then reservoir sampling is a reasonable way of estimating percentiles/medians from an arbitrarily long stream of numbers.

int n = 0;  // Running count of elements observed so far  
#define SIZE 10000
int reservoir[SIZE];  

while(streamHasData())
{
  int x = readNumberFromStream();

  if (n < SIZE)
  {
       reservoir[n++] = x;
  }         
  else 
  {
      int p = random(++n); // Choose a random number 0 >= p < n
      if (p < SIZE)
      {
           reservoir[p] = x;
      }
  }
}

"reservoir" is then a running, uniform (fair), sample of all input - regardless of size. Finding the median (or any percentile) is then a straight-forward matter of sorting the reservoir and polling the interesting point.

Since the reservoir is fixed size, the sort can be considered to be effectively O(1) - and this method runs with both constant time and memory consumption.

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

Pass array to MySQL stored routine

Use a join with a temporary table. You don't need to pass temporary tables to functions, they are global.

create temporary table ids( id int ) ;
insert into ids values (1),(2),(3) ;

delimiter //
drop procedure if exists tsel //
create procedure tsel() -- uses temporary table named ids. no params
READS SQL DATA
BEGIN
  -- use the temporary table `ids` in the SELECT statement or
  -- whatever query you have
  select * from Users INNER JOIN ids on userId=ids.id ;
END //
DELIMITER ;

CALL tsel() ; -- call the procedure

Why doesn't JavaScript support multithreading?

Node.js 10.5+ supports worker threads as experimental feature (you can use it with --experimental-worker flag enabled): https://nodejs.org/api/worker_threads.html

So, the rule is:

  • if you need to do I/O bound ops, then use the internal mechanism (aka callback/promise/async-await)
  • if you need to do CPU bound ops, then use worker threads.

Worker threads are intended to be long-living threads, meaning you spawn a background thread and then you communicate with it via message passing.

Otherwise, if you need to execute a heavy CPU load with an anonymous function, then you can go with https://github.com/wilk/microjob, a tiny library built around worker threads.

Import SQL file by command line in Windows 7

First open Your cmd pannel And enter mysql -u root -p (And Hit Enter) After cmd ask's for mysql password (if you have mysql password so enter now and hit enter again) now type source mysqldata.sql(Hit Enter) Your database will import without any error

Parameter in like clause JPQL

I don't use named parameters for all queries. For example it is unusual to use named parameters in JpaRepository.

To workaround I use JPQL CONCAT function (this code emulate start with):

@Repository
public interface BranchRepository extends JpaRepository<Branch, String> {
    private static final String QUERY = "select b from Branch b"
       + " left join b.filial f"
       + " where f.id = ?1 and b.id like CONCAT(?2, '%')";
    @Query(QUERY)
    List<Branch> findByFilialAndBranchLike(String filialId, String branchCode);
}

I found this technique in excellent docs: http://openjpa.apache.org/builds/1.0.1/apache-openjpa-1.0.1/docs/manual/jpa_overview_query.html

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

I had a similar issue when trying to loop on each sheet of a workbook. To resolve it I did something like this

dim mySheet as sheet

for each mysheet in myWorkbook.sheets

    mySheet.activate
    activesheet.range("A1").select

    with Selection
    'any wanted operations here
    end with

next

And it worked just fine

I hope you can adapt it in your situation

Usage of __slots__?

A very simple example of __slot__ attribute.

Problem: Without __slots__

If I don't have __slot__ attribute in my class, I can add new attributes to my objects.

class Test:
    pass

obj1=Test()
obj2=Test()

print(obj1.__dict__)  #--> {}
obj1.x=12
print(obj1.__dict__)  # --> {'x': 12}
obj1.y=20
print(obj1.__dict__)  # --> {'x': 12, 'y': 20}

obj2.x=99
print(obj2.__dict__)  # --> {'x': 99}

If you look at example above, you can see that obj1 and obj2 have their own x and y attributes and python has also created a dict attribute for each object (obj1 and obj2).

Suppose if my class Test has thousands of such objects? Creating an additional attribute dict for each object will cause lot of overhead (memory, computing power etc.) in my code.

Solution: With __slots__

Now in the following example my class Test contains __slots__ attribute. Now I can't add new attributes to my objects (except attribute x) and python doesn't create a dict attribute anymore. This eliminates overhead for each object, which can become significant if you have many objects.

class Test:
    __slots__=("x")

obj1=Test()
obj2=Test()
obj1.x=12
print(obj1.x)  # --> 12
obj2.x=99
print(obj2.x)  # --> 99

obj1.y=28
print(obj1.y)  # --> AttributeError: 'Test' object has no attribute 'y'

How to access a RowDataPacket object

Hi try this 100% works:

results=JSON.parse(JSON.stringify(results))
doStuffwithTheResult(results); 

How to reload/refresh jQuery dataTable?

You could use an extensive API of DataTable to reload it by ajax.reload()

If you declare your datatable as DataTable() (new version) you need:

var oTable = $('#filtertable_data').DataTable( );
// to reload
oTable.ajax.reload();

If you declare your datatable as dataTable() (old version) you need:

var oTable = $('#filtertable_data').dataTable( );
// to reload
oTable.api().ajax.reload();

Put content in HttpResponseMessage object?

For a string specifically, the quickest way is to use the StringContent constructor

response.Content = new StringContent("Your response text");

There are a number of additional HttpContent class descendants for other common scenarios.

How to create multiple class objects with a loop in python?

you can use list to define it.

objs = list()
for i in range(10):
    objs.append(MyClass())

Adding a guideline to the editor in Visual Studio

Without the need to edit any registry keys, the Productivity Power Tools extension (available for all versions of visual studio) provides guideline functionality.

Once installed just right click while in the editor window and choose the add guide line option. Note that the guideline will always be placed on the column where your editing cursor is currently at, regardless of where you right click in the editor window.

enter image description here

To turn off go to options and find Productivity Power Tools and in that section turn off Column Guides. A reboot will be necessary.

enter image description here

How to calculate percentage with a SQL statement

I have tested the following and this does work. The answer by gordyii was close but had the multiplication of 100 in the wrong place and had some missing parenthesis.

Select Grade, (Count(Grade)* 100 / (Select Count(*) From MyTable)) as Score
From MyTable
Group By Grade

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

i followed all the suggested steps, in particular the ones provided from ios_dev but my iPhone was not recognized from Xcode and i was not able to debug over WiFi. Right click on the left panel over my iDevice in "Devices and Simulators" window, then "Connect via IP Address...", inserted the iPhone IP and now it correctly works

Simple way to get element by id within a div tag?

var x = document.getElementById("parent").querySelector("#child");
// don't forget a #

or

var x = document.querySelector("#parent").querySelector("#child");

or

var x = document.querySelector("#parent #child");

or

var x = document.querySelector("#parent");
var y = x.querySelector("#child");

eg.

var x = document.querySelector("#div1").querySelector("#edit2");

How do I check out a remote Git branch?

Simply run git checkout with the name of the remote branch. Git will automatically create a local branch that tracks the remote one:

git fetch
git checkout test

However, if that branch name is found in more than one remote, this won't work as Git doesn't know which to use. In that case you can use either:

git checkout --track origin/test

or

git checkout -b test origin/test

In 2.19, Git learned the checkout.defaultRemote configuration, which specifies a remote to default to when resolving such an ambiguity.

HTML/CSS: how to put text both right and left aligned in a paragraph

The only half-way proper way to do this is

<p>
  <span style="float: right">Text on the right</span>
  <span style="float: left">Text on the left</span>
</p> 

however, this will get you into trouble if the text overflows. If you can, use divs (block level elements) and give them a fixed width.

A table (or a number of divs with the according display: table / table-row / table-cell properties) would in fact be the safest solution for this - it will be impossible to break, even if you have lots of difficult content.

How to import Swagger APIs into Postman?

The accepted answer is correct but I will rewrite complete steps for java.

I am currently using Swagger V2 with Spring Boot 2 and it's straightforward 3 step process.

Step 1: Add required dependencies in pom.xml file. The second dependency is optional use it only if you need Swagger UI.

        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

Step 2: Add configuration class

@Configuration
@EnableSwagger2
public class SwaggerConfig {

     public static final Contact DEFAULT_CONTACT = new Contact("Usama Amjad", "https://stackoverflow.com/users/4704510/usamaamjad", "[email protected]");
      public static final ApiInfo DEFAULT_API_INFO = new ApiInfo("Article API", "Article API documentation sample", "1.0", "urn:tos",
              DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList<VendorExtension>());

    @Bean
    public Docket api() {
        Set<String> producesAndConsumes = new HashSet<>();
        producesAndConsumes.add("application/json");
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(DEFAULT_API_INFO)
                .produces(producesAndConsumes)
                .consumes(producesAndConsumes);

    }
}

Step 3: Setup complete and now you need to document APIs in controllers

    @ApiOperation(value = "Returns a list Articles for a given Author", response = Article.class, responseContainer = "List")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
            @ApiResponse(code = 404, message = "The resource you were trying to reach is not found") })
    @GetMapping(path = "/articles/users/{userId}")
    public List<Article> getArticlesByUser() {
       // Do your code
    }

Usage:

You can access your Documentation from http://localhost:8080/v2/api-docs just copy it and paste in Postman to import collection.

enter image description here

Optional Swagger UI: You can also use standalone UI without any other rest client via http://localhost:8080/swagger-ui.html and it's pretty good, you can host your documentation without any hassle.

enter image description here

What is the Regular Expression For "Not Whitespace and Not a hyphen"

It can be done much easier:

\S which equals [^ \t\r\n\v\f]

Remove gutter space for a specific div only

Simplest way to remove padding and margin is with simple css.

<div class="header" style="margin:0px;padding:0px;">
.....
.....
.....
</div>

How to use Collections.sort() in Java?

The answer given by NINCOMPOOP can be made simpler using Lambda Expressions:

Collections.sort(recipes, (Recipe r1, Recipe r2) ->
r1.getID().compareTo(r2.getID()));

Also introduced after Java 8 is the comparator construction methods in the Comparator interface. Using these, one can further reduce this to 1:

recipes.sort(comparingInt(Recipe::getId));

1 Bloch, J. Effective Java (3rd Edition). 2018. Item 42, p. 194.

Can I set up HTML/Email Templates with ASP.NET?

I'd use a templating library like TemplateMachine. this allows you mostly put your email template together with normal text and then use rules to inject/replace values as necessary. Very similar to ERB in Ruby. This allows you to separate the generation of the mail content without tying you too heavily to something like ASPX etc. then once the content is generated with this, you can email away.

How to open Visual Studio Code from the command line on OSX?

We since updated the script to the following syntax to support multiple files and folders as arguments and to fix an issue with not detecting the current working directory properly:

code () {
    VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $*
}

Update for our VS Code 1.0 release:

Please use the command Install 'Code' command in path or Install 'code-insiders' command in path from the command palette (View | Command Palette) to make Code available to the command line.

String to Binary in C#

Here you go:

public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
    return encoding.GetBytes(str);
}

public static String ToBinary(Byte[] data)
{
    return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}

// Use any sort of encoding you like. 
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));

How to add pandas data to an existing csv file?

Initially starting with a pyspark dataframes - I got type conversion errors (when converting to pandas df's and then appending to csv) given the schema/column types in my pyspark dataframes

Solved the problem by forcing all columns in each df to be of type string and then appending this to csv as follows:

with open('testAppend.csv', 'a') as f:
    df2.toPandas().astype(str).to_csv(f, header=False)

How to include a PHP variable inside a MySQL statement

The rules of adding a PHP variable inside of any MySQL statement are plain and simple:

  1. Any variable that represents an SQL data literal, (or, to put it simply - an SQL string, or a number) MUST be added through a prepared statement. No exceptions.
  2. Any other query part, such as an SQL keyword, a table or a field name, or an operator - must be filtered through a white list.

So as your example only involves data literals, then all variables must be added through placeholders (also called parameters). To do so:

  • In your SQL statement, replace all variables with placeholders
  • prepare the resulting query
  • bind variables to placeholders
  • execute the query

And here is how to do it with all popular PHP database drivers:

Adding data literals using mysql ext

Such a driver doesn't exist.

Adding data literals using mysqli

$type = 'testing';
$reporter = "John O'Hara";
$query = "INSERT INTO contents (type, reporter, description) 
             VALUES(?, ?, 'whatever')";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $type, $reporter);
$stmt->execute();

The code is a bit complicated but the detailed explanation of all these operators can be found in my article, How to run an INSERT query using Mysqli, as well as a solution that eases the process dramatically.

For a SELECT query you will need to add just a call to get_result() method to get a familiar mysqli_result from which you can fetch the data the usual way:

$reporter = "John O'Hara";
$stmt = $mysqli->prepare("SELECT * FROM users WHERE name=?");
$stmt->bind_param("s", $reporter);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc(); // or while (...)

Adding data literals using PDO

$type = 'testing';
$reporter = "John O'Hara";
$query = "INSERT INTO contents (type, reporter, description) 
             VALUES(?, ?, 'whatever')";
$stmt = $pdo->prepare($query);
$stmt->execute([$type, $reporter]);

In PDO, we can have the bind and execute parts combined, which is very convenient. PDO also supports named placeholders which some find extremely convenient.

Adding keywords or identifiers

Sometimes we have to add a variable that represents another part of a query, such as a keyword or an identifier (a database, table or a field name). It's a rare case but it's better to be prepared.

In this case, your variable must be checked against a list of values explicitly written in your script. This is explained in my other article, Adding a field name in the ORDER BY clause based on the user's choice:

Unfortunately, PDO has no placeholder for identifiers (table and field names), therefore a developer must filter them out manually. Such a filter is often called a "white list" (where we only list allowed values) as opposed to a "black-list" where we list disallowed values.

So we have to explicitly list all possible variants in the PHP code and then choose from them.

Here is an example:

$orderby = $_GET['orderby'] ?: "name"; // set the default value
$allowed = ["name","price","qty"]; // the white list of allowed field names
$key = array_search($orderby, $allowed, true); // see if we have such a name
if ($key === false) { 
    throw new InvalidArgumentException("Invalid field name"); 
}

Exactly the same approach should be used for the direction,

$direction = $_GET['direction'] ?: "ASC";
$allowed = ["ASC","DESC"];
$key = array_search($direction, $allowed, true);
if ($key === false) { 
    throw new InvalidArgumentException("Invalid ORDER BY direction"); 
}

After such a code, both $direction and $orderby variables can be safely put in the SQL query, as they are either equal to one of the allowed variants or there will be an error thrown.

The last thing to mention about identifiers, they must be also formatted according to the particular database syntax. For MySQL it should be backtick characters around the identifier. So the final query string for our order by example would be

$query = "SELECT * FROM `table` ORDER BY `$orderby` $direction";

How to SHUTDOWN Tomcat in Ubuntu?

I had a similar problem and found the following command to work:

sudo systemctl stop tomcat

After running this command you can type the following to verify that it is "disabled":

systemctl list-units

output for systemctl list-units

Resetting a form in Angular 2 after submit

form: NgForm;

form.reset()

This didn't work for me. It cleared the values but the controls raised an error.

But what worked for me was creating a hidden reset button and clicking the button when we want to clear the form.

<button class="d-none" type="reset" #btnReset>Reset</button>

And on the component, define the ViewChild and reference it in code.

@ViewChild('btnReset') btnReset: ElementRef<HTMLElement>;

Use this to reset the form.

this.btnReset.nativeElement.click();

Notice that the class d-none sets display: none; on the button.

Postgresql: error "must be owner of relation" when changing a owner object

This solved my problem : Sample alter table statement to change the ownership.

ALTER TABLE databasechangelog OWNER TO arwin_ash;
ALTER TABLE databasechangeloglock OWNER TO arwin_ash;

What's better at freeing memory with PHP: unset() or $var = null

unset code if not freeing immediate memory is still very helpful and would be a good practice to do this each time we pass on code steps before we exit a method. take note its not about freeing immediate memory. immediate memory is for CPU, what about secondary memory which is RAM.

and this also tackles about preventing memory leaks.

please see this link http://www.hackingwithphp.com/18/1/11/be-wary-of-garbage-collection-part-2

i have been using unset for a long time now.

better practice like this in code to instanly unset all variable that have been used already as array.

$data['tesst']='';
$data['test2']='asdadsa';
....
nth.

and just unset($data); to free all variable usage.

please see related topic to unset

How important is it to unset variables in PHP?

[bug]

JQuery Ajax Post results in 500 Internal Server Error

I suspect that the server method is throwing an exception after it passes your breakpoint. Use Firefox/Firebug or the IE8 developer tools to look at the actual response you are getting from the server. If there has been an exception you'll get the YSOD html, which should help you figure out where to look.

One more thing -- your data property should be {} not "{}", the former is an empty object while the latter is a string that is invalid as a query parameter. Better yet, just leave it out if you aren't passing any data.

How do I split a string with multiple separators in JavaScript?

Splitting URL by .com/ or .net/

url.split(/\.com\/|\.net\//)

How do I get the Session Object in Spring?

Since you're using Spring, stick with Spring, don't hack it yourself like the other post posits.

The Spring manual says:

You shouldn't interact directly with the HttpSession for security purposes. There is simply no justification for doing so - always use the SecurityContextHolder instead.

The suggested best practice for accessing the session is:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
  String username = ((UserDetails)principal).getUsername();
} else {
  String username = principal.toString();
}

The key here is that Spring and Spring Security do all sorts of great stuff for you like Session Fixation Prevention. These things assume that you're using the Spring framework as it was designed to be used. So, in your servlet, make it context aware and access the session like the above example.

If you just need to stash some data in the session scope, try creating some session scoped bean like this example and let autowire do its magic. :)

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

If you try to be aware of i18n the solution get even more complicated.

The problem is that in other languages the suffix may depend not only on the number itself, but also on the noun it counts. For example in Russian it would be "2-?? ????", but "2-?? ??????" (these mean "2nd day", but "2nd week"). This is not apply if we formatting only days, but in a bit more generic case you should be aware of complexity.

I think nice solution (I didn't have time to actually implement) would be to extend SimpleDateFormetter to apply Locale-aware MessageFormat before passing to the parent class. This way you would be able to support let say for March formats %M to get "3-rd", %MM to get "03-rd" and %MMM to get "third". From outside this class looks like regular SimpleDateFormatter, but supports more formats. Also if this pattern would be by mistake applied by regular SimpleDateFormetter the result would be incorrectly formatted, but still readable.

Stretch Image to Fit 100% of Div Height and Width

Or you can put in the CSS,

<style>
div#img {
  background-image: url(“file.png");
  color:yellow (this part doesn't matter;
  height:100%;
  width:100%;
}
</style>

How can I get last characters of a string

Last 5

_x000D_
_x000D_
var id="ctl03_Tabs1";_x000D_
var res = id.charAt(id.length-5)_x000D_
alert(res);
_x000D_
_x000D_
_x000D_

Last

_x000D_
_x000D_
   _x000D_
 var id="ctl03_Tabs1";_x000D_
 var res = id.charAt(id.length-1)_x000D_
alert(res);
_x000D_
_x000D_
_x000D_

How to generate random number in Bash?

Based on the great answers of @Nelson, @Barun and @Robert, here is a Bash script that generates random numbers.

  • Can generate how many digits you want.
  • each digit is separately generated by /dev/urandom which is much better than Bash's built-in $RANDOM
#!/usr/bin/env bash

digits=10

rand=$(od -A n -t d -N 2 /dev/urandom |tr -d ' ')
num=$((rand % 10))
while [ ${#num} -lt $digits ]; do
  rand=$(od -A n -t d -N 1 /dev/urandom |tr -d ' ')
  num="${num}$((rand % 10))"
done
echo $num

Gradients on UIView and UILabels On iPhone

You can use Core Graphics to draw the gradient, as pointed to in Mike's response. As a more detailed example, you could create a UIView subclass to use as a background for your UILabel. In that UIView subclass, override the drawRect: method and insert code similar to the following:

- (void)drawRect:(CGRect)rect 
{
    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    CGGradientRef glossGradient;
    CGColorSpaceRef rgbColorspace;
    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = { 1.0, 1.0, 1.0, 0.35,  // Start color
         1.0, 1.0, 1.0, 0.06 }; // End color

    rgbColorspace = CGColorSpaceCreateDeviceRGB();
    glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);

    CGRect currentBounds = self.bounds;
    CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
    CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds));
    CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);

    CGGradientRelease(glossGradient);
    CGColorSpaceRelease(rgbColorspace); 
}

This particular example creates a white, glossy-style gradient that is drawn from the top of the UIView to its vertical center. You can set the UIView's backgroundColor to whatever you like and this gloss will be drawn on top of that color. You can also draw a radial gradient using the CGContextDrawRadialGradient function.

You just need to size this UIView appropriately and add your UILabel as a subview of it to get the effect you desire.

EDIT (4/23/2009): Per St3fan's suggestion, I have replaced the view's frame with its bounds in the code. This corrects for the case when the view's origin is not (0,0).

Printing long int value in C

Use printf("%ld",a);

Have a look at format specifiers for printf

How to Fill an array from user input C#?

of course....Console.ReadLine always return string....so you have to convert type string to double

array[i]=double.Parse(Console.ReadLine());

encrypt and decrypt md5

This question is tagged with PHP. But many people are using Laravel framework now. It might help somebody in future. That's why I answering for Laravel. It's more easy to encrypt and decrypt with internal functions.

$string = 'c4ca4238a0b923820dcc';
$encrypted = \Illuminate\Support\Facades\Crypt::encrypt($string);
$decrypted_string = \Illuminate\Support\Facades\Crypt::decrypt($encrypted);

var_dump($string);
var_dump($encrypted);
var_dump($decrypted_string);

Note: Be sure to set a 16, 24, or 32 character random string in the key option of the config/app.php file. Otherwise, encrypted values will not be secure.

But you should not use encrypt and decrypt for authentication. Rather you should use hash make and check.

To store password in database, make hash of password and then save.

$password = Input::get('password_from_user'); 
$hashed = Hash::make($password); // save $hashed value

To verify password, get password stored of account from database

// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
  // Password is not matching 
} else {
  // Password is matching 
}

I need to learn Web Services in Java. What are the different types in it?

If your application often uses http protocol then REST is best because of its light weight, and knowing that your application uses only http protocol choosing SOAP is not so good because it heavy,Better to make decision on web service selection based on the protocols we use in our applications.

How can I disable selected attribute from select2() dropdown Jquery?

I'm disable on value:

<option disabled="disabled">value</option>

How to serve .html files with Spring

The initial problem is that the the configuration specifies a property suffix=".jsp" so the ViewResolver implementing class will add .jsp to the end of the view name being returned from your method.

However since you commented out the InternalResourceViewResolver then, depending on the rest of your application configuration, there might not be any other ViewResolver registered. You might find that nothing is working now.

Since .html files are static and do not require processing by a servlet then it is more efficient, and simpler, to use an <mvc:resources/> mapping. This requires Spring 3.0.4+.

For example:

<mvc:resources mapping="/static/**" location="/static/" />

which would pass through all requests starting with /static/ to the webapp/static/ directory.

So by putting index.html in webapp/static/ and using return "static/index.html"; from your method, Spring should find the view.

How to make popup look at the centre of the screen?

These are the changes to make:

CSS:

#container {
    width: 100%;
    height: 100%;
    top: 0;
    position: absolute;
    visibility: hidden;
    display: none;
    background-color: rgba(22,22,22,0.5); /* complimenting your modal colors */
}
#container:target {
    visibility: visible;
    display: block;
}
.reveal-modal {
    position: relative;
    margin: 0 auto;
    top: 25%;
}
    /* Remove the left: 50% */

HTML:

<a href="#container">Reveal</a>
<div id="container">
    <div id="exampleModal" class="reveal-modal">
    ........
    <a href="#">Close Modal</a>
    </div>
</div>

JSFiddle - Updated with CSS only

Oracle Insert via Select from multiple tables where one table may not have a row

insert into received_messages(id, content, status)
    values (RECEIVED_MESSAGES_SEQ.NEXT_VAL, empty_blob(), '');

Rails DateTime.now without Time

If you're happy to require 'active_support/core_ext', then you can use

DateTime.now.midnight # => Sat, 19 Nov 2011 00:00:00 -0800

How do I format a String in an email so Outlook will print the line breaks?

I was facing the same issue and here is the code that resolved it:

\t\n - for new line in Email service JavaMailSender

String mailMessage = JSONObject.toJSONString("Your message").replace(",", "\t\n").trim();

load and execute order of scripts

If you aren't dynamically loading scripts or marking them as defer or async, then scripts are loaded in the order encountered in the page. It doesn't matter whether it's an external script or an inline script - they are executed in the order they are encountered in the page. Inline scripts that come after external scripts are held until all external scripts that came before them have loaded and run.

Async scripts (regardless of how they are specified as async) load and run in an unpredictable order. The browser loads them in parallel and it is free to run them in whatever order it wants.

There is no predictable order among multiple async things. If one needed a predictable order, then it would have to be coded in by registering for load notifications from the async scripts and manually sequencing javascript calls when the appropriate things are loaded.

When a script tag is inserted dynamically, how the execution order behaves will depend upon the browser. You can see how Firefox behaves in this reference article. In a nutshell, the newer versions of Firefox default a dynamically added script tag to async unless the script tag has been set otherwise.

A script tag with async may be run as soon as it is loaded. In fact, the browser may pause the parser from whatever else it was doing and run that script. So, it really can run at almost any time. If the script was cached, it might run almost immediately. If the script takes awhile to load, it might run after the parser is done. The one thing to remember with async is that it can run anytime and that time is not predictable.

A script tag with defer waits until the entire parser is done and then runs all scripts marked with defer in the order they were encountered. This allows you to mark several scripts that depend upon one another as defer. They will all get postponed until after the document parser is done, but they will execute in the order they were encountered preserving their dependencies. I think of defer like the scripts are dropped into a queue that will be processed after the parser is done. Technically, the browser may be downloading the scripts in the background at any time, but they won't execute or block the parser until after the parser is done parsing the page and parsing and running any inline scripts that are not marked defer or async.

Here's a quote from that article:

script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4.0 Firefox.

The relevant part of the HTML5 spec (for newer compliant browsers) is here. There is a lot written in there about async behavior. Obviously, this spec doesn't apply to older browsers (or mal-conforming browsers) whose behavior you would probably have to test to determine.

A quote from the HTML5 spec:

Then, the first of the following options that describes the situation must be followed:

If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element does not have a src attribute, and the element has been flagged as "parser-inserted", and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:

If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.

Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.

Remove the first element from this list of scripts that will execute in order as soon as possible.

If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.

If the element has a src attribute The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.

Otherwise The user agent must immediately execute the script block, even if other scripts are already executing.


What about Javascript module scripts, type="module"?

Javascript now has support for module loading with syntax like this:

<script type="module">
  import {addTextToBody} from './utils.mjs';

  addTextToBody('Modules are pretty cool.');
</script>

Or, with src attribute:

<script type="module" src="http://somedomain.com/somescript.mjs">
</script>

All scripts with type="module" are automatically given the defer attribute. This downloads them in parallel (if not inline) with other loading of the page and then runs them in order, but after the parser is done.

Module scripts can also be given the async attribute which will run inline module scripts as soon as possible, not waiting until the parser is done and not waiting to run the async script in any particular order relative to other scripts.

There's a pretty useful timeline chart that shows fetch and execution of different combinations of scripts, including module scripts here in this article: Javascript Module Loading.

How to get the first word in the string

Don't need a regex. string[: string.find(' ')]

How do I make a new line in swift

You should be able to use \n inside a Swift string, and it should work as expected, creating a newline character. You will want to remove the space after the \n for proper formatting like so:

var example: String = "Hello World \nThis is a new line"

Which, if printed to the console, should become:

Hello World
This is a new line

However, there are some other considerations to make depending on how you will be using this string, such as:

  • If you are setting it to a UILabel's text property, make sure that the UILabel's numberOfLines = 0, which allows for infinite lines.
  • In some networking use cases, use \r\n instead, which is the Windows newline.

Edit: You said you're using a UITextField, but it does not support multiple lines. You must use a UITextView.

Get java.nio.file.Path object from java.io.File

As many have suggested, JRE v1.7 and above has File.toPath();

File yourFile = ...;
Path yourPath = yourFile.toPath();

On Oracle's jdk 1.7 documentation which is also mentioned in other posts above, the following equivalent code is described in the description for toPath() method, which may work for JRE v1.6;

File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());

How can you integrate a custom file browser/uploader with CKEditor?

An article at zerokspot entitled Custom filebrowser callbacks in CKEditor 3.0 handles this. The most relevant section is quoted below:

So all you have to do from the file browser when you have a file selected is to call this code with the right callback number (normally 1) and the URL of the selected file:

window.opener.CKEDITOR.tools.callFunction(CKEditorFuncNum,url);

For the quick-uploader the process is quite similar. At first I thought that the editor might be listening for a 200 HTTP return code and perhaps look into some header field or something like that to determine the location of the uploaded file, but then - through some Firebug monitoring - I noticed that all that happens after an upload is the following code:

<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(CKEditorFuncNum,url, errorMessage); </script>

If the upload failed, set the errorMessage to some non-zero-length string and empty the url, and vice versa on success.

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

OK, two steps to this - first is to write a function that does the translation you want - I've put an example together based on your pseudo-code:

def label_race (row):
   if row['eri_hispanic'] == 1 :
      return 'Hispanic'
   if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
      return 'Two Or More'
   if row['eri_nat_amer'] == 1 :
      return 'A/I AK Native'
   if row['eri_asian'] == 1:
      return 'Asian'
   if row['eri_afr_amer']  == 1:
      return 'Black/AA'
   if row['eri_hawaiian'] == 1:
      return 'Haw/Pac Isl.'
   if row['eri_white'] == 1:
      return 'White'
   return 'Other'

You may want to go over this, but it seems to do the trick - notice that the parameter going into the function is considered to be a Series object labelled "row".

Next, use the apply function in pandas to apply the function - e.g.

df.apply (lambda row: label_race(row), axis=1)

Note the axis=1 specifier, that means that the application is done at a row, rather than a column level. The results are here:

0           White
1        Hispanic
2           White
3           White
4           Other
5           White
6     Two Or More
7           White
8    Haw/Pac Isl.
9           White

If you're happy with those results, then run it again, saving the results into a new column in your original dataframe.

df['race_label'] = df.apply (lambda row: label_race(row), axis=1)

The resultant dataframe looks like this (scroll to the right to see the new column):

      lname   fname rno_cd  eri_afr_amer  eri_asian  eri_hawaiian   eri_hispanic  eri_nat_amer  eri_white rno_defined    race_label
0      MOST    JEFF      E             0          0             0              0             0          1       White         White
1    CRUISE     TOM      E             0          0             0              1             0          0       White      Hispanic
2      DEPP  JOHNNY    NaN             0          0             0              0             0          1     Unknown         White
3     DICAP     LEO    NaN             0          0             0              0             0          1     Unknown         White
4    BRANDO  MARLON      E             0          0             0              0             0          0       White         Other
5     HANKS     TOM    NaN             0          0             0              0             0          1     Unknown         White
6    DENIRO  ROBERT      E             0          1             0              0             0          1       White   Two Or More
7    PACINO      AL      E             0          0             0              0             0          1       White         White
8  WILLIAMS   ROBIN      E             0          0             1              0             0          0       White  Haw/Pac Isl.
9  EASTWOOD   CLINT      E             0          0             0              0             0          1       White         White

how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)

and

int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

sql query to find the duplicate records

This query uses the Group By and and Having clauses to allow you to select (locate and list out) for each duplicate record. The As clause is a convenience to refer to Quantity in the select and Order By clauses, but is not really part of getting you the duplicate rows.

Select
    Title,
    Count( Title ) As [Quantity]
   From
    Training
   Group By
    Title
   Having 
    Count( Title ) > 1
   Order By
    Quantity desc

Allow anything through CORS Policy

Simply you can add rack-cors gem https://rubygems.org/gems/rack-cors/versions/0.4.0

1st Step: add gem to your Gemfile:

gem 'rack-cors', :require => 'rack/cors'

and then save and run bundle install

2nd Step: update your config/application.rb file by adding this:

config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end

for more details you can go to https://github.com/cyu/rack-cors Specailly if you don't use rails 5.

regular expression to match exactly 5 digits

I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets.

Try this...

var str = 'f 34 545 323 12345 54321 123456',
    matches = str.match(/\b\d{5}\b/g);

console.log(matches); // ["12345", "54321"]

jsFiddle.

The word boundary \b is your friend here.

Update

My regex will get a number like this 12345, but not like a12345. The other answers provide great regexes if you require the latter.

How to access PHP session variables from jQuery function in a .js file?

This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.

Three javascript libraries are required, createCookie, readCookie and eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.

createCookie = function(name, value, days) {
if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
}
else var expires = "";

document.cookie = name + "=" + value + expires + "; path=/";
}

readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
   createCookie(name, "", -1);
}

To call them you need to create a small PHP function, normally as part of your support library, as follows:

<?php
 function createjavaScriptCookie($sessionVarible) {
 $s =  "<script>";
 $s = $s.'createCookie('. '"'. $sessionVarible                 
 .'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
 $s = $s."</script>";
 echo $s;
}
?>

So to use all you now have to include within your index.php file is

$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");

Now in your javascript library.js you can recover the cookie with the following code:

var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';

I hope this helps.

JavaScript TypeError: Cannot read property 'style' of null

In your script, this part:

document.getElementById('Noite')

must be returning null and you are also attempting to set the display property to an invalid value. There are a couple of possible reasons for this first part to be null.

  1. You are running the script too early before the document has been loaded and thus the Noite item can't be found.

  2. There is no Noite item in your HTML.

I should point out that your use of document.write() in this case code probably signifies a problem. If the document has already loaded, then a new document.write() will clear the old content and start a new fresh document so no Noite item would be found.

If your document has not yet been loaded and thus you're doing document.write() inline to add HTML inline to the current document, then your document has not yet been fully loaded so that's probably why it can't find the Noite item.

The solution is probably to put this part of your script at the very end of your document so everything before it has already been loaded. So move this to the end of your body:

document.getElementById('Noite').style.display='block';

And, make sure that there are no document.write() statements in javascript after the document has been loaded (because they will clear the previous document and start a new one).


In addition, setting the display property to "display" doesn't make sense to me. The valid options for that are "block", "inline", "none", "table", etc... I'm not aware of any option named "display" for that style property. See here for valid options for teh display property.

You can see the fixed code work here in this demo: http://jsfiddle.net/jfriend00/yVJY4/. That jsFiddle is configured to have the javascript placed at the end of the document body so it runs after the document has been loaded.


P.S. I should point out that your lack of braces for your if statements and your inclusion of multiple statements on the same line makes your code very misleading and unclear.


I'm having a really hard time figuring out what you're asking, but here's a cleaned up version of your code that works which you can also see working here: http://jsfiddle.net/jfriend00/QCxwr/. Here's a list of the changes I made:

  1. The script is located in the body, but after the content that it is referencing.
  2. I've added var declarations to your variables (a good habit to always use).
  3. The if statement was changed into an if/else which is a lot more efficient and more self-documenting as to what you're doing.
  4. I've added braces for every if statement so it absolutely clear which statements are part of the if/else and which are not.
  5. I've properly closed the </dd> tag you were inserting.
  6. I've changed style.display = ''; to style.display = 'block';.
  7. I've added semicolons at the end of every statement (another good habit to follow).

The code:

<div id="Night" style="display: none;">
    <img src="Img/night.png" style="position: fixed; top: 0px; left: 5%; height: auto; width: 100%; z-index: -2147483640;">
    <img src="Img/moon.gif" style="position: fixed; top: 0px; left: 5%; height: 100%; width: auto; z-index: -2147483639;">
</div>    
<script>
document.write("<dl><dd>");
var day = new Date();
var hr = day.getHours();
if (hr == 0) {
    document.write("Meia-noite!<br>Já é amanhã!");
} else if (hr <=5 ) {
    document.write("&nbsp;&nbsp;Você não<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;devia<br>&nbsp;&nbsp;&nbsp;&nbsp;estar<br>dormindo?");
} else if (hr <= 11) {         
    document.write("Bom dia!");
} else if (hr == 12) {
    document.write("&nbsp;&nbsp;&nbsp;&nbsp;Vamos<br>&nbsp;almoçar?");
} else if (hr <= 17) {
    document.write("Boa Tarde");
} else if (hr <= 19) {
    document.write("&nbsp;Bom final<br>&nbsp;de tarde!");
} else if (hr == 20) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='block';
} else if (hr == 21) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='none';
} else if (hr == 22) {
    document.write("&nbsp;Boa Noite");
} else if (hr == 23) {
    document.write("Ó Meu! Já é quase meia-noite!");
}
document.write("</dl></dd>");
</script>

Difference Between Cohesion and Coupling

Cohesion is an indication of how related and focused the responsibilities of an software element are.

Coupling refers to how strongly a software element is connected to other elements.

The software element could be class, package, component, subsystem or a system. And while designing the systems it is recommended to have software elements that have High cohesion and support Low coupling.

Low cohesion results in monolithic classes that are difficult to maintain, understand and reduces re-usablity. Similarly High Coupling results in classes that are tightly coupled and changes tend not be non-local, difficult to change and reduces the reuse.

We can take a hypothetical scenario where we are designing an typical monitor-able ConnectionPool with the following requirements. Note that, it might look too much for a simple class like ConnectionPool but the basic intent is just to demonstrate low coupling and high cohesion with some simple example and I think should help.

  1. support getting a connection
  2. release a connection
  3. get stats about connection vs usage count
  4. get stats about connection vs time
  5. Store the connection retrieval and release information to a database for reporting later.

With low cohesion we could design a ConnectionPool class by forcefully stuffing all this functionality/responsibilities into a single class as below. We can see that this single class is responsible for connection management, interacting with database as well maintaining connection stats.

Low Cohesion Connection Pool

With high cohesion we can assign these responsibility across the classes and make it more maintainable and reusable.

High Cohesion Connection Pool

To demonstrate Low coupling we will continue with the high cohesion ConnectionPool diagram above. If we look at the above diagram although it supports high cohesion, the ConnectionPool is tightly coupled with ConnectionStatistics class and PersistentStore it interacts with them directly. Instead to reduce the coupling we could introduce a ConnectionListener interface and let these two classes implement the interface and let them register with ConnectionPool class. And the ConnectionPool will iterate through these listeners and notify them of connection get and release events and allows less coupling.

Low Coupling ConnectionPool

Note/Word or Caution: For this simple scenario it may look like an overkill but if we imagine a real-time scenario where our application needs to interact with multiple third party services to complete a transaction: Directly coupling our code with the third party services would mean that any changes in the third party service could result in changes to our code at multiple places, instead we could have Facade that interacts with these multiple services internally and any changes to the services become local to the Facade and enforce low coupling with the third party services.

Difference between Groovy Binary and Source release?

Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

You can convert the value to a date using a formula like this, next to the cell:

=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))

Where A1 is the field you need to convert.

Alternatively, you could use this code in VBA:

Sub ConvertYYYYMMDDToDate()
   Dim c As Range
   For Each c In Selection.Cells
       c.Value = DateSerial(Left(c.Value, 4), Mid(c.Value, 5, 2), Right(c.Value, 2))
       'Following line added only to enforce the format.
       c.NumberFormat = "mm/dd/yyyy"
   Next
End Sub

Just highlight any cells you want fixed and run the code.

Note as RJohnson mentioned in the comments, this code will error if one of your selected cells is empty. You can add a condition on c.value to skip the update if it is blank.

How to calculate date difference in JavaScript?

this should work just fine if you just need to show what time left, since JavaScript uses frames for its time you'll have get your End Time - The Time RN after that we can divide it by 1000 since apparently 1000 frames = 1 seconds, after that you can use the basic math of time, but there's still a problem to this code, since the calculation is static, it can't compensate for the different day total in a year (360/365/366), the bunch of IF after the calculation is to make it null if the time is lower than 0, hope this helps even though it's not exactly what you're asking :)

var now = new Date();
var end = new Date("End Time");
var total = (end - now) ;
var totalD =  Math.abs(Math.floor(total/1000));

var years = Math.floor(totalD / (365*60*60*24));
var months = Math.floor((totalD - years*365*60*60*24) / (30*60*60*24));
var days = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24)/ (60*60*24));
var hours = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24)/ (60*60));
var minutes = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60)/ (60));
var seconds = Math.floor(totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60 - minutes*60);

var Y = years < 1 ? "" : years + " Years ";
var M = months < 1 ? "" : months + " Months ";
var D = days < 1 ? "" : days + " Days ";
var H = hours < 1 ? "" : hours + " Hours ";
var I = minutes < 1 ? "" : minutes + " Minutes ";
var S = seconds < 1 ? "" : seconds + " Seconds ";
var A = years == 0 && months == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0 ? "Sending" : " Remaining";

document.getElementById('txt').innerHTML = Y + M + D + H + I + S + A;

Node.js/Express.js App Only Works on Port 3000

I think the best way is to use dotenv package and set the port on the .env config file without to modify the file www inside the folder bin.

Just install the package with the command:

npm install dotenv

require it on your application:

require('dotenv').config()

Create a .env file in the root directory of your project, and add the port in it (for example) to listen on port 5000

PORT=5000

and that's it.

More info here

How to POST request using RestSharp

My RestSharp POST method:

var client = new RestClient(ServiceUrl);

var request = new RestRequest("/resource/", Method.POST);

// Json to post.
string jsonToSend = JsonHelper.ToJson(json);

request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;

try
{
    client.ExecuteAsync(request, response =>
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            // OK
        }
        else
        {
            // NOK
        }
    });
}
catch (Exception error)
{
    // Log
}

How to implement a custom AlertDialog View

After changing the ID it android.R.id.custom, I needed to add the following to get the View to display:

((View) f1.getParent()).setVisibility(View.VISIBLE);

However, this caused the new View to render in a big parent view with no background, breaking the dialog box in two parts (text and buttons, with the new View in between). I finally got the effect that I wanted by inserting my View next to the message:

LinearLayout f1 = (LinearLayout)findViewById(android.R.id.message).getParent().getParent();

I found this solution by exploring the View tree with View.getParent() and View.getChildAt(int). Not really happy about either, though. None of this is in the Android docs and if they ever change the structure of the AlertDialog, this might break.

Open multiple Eclipse workspaces on the Mac

This seems to be the supported native method in OS X:

cd /Applications/eclipse/

open -n Eclipse.app

Be sure to specify the ".app" version (directory); in OS X Mountain Lion erroneously using the symbolic link such as open -n eclipse, might get one GateKeeper stopping access:

"eclipse" can't be opened because it is from an unidentified developer.

Your security preferences allow installation of only apps from the Mac App Store and identified developers.

Even removing the extended attribute com.apple.quarantine does not fix that. Instead, simply using the ".app" version will rely on your previous consent, or prompt you once:

"Eclipse" is an application downloaded from the Internet. Are you sure you want to open it?

How do I get a value of datetime.today() in Python that is "timezone aware"?

Another alternative, in my mind a better one, is using Pendulum instead of pytz. Consider the following simple code:

>>> import pendulum

>>> dt = pendulum.now().to_iso8601_string()
>>> print (dt)
2018-03-27T13:59:49+03:00
>>>

To install Pendulum and see their documentation, go here. It have tons of options (like simple ISO8601, RFC3339 and many others format support), better performance and tend to yield simpler code.

Eclipse java debugging: source not found

In my case, even after Editing source lookup and Adding project, it didn't worked. I configured the Build path of the project.

enter image description here

After that, I selected JRE System Library and it worked.

enter image description here

C#: calling a button event handler method without actually clicking the button

You can call the btnTest_Click just like any other function.

The most basic form would be this:

btnTest_Click(this, null);

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

  1. Go to services.msc from run prompt.
  2. Restart the services of SQL server(MSSQLSERVER)
  3. Restart the services of SQL server(SQLEXPRESS)

Filename too long in Git for Windows

To be entirely sure that it takes effect immediately after the repository is initialized, but before the remote history is fetched or any files checked out, it is safer to use it this way:

git clone -c core.longpaths=true <repo-url>

-c key=value

Set a configuration variable in the newly-created repository; this takes effect immediately after the repository is initialized, but before the remote history is fetched or any files checked out. The key is in the same format as expected by git-config1 (e.g., core.eol=true). If multiple values are given for the same key, each value will be written to the config file. This makes it safe, for example, to add additional fetch refspecs to the origin remote.

More info

Get list of Excel files in a folder using VBA

Regarding the upvoted answer, I liked it except that if the resulting "listfiles" array is used in an array formula {CSE}, the list values come out all in a horizontal row. To make them come out in a vertical column, I simply made the array two dimensional as follows:

ReDim vaArray(1 To oFiles.Count, 0)
i = 1
For Each oFile In oFiles
    vaArray(i, 0) = oFile.Name
    i = i + 1
Next

Mysql command not found in OS X 10.7

I faced the same issue, and finally i got a solution. Please go through with the below steps, if you are using MAMP.

  1. Start MAMP or MAMP PRO
  2. Start the server
  3. Open Terminal (Applications -> Utilities)
  4. Type in: (one line) ? /Applications/MAMP/Library/bin/mysql --host=localhost -uroot -proot

This works for me.

How to convert answer into two decimal point

If you just want to print a decimal number with 2 digits after decimal point in specific format no matter of locals use something like this

dim d as double = 1.23456789
dim s as string = d.Tostring("0.##", New System.Globalization.CultureInfo("en-US"))

How to send UTF-8 email?

You can add header "Content-Type: text/html; charset=UTF-8" to your message body.

$headers = "Content-Type: text/html; charset=UTF-8";

If you use native mail() function $headers array will be the 4th parameter mail($to, $subject, $message, $headers)

If you user PEAR Mail::factory() code will be:

$smtp = Mail::factory('smtp', $params);

$mail = $smtp->send($to, $headers, $body);

SQL Server: Null VS Empty String

An empty string is a string with zero length or no character. Null is absence of data.

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

How does delete[] know it's an array?

The answer:

int* pArray = new int[5];

int size = *(pArray-1);

Posted above is not correct and produces invalid value. The "-1"counts elements On 64 bit Windows OS the correct buffer size resides in Ptr - 4 bytes address

How can I initialize C++ object member variables in the constructor?

You can specify how to initialize members in the member initializer list:

BigMommaClass {
    BigMommaClass(int, int);

private:
    ThingOne thingOne;
    ThingTwo thingTwo;
};

BigMommaClass::BigMommaClass(int numba1, int numba2)
    : thingOne(numba1 + numba2), thingTwo(numba1, numba2) {}

JSON character encoding

finally I got the solution:

Only put this line

@RequestMapping(value = "/YOUR_URL_Name",method = RequestMethod.POST,produces = "application/json; charset=utf-8")

this will definitely help.

Angularjs $q.all

$http is a promise too, you can make it simpler:

return $q.all(tasks.map(function(d){
        return $http.post('upload/tasks',d).then(someProcessCallback, onErrorCallback);
    }));

React Native Error: ENOSPC: System limit for number of file watchers reached

I had the same problem by using library wifi but when i changed my network it worked perfectly.

Change your network connection

PostgreSQL delete with inner join

This worked for me:

DELETE from m_productprice
WHERE  m_pricelist_version_id='1000020'
       AND m_product_id IN (SELECT m_product_id
                            FROM   m_product
                            WHERE  upc = '7094'); 

How to get row count using ResultSet in Java?

Here's some code that avoids getting the count to instantiate an array, but uses an ArrayList instead and just before returning converts the ArrayList to the needed array type.

Note that Supervisor class here implements ISupervisor interface, but in Java you can't cast from object[] (that ArrayList's plain toArray() method returns) to ISupervisor[] (as I think you are able to do in C#), so you have to iterate through all list items and populate the result array.

/**
 * Get Supervisors for given program id
 * @param connection
 * @param programId
 * @return ISupervisor[]
 * @throws SQLException
 */
public static ISupervisor[] getSupervisors(Connection connection, String programId)
  throws SQLException
{
  ArrayList supervisors = new ArrayList();

  PreparedStatement statement = connection.prepareStatement(SQL.GET_SUPERVISORS);
  try {
    statement.setString(SQL.GET_SUPERVISORS_PARAM_PROGRAMID, programId);
    ResultSet resultSet = statement.executeQuery();  

    if (resultSet != null) {
      while (resultSet.next()) {
        Supervisor s = new Supervisor();
        s.setId(resultSet.getInt(SQL.GET_SUPERVISORS_RESULT_ID));
        s.setFirstName(resultSet.getString(SQL.GET_SUPERVISORS_RESULT_FIRSTNAME));
        s.setLastName(resultSet.getString(SQL.GET_SUPERVISORS_RESULT_LASTNAME));
        s.setAssignmentCount(resultSet.getInt(SQL.GET_SUPERVISORS_RESULT_ASSIGNMENT_COUNT));
        s.setAssignment2Count(resultSet.getInt(SQL.GET_SUPERVISORS_RESULT_ASSIGNMENT2_COUNT));
        supervisors.add(s);
      }
      resultSet.close();
    }
  } finally {
    statement.close();
  }

  int count = supervisors.size();
  ISupervisor[] result = new ISupervisor[count];
  for (int i=0; i<count; i++)
    result[i] = (ISupervisor)supervisors.get(i);
  return result;
}

How to create a trie in Python

Python Class for Trie


Trie Data Structure can be used to store data in O(L) where L is the length of the string so for inserting N strings time complexity would be O(NL) the string can be searched in O(L) only same goes for deletion.

Can be clone from https://github.com/Parikshit22/pytrie.git

class Node:
    def __init__(self):
        self.children = [None]*26
        self.isend = False
        
class trie:
    def __init__(self,):
        self.__root = Node()
        
    def __len__(self,):
        return len(self.search_byprefix(''))
    
    def __str__(self):
        ll =  self.search_byprefix('')
        string = ''
        for i in ll:
            string+=i
            string+='\n'
        return string
        
    def chartoint(self,character):
        return ord(character)-ord('a')
    
    def remove(self,string):
        ptr = self.__root
        length = len(string)
        for idx in range(length):
            i = self.chartoint(string[idx])
            if ptr.children[i] is not None:
                ptr = ptr.children[i]
            else:
                raise ValueError("Keyword doesn't exist in trie")
        if ptr.isend is not True:
            raise ValueError("Keyword doesn't exist in trie")
        ptr.isend = False
        return
    
    def insert(self,string):
        ptr = self.__root
        length = len(string)
        for idx in range(length):
            i = self.chartoint(string[idx])
            if ptr.children[i] is not None:
                ptr = ptr.children[i]
            else:
                ptr.children[i] = Node()
                ptr = ptr.children[i]
        ptr.isend = True
        
    def search(self,string):
        ptr = self.__root
        length = len(string)
        for idx in range(length):
            i = self.chartoint(string[idx])
            if ptr.children[i] is not None:
                ptr = ptr.children[i]
            else:
                return False
        if ptr.isend is not True:
            return False
        return True
    
    def __getall(self,ptr,key,key_list):
        if ptr is None:
            key_list.append(key)
            return
        if ptr.isend==True:
            key_list.append(key)
        for i in range(26):
            if ptr.children[i]  is not None:
                self.__getall(ptr.children[i],key+chr(ord('a')+i),key_list)
        
    def search_byprefix(self,key):
        ptr = self.__root
        key_list = []
        length = len(key)
        for idx in range(length):
            i = self.chartoint(key[idx])
            if ptr.children[i] is not None:
                ptr = ptr.children[i]
            else:
                return None
        
        self.__getall(ptr,key,key_list)
        return key_list
        

t = trie()
t.insert("shubham")
t.insert("shubhi")
t.insert("minhaj")
t.insert("parikshit")
t.insert("pari")
t.insert("shubh")
t.insert("minakshi")
print(t.search("minhaj"))
print(t.search("shubhk"))
print(t.search_byprefix('m'))
print(len(t))
print(t.remove("minhaj"))
print(t)

Code Oputpt

True
False
['minakshi', 'minhaj']
7
minakshi
minhajsir
pari
parikshit
shubh
shubham
shubhi

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

Float right and position absolute doesn't work together

I was able to absolutely position a right-floated element with one layer of nesting and a tricky margin:

_x000D_
_x000D_
function test() {_x000D_
  document.getElementById("box").classList.toggle("hide");_x000D_
}
_x000D_
.right {_x000D_
  float:right;_x000D_
}_x000D_
#box {_x000D_
  position:absolute; background:#feb;_x000D_
  width:20em; margin-left:-20em; padding:1ex;_x000D_
}_x000D_
#box.hide {_x000D_
  display:none;_x000D_
}
_x000D_
<div>_x000D_
  <div class="right">_x000D_
    <button onclick="test()">box</button>_x000D_
    <div id="box">Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
      sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
      Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
      nisi ut aliquip ex ea commodo consequat._x000D_
    </div>_x000D_
  </div>_x000D_
  <p>_x000D_
    Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
    nisi ut aliquip ex ea commodo consequat._x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I decided to make this toggleable so you can see how it does not affect the flow of the surrounding text (run it and press the button to show/hide the floated absolute box).

Adjusting and image Size to fit a div (bootstrap)

Try this way:

<div class="container">
    <div class="col-md-4" style="padding-left: 0px;  padding-right: 0px;">
        <img src="images/food1.jpg" class="img-responsive">
    </div>
</div>

UPDATE:

In Bootstrap 4 img-responsive becomes img-fluid, so the solution using Bootstrap 4 is:

<div class="container">
    <div class="col-md-4 px-0">
        <img src="images/food1.jpg" class="img-fluid">
    </div>
</div>

How can I get the corresponding table header (th) from a table cell (td)?

That's simple, if you reference them by index. If you want to hide the first column, you would:

Copy code

$('#thetable tr').find('td:nth-child(1),th:nth-child(1)').toggle();

The reason I first selected all table rows and then both td's and th's that were the n'th child is so that we wouldn't have to select the table and all table rows twice. This improves script execution speed. Keep in mind, nth-child() is 1 based, not 0.

Add newline to VBA or Visual Basic 6

There are actually two ways of doing this:

  1. st = "Line 1" + vbCrLf + "Line 2"

  2. st = "Line 1" + vbNewLine + "Line 2"

These even work for message boxes (and all other places where strings are used).

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

I tried this and it works without any issues to validate if the field is empty. I have answered your question partially as I haven't personally tried to add default values to attributes

if(field.getText()!= null && !field.getText().isEmpty())

Hope it helps

window.open with headers

Can I control the HTTP headers sent by window.open (cross browser)?

No

If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?

  • You can request a URL that triggers a server side program which makes the request with arbitrary headers and then returns the response
  • You can run JavaScript (probably saying goodbye to Progressive Enhancement) that uses XHR to make the request with arbitrary headers (assuming the URL fits within the Same Origin Policy) and then process the result in JS.

I need some cunning hacks...

It might help if you described the problem instead of asking if possible solutions would work.

PHP Fatal error: Call to undefined function mssql_connect()

I am using IIS and mysql (directly downloaded, without wamp or xampp) My php was installed in c:\php I was getting the error of "call to undefined function mysql_connect()" For me the change of extension_dir worked. This is what I did. In the php.ini, Originally, I had this line

; On windows: extension_dir = "ext"

I changed it to:

; On windows: extension_dir = "C:\php\ext"

And it worked. Of course, I did the other things also like uncommenting the dll extensions etc, as explained in others remarks.

Android textview outline text

You can do this programmatically with the below snippet. That provides white letters with black background:

textView.setTextColor(Color.WHITE);            
textView.setShadowLayer(1.6f,1.5f,1.3f,Color.BLACK);

The parameters of the method are radius,dx,dy,color. You can change them for you specific needs.

I hope I will help someone that creates TextView programmatically and not having it inside xml.

Cheers to the stackOverflow community!

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

You can use numpy.ravel to return a flattened array from n-dimensional array:

>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> a.ravel()
array([0, 1, 2, 3, 4, 5, 6, 7, 8])

How do I install a plugin for vim?

Those two commands will create a ~/.vim/vim-haml/ directory with the ftplugin, syntax, etc directories in it. Those directories need to be immediately in the ~/.vim directory proper or ~/.vim/vim-haml needs to be added to the list of paths that vim searches for plugins.

Edit:

I recently decided to tweak my vim config and in the process wound up writing the following rakefile. It only works on Mac/Linux, but the advantage over cp versions is that it's completely safe (symlinks don't overwrite existing files, uninstall only deletes symlinks) and easy to keep things updated.

# Easily install vim plugins from a source control checkout (e.g. Github)
#
# alias vim-install=rake -f ~/.vim/rakefile-vim-install
# vim-install
# vim-install uninstall

require 'ftools'
require 'fileutils'

task :default => :install
desc "Install a vim plugin the lazy way"
task :install do
  vim_dir      = File.expand_path("~/.vim")
  plugin_dir   = Dir.pwd

  if not (FileTest.exists? File.join(plugin_dir,".git") or
          FileTest.exists? File.join(plugin_dir,".svn") or
          FileTest.exists? File.join(plugin_dir,".hg"))
      puts "#{plugin_dir} isn't a source controlled directory. Aborting."
      exit 1
  end

  Dir['**/'].each do |d|
    FileUtils.mkdir_p File.join(vim_dir, d)
  end

  Dir["**/*.{txt,snippet,snippets,vim,js,wsf}"].each do |f|
    ln File.join(plugin_dir, f), File.join(vim_dir,f)
  end

  boldred = "\033[1;31m"
  clear = "\033[0m"
  puts "\nDone. Remember to #{boldred}:helptags ~/.vim/doc#{clear}"
end

task :uninstall do
  vim_dir      = File.expand_path("~/.vim")
  plugin_dir   = Dir.pwd
  Dir["**/*.{txt,snippet,snippets,vim}"].each do |f|
    safe_rm File.join(vim_dir, f)
  end
end

def nicename(path)
    boldgreen = "\033[1;32m"
    clear = "\033[0m"
    return "#{boldgreen}#{File.join(path.split('/')[-2..-1])}#{clear}\t"
end

def ln(src, dst)
    begin
        FileUtils.ln_s src, dst
        puts "    Symlink #{nicename src}\t => #{nicename dst}"
    rescue Errno::EEXIST
        puts "  #{nicename dst} exists! Skipping."
    end
end

def cp(src, dst)
  puts "    Copying #{nicename src}\t=> #{nicename dst}"
  FileUtils.cp src, dst
end

def safe_rm(target)
    if FileTest.exists? target and FileTest.symlink? target
        puts "    #{nicename target} removed."
        File.delete target
    else
        puts "  #{nicename target} is not a symlink. Skipping"
    end
end

Finding an elements XPath using IE Developer tool

You can find/debug XPath/CSS locators in the IE as well as in different browsers with the tool called SWD Page Recorder

The only restrictions/limitations:

  1. The browser should be started from the tool
  2. Internet Explorer Driver Server - IEDriverServer.exe - should be downloaded separately and placed near SwdPageRecorder.exe

Is Safari on iOS 6 caching $.ajax results?

Simple solution for all your web service requests, assuming you're using jQuery:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    // you can use originalOptions.type || options.type to restrict specific type of requests
    options.data = jQuery.param($.extend(originalOptions.data||{}, { 
      timeStamp: new Date().getTime()
    }));
});

Read more about the jQuery prefilter call here.

If you aren't using jQuery, check the docs for your library of choice. They may have similar functionality.

Python way to clone a git repository

Using GitPython will give you a good python interface to Git.

For example, after installing it (pip install gitpython), for cloning a new repository you can use clone_from function:

from git import Repo

Repo.clone_from(git_url, repo_dir)

See the GitPython Tutorial for examples on using the Repo object.

Note: GitPython requires git being installed on the system, and accessible via system's PATH.

React native text going off my screen, refusing to wrap. What to do?

This is a known bug. flexWrap: 'wrap' didn't work for me but this solution seems to work for most people

Code

<View style={styles.container}>
    <Text>Some text</Text>
</View>

Styles

export default StyleSheet.create({
    container: {
        width: 0,
        flexGrow: 1,
        flex: 1,
    }
});

Adding Only Untracked Files

Lot of good tips here, but inside Powershell I could not get it to work.

I am a .NET developer and we mainly still use Windows OS as we haven't made use of .Net core and cross platform so much, so my everyday use with Git is in a Windows environment, where the shell used is more often Powershell and not Git bash.

The following procedure can be followed to create an aliased function for adding untracked files in a Git repository.

Inside your $profile file of Powershell (in case it is missing - you can run: New-Item $Profile)

notepad $Profile

Now add this Powershell method:

function AddUntracked-Git() {
 &git ls-files -o --exclude-standard | select | foreach { git add $_ }
}

Save the $profile file and reload it into Powershell. Then reload your $profile file with: . $profile

This is similar to the source command in *nix environments IMHO.

So next time you, if you are developer using Powershell in Windows against Git repo and want to just include untracked files you can run:

AddUntracked-Git

This follows the Powershell convention where you have verb-nouns.

Add values to app.config and retrieve them

sorry for late answer but may be my code may help u.

I placed 3 buttons on the winform surface. button1 & 2 will set different value and button3 will retrieve current value. so when run my code first add the reference System.configuration

and click on first button and then click on 3rd button to see what value has been set. next time again click on second & 3rd button to see again what value has been set after change.

so here is the code.

using System.Configuration;

 private void button1_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Remove("DBServerName");
    config.AppSettings.Settings.Add("DBServerName", "FirstAddedValue1");
    config.Save(ConfigurationSaveMode.Modified);
}

private void button2_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Remove("DBServerName");
    config.AppSettings.Settings.Add("DBServerName", "SecondAddedValue1");
    config.Save(ConfigurationSaveMode.Modified);
}

private void button3_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
          MessageBox.Show(config.AppSettings.Settings["DBServerName"].Value);
}

How to create custom view programmatically in swift having controls text field, button etc

var customView = UIView()


@IBAction func drawView(_ sender: AnyObject) {

    customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
    customView.backgroundColor = UIColor.black     //give color to the view 
    customView.center = self.view.center  
    self.view.addSubview(customView)
       }

SSL cert "err_cert_authority_invalid" on mobile chrome only

if you're like me who is using AWS and CloudFront, here's how to solve the issue. it's similar to what others have shared except you don't use your domain's crt file, just what comodo emailed you.

cat COMODORSADomainValidationSecureServerCA.crt COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt > ssl-bundle.crt

this worked for me and my site no longer displays the ssl warning on chrome in android.

Tomcat starts but home page cannot open with url http://localhost:8080

1) Using Terminal (On Linux), go to the apache-tomcat-directory/bin folder.

2) Type ./catalina.sh start

3) To stop Tomcat, type ./catalina.sh stop from the bin folder. For some reason ./startup.sh doesn't work sometimes.

How to call an element in a numpy array?

TL;DR:

Using slicing:

>>> import numpy as np
>>> 
>>> arr = np.array([[1,2,3,4,5],[6,7,8,9,10]])
>>> 
>>> arr[0,0]
1
>>> arr[1,1]
7
>>> arr[1,0]
6
>>> arr[1,-1]
10
>>> arr[1,-2]
9

In Long:

Hopefully this helps in your understanding:

>>> import numpy as np
>>> np.array([ [1,2,3], [4,5,6] ])
array([[1, 2, 3],
       [4, 5, 6]])
>>> x = np.array([ [1,2,3], [4,5,6] ])
>>> x[1][2] # 2nd row, 3rd column 
6
>>> x[1,2] # Similarly
6

But to appreciate why slicing is useful, in more dimensions:

>>> np.array([ [[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]] ])
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])
>>> x = np.array([ [[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]] ])

>>> x[1][0][2] # 2nd matrix, 1st row, 3rd column
9
>>> x[1,0,2] # Similarly
9

>>> x[1][0:2][2] # 2nd matrix, 1st row, 3rd column
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 2 is out of bounds for axis 0 with size 2

>>> x[1, 0:2, 2] # 2nd matrix, 1st and 2nd row, 3rd column
array([ 9, 12])

>>> x[1, 0:2, 1:3] # 2nd matrix, 1st and 2nd row, 2nd and 3rd column
array([[ 8,  9],
       [11, 12]])

.NET NewtonSoft JSON deserialize map to a different property name

Adding to Jacks solution. I need to Deserialize using the JsonProperty and Serialize while ignoring the JsonProperty (or vice versa). ReflectionHelper and Attribute Helper are just helper classes that get a list of properties or attributes for a property. I can include if anyone actually cares. Using the example below you can serialize the viewmodel and get "Amount" even though the JsonProperty is "RecurringPrice".

    /// <summary>
    /// Ignore the Json Property attribute. This is usefule when you want to serialize or deserialize differently and not 
    /// let the JsonProperty control everything.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class IgnoreJsonPropertyResolver<T> : DefaultContractResolver
    {
        private Dictionary<string, string> PropertyMappings { get; set; }

        public IgnoreJsonPropertyResolver()
        {
            this.PropertyMappings = new Dictionary<string, string>();
            var properties = ReflectionHelper<T>.GetGetProperties(false)();
            foreach (var propertyInfo in properties)
            {
                var jsonProperty = AttributeHelper.GetAttribute<JsonPropertyAttribute>(propertyInfo);
                if (jsonProperty != null)
                {
                    PropertyMappings.Add(jsonProperty.PropertyName, propertyInfo.Name);
                }
            }
        }

        protected override string ResolvePropertyName(string propertyName)
        {
            string resolvedName = null;
            var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
            return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
        }
    }

Usage:

        var settings = new JsonSerializerSettings();
        settings.DateFormatString = "YYYY-MM-DD";
        settings.ContractResolver = new IgnoreJsonPropertyResolver<PlanViewModel>();
        var model = new PlanViewModel() {Amount = 100};
        var strModel = JsonConvert.SerializeObject(model,settings);

Model:

public class PlanViewModel
{

    /// <summary>
    ///     The customer is charged an amount over an interval for the subscription.
    /// </summary>
    [JsonProperty(PropertyName = "RecurringPrice")]
    public double Amount { get; set; }

    /// <summary>
    ///     Indicates the number of intervals between each billing. If interval=2, the customer would be billed every two
    ///     months or years depending on the value for interval_unit.
    /// </summary>
    public int Interval { get; set; } = 1;

    /// <summary>
    ///     Number of free trial days that can be granted when a customer is subscribed to this plan.
    /// </summary>
    public int TrialPeriod { get; set; } = 30;

    /// <summary>
    /// This indicates a one-time fee charged upfront while creating a subscription for this plan.
    /// </summary>
    [JsonProperty(PropertyName = "SetupFee")]
    public double SetupAmount { get; set; } = 0;


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "TypeId")]
    public string Type { get; set; }

    /// <summary>
    /// Billing Frequency
    /// </summary>
    [JsonProperty(PropertyName = "BillingFrequency")]
    public string Period { get; set; }


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "PlanUseType")]
    public string Purpose { get; set; }
}

Sort objects in an array alphabetically on one property of the array

objArray.sort((a, b) => a.DepartmentName.localeCompare(b.DepartmentName))

How to check if Location Services are enabled?

You can request the location updates and show the dialog together, like GoogleMaps doas also. Here is the code:

googleApiClient = new GoogleApiClient.Builder(getActivity())
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).build();
googleApiClient.connect();

LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);

builder.setAlwaysShow(true); //this is the key ingredient

PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
    @Override
    public void onResult(LocationSettingsResult result) {
        final Status status = result.getStatus();
        final LocationSettingsStates state = result.getLocationSettingsStates();
        switch (status.getStatusCode()) {
            case LocationSettingsStatusCodes.SUCCESS:
                // All location settings are satisfied. The client can initialize location
                // requests here.
                break;
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                // Location settings are not satisfied. But could be fixed by showing the user
                // a dialog.
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    status.startResolutionForResult(getActivity(), 1000);
                } catch (IntentSender.SendIntentException ignored) {}
                break;
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                // Location settings are not satisfied. However, we have no way to fix the
                // settings so we won't show the dialog.
                break;
            }
        }
    });
}

If you need more info check the LocationRequest class.

What is the difference between dim and set in vba

Dim simply declares the value and the type.

Set assigns a value to the variable.

How can I check if a program exists from a Bash script?

There are a ton of options here, but I was surprised no quick one-liners. This is what I used at the beginning of my scripts:

[[ "$(command -v mvn)" ]] || { echo "mvn is not installed" 1>&2 ; exit 1; }
[[ "$(command -v java)" ]] || { echo "java is not installed" 1>&2 ; exit 1; }

This is based on the selected answer here and another source.

json_encode function: special characters

Use the below function.

function utf8_converter($array)
{
    array_walk_recursive($array, function (&$item, $key) {
        if (!mb_detect_encoding($item, 'utf-8', true)) {
                $item = utf8_encode($item);
        }
    });

    return $array;
}

What is the best project structure for a Python application?

Doesn't too much matter. Whatever makes you happy will work. There aren't a lot of silly rules because Python projects can be simple.

  • /scripts or /bin for that kind of command-line interface stuff
  • /tests for your tests
  • /lib for your C-language libraries
  • /doc for most documentation
  • /apidoc for the Epydoc-generated API docs.

And the top-level directory can contain README's, Config's and whatnot.

The hard choice is whether or not to use a /src tree. Python doesn't have a distinction between /src, /lib, and /bin like Java or C has.

Since a top-level /src directory is seen by some as meaningless, your top-level directory can be the top-level architecture of your application.

  • /foo
  • /bar
  • /baz

I recommend putting all of this under the "name-of-my-product" directory. So, if you're writing an application named quux, the directory that contains all this stuff is named /quux.

Another project's PYTHONPATH, then, can include /path/to/quux/foo to reuse the QUUX.foo module.

In my case, since I use Komodo Edit, my IDE cuft is a single .KPF file. I actually put that in the top-level /quux directory, and omit adding it to SVN.

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

The best way to deal with audio timing is with the Web Audio Api, it has a separate clock that is accurate regardless of what is happening in the main thread. There is a great explanation, examples, etc from Chris Wilson here:

http://www.html5rocks.com/en/tutorials/audio/scheduling/

Have a look around this site for more Web Audio API, it was developed to do exactly what you are after.

Relative paths in Python

Instead of using

import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

as in the accepted answer, it would be more robust to use:

import inspect
import os
dirname = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

because using __file__ will return the file from which the module was loaded, if it was loaded from a file, so if the file with the script is called from elsewhere, the directory returned will not be correct.

These answers give more detail: https://stackoverflow.com/a/31867043/5542253 and https://stackoverflow.com/a/50502/5542253

Loop through list with both content and index

enumerate is what you want:

for i, s in enumerate(S):
    print s, i

Opening PDF String in new window with javascript

Just for information, the below

window.open("data:application/pdf," + encodeURI(pdfString)); 

does not work anymore in Chrome. Yesterday, I came across with the same issue and tried this solution, but did not work (it is 'Not allowed to navigate top frame to data URL'). You cannot open the data URL directly in a new window anymore. But, you can wrap it in iframe and make it open in a new window like below. =)

let pdfWindow = window.open("")
pdfWindow.document.write(
    "<iframe width='100%' height='100%' src='data:application/pdf;base64, " +
    encodeURI(yourDocumentBase64VarHere) + "'></iframe>"
)

rails bundle clean

Just remove the obsolete gems from your Gemfile. If you're talking about Heroku (you didn't mention that) then the slug is compiled each new release, just using the current contents of that file.

Whats the CSS to make something go to the next line in the page?

Have the element display as a block:

display: block;

generate model using user:references vs user_id:integer

For the former, convention over configuration. Rails default when you reference another table with

 belongs_to :something

is to look for something_id.

references, or belongs_to is actually newer way of writing the former with few quirks.

Important is to remember that it will not create foreign keys for you. In order to do that, you need to set it up explicitly using either:

t.references :something, foreign_key: true
t.belongs_to :something_else, foreign_key: true

or (note the plural):

add_foreign_key :table_name, :somethings
add_foreign_key :table_name, :something_elses`

How to parse a String containing XML in Java and retrieve the value of the root node?

One of the above answer states to convert XML String to bytes which is not needed. Instead you can can use InputSource and supply it with StringReader.

String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());

ImageView in circular through xml

I did it like that, I used my background color in my vector image

ic_bg_picture.xml

 <vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="100dp"
    android:height="100dp"
    android:viewportWidth="100"
    android:viewportHeight="100">
  <path
      android:pathData="M100.6,95.5c0,-0.4 -0.1,-0.7 0,-1.1c-0.2,-0.7 -0.2,-1.4 -0.1,-2.1c0,-0.1 0,-0.2 0,-0.3c-0.1,-0.6 -0.1,-1.2 0,-1.8c-1,-1.3 -0.3,-2.9 -0.3,-4.3c-0.1,-28.7 -0.1,-57.3 -0.1,-86C68,-0.1 35.9,-0.1 3.8,-0.2C0.7,-0.2 0,0.5 0,3.6c0.1,32.1 0.1,64.2 0.1,96.2c31,0 62,-0.1 92.9,0.1c3.6,0 6.3,-0.2 7.5,-3.2C100.5,96.4 100.5,95.9 100.6,95.5zM46.3,95.2C26.4,94 2,74.4 3.8,46.8C5.1,27.2 24.4,2.7 52.6,4.6c20.2,1.4 43,21.3 41.5,45.1C96.1,72.4 73,96.8 46.3,95.2z"
      android:fillColor="#6200EE"/>
</vector>

in my case I created a vector and changed the android:fillColor="#6200EE"

by the color of my background

  <ImageView
    android:id="@+id/iv_profile_image"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:contentDescription="@string/app_name"
    app:srcCompat="@color/colorPrimaryDark" />

<ImageView
    android:id="@+id/container_profile_image"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:contentDescription="@string/app_name"
    app:srcCompat="@drawable/ic_bg_picture"/>

example example 2

How to run a Runnable thread in Android at defined intervals?

new Handler().postDelayed(new Runnable() {
    public void run() {
        // do something...              
    }
}, 100);

How Long Does it Take to Learn Java for a Complete Newbie?

I'm computer science student who just finished my first Java course.. I'd say it's possible to learn Java on 10 weeks if you hard work on it. But you'll only get an intro! Programming is much more than just knowing the language (API, syntax etc)..

Best Java book ever: http://www.amazon.com/Introduction-Java-Programming-Comprehensive-Version/dp/0136012671/ref=sr_1_1?ie=UTF8&s=books&qid=1242328533&sr=8-1

Check if record exists from controller in Rails

I would do it this way if you needed an instance variable of the object to work with:

if @business = Business.where(:user_id => current_user.id).first
  #Do stuff
else
  #Do stuff
end

How to check if a registry value exists using C#?

        internal static Func<string, string, bool> regKey = delegate (string KeyLocation, string Value)
        {
            // get registry key with Microsoft.Win32.Registrys
            RegistryKey rk = (RegistryKey)Registry.GetValue(KeyLocation, Value, null); // KeyLocation and Value variables from method, null object because no default value is present. Must be casted to RegistryKey because method returns object.
            if ((rk) == null) // if the RegistryKey is null which means it does not exist
            {
                // the key does not exist
                return false; // return false because it does not exist
            }
            // the registry key does exist
            return true; // return true because it does exist
        };

usage:

        // usage:
        /* Create Key - while (loading)
        {
            RegistryKey k;
            k = Registry.CurrentUser.CreateSubKey("stuff");
            k.SetValue("value", "value");
            Thread.Sleep(int.MaxValue);
        }; // no need to k.close because exiting control */


        if (regKey(@"HKEY_CURRENT_USER\stuff  ...  ", "value"))
        {
             // key exists
             return;
        }
        // key does not exist

How to Consolidate Data from Multiple Excel Columns All into One Column

Take a look at Blockspring - you do need to install the plugin, but then it's just another function you call like this:

=BLOCKSPRING("twodee-array-reduce","input_array",D5:F7)

The source code and other details are here. If this doesn't suit and/or you want to build off my solution, you can fork my function (Python) or use another supported scripting language (Ruby, R, JS, etc...).

iFrame src change event detection?

If you have no control over the page and wish to watch for some kind of change then the modern method is to use MutationObserver

An example of its use, watching for the src attribute to change of an iframe

_x000D_
_x000D_
new MutationObserver(function(mutations) {_x000D_
  mutations.some(function(mutation) {_x000D_
    if (mutation.type === 'attributes' && mutation.attributeName === 'src') {_x000D_
      console.log(mutation);_x000D_
      console.log('Old src: ', mutation.oldValue);_x000D_
      console.log('New src: ', mutation.target.src);_x000D_
      return true;_x000D_
    }_x000D_
_x000D_
    return false;_x000D_
  });_x000D_
}).observe(document.body, {_x000D_
  attributes: true,_x000D_
  attributeFilter: ['src'],_x000D_
  attributeOldValue: true,_x000D_
  characterData: false,_x000D_
  characterDataOldValue: false,_x000D_
  childList: false,_x000D_
  subtree: true_x000D_
});_x000D_
_x000D_
setTimeout(function() {_x000D_
  document.getElementsByTagName('iframe')[0].src = 'http://jsfiddle.net/';_x000D_
}, 3000);
_x000D_
<iframe src="http://www.google.com"></iframe>
_x000D_
_x000D_
_x000D_

Output after 3 seconds

MutationRecord {oldValue: "http://www.google.com", attributeNamespace: null, attributeName: "src", nextSibling: null, previousSibling: null…}
Old src:  http://www.google.com
New src:  http://jsfiddle.net/ 

On jsFiddle

Posted answer here as original question was closed as a duplicate of this one.

How to make System.out.println() shorter

As Bakkal explained, for the keyboard shortcuts, in netbeans you can go to tools->options->editor->code templates and add or edit your own shortcuts.

In Eclipse it's on templates.

How do you get the logical xor of two variables in Python?

As I don't see the simple variant of xor using variable arguments and only operation on Truth values True or False, I'll just throw it here for anyone to use. It's as noted by others, pretty (not to say very) straightforward.

def xor(*vars):
    result = False
    for v in vars:
        result = result ^ bool(v)
    return result

And usage is straightforward as well:

if xor(False, False, True, False):
    print "Hello World!"

As this is the generalized n-ary logical XOR, it's truth value will be True whenever the number of True operands is odd (and not only when exactly one is True, this is just one case in which n-ary XOR is True).

Thus if you are in search of a n-ary predicate that is only True when exactly one of it's operands is, you might want to use:

def isOne(*vars):
    result = False
    for v in vars:
        if result and v:
            return False
        else:
            result = result or v
    return result

In a unix shell, how to get yesterday's date into a variable?

dt=$(date --date yesterday "+%a %d/%m/%Y")
echo $dt

jQuery how to find an element based on a data-attribute value?

Going back to his original question, about how to make this work without knowing the element type in advance, the following does this:

$(ContainerNode).find(el.nodeName + "[data-slide='" + current + "']");

Web-scraping JavaScript page with Python

It sounds like the data you're really looking for can be accessed via secondary URL called by some javascript on the primary page.

While you could try running javascript on the server to handle this, a simpler approach to might be to load up the page using Firefox and use a tool like Charles or Firebug to identify exactly what that secondary URL is. Then you can just query that URL directly for the data you are interested in.

How to refresh page on back button click?

did you try something like this? not tested...

$(document).ready(function(){
    $('.ajaxAnchor').on('click', function (event){ 
        event.preventDefault(); 
        var url = $(this).attr('href');
        $.get(url, function(data) {
            $('section.center').html(data);
            var shortened = url.substring(0,url.length - 5);
            window.location.hash = shortened;
        });
    });
});

What is the difference between DAO and Repository patterns?

A DAO allows for a simpler way to get data from storage, hiding the ugly queries.

Repository deals with data too and hides queries and all that but, a repository deals with business/domain objects.

A repository will use a DAO to get the data from the storage and uses that data to restore a business object.

For example, A DAO can contain some methods like that -

 public abstract class MangoDAO{
   abstract List<Mango>> getAllMangoes();
   abstract Mango getMangoByID(long mangoID);
}

And a Repository can contain some method like that -

   public abstract class MangoRepository{
       MangoDao mangoDao = new MangDao;

       Mango getExportQualityMango(){

       for(Mango mango:mangoDao.getAllMangoes()){
        /*Here some business logics are being applied.*/
        if(mango.isSkinFresh()&&mangoIsLarge(){
           mango.setDetails("It is an export quality mango");
            return mango;
           }
       }
    }
}

This tutorial helped me to get the main concept easily.

How to create a zip archive of a directory in Python?

Use shutil, which is part of python standard library set. Using shutil is so simple(see code below):

  • 1st arg: Filename of resultant zip/tar file,
  • 2nd arg: zip/tar,
  • 3rd arg: dir_name

Code:

import shutil
shutil.make_archive('/home/user/Desktop/Filename','zip','/home/username/Desktop/Directory')

How to make tesseract to recognize only numbers, when they are mixed with letters?

Recognizing only numbers is actually answered on the tesseract FAQ page. See that page for more info, but if you have the version 3 package, the config files are already set up. You just specify on the commandline:

tesseract image.tif outputbase nobatch digits

As for the threshold value, I'm not sure which you mean. If your input is an unusual font, perhaps you might retrain with a sample of your input. An alternative is to change tesseract's pruning threshold. Both options are also mentioned in the FAQ.

XML Schema Validation : Cannot find the declaration of element

Thanks to everyone above, but this is now fixed. For the benefit of others the most significant error was in aligning the three namespaces as suggested by Ian.

For completeness, here is the corrected XML and XSD

Here is the XML, with the typos corrected (sorry for any confusion caused by tardiness)

<?xml version="1.0" encoding="UTF-8"?>

<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="urn:Test.Namespace"  
      xsi:schemaLocation="urn:Test.Namespace Test1.xsd">
    <element1 id="001">
        <element2 id="001.1">
            <element3 id="001.1" />
        </element2>
    </element1>
</Root>

and, here is the Schema

<?xml version="1.0"?>

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="urn:Test.Namespace"
            xmlns="urn:Test.Namespace"
            elementFormDefault="qualified">
    <xsd:element name="Root">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="element1" maxOccurs="unbounded" type="element1Type"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
       
    <xsd:complexType name="element1Type">
        <xsd:sequence>
            <xsd:element name="element2" maxOccurs="unbounded" type="element2Type"/>
        </xsd:sequence>
        <xsd:attribute name="id" type="xsd:string"/>
    </xsd:complexType>
       
    <xsd:complexType name="element2Type">
        <xsd:sequence>
            <xsd:element name="element3" type="element3Type"/>
        </xsd:sequence>
        <xsd:attribute name="id" type="xsd:string"/>
    </xsd:complexType>

    <xsd:complexType name="element3Type">
        <xsd:attribute name="id" type="xsd:string"/>
    </xsd:complexType>        
</xsd:schema>

Thanks again to everyone, I hope this is of use to somebody else in the future.

PHPExcel Make first row bold

Try this

    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                                 ->setLastModifiedBy("Maarten Balliauw")
                                 ->setTitle("Office 2007 XLSX Test Document")
                                 ->setSubject("Office 2007 XLSX Test Document")
                                 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                                 ->setKeywords("office 2007 openxml php")
                                 ->setCategory("Test result file");
    $objPHPExcel->setActiveSheetIndex(0);
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->setCellValue('A1', 'No');
    $sheet->setCellValue('B1', 'Job ID');
    $sheet->setCellValue('C1', 'Job completed Date');
    $sheet->setCellValue('D1', 'Job Archived Date');
    $styleArray = array(
        'font' => array(
        'bold' => true
        )
    );
    $sheet->getStyle('A1')->applyFromArray($styleArray);
    $sheet->getStyle('B1')->applyFromArray($styleArray);
    $sheet->getStyle('C1')->applyFromArray($styleArray);
    $sheet->getStyle('D1')->applyFromArray($styleArray);
    $sheet->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);
    

This is give me output like below link.(https://www.screencast.com/t/ZkKFHbDq1le)

Identifier not found error on function call

You have to define void swapCase before the main definition.

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

After some serious searching it seems i've found the answer to my question:

from: http://www.brunildo.org/test/Overflowxy2.html

In Gecko, Safari, Opera, ‘visible’ becomes ‘auto’ also when combined with ‘hidden’ (in other words: ‘visible’ becomes ‘auto’ when combined with anything else different from ‘visible’). Gecko 1.8, Safari 3, Opera 9.5 are pretty consistent among them.

also the W3C spec says:

The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as their specified values, except that some combinations with ‘visible’ are not possible: if one is specified as ‘visible’ and the other is ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if ‘overflow-y’ is the same; otherwise it is the pair of computed values of ‘overflow-x’ and ‘overflow-y’.

Short Version:

If you are using visible for either overflow-x or overflow-y and something other than visible for the other, the visible value is interpreted as auto.

How do I join two lists in Java?

I'm not claiming that it's simple, but you mentioned bonus for one-liners ;-)

Collection mergedList = Collections.list(new sun.misc.CompoundEnumeration(new Enumeration[] {
    new Vector(list1).elements(),
    new Vector(list2).elements(),
    ...
}))

Formatting doubles for output in C#

The answer is yes, double printing is broken in .NET, they are printing trailing garbage digits.

You can read how to implement it correctly here.

I have had to do the same for IronScheme.

> (* 10.0 0.69)
6.8999999999999995
> 6.89999999999999946709
6.8999999999999995
> (- 6.9 (* 10.0 0.69))
8.881784197001252e-16
> 6.9
6.9
> (- 6.9 8.881784197001252e-16)
6.8999999999999995

Note: Both C and C# has correct value, just broken printing.

Update: I am still looking for the mailing list conversation I had that lead up to this discovery.

Accessing the last entry in a Map

When using numbers as the key, I suppose you could also try this:

        Map<Long, String> map = new HashMap<>();
        map.put(4L, "The First");
        map.put(6L, "The Second");
        map.put(11L, "The Last");

        long lastKey = 0;
        //you entered Map<Long, String> entry
        for (Map.Entry<Long, String> entry : map.entrySet()) {
            lastKey = entry.getKey();
        }
        System.out.println(lastKey); // 11

How to convert String to DOM Document object in java?

you can try

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));

Document doc = db.parse(is);

refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm

Calculate average in java

int values[] = { 23, 1, 5, 78, 22, 4};

int sum = 0;
for (int i = 0; i < values.length; i++)
    sum += values[i];

double average = ((double) sum) / values.length;

How to configure Visual Studio to use Beyond Compare

In Visual Studio 2008 + , go to the

Tools menu -->  select Options 

enter image description here

In Options Window --> expand Source Control --> Select Subversion User Tools --> Select Beyond Compare

and click OK button..

Git error: src refspec master does not match any

You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:

 git add a_text_file.txt 

... do:

 git commit -m "Initial commit."

... and those errors should go away.

How to set a default value in react-select

I was having a similar error. Make sure your options have a value attribute.

<option key={index} value={item}> {item} </option>

Then match the selects element value initially to the options value.

<select 
    value={this.value} />

Is there a way to get the git root directory in one command?

git-extras

adds $ git root
see https://github.com/tj/git-extras/blob/master/Commands.md#git-root

$ pwd
.../very-deep-from-root-directory
$ cd `git root`
$ git add . && git commit

Availability of git-extras

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

You can do this easily with the KoGrid plugin for KnockoutJS.

<script type="text/javascript">
    $(function () {
        window.viewModel = {
            myObsArray: ko.observableArray([
                { id: 1, firstName: 'John', lastName: 'Doe', createdOn: '1/1/2012', birthday: '1/1/1977', salary: 40000 },
                { id: 1, firstName: 'Jane', lastName: 'Harper', createdOn: '1/2/2012', birthday: '2/1/1976', salary: 45000 },
                { id: 1, firstName: 'Jim', lastName: 'Carrey', createdOn: '1/3/2012', birthday: '3/1/1985', salary: 60000 },
                { id: 1, firstName: 'Joe', lastName: 'DiMaggio', createdOn: '1/4/2012', birthday: '4/1/1991', salary: 70000 }
            ])
        };

        ko.applyBindings(viewModel);
    });
</script>

<div data-bind="koGrid: { data: myObsArray }">

Sample

Copying PostgreSQL database to another server

You don't need to create an intermediate file. You can do

pg_dump -C -h localhost -U localuser dbname | psql -h remotehost -U remoteuser dbname

or

pg_dump -C -h remotehost -U remoteuser dbname | psql -h localhost -U localuser dbname

using psql or pg_dump to connect to a remote host.

With a big database or a slow connection, dumping a file and transfering the file compressed may be faster.

As Kornel said there is no need to dump to a intermediate file, if you want to work compressed you can use a compressed tunnel

pg_dump -C dbname | bzip2 | ssh  remoteuser@remotehost "bunzip2 | psql dbname"

or

pg_dump -C dbname | ssh -C remoteuser@remotehost "psql dbname"

but this solution also requires to get a session in both ends.

Note: pg_dump is for backing up and psql is for restoring. So, the first command in this answer is to copy from local to remote and the second one is from remote to local. More -> https://www.postgresql.org/docs/9.6/app-pgdump.html

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

Changing ImageView source

Just write a method for changing imageview

public void setImage(final Context mContext, final ImageView imageView, int picture)
{
    if (mContext != null && imageView != null)
    {
        try
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            {
                imageView.setImageDrawable(mContext.getResources().getDrawable(picture, mContext.getApplicationContext().getTheme()));
            } else
            {
                imageView.setImageDrawable(mContext.getResources().getDrawable(picture));
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

use video as background for div

Why not fix a <video> and use z-index:-1 to put it behind all other elements?

html, body { width:100%; height:100%; margin:0; padding:0; }

<div style="position: fixed; top: 0; width: 100%; height: 100%; z-index: -1;">
    <video id="video" style="width:100%; height:100%">
        ....
    </video>
</div>
<div class='content'>
    ....

Demo

If you want it within a container you have to add a container element and a little more CSS

/* HTML */
<div class='vidContain'>
    <div class='vid'>
        <video> ... </video>
    </div>
    <div class='content'> ... The rest of your content ... </div>
</div>

/* CSS */
.vidContain {
    width:300px; height:200px;
    position:relative;
    display:inline-block;
    margin:10px;
}
.vid {
    position: absolute; 
    top: 0; left:0;
    width: 100%; height: 100%; 
    z-index: -1;
}    
.content {
    position:absolute;
    top:0; left:0;
    background: black;
    color:white;
}

Demo

How to tell if UIViewController's view is visible

The approach that I used for a modal presented view controller was to check the class of the presented controller. If the presented view controller was ViewController2 then I would execute some code.

UIViewController *vc = [self presentedViewController];

if ([vc isKindOfClass:[ViewController2 class]]) {
    NSLog(@"this is VC2");
}

Browser Timeouts

You can see the default value in Chrome in this link

int64_t g_used_idle_socket_timeout_s = 300 // 5 minutes

In Chrome, as far as I know, there isn't an easy way (as Firefox do) to change the timeout value.

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

Sometime this error also occur when you change the order of Component Function while passing to connect.

Incorrect Order:

export default connect(mapDispatchToProps, mapStateToProps)(TodoList);

Correct Order:

export default connect(mapStateToProps,mapDispatchToProps)(TodoList);

Creating a list of pairs in java

You can use the Entry<U,V> class that HashMap uses but you'll be stuck with its semantics of getKey and getValue:

List<Entry<Float,Short>> pairList = //...

My preference would be to create your own simple Pair class:

public class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r){
        this.l = l;
        this.r = r;
    }
    public L getL(){ return l; }
    public R getR(){ return r; }
    public void setL(L l){ this.l = l; }
    public void setR(R r){ this.r = r; }
}

Then of course make a List using this new class, e.g.:

List<Pair<Float,Short>> pairList = new ArrayList<Pair<Float,Short>>();

You can also always make a Lists of Lists, but it becomes difficult to enforce sizing (that you have only pairs) and you would be required, as with arrays, to have consistent typing.

Detecting Windows or Linux?

I think It's a best approach to use Apache lang dependency to decide which OS you're running programmatically through Java

import org.apache.commons.lang3.SystemUtils;

public class App {
    public static void main( String[] args ) {
        if(SystemUtils.IS_OS_WINDOWS_7)
            System.out.println("It's a Windows 7 OS");
        if(SystemUtils.IS_OS_WINDOWS_8)
            System.out.println("It's a Windows 8 OS");
        if(SystemUtils.IS_OS_LINUX)
            System.out.println("It's a Linux OS");
        if(SystemUtils.IS_OS_MAC)
            System.out.println("It's a MAC OS");
    }
}

Transparent ARGB hex value

Adding to the other answers and doing nothing more of what @Maleta explained in a comment on https://stackoverflow.com/a/28481374/1626594, doing alpha*255 then round then to hex. Here's a quick converter http://jsfiddle.net/8ajxdLap/4/

_x000D_
_x000D_
function rgb2hex(rgb) {_x000D_
  var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?((?:[0-9]*[.])?[0-9]+)[\s+]?\)/i);_x000D_
  if (rgbm && rgbm.length === 5) {_x000D_
    return "#" +_x000D_
      ('0' + Math.round(parseFloat(rgbm[4], 10) * 255).toString(16).toUpperCase()).slice(-2) +_x000D_
      ("0" + parseInt(rgbm[1], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
      ("0" + parseInt(rgbm[2], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
      ("0" + parseInt(rgbm[3], 10).toString(16).toUpperCase()).slice(-2);_x000D_
  } else {_x000D_
    var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);_x000D_
    if (rgbm && rgbm.length === 4) {_x000D_
      return "#" +_x000D_
        ("0" + parseInt(rgbm[1], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
        ("0" + parseInt(rgbm[2], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
        ("0" + parseInt(rgbm[3], 10).toString(16).toUpperCase()).slice(-2);_x000D_
    } else {_x000D_
      return "cant parse that";_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
$('button').click(function() {_x000D_
  var hex = rgb2hex($('#in_tb').val());_x000D_
  $('#in_tb_result').html(hex);_x000D_
});
_x000D_
body {_x000D_
  padding: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
Convert RGB/RGBA to hex #RRGGBB/#AARRGGBB:<br>_x000D_
<br>_x000D_
<input id="in_tb" type="text" value="rgba(200, 90, 34, 0.75)"> <button>Convert</button><br>_x000D_
<br> Result: <span id="in_tb_result"></span>
_x000D_
_x000D_
_x000D_

How to convert an ASCII character into an int in C

Are you searching for this:

int c = some_ascii_character;

Or just converting without assignment:

(int)some_aschii_character;

How to sort strings in JavaScript

Use String.prototype.localeCompare a per your example:

list.sort(function (a, b) {
    return ('' + a.attr).localeCompare(b.attr);
})

We force a.attr to be a string to avoid exceptions. localeCompare has been supported since Internet Explorer 6 and Firefox 1. You may also see the following code used that doesn't respect a locale:

if (item1.attr < item2.attr)
  return -1;
if ( item1.attr > item2.attr)
  return 1;
return 0;

Convert python datetime to epoch with strftime

This works in Python 2 and 3:

>>> import time
>>> import calendar
>>> calendar.timegm(time.gmtime())
1504917998

Just following the official docs... https://docs.python.org/2/library/time.html#module-time

Access elements in json object like an array

var coordinates = [jsonObject[3][0], 
                   jsonObject[3][0],
                   jsonObject[4][1], 
                   jsonObject[4][1]];

What is the difference between require_relative and require in Ruby?

require_relative is a convenient subset of require

require_relative('path')

equals:

require(File.expand_path('path', File.dirname(__FILE__)))

if __FILE__ is defined, or it raises LoadError otherwise.

This implies that:

  • require_relative 'a' and require_relative './a' require relative to the current file (__FILE__).

    This is what you want to use when requiring inside your library, since you don't want the result to depend on the current directory of the caller.

  • eval('require_relative("a.rb")') raises LoadError because __FILE__ is not defined inside eval.

    This is why you can't use require_relative in RSpec tests, which get evaled.

The following operations are only possible with require:

  • require './a.rb' requires relative to the current directory

  • require 'a.rb' uses the search path ($LOAD_PATH) to require. It does not find files relative to current directory or path.

    This is not possible with require_relative because the docs say that path search only happens when "the filename does not resolve to an absolute path" (i.e. starts with / or ./ or ../), which is always the case for File.expand_path.

The following operation is possible with both, but you will want to use require as it is shorter and more efficient:

  • require '/a.rb' and require_relative '/a.rb' both require the absolute path.

Reading the source

When the docs are not clear, I recommend that you take a look at the sources (toggle source in the docs). In some cases, it helps to understand what is going on.

require:

VALUE rb_f_require(VALUE obj, VALUE fname) {
  return rb_require_safe(fname, rb_safe_level());
}

require_relative:

VALUE rb_f_require_relative(VALUE obj, VALUE fname) {
    VALUE base = rb_current_realfilepath();
    if (NIL_P(base)) {
        rb_loaderror("cannot infer basepath");
    }
    base = rb_file_dirname(base);
    return rb_require_safe(rb_file_absolute_path(fname, base), rb_safe_level());
}

This allows us to conclude that

require_relative('path')

is the same as:

require(File.expand_path('path', File.dirname(__FILE__)))

because:

rb_file_absolute_path   =~ File.expand_path
rb_file_dirname1        =~ File.dirname
rb_current_realfilepath =~ __FILE__

Java: get greatest common divisor

For int and long, as primitives, not really. For Integer, it is possible someone wrote one.

Given that BigInteger is a (mathematical/functional) superset of int, Integer, long, and Long, if you need to use these types, convert them to a BigInteger, do the GCD, and convert the result back.

private static int gcdThing(int a, int b) {
    BigInteger b1 = BigInteger.valueOf(a);
    BigInteger b2 = BigInteger.valueOf(b);
    BigInteger gcd = b1.gcd(b2);
    return gcd.intValue();
}

ActionBarActivity: cannot be resolved to a type

It does not sound like you imported the library right especially when you say at the point Add the library to your application project: I felt lost .. basically because I don't have the "add" option by itself .. however I clicked on "add library" and moved on ..

in eclipse you need to right click on the project, go to Properties, select Android in the list then Add to add the library

follow this tutorial in the docs

http://developer.android.com/tools/support-library/setup.html

How to execute the start script with Nodemon

In package.json file. change file like this

"scripts":{ 
   "start": "node ./bin/www", 
   "start-dev": "nodemon ./app.js"
 },

and then execute npm run start-dev

Removing an element from an Array (Java)

You can not change the length of an array, but you can change the values the index holds by copying new values and store them to a existing index number. 1=mike , 2=jeff // 10 = george 11 goes to 1 overwriting mike .

Object[] array = new Object[10];
int count = -1;

public void myFunction(String string) {
    count++;
    if(count == array.length) { 
        count = 0;  // overwrite first
    }
    array[count] = string;    
}

LoDash: Get an array of values from an array of object properties

This will give you what you want in a pop-up.

for(var i = 0; i < users.Count; i++){
   alert(users[i].id);  
}

DropdownList DataSource

You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable.
Main you have to consider three thing while binding the datasource of a dropdown.

  1. DataSource - Name of the dataset or datatable or your datasource
  2. DataValueField - These field will be hidden
  3. DataTextField - These field will be displayed on the dropdwon.

you can use following code to bind a dropdownlist to a datasource as a datatable:

  SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);

    SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);

    SqlDataAdapter da = new SqlDataAdapter(cmd);

    DataTable dt=new DataTable();
    da.Fill(dt);

    DropDownList1.DataTextField = "QUIZ_Name";
    DropDownList1.DataValueField = "QUIZ_ID"

    DropDownList1.DataSource = dt;
    DropDownList1.DataBind();

if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true" you can use SelectedIndexChanged event to write your code.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string strQUIZ_ID=DropDownList1.SelectedValue;
    string strQUIZ_Name=DropDownList1.SelectedItem.Text;
    // Your code..............
}

Python function global variables?

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

insert datetime value in sql database with c#

INSERT INTO <table> (<date_column>) VALUES ('1/1/2010 12:00')

How to download excel (.xls) file from API in postman?

If the endpoint really is a direct link to the .xls file, you can try the following code to handle downloading:

public static boolean download(final File output, final String source) {
    try {
        if (!output.createNewFile()) {
            throw new RuntimeException("Could not create new file!");
        }
        URL url = new URL(source);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // Comment in the code in the following line in case the endpoint redirects instead of it being a direct link
        // connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("AUTH-KEY-PROPERTY-NAME", "yourAuthKey");
        final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
        final FileOutputStream fos = new FileOutputStream(output);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        fos.close();
        return true;
    } catch (final Exception e) {
        e.printStackTrace();
    }
    return false;
}

All you should need to do is set the proper name for the auth token and fill it in.

Example usage:

download(new File("C:\\output.xls"), "http://www.website.com/endpoint");

How to display databases in Oracle 11g using SQL*Plus

SELECT NAME FROM v$database; shows the database name in oracle

How to get $(this) selected option in jQuery?

var cur_value = $('option:selected',this).text();

How to change the size of the font of a JLabel to take the maximum size

Just wanted to point out that the accepted answer has a couple of limitations (which I discovered when I tried to use it)

  1. As written, it actually keeps recalculating the font size based on a ratio of the previous font size... thus after just a couple of calls it has rendered the font size as much too large. (eg Start with 12 point as your DESIGNED Font, expand the label by just 1 pixel, and the published code will calculate the Font size as 12 * (say) 1.2 (ratio of field space to text) = 14.4 or 14 point font. 1 more Pixel and call and you are at 16 point !).

It is thus not suitable (without adaptation) for use in a repeated-call setting (eg a ComponentResizedListener, or a custom/modified LayoutManager).

The listed code effectively assumes a starting size of 10 pt but refers to the current font size and is thus suitable for calling once (to set the size of the font when the label is created). It would work better in a multi-call environment if it did int newFontSize = (int) (widthRatio * 10); rather than int newFontSize = (int)(labelFont.getSize() * widthRatio);

  1. Because it uses new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse)) to generate the new font, there is no support for Bolding, Italic or Color etc from the original font in the updated font. It would be more flexible if it made use of labelFont.deriveFont instead.

  2. The solution does not provide support for HTML label Text. (I know that was probably not ever an intended outcome of the answer code offered, but as I had an HTML-text JLabel on my JPanel I formally discovered the limitation. The FontMetrics.stringWidth() calculates the text length as inclusive of the width of the html tags - ie as simply more text)

I recommend looking at the answer to this SO question where trashgod's answer points to a number of different answers (including this one) to an almost identical question. On that page I will provide an additional answer that speeds up one of the other answers by a factor of 30-100.

CryptographicException 'Keyset does not exist', but only through WCF

I just reinstalled my certificate in local machine and then it is working fine

How to get local server host and port in Spring Boot?

An easy workaround, at least to get the running port, is to add the parameter javax.servlet.HttpServletRequest in the signature of one of the controller's methods. Once you have the HttpServletRequest instance is straightforward to get the baseUrl with this: request.getRequestURL().toString()

Have a look at this code:

@PostMapping(value = "/registration" , produces = "application/json")
public StringResponse register(@RequestBody RequestUserDTO userDTO, 
    HttpServletRequest request) {
request.getRequestURL().toString();
//value: http://localhost:8080/registration
------
return "";
}

How to assign a NULL value to a pointer in python?

All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.

The python equivalent of NULL is called None (good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:

class Node:
    def __init__(self): #object initializer to set attributes (fields)
        self.val = 0
        self.right = None
        self.left = None

And then it works pretty much like you would expect:

node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()

Note that unlike in NULL in C, None is not a "pointer to nowhere": it is actually the only instance of class NoneType. Therefore, as None is a regular object, you can test for it just like any other object:

if node.left == None:
   print("The left node is None/Null.")

Although since None is a singleton instance, it is considered more idiomatic to use is and compare for reference equality:

if node.left is None:
   print("The left node is None/Null.")

How can I scroll a web page using selenium webdriver in python?

If you want to scroll down to bottom of infinite page (like linkedin.com), you can use this code:

SCROLL_PAUSE_TIME = 0.5

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

Reference: https://stackoverflow.com/a/28928684/1316860

Where is Ubuntu storing installed programs?

for some applications, for example google chrome, they store it under /opt. you can follow the above instruction using dpkg -l to get the correct naming then dpkg -L to get the detail.

hope it helps

Unable to establish SSL connection, how do I fix my SSL cert?

There are a few possibilities:

  1. Your workstation doesn't have the root CA cert used to sign your server's cert. How exactly you fix that depends on what OS you're running and what release, etc. (I suspect this is not related)
  2. Your cert isn't installed properly. If your SSL cert requires an intermediate cert to be presented and you didn't set that up, you can get these warnings.
  3. Are you sure you've enabled SSL on port 443?

For starters, to eliminate (3), what happens if you telnet to that port?

Assuming it's not (3), then depending on your needs you may be fine with ignoring these errors and just passing --no-certificate-check. You probably want to use a regular browser (which generally will bundle the root certs directly) and see if things are happy.

If you want to manually verify the cert, post more details from the openssl s_client output. Or use openssl x509 -text -in /path/to/cert to print it out to your terminal.

Using true and false in C

There is no real speed difference. They are really all the same to the compiler. The difference is with the human beings trying to use and read your code.

For me that makes bool, true, and false the best choice in C++ code. In C code, there are some compilers around that don't support bool (I often have to work with old systems), so I might go with the defines in some circumstances.

How to capitalize the first letter of word in a string using Java?

I would like to add a NULL check and IndexOutOfBoundsException on the accepted answer.

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

Java Code:

  class Main {
      public static void main(String[] args) {
        System.out.println("Capitalize first letter ");
        System.out.println("Normal  check #1      : ["+ captializeFirstLetter("one thousand only")+"]");
        System.out.println("Normal  check #2      : ["+ captializeFirstLetter("two hundred")+"]");
        System.out.println("Normal  check #3      : ["+ captializeFirstLetter("twenty")+"]");
        System.out.println("Normal  check #4      : ["+ captializeFirstLetter("seven")+"]");

        System.out.println("Single letter check   : ["+captializeFirstLetter("a")+"]");
        System.out.println("IndexOutOfBound check : ["+ captializeFirstLetter("")+"]");
        System.out.println("Null Check            : ["+ captializeFirstLetter(null)+"]");
      }

      static String captializeFirstLetter(String input){
             if(input!=null && input.length() >0){
                input = input.substring(0, 1).toUpperCase() + input.substring(1);
            }
            return input;
        }
    }

Output:

Normal  check #1      : [One thousand only]
Normal  check #2      : [Two hundred]
Normal  check #3      : [Twenty]
Normal  check #4      : [Seven]
Single letter check   : [A]
IndexOutOfBound check : []
Null Check            : [null]

Convert an object to an XML string

 public static class XMLHelper
    {
        /// <summary>
        /// Usage: var xmlString = XMLHelper.Serialize<MyObject>(value);
        /// </summary>
        /// <typeparam name="T">Ki?u d? li?u</typeparam>
        /// <param name="value">giá tr?</param>
        /// <param name="omitXmlDeclaration">b? qua declare</param>
        /// <param name="removeEncodingDeclaration">xóa encode declare</param>
        /// <returns>xml string</returns>
        public static string Serialize<T>(T value, bool omitXmlDeclaration = false, bool omitEncodingDeclaration = true)
        {
            if (value == null)
            {
                return string.Empty;
            }
            try
            {
                var xmlWriterSettings = new XmlWriterSettings
                {
                    Indent = true,
                    OmitXmlDeclaration = omitXmlDeclaration, //true: remove <?xml version="1.0" encoding="utf-8"?>
                    Encoding = Encoding.UTF8,
                    NewLineChars = "", // remove \r\n
                };

                var xmlserializer = new XmlSerializer(typeof(T));

                using (var memoryStream = new MemoryStream())
                {
                    using (var xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
                    {
                        xmlserializer.Serialize(xmlWriter, value);
                        //return stringWriter.ToString();
                    }

                    memoryStream.Position = 0;
                    using (var sr = new StreamReader(memoryStream))
                    {
                        var pureResult = sr.ReadToEnd();
                        var resultAfterOmitEncoding = ReplaceFirst(pureResult, " encoding=\"utf-8\"", "");
                        if (omitEncodingDeclaration)
                            return resultAfterOmitEncoding;
                        return pureResult;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("XMLSerialize error: ", ex);
            }
        }

        private static string ReplaceFirst(string text, string search, string replace)
        {
            int pos = text.IndexOf(search);

            if (pos < 0)
            {
                return text;
            }

            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
        }
    }

Django CharField vs TextField

I had an strange problem and understood an unpleasant strange difference: when I get an URL from user as an CharField and then and use it in html a tag by href, it adds that url to my url and that's not what I want. But when I do it by Textfield it passes just the URL that user entered. look at these: my website address: http://myweb.com

CharField entery: http://some-address.com

when clicking on it: http://myweb.comhttp://some-address.com

TextField entery: http://some-address.com

when clicking on it: http://some-address.com

I must mention that the URL is saved exactly the same in DB by two ways but I don't know why result is different when clicking on them

Set timeout for webClient.DownloadFile()

Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result:

using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
     if (stream != null)
     {
          stream.ReadTimeout = Timeout.Infinite;
          using (var reader = new StreamReader(stream, Encoding.UTF8, false))
          {
               string line;
               while ((line = reader.ReadLine()) != null)
               {
                    if (line != String.Empty)
                    {
                        Console.WriteLine("Count {0}", count++);
                    }
                    Console.WriteLine(line);
               }
          }
     }
}

Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did.

Get operating system info

If you want very few info like a class in your html for common browsers for instance, you could use:

function get_browser()
{
    $browser = '';
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (preg_match('~(?:msie ?|trident.+?; ?rv: ?)(\d+)~', $ua, $matches)) $browser = 'ie ie'.$matches[1];
    elseif (preg_match('~(safari|chrome|firefox)~', $ua, $matches)) $browser = $matches[1];

    return $browser;
}

which will return 'safari' or 'firefox' or 'chrome', or 'ie ie8', 'ie ie9', 'ie ie10', 'ie ie11'.

How to develop Android app completely using python?

To answer your first question: yes it is feasible to develop an android application in pure python, in order to achieve this I suggest you use BeeWare, which is just a suite of python tools, that work together very well and they enable you to develop platform native applications in python.

checkout this video by the creator of BeeWare that perfectly explains and demonstrates it's application

How it works

Android's preferred language of implementation is Java - so if you want to write an Android application in Python, you need to have a way to run your Python code on a Java Virtual Machine. This is what VOC does. VOC is a transpiler - it takes Python source code, compiles it to CPython Bytecode, and then transpiles that bytecode into Java-compatible bytecode. The end result is that your Python source code files are compiled directly to a Java .class file, which can be packaged into an Android application.

VOC also allows you to access native Java objects as if they were Python objects, implement Java interfaces with Python classes, and subclass Java classes with Python classes. Using this, you can write an Android application directly against the native Android APIs.

Once you've written your native Android application, you can use Briefcase to package your Python code as an Android application.

Briefcase is a tool for converting a Python project into a standalone native application. You can package projects for:

  • Mac
  • Windows
  • Linux
  • iPhone/iPad
  • Android
  • AppleTV
  • tvOS.

You can check This native Android Tic Tac Toe app written in Python, using the BeeWare suite. on GitHub

in addition to the BeeWare tools, you'll need to have a JDK and Android SDK installed to test run your application.

and to answer your second question: a good environment can be anything you are comfortable with be it a text editor and a command line, or an IDE, if you're looking for a good python IDE I would suggest you try Pycharm, it has a community edition which is free, and it has a similar environment as android studio, due to to the fact that were made by the same company.

I hope this has been helpful