Programs & Examples On #Yammer

Yammer is a private social network for business.

java.io.IOException: Broken pipe

I agree with @arcy, the problem is on client side, on my case it was because of nginx, let me elaborate I am using nginx as the frontend (so I can distribute load, ssl, etc ...) and using proxy_pass http://127.0.0.1:8080 to forward the appropiate requests to tomcat.

There is a default value for the nginx variable proxy_read_timeout of 60s that should be enough, but on some peak moments my setup would error with the java.io.IOException: Broken pipe changing the value will help until the root cause (60s should be enough) can be fixed.

NOTE: I made a new answer so I could expand a bit more with my case (it was the only mention I found about this error on internet after looking quite a lot)

Difference between x86, x32, and x64 architectures?

x86 means Intel 80x86 compatible. This used to include the 8086, a 16-bit only processor. Nowadays it roughly means any CPU with a 32-bit Intel compatible instruction set (usually anything from Pentium onwards). Never read x32 being used.

x64 means a CPU that is x86 compatible but has a 64-bit mode as well (most often the 64-bit instruction set as introduced by AMD is meant; Intel's idea of a 64-bit mode was totally stupid and luckily Intel admitted that and is now using AMDs variant).

So most of the time you can simplify it this way: x86 is Intel compatible in 32-bit mode, x64 is Intel compatible in 64-bit mode.

How to pass multiple parameters to a get method in ASP.NET Core

Why not using just one controller action?

public string Get(int? id, string firstName, string lastName, string address)
{
   if (id.HasValue)
      GetById(id);
   else if (string.IsNullOrEmpty(address))
      GetByName(firstName, lastName);
   else
      GetByNameAddress(firstName, lastName, address);
}

Another option is to use attribute routing, but then you'd need to have a different URL format:

//api/person/byId?id=1
[HttpGet("byId")] 
public string Get(int id)
{
}

//api/person/byName?firstName=a&lastName=b
[HttpGet("byName")]
public string Get(string firstName, string lastName, string address)
{
}

What is aria-label and how should I use it?

The title attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).

As such, the mindful approach here would be to serve all users. I would add both title and aria-label attributes (serving different types of users and different types of usage of the web).

Here's a good article that explains aria-label in depth

How can I show/hide a specific alert with twitter bootstrap?

Use the id selector #

$('#passwordsNoMatchRegister').show();

intl extension: installing php_intl.dll

I have XAMPP 1.8.3-0 and PHP 5.5.0 installed.

1) edit php.ini:

from

;extension=php_intl.dll

to

extension=php_intl.dll

Note: After modification, need to save the file(php.ini) as well as need to restart the Apache Server.

2) Simply copy all icu* * * *.dll files:

from

C:\xampp\php

to

C:\xampp\apache\bin

Then intl extension works!!!

How to change value of a request parameter in laravel

Try to:

$requestData = $request->all();
$requestData['img'] = $img;

Another way to do it:

$request->merge(['img' => $img]);

Thanks to @JoelHinz for this.

If you want to add or overwrite nested data:

$data['some']['thing'] = 'value';
$request->merge($data);

If you do not inject Request $request object, you can use the global request() helper or \Request:: facade instead of $request

SQL Server Management Studio – tips for improving the TSQL coding process

I warmly recommend Red Gate's SQL Prompt. Auto-discovery (intellisense on tables, stored procedures, functions and native functions) is nothing short of awesome! :)

It comes with a price though. There is no free-ware version of the thing.

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Ya its possible to do without support of javascript..
We can use html5 auto focus attribute
For Example:

<input type="text" name="name" autofocus="autofocus" id="xax" />

If use it (autofocus="autofocus") in text field means that text field get focused when page gets loaded.. For more details:
http://www.hscripts.com/tutorials/html5/autofocus-attribute.html

Difference between break and continue in PHP?

'continue' is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

'break' ends execution of the current for, foreach, while, do-while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

Check out the following links:

http://www.php.net/manual/en/control-structures.break.php

http://www.php.net/manual/en/control-structures.continue.php

Hope it helps..

Python pandas: how to specify data types when reading an Excel file?

If you are able to read the excel file correctly and only the integer values are not showing up. you can specify like this.

df = pd.read_excel('my.xlsx',sheetname='Sheet1', engine="openpyxl", dtype=str)

this should change your integer values into a string and show in dataframe

File upload from <input type="file">

I think that it's not supported. If you have a look at this DefaultValueAccessor directive (see https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/default_value_accessor.ts#L23). You will see that the value used to update the bound element is $event.target.value.

This doesn't apply in the case of inputs with type file since the file object can be reached $event.srcElement.files instead.

For more details, you can have a look at this plunkr: https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" (change)="onChange($event)"/>
    </div>
  `,
  providers: [ UploadService ]
})
export class AppComponent {
  onChange(event) {
    var files = event.srcElement.files;
    console.log(files);
  }
}

XSD - how to allow elements in any order any number of times?

The alternative formulation of the question added in a later edit seems still to be unanswered: how to specify that among the children of an element, there must be one named child3, one named child4, and any number named child1 or child2, with no constraint on the order in which the children appear.

This is a straightforwardly definable regular language, and the content model you need is isomorphic to a regular expression defining the set of strings in which the digits '3' and '4' each occur exactly once, and the digits '1' and '2' occur any number of times. If it's not obvious how to write this, it may help to think about what kind of finite state machine you would build to recognize such a language. It would have at least four distinct states:

  • an initial state in which neither '3' nor '4' has been seen
  • an intermediate state in which '3' has been seen but not '4'
  • an intermediate state in which '4' has been seen but not '3'
  • a final state in which both '3' and '4' have been seen

No matter what state the automaton is in, '1' and '2' may be read; they do not change the machine's state. In the initial state, '3' or '4' will also be accepted; in the intermediate states, only '4' or '3' is accepted; in the final state, neither '3' nor '4' is accepted. The structure of the regular expression is easiest to understand if we first define a regex for the subset of our language in which only '3' and '4' occur:

(34)|(43)

To allow '1' or '2' to occur any number of times at a given location, we can insert (1|2)* (or [12]* if our regex language accepts that notation). Inserting this expression at all available locations, we get

(1|2)*((3(1|2)*4)|(4(1|2)*3))(1|2)*

Translating this into a content model is straightforward. The basic structure is equivalent to the regex (34)|(43):

<xsd:complexType name="paul0">
  <xsd:choice>
    <xsd:sequence>
      <xsd:element ref="child3"/>
      <xsd:element ref="child4"/>
    </xsd:sequence>
    <xsd:sequence>
      <xsd:element ref="child4"/>
      <xsd:element ref="child3"/>
    </xsd:sequence>
  </xsd:choice>
</xsd:complexType>

Inserting a zero-or-more choice of child1 and child2 is straightforward:

<xsd:complexType name="paul1">
  <xsd:sequence>
    <xsd:choice minOccurs="0" maxOccurs="unbounded">
      <xsd:element ref="child1"/>
      <xsd:element ref="child2"/>
    </xsd:choice>      
    <xsd:choice>
      <xsd:sequence>
        <xsd:element ref="child3"/>
        <xsd:choice minOccurs="0" maxOccurs="unbounded">
          <xsd:element ref="child1"/>
          <xsd:element ref="child2"/>
        </xsd:choice>      
        <xsd:element ref="child4"/>
      </xsd:sequence>
      <xsd:sequence>
        <xsd:element ref="child4"/>
        <xsd:choice minOccurs="0" maxOccurs="unbounded">
          <xsd:element ref="child1"/>
          <xsd:element ref="child2"/>
        </xsd:choice>      
        <xsd:element ref="child3"/>
      </xsd:sequence>
    </xsd:choice>
    <xsd:choice minOccurs="0" maxOccurs="unbounded">
      <xsd:element ref="child1"/>
      <xsd:element ref="child2"/>
    </xsd:choice>      
  </xsd:sequence>
</xsd:complexType>

If we want to minimize the bulk a bit, we can define a named group for the repeating choices of child1 and child2:

<xsd:group name="onetwo">
  <xsd:choice>
    <xsd:element ref="child1"/>
    <xsd:element ref="child2"/>
  </xsd:choice>   
</xsd:group>

<xsd:complexType name="paul2">
  <xsd:sequence>
    <xsd:group ref="onetwo" minOccurs="0" maxOccurs="unbounded"/>
    <xsd:choice>
      <xsd:sequence>
        <xsd:element ref="child3"/>
        <xsd:group ref="onetwo" minOccurs="0" maxOccurs="unbounded"/>
        <xsd:element ref="child4"/>
      </xsd:sequence>
      <xsd:sequence>
        <xsd:element ref="child4"/>
        <xsd:group ref="onetwo" minOccurs="0" maxOccurs="unbounded"/>
        <xsd:element ref="child3"/>
      </xsd:sequence>
    </xsd:choice>  
    <xsd:group ref="onetwo" minOccurs="0" maxOccurs="unbounded"/>
  </xsd:sequence>
</xsd:complexType>

In XSD 1.1, some of the constraints on all-groups have been lifted, so it's possible to define this content model more concisely:

<xsd:complexType name="paul3">
  <xsd:all>
    <xsd:element ref="child1" minOccurs="0" maxOccurs="unbounded"/>
    <xsd:element ref="child2" minOccurs="0" maxOccurs="unbounded"/>
    <xsd:element ref="child3"/>
    <xsd:element ref="child4"/>      
  </xsd:all>
</xsd:complexType>

But as can be seen from the examples given earlier, these changes to all-groups do not in fact change the expressive power of the language; they only make the definition of certain kinds of languages more succinct.

How do I setup a SSL certificate for an express.js server?

I was able to get SSL working with the following boilerplate code:

var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    express = require('express');

var port = 8000;

var options = {
    key: fs.readFileSync('./ssl/privatekey.pem'),
    cert: fs.readFileSync('./ssl/certificate.pem'),
};

var app = express();

var server = https.createServer(options, app).listen(port, function(){
  console.log("Express server listening on port " + port);
});

app.get('/', function (req, res) {
    res.writeHead(200);
    res.end("hello world\n");
});

Android studio: emulator is running but not showing up in Run App "choose a running device"

For anyone else having the issue - none of the answers provided worked for me.

My case may be different to others but I had Android Studio installed first which installs the SDK by default to: C:\Users\[user]\AppData\Local\Android\sdk. We then decided to use Xamarin for our projects, so Xamarin was installed and installed an additional SDK by default, located here: C:\Program Files (x86)\Android\android-sdk.

Changing Xamarin to match the same SDK path worked for me which I did in the registry (although through the VS settings I'd guess it's the same):

\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Android SDK Tools\Path

Change the path to match the Android Studio SDK path, close everything, start the VS Emulator, run Android Studio, ensure ADB integration is off and try. It worked for me.

How do I force make/GCC to show me the commands?

Depending on your automake version, you can also use this:

make AM_DEFAULT_VERBOSITY=1

Reference: AM_DEFAULT_VERBOSITY

Note: I added this answer since V=1 did not work for me.

Insert new item in array on any position in PHP

This can be done with array_splice however, array_splice fails when inserting an array or using a string key. I wrote a function to handle all cases:

function array_insert(&$arr, $index, $val)
{
    if (is_string($index))
        $index = array_search($index, array_keys($arr));
    if (is_array($val))
        array_splice($arr, $index, 0, [$index => $val]);
    else
        array_splice($arr, $index, 0, $val);
}

How to create global variables accessible in all views using Express / Node.JS?

One way to do this by updating the app.locals variable for that app in app.js

Set via following

var app = express();
app.locals.appName = "DRC on FHIR";

Get / Access

app.listen(3000, function () {
    console.log('[' + app.locals.appName + '] => app listening on port 3001!');
});

Elaborating with a screenshot from @RamRovi example with slight enhancement.

enter image description here

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

<?php 
    $sessionDetails = $this->Session->read('Auth.User');

    if (!empty($sessionDetails)) {


        $loginFlag = 1;
        # code...
    }else{
        $loginFlag =  0;
    }


?>

<script type="text/javascript">

    var sessionValue = '<?php echo $loginFlag; ?>';
    if (sessionValue = 0) {

        //model show
    }
</script>

Selecting distinct values from a JSON

As you can see here, when you have more values there is a better approach.

http://jsfiddle.net/MsYGJ/

temp = {}
// Store each of the elements in an object keyed of of the name field.  If there is a collision (the name already exists) then it is just replaced with the most recent one.
for (var i = 0; i < varjson.DATA.length; i++) {
    temp[varjson.DATA[i].name] = varjson.DATA[i];
}
// Reset the array in varjson
varjson.DATA = [];
// Push each of the values back into the array.
for (var o in temp) {
    varjson.DATA.push(temp[o]);
}

Here we are creating an object with the name as the key. The value is simply the original object from the array. Doing this, each replacement is O(1) and there is no need to check if it already exists. You then pull each of the values out and repopulate the array.

NOTE
For smaller arrays, your approach is slightly faster.

NOTE 2
This will not preserve the original order.

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

You can rewrite code as below :

List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList = sourceLongList.stream().filter(l -> l > 100).collect(Collectors.toList());

How to set up default schema name in JPA configuration?

If you are using (org.springframework.jdbc.datasource.DriverManagerDataSource) in ApplicationContext.xml to specify Database details then use below simple property to specify the schema.

<property name="schema" value="schemaName" />

How would you do a "not in" query with LINQ?

 DynamicWebsiteEntities db = new DynamicWebsiteEntities();
    var data = (from dt_sub in db.Subjects_Details
                                //Sub Query - 1
                            let sub_s_g = (from sg in db.Subjects_In_Group
                                           where sg.GroupId == groupId
                                           select sg.SubjectId)
                            //Where Cause
                            where !sub_s_g.Contains(dt_sub.Id) && dt_sub.IsLanguage == false
                            //Order By Cause
                            orderby dt_sub.Subject_Name

                            select dt_sub)
                           .AsEnumerable();
                  
                                SelectList multiSelect = new SelectList(data, "Id", "Subject_Name", selectedValue);

    //======================================OR===========================================

    var data = (from dt_sub in db.Subjects_Details

                               
                            //Where Cause
                            where !(from sg in db.Subjects_In_Group
                                           where sg.GroupId == groupId
                                           select sg.SubjectId).Contains(dt_sub.Id) && dt_sub.IsLanguage == false

                            //Order By Cause
                            orderby dt_sub.Subject_Name

                            select dt_sub)

                           .AsEnumerable();

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

If you don't care about the data, you can drop database first and then recreate it:

DROP DATABASE IF EXISTS dbname;
CREATE DATABASE dbname;

Multipart File upload Spring Boot

In Controller, your method should be;

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseEntity<SaveResponse> uploadAttachment(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
....

Further, you need to update application.yml (or application.properties) to support maximum file size and request size.

spring:
    http:
        multipart:
            max-file-size: 5MB
            max-request-size: 20MB

Running sites on "localhost" is extremely slow

For people using a mac. When you're using different host names say test.local and test2.local. Try changing test.local to test.dev. I found out that Mac OS X lion controls the .local tld. So when you change it to something else it's faster.

And of course use above suggestions like turning off the ipv6 reference in your hosts file:
#::1 localhost

and setting this in the hosts file: 127.0.0.1 localhost

so it points to ipv4.

json_encode() escaping forward slashes

Yes, but don't - escaping forward slashes is a good thing. When using JSON inside <script> tags it's necessary as a </script> anywhere - even inside a string - will end the script tag.

Depending on where the JSON is used it's not necessary, but it can be safely ignored.

PuTTY scripting to log onto host

For me it works this way:

putty -ssh [email protected] 22 -pw password

putty, protocol, user name @ ip address port and password. To connect in less than a second.

Using ADB to capture the screen

To start recording your device’s screen, run the following command:

adb shell screenrecord /sdcard/example.mp4

This command will start recording your device’s screen using the default settings and save the resulting video to a file at /sdcard/example.mp4 file on your device.

When you’re done recording, press Ctrl+C in the Command Prompt window to stop the screen recording. You can then find the screen recording file at the location you specified. Note that the screen recording is saved to your device’s internal storage, not to your computer.

The default settings are to use your device’s standard screen resolution, encode the video at a bitrate of 4Mbps, and set the maximum screen recording time to 180 seconds. For more information about the command-line options you can use, run the following command:

adb shell screenrecord --help

This works without rooting the device. Hope this helps.

How to insert an object in an ArrayList at a specific position

This method Appends the specified element to the end of this list.

add(E e) //append element to the end of the arraylist.

This method Inserts the specified element at the specified position in this list.

void add(int index, E element) //inserts element at the given position in the array list.

This method Replaces the element at the specified position in this list with the specified element.

set(int index, E element) //Replaces the element at the specified position in this list with the specified element.
      

      

Laravel 5.2 - pluck() method returns array

In the original example, why not use the select() method in your database query?

$name = DB::table('users')->where('name', 'John')->select("id");

This will be faster than using a PHP framework, for it'll utilize the SQL query to do the row selection for you. For ordinary collections, I don't believe this applies, but since you're using a database...

Larvel 5.3: Specifying a Select Clause

Current timestamp as filename in Java

Improving the @Derek Springer post with fill length function:

public static String getFileWithDate(String fileName, String fileSaperator, String dateFormat) {
    String FileNamePrefix = fileName.substring(0, fileName.lastIndexOf(fileSaperator));
    String FileNameSuffix = fileName.substring(fileName.lastIndexOf(fileSaperator)+1, fileName.length());
    //System.out.println("File= Prefix~Suffix:"+FileNamePrefix +"~"+FileNameSuffix);
    
    String newFileName = new SimpleDateFormat("'"+FileNamePrefix+"_'"+dateFormat+"'"+fileSaperator+FileNameSuffix+"'").format(new Date());
    System.out.println("New File:"+newFileName);
    return newFileName;
}

Using the funciton and its Output:

String fileSaperator = ".", format = "yyyyMMMdd_HHmm";
getFileWithDate("Text1.txt", fileSaperator, format);
getFileWithDate("Text1.doc", fileSaperator, format);
getFileWithDate("Text1.txt.json", fileSaperator, format);

Output:

Old File:Text1.txt   New File:Text1_2020Nov11_1807.txt
Old File:Text1.doc   New File:Text1_2020Nov11_1807.doc
Old File:Text1.txt.json  New File:Text1.txt_2020Nov11_1807.json

How to forward declare a template class in namespace std?

there is a limited alternative you can use

header:

class std_int_vector;

class A{
    std_int_vector* vector;
public:
    A();
    virtual ~A();
};

cpp:

#include "header.h"
#include <vector>
class std_int_vector: public std::vectror<int> {}

A::A() : vector(new std_int_vector()) {}
[...]

not tested in real programs, so expect it to be non-perfect.

How to send push notification to web browser?

May I redefine you question as below

Can we have our own back-end to send push notification to Chrome, Firefox, Opera & Safari?

Yes. By today (2017/05), you can use same client and server side implementation to handle Chrome, Firefox and Opera (no Safari). Because they have implemented web push notifications in a same way. That is Push API protocol by W3C. But Safari have their own old architecture. So we have to maintain Safari separately.

Refer browser-push repo for guide lines to implement web push notification for your web-app with your own back-end. It explains with examples how you can add web push notification support for your web application without any third party services.

JavaScript - Get Portion of URL Path

window.location.href.split('/');

Will give you an array containing all the URL parts, which you can access like a normal array.

Or an ever more elegant solution suggested by @Dylan, with only the path parts:

window.location.pathname.split('/');

Find out a Git branch creator

You can find out who created a branch in your local repository by

git reflog --format=full

Example output:

commit e1dd940
Reflog: HEAD@{0} (a <a@none>)
Reflog message: checkout: moving from master to b2
Author: b <b.none>
Commit: b <b.none>
(...)

But this is probably useless as typically on your local repository only you create branches.

The information is stored at ./.git/logs/refs/heads/branch. Example content:

0000000000000000000000000000000000000000 e1dd9409c4ba60c28ad9e7e8a4b4c5ed783ba69b a <a@none> 1438788420 +0200   branch: Created from HEAD

The last commit in this example was from user "b" while the branch "b2" was created by user "a". If you change your username you can verify that git reflog takes the information from the log and does not use the local user.

I don't know about any possibility to transmit that local log information to a central repository.

Defining arrays in Google Scripts

I think that maybe it is because you are declaring a variable that you already declared:

var Name = new Array(6);
//...
var Name[0] = Name_cell.getValue();  //  <-- Here's the issue: 'var'

I think this should be like this:

var Name = new Array(6);
//...
Name[0] = Name_cell.getValue();

Tell me if it works! ;)

gcc-arm-linux-gnueabi command not found

I was also facing the same issue and resolved it after installing the following dependency:

sudo apt-get install lib32z1-dev

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

FWIW, sp_test will not be returning anything but an integer (all SQL Server stored procs just return an integer) and no result sets on the wire (since no SELECT statements). To get the output of the PRINT statements, you normally use the InfoMessage event on the connection (not the command) in ADO.NET.

Unsupported major.minor version 52.0 when rendering in Android Studio

Make sure to do a clean build after changing a version of Java. As it turns out Android Studio does some work when you switch the JDK but doesn't clean the workspace and creates confusion ¯\_(?)_/¯

AngularJs: How to set radio button checked based on model

Ended up just using the built-in angular attribute ng-checked="model"

How to move Jenkins from one PC to another

Jenkins Server Automation:

Step 1:

Set up a repository to store the Jenkins home (jobs, configurations, plugins, etc.) in a GitLab local or on GitHub private repository and keep it updated regularly by pushing any new changes to Jenkins jobs, plugins, etc.

Step 2:

Configure a Puppet host-group/role for Jenkins that can be used to spin up new Jenkins servers. Do all the basic configuration in a Puppet recipe and make sure it installs the latest version of Jenkins and sets up a separate directory/mount for JENKINS_HOME.

Step 3:

Spin up a new machine using the Jenkins-puppet configuration above. When everything is installed, grab/clone the Jenkins configuration from the Git repository to the Jenkins home direcotry and restart Jenkins.

Step 4:

Go to the Jenkins URL, Manage Jenkins ? Manage Plugins and update all the plugins that require an update.

Done

You can use Docker Swarm or Kubernetes to auto-scale the slave nodes.

LINQ equivalent of foreach for IEnumerable<T>

MoreLinq has IEnumerable<T>.ForEach and a ton of other useful extensions. It's probably not worth taking the dependency just for ForEach, but there's a lot of useful stuff in there.

https://www.nuget.org/packages/morelinq/

https://github.com/morelinq/MoreLINQ

What is git tag, How to create tags & How to checkout git remote tag(s)

In order to checkout a git tag , you would execute the following command

git checkout tags/tag-name -b branch-name

eg as mentioned below.

 git checkout tags/v1.0 -b v1.0-branch

To fetch the all tags use the command

git fetch --all --tags

How to return multiple values?

You can do something like this:

public class Example
{
    public String name;
    public String location;

    public String[] getExample()
    {
        String ar[] = new String[2];
        ar[0]= name;
        ar[1] =  location;
        return ar; //returning two values at once
    }
}

Is there an easy way to convert Android Application to IPad, IPhone

I'm not sure how helpful this answer is for your current application, but it may prove helpful for the next applications that you will be developing.

As iOS does not use Java like Android, your options are quite limited:

1) if your application is written mostly in C/C++ using JNI, you can write a wrapper and interface it with the iOS (i.e. provide callbacks from iOS to your JNI written function). There may be frameworks out there that help you do this easier, but there's still the problem of integrating the application and adapting it to the framework (and of course the fact that the application has to be written in C/C++).

2) rewrite it for iOS. I don't know whether there are any good companies that do this for you. Also, due to the variety of applications that can be written which can use different services and API, there may not be any software that can port it for you (I guess this kind of software is like a gold mine heh) or do a very good job at that.

3) I think that there are Java->C/C++ converters, but there won't help you at all when it comes to API differences. Also, you may find yourself struggling more to get the converted code working on any of the platforms rather than rewriting your application from scratch for iOS.

The problem depends quite a bit on the services and APIs your application is using. I haven't really look this up, but there may be some APIs that provide certain functionality in Android that iOS doesn't provide.

Using C/C++ and natively compiling it for the desired platform looks like the way to go for Android-iOS-Win7Mobile cross-platform development. This gets you somewhat of an application core/kernel which you can use to do the actual application logic.

As for the OS specific parts (APIs) that your application is using, you'll have to set up communication interfaces between them and your application's core.

Limit the length of a string with AngularJS

This solution is purely using ng tag on HTML.

The solution is to limit the long text displayed with 'show more...' link at the end of it. If user click 'show more...' link, it will show the rest of the text and removed the 'show more...' link.

HTML:

<div ng-init="limitText=160">
   <p>{{ veryLongText | limitTo: limitText }} 
       <a href="javascript:void(0)" 
           ng-hide="veryLongText.length < limitText" 
           ng-click="limitText = veryLongText.length + 1" > show more..
       </a>
   </p>
</div>

Using scanner.nextLine()

I think your problem is that

int selection = scanner.nextInt();

reads just the number, not the end of line or anything after the number. When you declare

String sentence = scanner.nextLine();

This reads the remainder of the line with the number on it (with nothing after the number I suspect)

Try placing a scanner.nextLine(); after each nextInt() if you intend to ignore the rest of the line.

Checking for empty or null JToken in a JObject

There is also a type - JTokenType.Undefined.

This check must be included in @Brian Rogers answer.

token.Type == JTokenType.Undefined

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

For those who encounter this when you just recently updated IntelliJ (In my case 2019.2).

I am using JBoss server so i tried to run standalone.bat in the command line and I saw the real issue on the console.

It can be different to yours, but in my case I saw:

failure description: "WFLYSRV0137: No deployment content with

And on that error I was able to fix this by removing the items (war or ear) inside the <deployments/> node in my standalone.xml

Hope this helps for those using JBoss+IntelliJ

Inserting created_at data with Laravel

$data = array();
$data['created_at'] =new \DateTime();
DB::table('practice')->insert($data);

How to find if an array contains a string

Using the code from my answer to a very similar question:

Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range

Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"

For Each cell In Selection
  If IsInArray(cell.Value, MainFram) Then
    Row(cell.Row).Style = "Accent1"
  End If
Next cell

End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

This problem has been addressed in ASP.Net MVC 3. They now automatically convert underscores in html attribute properties to dashes. They got lucky on this one, as underscores are not legal in html attributes, so MVC can confidently imply that you'd like a dash when you use an underscore.

For example:

@Html.TextBoxFor(vm => vm.City, new { data_bind = "foo" })

will render this in MVC 3:

<input data-bind="foo" id="City" name="City" type="text" value="" />

If you're still using an older version of MVC, you can mimic what MVC 3 is doing by creating this static method that I borrowed from MVC3's source code:

public class Foo {
    public static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes) {
        RouteValueDictionary result = new RouteValueDictionary();
        if (htmlAttributes != null) {
            foreach (System.ComponentModel.PropertyDescriptor property in System.ComponentModel.TypeDescriptor.GetProperties(htmlAttributes)) {
                result.Add(property.Name.Replace('_', '-'), property.GetValue(htmlAttributes));
            }
        }
        return result;
    }
}

And then you can use it like this:

<%: Html.TextBoxFor(vm => vm.City, Foo.AnonymousObjectToHtmlAttributes(new { data_bind = "foo" })) %>

and this will render the correct data-* attribute:

<input data-bind="foo" id="City" name="City" type="text" value="" />

How to check Network port access and display useful message?

With the latest versions of PowerShell, there is a new cmdlet, Test-NetConnection.

This cmdlet lets you, in effect, ping a port, like this:

Test-NetConnection -ComputerName <remote server> -Port nnnn

I know this is an old question, but if you hit this page (as I did) looking for this information, this addition may be helpful!

How to git-svn clone the last n revisions from a Subversion repository?

... 7 years later, in the desert, a tumbleweed blows by ...

I wasn't satisfied with the accepted answer so I created some scripts to do this for you available on Github. These should help anyone who wants to use git svn clone but doesn't want to clone the entire repository and doesn't want to hunt for a specific revision to clone from in the middle of the history (maybe you're cloning a bunch of repos). Here we can just clone the last N revisions:

Use git svn clone to clone the last 50 revisions

# -u    The SVN URL to clone
# -l    The limit of revisions
# -o    The output directory

./git-svn-cloneback.sh -u https://server/project/trunk -l 50 -o myproj --authors-file=svn-authors.txt

Find the previous N revision from an SVN repo

# -u    The SVN URL to clone
# -l    The limit of revisions

./svn-lookback.sh -u https://server/project/trunk -l 5     

Visual Studio Code cannot detect installed git

In my case GIT was installed on my WIndows 10 OS and there was an entry in PATH variable. But VS CODE 1.52.1 still unable to detect it from terminal window but it was available in CMD console.

Problem was solved by switching terminal from PowerShell to CMD or Shell + VsCode restart.

How do I write a RGB color value in JavaScript?

this is better function

function RGB2HTML(red, green, blue)
{
    var decColor =0x1000000+ blue + 0x100 * green + 0x10000 *red ;
    return '#'+decColor.toString(16).substr(1);
}

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

The official way to detect .NET 3.0 is described here

http://msdn.microsoft.com/en-us/library/aa480198.aspx

Flawed, because it requires the caller to have registry access permissions.

MSDN also mentions a technique for detecting .NET 3.5 by checking the User Agent string:

http://msdn.microsoft.com/en-us/library/bb909885.aspx

I think Microsoft should have done a better job than this.

How to create a directory using Ansible

you can use the "file" module in this case, there are so many arguments that you can pass for a newly created directory like the owner, group, location, mode and so on.....

please refer to this document for the detailed explanation on the file module...

https://docs.ansible.com/ansible/latest/modules/file_module.html#file-module

remember this module is not just for creating the directory !!!

How to Change Margin of TextView

Here is another approach...

When I've got to the same problem, I didn't like the suggested solutions here. So, I've come up with another way: I've inserted a TextView in the XML file between the two fields I wanted to separate with two important fields:

  1. visibility set to "GONE" (doesn't occupy any space..)
  2. height is set to whatever I needed the separation to be.

    XML:
    ...//some view up here
    <TextView
        android:id="@+id/dialogSeparator"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:visibility="gone"/>
    ...//some view down here
    

Now, I the code, all I needed to do it simple change the visibility to invisible (i.e. it's there, and taking the needed space, but it's unseen)

    JAVA:

    TextView tvSeparator = (TextView)activity.findViewById(R.id.dialogSeparator);
    tvSeparator.setVisibility(View.INVISIBLE);
    //Inside an activity extended class I can use 'this' instead of 'activity'.

Viola...I got the needed margin. BTW, This solution is for LinearLayout with vertical orientation, but you can do it with different layouts.

Hope this helps.

TOMCAT - HTTP Status 404

You don't have to use Tomcat installation as a server location. It is much easier just to copy the files in the ROOT folder.

Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.8\webapps, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like your-eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or ../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

Source: HTTP Status 404 error in tomcat

Image resolution for mdpi, hdpi, xhdpi and xxhdpi

in order to know the phone resolution simply create a image with label mdpi, hdpi, xhdpi and xxhdpi. put these images in respective folder like mdpi, hdpi, xhdpi and xxhdpi. create a image view in layout and load this image. the phone will load the respective image from a specific folder. by this you will get the phone resolution or *dpi it is using.

Facebook page automatic "like" URL (for QR Code)

Have you tried using the fb:// protocol?

To have them like your page when they scan the qr code, it goes like this:

fb://page/(pageID)/addfan

If you need to get the pageID, replace "www" with "graph" in the Facebook url when you visit your page in a desktop browser and it will display the ID and other data.

Not only does this add them automatically, but it opens up the page in the FB app instead of the mobile browser.

As far as legality, I would assume as long as you put something like "Scan to like our page", you're in the clear. They know what they're getting into.

In-place edits with sed on OS X

This creates backup files. E.g. sed -i -e 's/hello/hello world/' testfile for me, creates a backup file, testfile-e, in the same dir.

Getting error in console : Failed to load resource: net::ERR_CONNECTION_RESET

I think you are using chrome. The problem is the certificate mismatch or the expiration of the certificate.Check your certificate properly.

Just visit here for more information.

Displaying the Error Messages in Laravel after being Redirected from controller

$validator = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required', ]);

if ($validator->fails()) { return $validator->errors(); }

How to make an ImageView with rounded corners?

Props to George Walters II above, I just took his answer and extended it a bit to support rounding individual corners differently. This could be optimized a bit further (some of the target rects overlap), but not a whole lot.

I know this thread is a bit old, but its one of the top results for queries on Google for how to round corners of ImageViews on Android.

/**
 * Use this method to scale a bitmap and give it specific rounded corners.
 * @param context Context object used to ascertain display density.
 * @param bitmap The original bitmap that will be scaled and have rounded corners applied to it.
 * @param upperLeft Corner radius for upper left.
 * @param upperRight Corner radius for upper right.
 * @param lowerRight Corner radius for lower right.
 * @param lowerLeft Corner radius for lower left.
 * @param endWidth Width to which to scale original bitmap.
 * @param endHeight Height to which to scale original bitmap.
 * @return Scaled bitmap with rounded corners.
 */
public static Bitmap getRoundedCornerBitmap(Context context, Bitmap bitmap, float upperLeft,
        float upperRight, float lowerRight, float lowerLeft, int endWidth,
        int endHeight) {
    float densityMultiplier = context.getResources().getDisplayMetrics().density;

    // scale incoming bitmap to appropriate px size given arguments and display dpi
    bitmap = Bitmap.createScaledBitmap(bitmap, 
            Math.round(endWidth * densityMultiplier),
            Math.round(endHeight * densityMultiplier), true);

    // create empty bitmap for drawing
    Bitmap output = Bitmap.createBitmap(
            Math.round(endWidth * densityMultiplier),
            Math.round(endHeight * densityMultiplier), Config.ARGB_8888);

    // get canvas for empty bitmap
    Canvas canvas = new Canvas(output);
    int width = canvas.getWidth();
    int height = canvas.getHeight();

    // scale the rounded corners appropriately given dpi
    upperLeft *= densityMultiplier;
    upperRight *= densityMultiplier;
    lowerRight *= densityMultiplier;
    lowerLeft *= densityMultiplier;

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(Color.WHITE);

    // fill the canvas with transparency
    canvas.drawARGB(0, 0, 0, 0);

    // draw the rounded corners around the image rect. clockwise, starting in upper left.
    canvas.drawCircle(upperLeft, upperLeft, upperLeft, paint);
    canvas.drawCircle(width - upperRight, upperRight, upperRight, paint);
    canvas.drawCircle(width - lowerRight, height - lowerRight, lowerRight, paint);
    canvas.drawCircle(lowerLeft, height - lowerLeft, lowerLeft, paint);

    // fill in all the gaps between circles. clockwise, starting at top.
    RectF rectT = new RectF(upperLeft, 0, width - upperRight, height / 2);
    RectF rectR = new RectF(width / 2, upperRight, width, height - lowerRight);
    RectF rectB = new RectF(lowerLeft, height / 2, width - lowerRight, height);
    RectF rectL = new RectF(0, upperLeft, width / 2, height - lowerLeft);

    canvas.drawRect(rectT, paint);
    canvas.drawRect(rectR, paint);
    canvas.drawRect(rectB, paint);
    canvas.drawRect(rectL, paint);

    // set up the rect for the image
    Rect imageRect = new Rect(0, 0, width, height);

    // set up paint object such that it only paints on Color.WHITE
    paint.setXfermode(new AvoidXfermode(Color.WHITE, 255, AvoidXfermode.Mode.TARGET));

    // draw resized bitmap onto imageRect in canvas, using paint as configured above
    canvas.drawBitmap(bitmap, imageRect, imageRect, paint);

    return output;
}

Passing event and argument to v-on in Vue.js

Depending on what arguments you need to pass, especially for custom event handlers, you can do something like this:

<div @customEvent='(arg1) => myCallback(arg1, arg2)'>Hello!</div>

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

How do I turn off the mysql password validation?

I was having a problem on Ubuntu 18.04 on Mysql. When I needed to create a new user, the policy was always high.

The way I figured out how to disable, for future colleagues who come to investigate, was set to low.

Login to the mysql server as root

mysql -h localhost -u root -p

Set the new type of validation

SET GLOBAL validate_password_policy=0; //For Low

Restart mysql

sudo service mysql restart

How to use vagrant in a proxy environment?

If your proxy requires authentication it is better to set the environment variable rather than storing your password in the Vagrantfile. Also your Vagrantfile can be used by others easily who are not behind a proxy.

For Mac/Linux (in Bash)

export http_proxy="http://user:password@host:port"
export https_proxy="http://user:password@host:port"
vagrant plugin install vagrant-proxyconf

then

export VAGRANT_HTTP_PROXY=${http_proxy}
export VAGRANT_HTTPS_PROXY=${https_proxy}
export VAGRANT_NO_PROXY="127.0.0.1"
vagrant up

For Windows use set instead of export.

set http_proxy=http://user:password@host:port
set https_proxy=https://user:password@host:port
vagrant plugin install vagrant-proxyconf

then

set VAGRANT_HTTP_PROXY=%http_proxy%
set VAGRANT_HTTPS_PROXY=%https_proxy%
set VAGRANT_NO_PROXY="127.0.0.1"
vagrant up

How do I protect javascript files?

As I said in the comment I left on gion_13 answer before (please read), you really can't. Not with javascript.

If you don't want the code to be available client-side (= stealable without great efforts), my suggestion would be to make use of PHP (ASP,Python,Perl,Ruby,JSP + Java-Servlets) that is processed server-side and only the results of the computation/code execution are served to the user. Or, if you prefer, even Flash or a Java-Applet that let client-side computation/code execution but are compiled and thus harder to reverse-engine (not impossible thus).

Just my 2 cents.

Does Python support short-circuiting?

Yes. Try the following in your python interpreter:

and

>>>False and 3/0
False
>>>True and 3/0
ZeroDivisionError: integer division or modulo by zero

or

>>>True or 3/0
True
>>>False or 3/0
ZeroDivisionError: integer division or modulo by zero

Where does Java's String constant pool live, the heap or the stack?

To the great answers that already included here I want to add something that missing in my perspective - an illustration.

As you already JVM divides the allocated memory to a Java program into two parts. one is stack and another one is heap. Stack is used for execution purpose and heap is used for storage purpose. In that heap memory, JVM allocates some memory specially meant for string literals. This part of the heap memory is called string constants pool.

So for example, if you init the following objects:

String s1 = "abc"; 
String s2 = "123";
String obj1 = new String("abc");
String obj2 = new String("def");
String obj3 = new String("456);

String literals s1 and s2 will go to string constant pool, objects obj1, obj2, obj3 to the heap. All of them, will be referenced from the Stack.

Also, please note that "abc" will appear in heap and in string constant pool. Why is String s1 = "abc" and String obj1 = new String("abc") will be created this way? It's because String obj1 = new String("abc") explicitly creates a new and referentially distinct instance of a String object and String s1 = "abc" may reuse an instance from the string constant pool if one is available. For a more elaborate explanation: https://stackoverflow.com/a/3298542/2811258

enter image description here

pandas three-way joining multiple dataframes on columns

I tweaked the accepted answer to perform the operation for multiple dataframes on different suffix parameters using reduce and i guess it can be extended to different on parameters as well.

from functools import reduce 

dfs_with_suffixes = [(df2,suffix2), (df3,suffix3), 
                     (df4,suffix4)]

merge_one = lambda x,y,sfx:pd.merge(x,y,on=['col1','col2'..], suffixes=sfx)

merged = reduce(lambda left,right:merge_one(left,*right), dfs_with_suffixes, df1)

Generate Controller and Model

Laravel 5

The other answers are great for Laravel 4 but Laravel 5 is here! We now have the ability to generate all kinds of stuff by default. Run php artisan help to view all artisan commands. Here are all of the make commands:

make
  make:command         Create a new command class
  make:console         Create a new Artisan command
  make:controller      Create a new resource controller class
  make:event           Create a new event class
  make:middleware      Create a new middleware class
  make:migration       Create a new migration file
  make:model           Create a new Eloquent model class
  make:provider        Create a new service provider class
  make:request         Create a new form request class

Note: we no longer use item:make. Instead we now have make:item.

Run php artisan help make:item to see what you can pass it. For instance php artisan help make:migration shows that we need to pass it the migration name but we can also pass it --create="" or --table="" to specify the table name to create or modify respectively. Run php artisan make:migration create_articles_table --create="articles" to generate the articles table. Moreover, generating models takes care of generating the migration for that model. Follow the naming conventions and it will be pluralized it for the migration.

How to zoom in/out an UIImage object when user pinches screen?

Keep in mind that you're NEVER zooming in on a UIImage. EVER.

Instead, you're zooming in and out on the view that displays the UIImage.

In this particular case, you chould choose to create a custom UIView with custom drawing to display the image, a UIImageView which displays the image for you, or a UIWebView which will need some additional HTML to back it up.

In all cases, you'll need to implement touchesBegan, touchesMoved, and the like to determine what the user is trying to do (zoom, pan, etc.).

Add an index (numeric ID) column to large data frame

If your data.frame is a data.table, you can use special symbol .I:

data[, ID := .I]

How to calculate age (in years) based on Date of Birth and getDate()

Just check whether the below answer is feasible.

DECLARE @BirthDate DATE = '09/06/1979'

SELECT 
 (
 YEAR(GETDATE()) - YEAR(@BirthDate) - 
 CASE  WHEN (MONTH(GETDATE()) * 100) + DATEPART(dd, GETDATE()) >     
 (MONTH(@BirthDate) * 100) + DATEPART(dd, @BirthDate)
 THEN 1             
 ELSE 0             
 END        
 )

React Native android build failed. SDK location not found

In your Project Directory there is a folder called "android" and inside it there is the local.properties file . Delete the file and the build should run successfully

Executing a stored procedure within a stored procedure

Here is an example of one of our stored procedures that executes multiple stored procedures within it:

ALTER PROCEDURE [dbo].[AssetLibrary_AssetDelete]
(
    @AssetID AS uniqueidentifier
)
AS

SET NOCOUNT ON

SET TRANSACTION ISOLATION LEVEL READ COMMITTED

EXEC AssetLibrary_AssetDeleteAttributes @AssetID
EXEC AssetLibrary_AssetDeleteComponents @AssetID
EXEC AssetLibrary_AssetDeleteAgreements @AssetID
EXEC AssetLibrary_AssetDeleteMaintenance @AssetID

DELETE FROM
    AssetLibrary_Asset
WHERE
    AssetLibrary_Asset.AssetID = @AssetID

RETURN (@@ERROR)

Oracle PL Sql Developer cannot find my tnsnames.ora file

You most certainly have a databases tab in sql developer (all versions I've used in the past have this). Maybe check again? Perhaps, you're looking in the wrong location.

On a mac, the preferences is under "Oracle SQL Developer" (top left) -> Preferences -> Database -> Advanced -> section called Tnsnames Directory is where you specify the file.

On windows (going from memory so might have to search if this isn't correct) Tools -> Preferences -> Database -> Advanced -> section called Tnsnames Directory is where you specify the file.

See this image enter image description here

Where do I find the line number in the Xcode editor?

For Xcode 4 and higher, open the preferences (command+,) and check "Show: Line numbers" in the "Text Editing" section.

Xcode 9 enter image description here

Xcode 8 and below Xcode Text Editing Preferences screen capture with Text Editing and Line Numbers highlighted

Excel Reference To Current Cell

I found the best way to handle this (for me) is to use the following:

Dim MyString as String
MyString = Application.ThisCell.Address
Range(MyString).Select

Hope this helps.

Can't get Gulp to run: cannot find module 'gulp-util'

You should install these as devDependencies:
- gulp-util
- gulp-load-plugins

Then, you can use them either this way:

var plugins     = require('gulp-load-plugins')();
Use gulp-util as : plugins.util()

or this:

var util = require('gulp-util')

How to merge 2 JSON objects from 2 files using jq?

Use jq -s add:

$ echo '{"a":"foo","b":"bar"} {"c":"baz","a":0}' | jq -s add
{
  "a": 0,
  "b": "bar",
  "c": "baz"
}

This reads all JSON texts from stdin into an array (jq -s does that) then it "reduces" them.

(add is defined as def add: reduce .[] as $x (null; . + $x);, which iterates over the input array's/object's values and adds them. Object addition == merge.)

How to create a new text file using Python

Looks like you forgot the mode parameter when calling open, try w:

file = open("copy.txt", "w") 
file.write("Your text goes here") 
file.close() 

The default value is r and will fail if the file does not exist

'r' open for reading (default)
'w' open for writing, truncating the file first

Other interesting options are

'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists

See Doc for Python2.7 or Python3.6

-- EDIT --

As stated by chepner in the comment below, it is better practice to do it with a withstatement (it guarantees that the file will be closed)

with open("copy.txt", "w") as file:
    file.write("Your text goes here")

LINQ query to return a Dictionary<string, string>

Use the ToDictionary method directly.

var result = 
  // as Jon Skeet pointed out, OrderBy is useless here, I just leave it 
  // show how to use OrderBy in a LINQ query
  myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
                   .ToDictionary(mc => mc.KeyProp.ToString(), 
                                 mc => mc.ValueProp.ToString(), 
                                 StringComparer.OrdinalIgnoreCase);

How can one print a size_t variable portably using the printf family?

Looks like it varies depending on what compiler you're using (blech):

...and of course, if you're using C++, you can use cout instead as suggested by AraK.

How to convert java.lang.Object to ArrayList?

I hope this will be help you

import java.util.ArrayList; 
public class Demo {

 public static void main(String[] args) {
    Object obj2 =null;
    ArrayList al1 = (ArrayList) obj2;
    al1 = (ArrayList) obj2;
    System.out.println("List2 Value: " + al1);
    }
 }

obj2 Object is default null before you cast it to ArrayList. That's why print 'al1' as null.

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

I know this is an old question but I came across it while trying to solve this same issue. I thought it'd be worth sharing this solution I hadn't found anywhere else.

Basically the solution is to use CSS to hide the <input> element and style a <label> around it to look like a button. Click the 'Run code snippet' button to see the results.

I had used a JavaScript solution before that worked fine too but it is nice to solve a 'presentation' issue with just CSS.

_x000D_
_x000D_
label.cameraButton {_x000D_
  display: inline-block;_x000D_
  margin: 1em 0;_x000D_
_x000D_
  /* Styles to make it look like a button */_x000D_
  padding: 0.5em;_x000D_
  border: 2px solid #666;_x000D_
  border-color: #EEE #CCC #CCC #EEE;_x000D_
  background-color: #DDD;_x000D_
}_x000D_
_x000D_
/* Look like a clicked/depressed button */_x000D_
label.cameraButton:active {_x000D_
  border-color: #CCC #EEE #EEE #CCC;_x000D_
}_x000D_
_x000D_
/* This is the part that actually hides the 'Choose file' text box for camera inputs */_x000D_
label.cameraButton input[accept*="camera"] {_x000D_
  display: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Nice image capture button</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <label class="cameraButton">Take a picture_x000D_
    <input type="file" accept="image/*;capture=camera">_x000D_
  </label>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

What does $_ mean in PowerShell?

$_ is an alias for automatic variable $PSItem (introduced in PowerShell V3.0; Usage information found here) which represents the current item from the pipe.

PowerShell (v6.0) online documentation for automatic variables is here.

pandas dataframe create new columns and fill with calculated values from same df

In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])

In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]: 
          A         B         C         D
1  0.319124  0.296653  0.138206  0.246017
2  0.376994  0.326481  0.230464  0.066062
3  0.036134  0.192954  0.430341  0.340571

How to decompile to java files intellij idea

You could use one of these (you can both use them online or download them, there is some info about each of them) : http://www.javadecompilers.com/

The one IntelliJ IDEA uses is fernflower, but it can't handle recent things - like String/Enum switches, generics (didn't test this one personally, only read about it), ... I just tried cfr from the above website and the result was the same as with the built-in decompiler (except for the Enum switch I had in my class).

Does Git Add have a verbose switch

For some git-commands you can specify --verbose,

git 'command' --verbose

or

git 'command' -v.

Make sure the switch is after the actual git command. Otherwise - it won't work!

Also useful:

git 'command' --dry-run 

Change value of input placeholder via model?

As Wagner Francisco said, (in JADE)

input(type="text", ng-model="someModel", placeholder="{{someScopeVariable}}")`

And in your controller :

$scope.someScopeVariable = 'somevalue'

Play multiple CSS animations at the same time

you can try something like this

set the parent to rotate and the image to scale so that the rotate and scale time can be different

_x000D_
_x000D_
div {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  width: 120px;_x000D_
  height: 120px;_x000D_
  margin: -60px 0 0 -60px;_x000D_
  -webkit-animation: spin 2s linear infinite;_x000D_
}_x000D_
.image {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  width: 120px;_x000D_
  height: 120px;_x000D_
  margin: -60px 0 0 -60px;_x000D_
  -webkit-animation: scale 4s linear infinite;_x000D_
}_x000D_
@-webkit-keyframes spin {_x000D_
  100% {_x000D_
    transform: rotate(180deg);_x000D_
  }_x000D_
}_x000D_
@-webkit-keyframes scale {_x000D_
  100% {_x000D_
    transform: scale(2);_x000D_
  }_x000D_
}
_x000D_
<div>_x000D_
  <img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why cannot change checkbox color whatever I do?

One line of CSS is enough using hue-rotate filter. You can change their sizes with transform: scale() as well.

.checkbox { filter: hue-rotate(0deg) }

Codepen

_x000D_
_x000D_
.c1 { filter: hue-rotate(0deg)   }
.c2 { filter: hue-rotate(30deg)  }
.c3 { filter: hue-rotate(60deg)  }
.c4 { filter: hue-rotate(90deg)  }
.c5 { filter: hue-rotate(120deg) }
.c6 { filter: hue-rotate(150deg) }
.c7 { filter: hue-rotate(180deg) }
.c8 { filter: hue-rotate(210deg) }
.c9 { filter: hue-rotate(240deg) }

input[type=checkbox] {
  transform: scale(2);
  margin: 10px;
  cursor: pointer;
}

/* Prevent cursor being `text` between checkboxes */
body { cursor: default }
_x000D_
<input type="checkbox" class="c1" />
<input type="checkbox" class="c2" />
<input type="checkbox" class="c3" />
<input type="checkbox" class="c4" />
<input type="checkbox" class="c5" />
<input type="checkbox" class="c6" />
<input type="checkbox" class="c7" />
<input type="checkbox" class="c8" />
<input type="checkbox" class="c9" />
_x000D_
_x000D_
_x000D_

How to add an extra column to a NumPy array

np.insert also serves the purpose.

matA = np.array([[1,2,3], 
                 [2,3,4]])
idx = 3
new_col = np.array([0, 0])
np.insert(matA, idx, new_col, axis=1)

array([[1, 2, 3, 0],
       [2, 3, 4, 0]])

It inserts values, here new_col, before a given index, here idx along one axis. In other words, the newly inserted values will occupy the idx column and move what were originally there at and after idx backward.

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

I just wanted to provide a bit of an update/special case since it looks like people still come here. If you're using a multi-index or otherwise using an index-slicer the inplace=True option may not be enough to update the slice you've chosen. For example in a 2x2 level multi-index this will not change any values (as of pandas 0.15):

idx = pd.IndexSlice
df.loc[idx[:,mask_1],idx[mask_2,:]].fillna(value=0,inplace=True)

The "problem" is that the chaining breaks the fillna ability to update the original dataframe. I put "problem" in quotes because there are good reasons for the design decisions that led to not interpreting through these chains in certain situations. Also, this is a complex example (though I really ran into it), but the same may apply to fewer levels of indexes depending on how you slice.

The solution is DataFrame.update:

df.update(df.loc[idx[:,mask_1],idx[[mask_2],:]].fillna(value=0))

It's one line, reads reasonably well (sort of) and eliminates any unnecessary messing with intermediate variables or loops while allowing you to apply fillna to any multi-level slice you like!

If anybody can find places this doesn't work please post in the comments, I've been messing with it and looking at the source and it seems to solve at least my multi-index slice problems.

How do I use CREATE OR REPLACE?

You can use CORT (www.softcraftltd.co.uk/cort). This tool allows to CREATE OR REPLACE table in Oracle. It looks like:

create /*# or replace */ table MyTable(
  ... -- standard table definition
);

It preserves data.

Else clause on Python while statement

The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed.

One way to think about it is as an if/else construct with respect to the condition:

if condition:
    handle_true()
else:
    handle_false()

is analogous to the looping construct:

while condition:
    handle_true()
else:
    # condition is false now, handle and go on with the rest of the program
    handle_false()

An example might be along the lines of:

while value < threshold:
    if not process_acceptable_value(value):
        # something went wrong, exit the loop; don't pass go, don't collect 200
        break
    value = update(value)
else:
    # value >= threshold; pass go, collect 200
    handle_threshold_reached()

Is it possible to opt-out of dark mode on iOS 13?

According to Apple's session on "Implementing Dark Mode on iOS" (https://developer.apple.com/videos/play/wwdc2019/214/ starting at 31:13) it is possible to set overrideUserInterfaceStyle to UIUserInterfaceStyleLight or UIUserInterfaceStyleDark on any view controller or view, which will the be used in the traitCollection for any subview or view controller.

As already mentioned by SeanR, you can set UIUserInterfaceStyle to Light or Dark in your app's plist file to change this for your whole app.

Translating touch events from Javascript to jQuery

$(window).on("touchstart", function(ev) {
    var e = ev.originalEvent;
    console.log(e.touches);
});

I know it been asked a long time ago, but I thought a concrete example might help.

Read user input inside a loop

Try to change the loop like this:

for line in $(cat filename); do
    read input
    echo $input;
done

Unit test:

for line in $(cat /etc/passwd); do
    read input
    echo $input;
    echo "[$line]"
done

What processes are using which ports on unix?

netstat -pln

EDIT: linux only, on other UNIXes netstat may not support all these options.

How to check the Angular version?

ng v

Simply run the command above in terminal.

How to list containers in Docker

Note that some time ago there was an update to this command. It will not show the container size by default (since this is rather expensive for many running containers). Use docker ps -s to display container size as well.

JavaScriptSerializer.Deserialize - how to change field names

For those who don't want to go for Newtonsoft Json.Net or DataContractJsonSerializer for some reason (I can't think of any :) ), here is an implementation of JavaScriptConverter that supports DataContract and enum to string conversion -

    public class DataContractJavaScriptConverter : JavaScriptConverter
    {
        private static readonly List<Type> _supportedTypes = new List<Type>();

        static DataContractJavaScriptConverter()
        {
            foreach (Type type in Assembly.GetExecutingAssembly().DefinedTypes)
            {
                if (Attribute.IsDefined(type, typeof(DataContractAttribute)))
                {
                    _supportedTypes.Add(type);
                }
            }
        }

        private bool ConvertEnumToString = false;

        public DataContractJavaScriptConverter() : this(false)
        {
        }

        public DataContractJavaScriptConverter(bool convertEnumToString)
        {
            ConvertEnumToString = convertEnumToString;
        }

        public override IEnumerable<Type> SupportedTypes
        {
            get { return _supportedTypes; }
        }

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (Attribute.IsDefined(type, typeof(DataContractAttribute)))
            {
                try
                {
                    object instance = Activator.CreateInstance(type);

                    IEnumerable<MemberInfo> members = ((IEnumerable<MemberInfo>)type.GetFields())
                        .Concat(type.GetProperties().Where(property => property.CanWrite && property.GetIndexParameters().Length == 0))
                        .Where((member) => Attribute.IsDefined(member, typeof(DataMemberAttribute)));
                    foreach (MemberInfo member in members)
                    {
                        DataMemberAttribute attribute = (DataMemberAttribute)Attribute.GetCustomAttribute(member, typeof(DataMemberAttribute));
                        object value;
                        if (dictionary.TryGetValue(attribute.Name, out value) == false)
                        {
                            if (attribute.IsRequired)
                            {
                                throw new SerializationException(String.Format("Required DataMember with name {0} not found", attribute.Name));
                            }
                            continue;
                        }
                        if (member.MemberType == MemberTypes.Field)
                        {
                            FieldInfo field = (FieldInfo)member;
                            object fieldValue;
                            if (ConvertEnumToString && field.FieldType.IsEnum)
                            {
                                fieldValue = Enum.Parse(field.FieldType, value.ToString());
                            }
                            else
                            {
                                fieldValue = serializer.ConvertToType(value, field.FieldType);
                            }
                            field.SetValue(instance, fieldValue);
                        }
                        else if (member.MemberType == MemberTypes.Property)
                        {
                            PropertyInfo property = (PropertyInfo)member;
                            object propertyValue;
                            if (ConvertEnumToString && property.PropertyType.IsEnum)
                            {
                                propertyValue = Enum.Parse(property.PropertyType, value.ToString());
                            }
                            else
                            {
                                propertyValue = serializer.ConvertToType(value, property.PropertyType);
                            }
                            property.SetValue(instance, propertyValue);
                        }
                    }
                    return instance;
                }
                catch (Exception)
                {
                    return null;
                }
            }
            return null;
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            if (obj != null && Attribute.IsDefined(obj.GetType(), typeof(DataContractAttribute)))
            {
                Type type = obj.GetType();
                IEnumerable<MemberInfo> members = ((IEnumerable<MemberInfo>)type.GetFields())
                    .Concat(type.GetProperties().Where(property => property.CanRead && property.GetIndexParameters().Length == 0))
                    .Where((member) => Attribute.IsDefined(member, typeof(DataMemberAttribute)));
                foreach (MemberInfo member in members)
                {
                    DataMemberAttribute attribute = (DataMemberAttribute)Attribute.GetCustomAttribute(member, typeof(DataMemberAttribute));
                    object value;
                    if (member.MemberType == MemberTypes.Field)
                    {
                        FieldInfo field = (FieldInfo)member;
                        if (ConvertEnumToString && field.FieldType.IsEnum)
                        {
                            value = field.GetValue(obj).ToString();
                        }
                        else
                        {
                            value = field.GetValue(obj);
                        }
                    }
                    else if (member.MemberType == MemberTypes.Property)
                    {
                        PropertyInfo property = (PropertyInfo)member;
                        if (ConvertEnumToString && property.PropertyType.IsEnum)
                        {
                            value = property.GetValue(obj).ToString();
                        }
                        else
                        {
                            value = property.GetValue(obj);
                        }
                    }
                    else
                    {
                        continue;
                    }
                    if (dictionary.ContainsKey(attribute.Name))
                    {
                        throw new SerializationException(String.Format("More than one DataMember found with name {0}", attribute.Name));
                    }
                    dictionary[attribute.Name] = value;
                }
            }
            return dictionary;
        }
    }

Note: This DataContractJavaScriptConverter will only handle DataContract classes defined in the assembly where it is placed. If you want classes from separate assemblies, modify the _supportedTypes list accordingly in the static constructror.

This can be used as follows -

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    serializer.RegisterConverters(new JavaScriptConverter[] { new DataContractJavaScriptConverter(true) });
    DataObject dataObject = serializer.Deserialize<DataObject>(JsonData);

The DataObject class would look like this -

    using System.Runtime.Serialization;

    [DataContract]
    public class DataObject
    {
        [DataMember(Name = "user_id")]
        public int UserId { get; set; }

        [DataMember(Name = "detail_level")]
        public string DetailLevel { get; set; }
    }

Please note that this solution doesn't handle EmitDefaultValue and Order properties supported by DataMember attribute.

How to browse localhost on Android device?

If your firewall is on, turn it off and use IPv4 to test your app in the actual device, then test your application.

Check if all elements in a list are identical

Check if all elements equal to the first.

np.allclose(array, array[0])

How do I kill a process using Vb.NET or C#?

It's better practise, safer and more polite to detect if the process is running and tell the user to close it manually. Of course you could also add a timeout and kill the process if they've gone away...

What are SP (stack) and LR in ARM?

LR is link register used to hold the return address for a function call.

SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.

From the ARM architecture reference:

SP, the Stack Pointer

Register R13 is used as a pointer to the active stack.

In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.

LR, the Link Register

Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.

When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:

• Return with a BX LR instruction.

• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...

This link gives an example of a trivial subroutine.

Here is an example of how registers are saved on the stack prior to a call and then popped back to restore their content.

Create a temporary table in MySQL with an index from a select

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
select_statement

Example :

CREATE TEMPORARY TABLE IF NOT EXISTS mytable
(id int(11) NOT NULL, PRIMARY KEY (id)) ENGINE=MyISAM;
INSERT IGNORE INTO mytable SELECT id FROM table WHERE xyz;

How to define object in array in Mongoose schema correctly with 2d geo index

You can declare trk by the following ways : - either

trk : [{
    lat : String,
    lng : String
     }]

or

trk : { type : Array , "default" : [] }

In the second case during insertion make the object and push it into the array like

db.update({'Searching criteria goes here'},
{
 $push : {
    trk :  {
             "lat": 50.3293714,
             "lng": 6.9389939
           } //inserted data is the object to be inserted 
  }
});

or you can set the Array of object by

db.update ({'seraching criteria goes here ' },
{
 $set : {
          trk : [ {
                     "lat": 50.3293714,
                     "lng": 6.9389939
                  },
                  {
                     "lat": 50.3293284,
                     "lng": 6.9389634
                  }
               ]//'inserted Array containing the list of object'
      }
});

Using parameters in batch files at Windows command line

Using parameters in batch files: %0 and %9

Batch files can refer to the words passed in as parameters with the tokens: %0 to %9.

%0 is the program name as it was called.
%1 is the first command line parameter
%2 is the second command line parameter
and so on till %9.

parameters passed in on the commandline must be alphanumeric characters and delimited by spaces. Since %0 is the program name as it was called, in DOS %0 will be empty for AUTOEXEC.BAT if started at boot time.

Example:

Put the following command in a batch file called mybatch.bat:

@echo off
@echo hello %1 %2
pause

Invoking the batch file like this: mybatch john billy would output:

hello john billy

Get more than 9 parameters for a batch file, use: %*

The Percent Star token %* means "the rest of the parameters". You can use a for loop to grab them, as defined here:

http://www.robvanderwoude.com/parameters.php

Notes about delimiters for batch parameters

Some characters in the command line parameters are ignored by batch files, depending on the DOS version, whether they are "escaped" or not, and often depending on their location in the command line:

commas (",") are replaced by spaces, unless they are part of a string in 
double quotes

semicolons (";") are replaced by spaces, unless they are part of a string in 
double quotes

"=" characters are sometimes replaced by spaces, not if they are part of a 
string in double quotes

the first forward slash ("/") is replaced by a space only if it immediately 
follows the command, without a leading space

multiple spaces are replaced by a single space, unless they are part of a 
string in double quotes

tabs are replaced by a single space

leading spaces before the first command line argument are ignored

Inline style to act as :hover in CSS

I put together a quick solution for anyone wanting to create hover popups without CSS using the onmouseover and onmouseout behaviors.

http://jsfiddle.net/Lk9w1mkv/

<div style="position:relative;width:100px;background:#ddffdd;overflow:hidden;" onmouseover="this.style.overflow='';" onmouseout="this.style.overflow='hidden';">first hover<div style="width:100px;position:absolute;top:5px;left:110px;background:white;border:1px solid gray;">stuff inside</div></div>

mysqli::query(): Couldn't fetch mysqli

I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.

$db_connection = new mysqli("127.0.0.1","root","","db_name");

Hope it helps.

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

forward

Control can be forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved. This is the major difference between forward and sendRedirect. When the forward is done, the original request and response objects are transfered along with additional parameters if needed.

redirect

Control can be redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost.

For example, sendRedirect can transfer control from http://google.com to http://anydomain.com but forward cannot do this.

‘session’ is not lost in both forward and redirect.

To feel the difference between forward and sendRedirect visually see the address bar of your browser, in forward, you will not see the forwarded address (since the browser is not involved) in redirect, you can see the redirected address.

Why is SQL Server 2008 Management Studio Intellisense not working?

Same problem, but just re-installing SQL Management Studio 2008 R2 Service Pack 1 worked for me. I left my DB engine alone. The DB engine is not the problem, just SQL Management Studio getting hosed by Visual Studio SP1.

Installers here...

http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=26727

I installed SQLManagementStudio_x86_ENU.exe (32 bit for my machine).

Getting the parent of a directory in Bash

...but what is "seen here" is broken. Here's the fix:

> pwd
/home/me
> x='Om Namah Shivaya'
> mkdir "$x" && cd "$x"
/home/me/Om Namah Shivaya
> parentdir="$(dirname "$(pwd)")"
> echo $parentdir
/home/me

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

Why doesn't [01-12] range work as expected?

You seem to have misunderstood how character classes definition works in regex.

To match any of the strings 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, or 12, something like this works:

0[1-9]|1[0-2]

References


Explanation

A character class, by itself, attempts to match one and exactly one character from the input string. [01-12] actually defines [012], a character class that matches one character from the input against any of the 3 characters 0, 1, or 2.

The - range definition goes from 1 to 1, which includes just 1. On the other hand, something like [1-9] includes 1, 2, 3, 4, 5, 6, 7, 8, 9.

Beginners often make the mistakes of defining things like [this|that]. This doesn't "work". This character definition defines [this|a], i.e. it matches one character from the input against any of 6 characters in t, h, i, s, | or a. More than likely (this|that) is what is intended.

References


How ranges are defined

So it's obvious now that a pattern like between [24-48] hours doesn't "work". The character class in this case is equivalent to [248].

That is, - in a character class definition doesn't define numeric range in the pattern. Regex engines doesn't really "understand" numbers in the pattern, with the exception of finite repetition syntax (e.g. a{3,5} matches between 3 and 5 a).

Range definition instead uses ASCII/Unicode encoding of the characters to define ranges. The character 0 is encoded in ASCII as decimal 48; 9 is 57. Thus, the character definition [0-9] includes all character whose values are between decimal 48 and 57 in the encoding. Rather sensibly, by design these are the characters 0, 1, ..., 9.

See also


Another example: A to Z

Let's take a look at another common character class definition [a-zA-Z]

In ASCII:

  • A = 65, Z = 90
  • a = 97, z = 122

This means that:

  • [a-zA-Z] and [A-Za-z] are equivalent
  • In most flavors, [a-Z] is likely to be an illegal character range
    • because a (97) is "greater than" than Z (90)
  • [A-z] is legal, but also includes these six characters:
    • [ (91), \ (92), ] (93), ^ (94), _ (95), ` (96)

Related questions

See full command of running/stopped container in Docker

TL-DR

docker ps --no-trunc and docker inspect CONTAINER provide the entrypoint executed to start the container, along the command passed to, but that may miss some parts such as ${ANY_VAR} because container environment variables are not printed as resolved.

To overcome that, docker inspect CONTAINER has an advantage because it also allow to retrieve separately env variables and their values defined in the container from the Config.Env property.

docker ps and docker inspect provide information about the executed entrypoint and its command. Often, that is a wrapper entrypoint script (.sh) and not the "real" program started by the container. To get information on that, requesting process information with ps or /proc/1/cmdline help.


1) docker ps --no-trunc

It prints the entrypoint and the command executed for all running containers. While it prints the command passed to the entrypoint (if we pass that), it doesn't show value of docker env variables (such as $FOO or ${FOO}).
If our containers use env variables, it may be not enough.

For example, run an alpine container :

docker run --name alpine-example -e MY_VAR=/var alpine:latest sh -c 'ls $MY_VAR'

When use docker -ps such as :

docker ps -a --filter name=alpine-example --no-trunc

It prints :

CONTAINER ID           IMAGE               COMMAND                CREATED             STATUS                     PORTS               NAMES
5b064a6de6d8417...   alpine:latest       "sh -c 'ls $MY_VAR'"   2 minutes ago       Exited (0) 2 minutes ago                       alpine-example

We see the command passed to the entrypoint : sh -c 'ls $MY_VAR' but $MY_VAR is indeed not resolved.

2) docker inspect CONTAINER

When we inspect the alpine-example container :

docker inspect alpine-example | grep -4 Cmd

The command is also there but we don't still see the env variable value :

        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ],

In fact, we could not see interpolated variables with these docker commands.
While as a trade-off, we could display separately both command and env variables for a container with docker inspect :

docker inspect  alpine-example  | grep -4 -E "Cmd|Env"

That prints :

        "Env": [
            "MY_VAR=/var",
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ],
        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ]

A more docker way would be to use the --format flag of docker inspect that allows to specify JSON attributes to render :

docker inspect --format '{{.Name}} {{.Config.Cmd}}  {{ (.Config.Env) }}'  alpine-example

That outputs :

/alpine-example [sh -c ls $MY_VAR]  [MY_VAR=/var PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

3) Retrieve the started process from the container itself for running containers

The entrypoint and command executed by docker may be helpful but in some cases, it is not enough because that is "only" a wrapper entrypoint script (.sh) that is responsible to start the real/core process.
For example when I run a Nexus container, the command executed and shown to run the container is "sh -c ${SONATYPE_DIR}/start-nexus-repository-manager.sh".
For PostgreSQL that is "docker-entrypoint.sh postgres".

To get more information, we could execute on a running container docker exec CONTAINER ps aux.
It may print other processes that may not interest us.
To narrow to the initial process launched by the entrypoint, we could do :

docker exec CONTAINER ps -1

I specify 1 because the process executed by the entrypoint is generally the one with the 1 id.

Without ps, we could still find the information in /proc/1/cmdline (in most of Linux distros but not all). For example :

docker exec CONTAINER cat /proc/1/cmdline | sed -e "s/\x00/ /g"; echo    

If we have access to the docker host that started the container, another alternative to get the full command of the process executed by the entrypoint is : : execute ps -PID where PID is the local process created by the Docker daemon to run the container such as :

ps -$(docker container inspect --format '{{.State.Pid}}'  CONTAINER)

User-friendly formatting with docker ps

docker ps --no-trunc is not always easy to read.
Specifying columns to print and in a tabular format may make it better :

docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"

Create an alias may help :

alias dps='docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"'

How to clear form after submit in Angular 2?

To angular version 4, you can use this:

this.heroForm.reset();

But, you could need a initial value like:

ngOnChanges() {
 this.heroForm.reset({
  name: this.hero.name, //Or '' to empty initial value. 
  address: this.hero.addresses[0] || new Address()
 });
}

It is important to resolve null problem in your object reference.

reference link, Search for "reset the form flags".

What is event bubbling and capturing?

Event bubbling and capturing are two ways of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. The event propagation mode determines in which order the elements receive the event.

With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.

With capturing, the event is first captured by the outermost element and propagated to the inner elements.

Capturing is also called "trickling", which helps remember the propagation order:

trickle down, bubble up

Back in the old days, Netscape advocated event capturing, while Microsoft promoted event bubbling. Both are part of the W3C Document Object Model Events standard (2000).

IE < 9 uses only event bubbling, whereas IE9+ and all major browsers support both. On the other hand, the performance of event bubbling may be slightly lower for complex DOMs.

We can use the addEventListener(type, listener, useCapture) to register event handlers for in either bubbling (default) or capturing mode. To use the capturing model pass the third argument as true.

Example

<div>
    <ul>
        <li></li>
    </ul>
</div>

In the structure above, assume that a click event occurred in the li element.

In capturing model, the event will be handled by the div first (click event handlers in the div will fire first), then in the ul, then at the last in the target element, li.

In the bubbling model, the opposite will happen: the event will be first handled by the li, then by the ul, and at last by the div element.

For more information, see

In the example below, if you click on any of the highlighted elements, you can see that the capturing phase of the event propagation flow occurs first, followed by the bubbling phase.

_x000D_
_x000D_
var logElement = document.getElementById('log');_x000D_
_x000D_
function log(msg) {_x000D_
    logElement.innerHTML += ('<p>' + msg + '</p>');_x000D_
}_x000D_
_x000D_
function capture() {_x000D_
    log('capture: ' + this.firstChild.nodeValue.trim());_x000D_
}_x000D_
_x000D_
function bubble() {_x000D_
    log('bubble: ' + this.firstChild.nodeValue.trim());_x000D_
}_x000D_
_x000D_
function clearOutput() {_x000D_
    logElement.innerHTML = "";_x000D_
}_x000D_
_x000D_
var divs = document.getElementsByTagName('div');_x000D_
for (var i = 0; i < divs.length; i++) {_x000D_
    divs[i].addEventListener('click', capture, true);_x000D_
    divs[i].addEventListener('click', bubble, false);_x000D_
}_x000D_
var clearButton = document.getElementById('clear');_x000D_
clearButton.addEventListener('click', clearOutput);
_x000D_
p {_x000D_
    line-height: 0;_x000D_
}_x000D_
_x000D_
div {_x000D_
    display:inline-block;_x000D_
    padding: 5px;_x000D_
_x000D_
    background: #fff;_x000D_
    border: 1px solid #aaa;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
div:hover {_x000D_
    border: 1px solid #faa;_x000D_
    background: #fdd;_x000D_
}
_x000D_
<div>1_x000D_
    <div>2_x000D_
        <div>3_x000D_
            <div>4_x000D_
                <div>5</div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
<button id="clear">clear output</button>_x000D_
<section id="log"></section>
_x000D_
_x000D_
_x000D_

Another example at JSFiddle.

Is it possible to force Excel recognize UTF-8 CSV files automatically?

I faced the same problem a few days ago, and could not find any solution because I cannot use the import from csv feature because it makes everything to be styled as string.

My solution was to first open the file with notpad++ and change the encode to ASCII. Then just opened the file in excel and it worked as expected.

How to change the commit author for one specific commit?

Commit before:

enter image description here

To fix author for all commits you can apply command from @Amber's answer:

git commit --amend --author="Author Name <[email protected]>"

Or to reuse your name and email you can just write:

git commit --amend --author=Eugen

Commit after the command:

enter image description here

For example to change all starting from 4025621:

enter image description here

You must run:

git rebase --onto 4025621 --exec "git commit --amend --author=Eugen" 4025621

Note: To include an author containing spaces such as a name and email address, the author must be surrounded by escaped quotes. For example:

git rebase --onto 4025621 --exec "git commit --amend --author=\"Foo Bar <[email protected]>\"" 4025621

or add this alias into ~/.gitconfig:

[alias]
    reauthor = !bash -c 'git rebase --onto $1 --exec \"git commit --amend --author=$2\" $1' --

And then run:

git reauthor 4025621 Eugen

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

If you are Clion/anyOtherJetBrainsIDE user, and yourFile.exe cause this problem, just delete it and let the app create and link it with libs from a scratch. It helps.

Format decimal for percentage values?

If you want to use a format that allows you to keep the number like your entry this format works for me: "# \\%"

Can you have multiple $(document).ready(function(){ ... }); sections?

Yes you can.

Multiple document ready sections are particularly useful if you have other modules haging off the same page that use it. With the old window.onload=func declaration, every time you specified a function to be called, it replaced the old.

Now all functions specified are queued/stacked (can someone confirm?) regardless of which document ready section they are specified in.

Upload file to FTP using C#

The existing answers are valid, but why re-invent the wheel and bother with lower level WebRequest types while WebClient already implements FTP uploading neatly:

using (var client = new WebClient())
{
    client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
    client.UploadFile("ftp://host/path.zip", WebRequestMethods.Ftp.UploadFile, localFile);
}

Are there any disadvantages to always using nvarchar(MAX)?

Based on the link provided in the accepted answer it appears that:

  1. 100 characters stored in an nvarchar(MAX) field will be stored no different to 100 characters in an nvarchar(100) field - the data will be stored inline and you will not have the overhead of reading and writing data 'out of row'. So no worries there.

  2. If the size is greater than 4000 the data would be stored 'out of row' automatically, which is what you would want. So no worries there either.

However...

  1. You cannot create an index on an nvarchar(MAX) column. You can use full-text indexing, but you cannot create an index on the column to improve query performance. For me, this seals the deal...it is a definite disadvantage to always use nvarchar(MAX).

Conclusion:

If you want a kind of "universal string length" throughout your whole database, which can be indexed and which will not waste space and access time, then you could use nvarchar(4000).

R: Select values from data table in range

Construct some data

df <- data.frame( name=c("John", "Adam"), date=c(3, 5) )

Extract exact matches:

subset(df, date==3)

  name date
1 John    3

Extract matches in range:

subset(df, date>4 & date<6)

  name date
2 Adam    5

The following syntax produces identical results:

df[df$date>4 & df$date<6, ]

  name date
2 Adam    5

Soft hyphen in HTML (<wbr> vs. &shy;)

I used soft hyphen unicode character successfully in few desktop and mobile browsers to solve the issue.

The unicode symbol is \u00AD and is pretty easy to insert into Python unicode string like s = u'????? ? ?????? ???????\u00AD??\u00AD??\u00AD??\u00AD???'.

Other solution is to insert the unicode char itself, and the source string will look perfectly ordinary in editors like Sublime Text, Kate, Geany, etc (cursor will feel the invisible symbol though).

Hex editors of in-house tools can automate this task easily.

An easy kludge is to use rare and visible character, like ¦, which is easy to copy and paste, and replace it on soft hyphen using, e.g. frontend script in $(document).ready(...). Source code like s = u'????? ? ?????? ???¦???¦?¦??¦??¦??¦???'.replace('¦', u'\u00AD') is easier to read than s = u'????? ? ?????? ???\u00AD?\u00AD??\u00AD?\u00AD??\u00AD??\u00AD??\u00AD???'.

Event listener for when element becomes visible?

Going forward, the new HTML Intersection Observer API is the thing you're looking for. It allows you to configure a callback that is called whenever one element, called the target, intersects either the device viewport or a specified element. It's available in latest versions of Chrome, Firefox and Edge. See https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API for more info.

Simple code example for observing display:none switching:

// Start observing visbility of element. On change, the
//   the callback is called with Boolean visibility as
//   argument:

function respondToVisibility(element, callback) {
  var options = {
    root: document.documentElement,
  };

  var observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      callback(entry.intersectionRatio > 0);
    });
  }, options);

  observer.observe(element);
}

In action: https://jsfiddle.net/elmarj/u35tez5n/5/

.NET String.Format() to add commas in thousands place for a number

C# 7.1 (perhaps earlier?) makes this as easy and nice-looking as it should be, with string interpolation:

var jackpot = 1000000;
var niceNumberString = $"Jackpot is {jackpot:n}";
var niceMoneyString = $"Jackpot is {jackpot:C}";

How to grant remote access permissions to mysql server for user?

Two steps:

  1. set up user with wildcard:
    create user 'root'@'%' identified by 'some_characters'; GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY PASSWORD 'some_characters' WITH GRANT OPTION

  2. vim /etc/my.cnf
    add the following:
    bind-address=0.0.0.0

restart server, you should not have any problem connecting to it.

How to use HTML Agility pack

First, install the HTMLAgilityPack nuget package into your project.

Then, as an example:

HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();

// There are various options, set as needed
htmlDoc.OptionFixNestedTags=true;

// filePath is a path to a file containing the html
htmlDoc.Load(filePath);

// Use:  htmlDoc.LoadHtml(xmlString);  to load from a string (was htmlDoc.LoadXML(xmlString)

// ParseErrors is an ArrayList containing any errors from the Load statement
if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
{
    // Handle any parse errors as required

}
else
{

    if (htmlDoc.DocumentNode != null)
    {
        HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");

        if (bodyNode != null)
        {
            // Do something with bodyNode
        }
    }
}

(NB: This code is an example only and not necessarily the best/only approach. Do not use it blindly in your own application.)

The HtmlDocument.Load() method also accepts a stream which is very useful in integrating with other stream oriented classes in the .NET framework. While HtmlEntity.DeEntitize() is another useful method for processing html entities correctly. (thanks Matthew)

HtmlDocument and HtmlNode are the classes you'll use most. Similar to an XML parser, it provides the selectSingleNode and selectNodes methods that accept XPath expressions.

Pay attention to the HtmlDocument.Option?????? boolean properties. These control how the Load and LoadXML methods will process your HTML/XHTML.

There is also a compiled help file called HtmlAgilityPack.chm that has a complete reference for each of the objects. This is normally in the base folder of the solution.

Block Comments in a Shell Script

The following should work for sh,bash, ksh and zsh.

The blocks of code to be commented can be put inside BEGINCOMMENT and ENDCOMMENT:

[ -z $BASH ] || shopt -s expand_aliases
alias BEGINCOMMENT="if [ ]; then"
alias ENDCOMMENT="fi"

BEGINCOMMENT
  echo "This line appears in a commented block"
  echo "And this one too!"
ENDCOMMENT

echo "This is outside the commented block"

Executing the above code would result in:

This is outside the commented block

In order to uncomment the code blocks thus commented, say

alias BEGINCOMMENT="if : ; then"

instead of

alias BEGINCOMMENT="if [ ]; then"

in the example above.

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

Add alternating row color to SQL Server Reporting services report

Go to the table row's BackgroundColor property and choose "Expression..."

Use this expression:

= IIf(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")

This trick can be applied to many areas of the report.

And in .NET 3.5+ You could use:

= If(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")

Not looking for rep--I just researched this question myself and thought I'd share.

How to get first 5 characters from string

You can use the substr function like this:

echo substr($myStr, 0, 5);

The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

String or binary data would be truncated. The statement has been terminated

The maximal length of the target column is shorter than the value you try to insert.

Rightclick the table in SQL manager and go to 'Design' to visualize your table structure and column definitions.

Edit:

Try to set a length on your nvarchar inserts thats the same or shorter than whats defined in your table.

What is Domain Driven Design?

DDD(domain driven design) is a useful concept for analyse of requirements of a project and handling the complexity of these requirements.Before that people were analysing these requirements with considering the relationships between classes and tables and in fact their design were based on database tables relationships it is not old but it has some problems:

  • In big projects with complex requirements it is not useful although this is a great way of design for small projects.

  • when you are dealing with none technical persons that they don,t have technical concept, this conflict may cause some huge problems in our project.

So DDD handle the first problem with considering the main project as a Domain and splitting each part of this project to small pieces which we are famous to Bounded Context and each of them do not have any influence on other pieces. And the second problem has been solved with a ubiquitous language which is a common language between technical team members and Product owners which are not technical but have enough knowledge about their requirements

Generally the simple definition for Domain is the main project that makes money for the owners and other teams.

Unable to execute dex: method ID not in [0, 0xffff]: 65536

You can analyse problem (dex file references) using Android Studio:

Build -> Analyse APK ..

On the result panel click on classes.dex file

And you'll see:

enter image description here

How do I do a Date comparison in Javascript?

You can use the getTime() method on a Date object to get the timestamp (in milliseconds) relative to January 1, 1970. If you convert your two dates into integer timestamps, you can then compare the difference by subtracting them. The result will be in milliseconds so you just divide by 1000 for seconds, then 60 for minutes, etc.

Viewing full output of PS command

Evidence for truncation mentioned by others, (a personal example)

foo=$(ps -p 689 -o command); echo "$foo"

COMMAND
/opt/conda/bin/python -m ipykernel_launcher -f /root/.local/share/jupyter/runtime/kernel-5732db1a-d484-4a58-9d67-de6ef5ac721b.json

That ^^ captures that long output in a variable As opposed to

ps -p 689 -o command

COMMAND
/opt/conda/bin/python -m ipykernel_launcher -f /root/.local/share/jupyter/runtim

Since I was trying this from a Docker jupyter notebook, I needed to run this with the bang of course ..

!foo=$(ps -p 689 -o command); echo "$foo"

Surprisingly jupyter notebooks let you execute even that! But glad to help find the offending notebook taking up all my memory =D

jQuery - how to write 'if not equal to' (opposite of ==)

The opposite of the == compare operator is !=.

how to inherit Constructor from super class to sub class

You inherit class attributes, not class constructors .This is how it goes :

If no constructor is added in the super class, if no then the compiler adds a no argument contructor. This default constructor is invoked implicitly whenever a new instance of the sub class is created . Here the sub class may or may not have constructor, all is ok .

if a constructor is provided in the super class, the compiler will see if it is a no arg constructor or a constructor with parameters.

if no args, then the compiler will invoke it for any sub class instanciation . Here also the sub class may or may not have constructor, all is ok .

if 1 or more contructors in the parent class have parameters and no args constructor is absent, then the subclass has to have at least 1 constructor where an implicit call for the parent class construct is made via super (parent_contractor params) .

this way you are sure that the inherited class attributes are always instanciated .

vba pass a group of cells as range to function

There is another way to pass multiple ranges to a function, which I think feels much cleaner for the user. When you call your function in the spreadsheet you wrap each set of ranges in brackets, for example: calculateIt( (A1,A3), (B6,B9) )

The above call assumes your two Sessions are in A1 and A3, and your two Customers are in B6 and B9.

To make this work, your function needs to loop through each of the Areas in the input ranges. For example:

Function calculateIt(Sessions As Range, Customers As Range) As Single

    ' check we passed the same number of areas
    If (Sessions.Areas.Count <> Customers.Areas.Count) Then
        calculateIt = CVErr(xlErrNA)
        Exit Function
    End If

    Dim mySession, myCustomers As Range

    ' run through each area and calculate
    For a = 1 To Sessions.Areas.Count

        Set mySession = Sessions.Areas(a)
        Set myCustomers = Customers.Areas(a)

        ' calculate them...
    Next a

End Function

The nice thing is, if you have both your inputs as a contiguous range, you can call this function just as you would a normal one, e.g. calculateIt(A1:A3, B6:B9).

Hope that helps :)

Register 32 bit COM DLL to 64 bit Windows 7

I was getting the error "The module may compatible with this version of windows" for both version of RegSvr32 (32 bit and 64 bit). I was trying to register a DLL that was built for XP (32 bit) in Server 2008 R2 (x64) and none of the Regsr32 resolutions worked for me. However, registering the assembly in the appropriate .Net worked perfect for me. C:\Windows\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe

How to redirect Valgrind's output to a file?

By default, Valgrind writes its output to stderr. So you need to do something like:

valgrind a.out > log.txt 2>&1

Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).

Cannot open new Jupyter Notebook [Permission Denied]

In windows, I copied, what I think is a snapshot:

.~SomeAmazingNotebook.ipynb

renamed it:

SomeAmazingNotebook.ipynb

and could open it.

What is the difference between `let` and `var` in swift?

let is used for constants that can’t be modified while var is an ordinary variable

Example:

let name = “Bob” Something like name = “Jim” will throw an error since a constant can’t be modified.

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

Just need to add: new SimpleDateFormat("bla bla bla", Locale.US)

public static void main(String[] args) throws ParseException {
    java.util.Date fecha = new java.util.Date("Mon Dec 15 00:00:00 CST 2014");
    DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
    Date date;
    date = (Date)formatter.parse(fecha.toString());
    System.out.println(date);        

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    String formatedDate = cal.get(Calendar.DATE) + "/" + 
            (cal.get(Calendar.MONTH) + 1) + 
            "/" +         cal.get(Calendar.YEAR);
    System.out.println("formatedDate : " + formatedDate);
}

How to change the default docker registry from docker.io to my private registry?

It turns out this is actually possible, but not using the genuine Docker CE or EE version.

You can either use Red Hat's fork of docker with the '--add-registry' flag or you can build docker from source yourself with registry/config.go modified to use your own hard-coded default registry namespace/index.

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

Download proxy script and check last line for return statement Proxy IP and Port.
Add this IP and Port using these step.

   1.  Windows -->Preferences-->General -->Network Connection
   2. Select Active Provider : Manual
   3.  Proxy entries select HTTP--> Click on Edit button
   4.  Then add Host as a proxy IP and port left Required Authentication blank.
   5.  Restart eclipse
   6.  Now Eclipse Marketplace... working.

calculating execution time in c++

Note: the question was originally about compilation time, but later it turned out that the OP really meant execution time. But maybe this answer will still be useful for someone.

For Visual Studio: go to Tools / Options / Projects and Solutions / VC++ Project Settings and set Build Timing option to 'yes'. After that the time of every build will be displayed in the Output window.

How do I get a list of files in a directory in C++?

You can use the following code for getting all files in a directory.A simple modification in the Andreas Bonini answer to remove the occurance of "." and ".."

CString dirpath="d:\\mydir"
DWORD errVal = ERROR_SUCCESS;
HANDLE dir;
WIN32_FIND_DATA file_data;
CString  file_name,full_file_name;
if ((dir = FindFirstFile((dirname+ "/*"), &file_data)) == INVALID_HANDLE_VALUE)
{
    errVal=ERROR_INVALID_ACCEL_HANDLE;
    return errVal;
}

while (FindNextFile(dir, &file_data)) {
    file_name = file_data.cFileName;
    full_file_name = dirname+ file_name;
    if (strcmp(file_data.cFileName, ".") != 0 && strcmp(file_data.cFileName, "..") != 0)
    {
        m_List.AddTail(full_file_name);
    }
}

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

This can also happen when the log file is restricted in size.

Right click database in Object Explorer

Select Properties

Select Files

On the log line, click the ellipsis in the Autogrowth / Maxsize column

Change/verify Maximum File Size is Unlimited.

enter image description here

After chaning to unlimited, database came back to life.

Python: count repeated elements in the list

Use Counter

>>> from collections import Counter
>>> MyList = ["a", "b", "a", "c", "c", "a", "c"]
>>> c = Counter(MyList)
>>> c
Counter({'a': 3, 'c': 3, 'b': 1})

Set formula to a range of cells

Range("C1:C10").Formula = "=A1+B1"

Simple as that.

It autofills (FillDown) the range with the formula.

How to Return partial view of another controller by controller?

Simply you could use:

PartialView("../ABC/XXX")

Most efficient way to concatenate strings?

It's also important to point it out that you should use the + operator if you are concatenating string literals.

When you concatenate string literals or string constants by using the + operator, the compiler creates a single string. No run time concatenation occurs.

How to: Concatenate Multiple Strings (C# Programming Guide)

Count length of array and return 1 if it only contains one element

A couple other options:

  1. Use the comma operator to create an array:

    $cars = ,"bmw"
    $cars.GetType().FullName
    # Outputs: System.Object[]
    
  2. Use array subexpression syntax:

    $cars = @("bmw")
    $cars.GetType().FullName
    # Outputs: System.Object[]
    

If you don't want an object array you can downcast to the type you want e.g. a string array.

 [string[]] $cars = ,"bmw"
 [string[]] $cars = @("bmw")

change Oracle user account status from EXPIRE(GRACE) to OPEN

No, you cannot directly change an account status from EXPIRE(GRACE) to OPEN without resetting the password.

The documentation says:

If you cause a database user's password to expire with PASSWORD EXPIRE, then the user (or the DBA) must change the password before attempting to log into the database following the expiration.


However, you can indirectly change the status to OPEN by resetting the user's password hash to the existing value. Unfortunately, setting the password hash to itself has the following complications, and almost every other solution misses at least one of these issues:

  1. Different versions of Oracle use different types of hashes.
  2. The user's profile may prevent re-using passwords.
  3. Profile limits can be changed, but we have to change the values back at the end.
  4. Profile values are not trivial because if the value is DEFAULT, that is a pointer to the DEFAULT profile's value. We may need to recursively check the profile.

The following, ridiculously large PL/SQL block, should handle all of those cases. It should reset any account to OPEN, with the same password hash, regardless of Oracle version or profile settings. And the profile will be changed back to the original limits.

--Purpose: Change a user from EXPIRED to OPEN by setting a user's password to the same value.
--This PL/SQL block requires elevated privileges and should be run as SYS.
--This task is difficult because we need to temporarily change profiles to avoid
--  errors like "ORA-28007: the password cannot be reused".
--
--How to use: Run as SYS in SQL*Plus and enter the username when prompted.
--  If using another IDE, manually replace the variable two lines below.
declare
    v_username varchar2(128) := trim(upper('&USERNAME'));
    --Do not change anything below this line.
    v_profile                 varchar2(128);
    v_old_password_reuse_time varchar2(128);
    v_uses_default_for_time   varchar2(3);
    v_old_password_reuse_max  varchar2(128);
    v_uses_default_for_max    varchar2(3);
    v_alter_user_sql          varchar2(4000);
begin
    --Get user's profile information.
    --(This is tricky because there could be an indirection to the DEFAULT profile.
    select
        profile,
        case when user_password_reuse_time = 'DEFAULT' then default_password_reuse_time else user_password_reuse_time end password_reuse_time,
        case when user_password_reuse_time = 'DEFAULT' then 'Yes' else 'No' end uses_default_for_time,
        case when user_password_reuse_max  = 'DEFAULT' then default_password_reuse_max  else user_password_reuse_max  end password_reuse_max,
        case when user_password_reuse_max  = 'DEFAULT' then 'Yes' else 'No' end uses_default_for_max
    into v_profile, v_old_password_reuse_time, v_uses_default_for_time, v_old_password_reuse_max, v_uses_default_for_max
    from
    (
        --User's profile information.
        select
            dba_profiles.profile,
            max(case when resource_name = 'PASSWORD_REUSE_TIME' then limit else null end) user_password_reuse_time,
            max(case when resource_name = 'PASSWORD_REUSE_MAX' then limit else null end) user_password_reuse_max
        from dba_profiles
        join dba_users
            on dba_profiles.profile = dba_users.profile
        where username = v_username
        group by dba_profiles.profile
    ) users_profile
    cross join
    (
        --Default profile information.
        select
            max(case when resource_name = 'PASSWORD_REUSE_TIME' then limit else null end) default_password_reuse_time,
            max(case when resource_name = 'PASSWORD_REUSE_MAX' then limit else null end) default_password_reuse_max
        from dba_profiles
        where profile = 'DEFAULT'
    ) default_profile;

    --Get user's password information.
    select
        'alter user '||name||' identified by values '''||
        spare4 || case when password is not null then ';' else null end || password ||
        ''''
    into v_alter_user_sql
    from sys.user$
    where name = v_username;

    --Change profile limits, if necessary.
    if v_old_password_reuse_time <> 'UNLIMITED' then
        execute immediate 'alter profile '||v_profile||' limit password_reuse_time unlimited';
    end if;

    if v_old_password_reuse_max <> 'UNLIMITED' then
        execute immediate 'alter profile '||v_profile||' limit password_reuse_max unlimited';
    end if;

    --Change the user's password.
    execute immediate v_alter_user_sql;

    --Change the profile limits back, if necessary.
    if v_old_password_reuse_time <> 'UNLIMITED' then
        if v_uses_default_for_time = 'Yes' then
            execute immediate 'alter profile '||v_profile||' limit password_reuse_time default';
        else
            execute immediate 'alter profile '||v_profile||' limit password_reuse_time '||v_old_password_reuse_time;
        end if;
    end if;

    if v_old_password_reuse_max <> 'UNLIMITED' then
        if v_uses_default_for_max = 'Yes' then
            execute immediate 'alter profile '||v_profile||' limit password_reuse_max default';
        else
            execute immediate 'alter profile '||v_profile||' limit password_reuse_max '||v_old_password_reuse_max;
        end if;
    end if;
end;
/

How to prevent favicon.ico requests?

In our experience, with Apache falling over on request of favicon.ico, we commented out extra headers in the .htaccess file.

For example we had Header set X-XSS-Protection "1; mode=block"

... but we had forgotten to sudo a2enmod headers beforehand. Commenting out extra headers being sent resolved our favicon.ico issue.

We also had several virtual hosts set up for development, and only failed out with 500 Internal Server Error when using http://localhost and fetching /favicon.ico. If you run "curl -v http://localhost/favicon.ico" and get a warning about the host name not being in the resolver cache or something to that effect, you might experience problems.

It could be as simple as not fetching (we tried that and it didn't work, because our root cause was different) or look around for directives in apache2.conf or .htaccess which might be causing strange 500 Internal Server Error messages.

We found it failed so quickly there was nothing useful in Apache's error logs whatsoever and spent an entire morning changing small things here and there until we resolved the problem of setting extra headers when we had forgotten to have mod_headers loaded!

How to Sort a List<T> by a property in the object

Make use of LiNQ OrderBy

List<Order> objListOrder=new List<Order> ();
    objListOrder=GetOrderList().OrderBy(o=>o.orderid).ToList();

Extract parameter value from url using regular expressions

Not tested but this should work:

/\?v=([a-z0-9\-]+)\&?/i

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

If you need to organize data in columns of 1 / 2 / 4 depending of the viewport size then push and pull may be no option at all. No matter how you order your items in the first place, one of the sizes may give you a wrong order.

A solution in this case is to use nested rows and cols without any push or pull classes.

Example

In XS you want...

A
B
C
D
E
F
G
H

In SM you want...

A   E
B   F
C   G
D   H

In MD and above you want...

A   C   E   G
B   D   F   H


Solution

Use nested two-column child elements in a surrounding two-column parent element:

Here is a working snippet:

_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript" ></script>_x000D_
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> _x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="row">_x000D_
  <div class="col-sm-6">_x000D_
    <div class="row">_x000D_
      <div class="col-md-6"><p>A</p><p>B</p></div>_x000D_
      <div class="col-md-6"><p>C</p><p>D</p></div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="col-sm-6">_x000D_
    <div class="row">_x000D_
      <div class="col-md-6"><p>E</p><p>F</p></div>_x000D_
      <div class="col-md-6"><p>G</p><p>H</p></div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Another beauty of this solution is, that the items appear in the code in their natural order (A, B, C, ... H) and don't have to be shuffled, which is nice for CMS generation.

Python syntax for "if a or b or c but not all of them"

This returns True if one and only one of the three conditions is True. Probably what you wanted in your example code.

if sum(1 for x in (a,b,c) if x) == 1:

How to configure socket connect timeout

I worked with Unity and had some problem with the BeginConnect and other async methods from socket.

There is something than I don't understand but the code samples before doesn't work for me.

So I wrote this piece of code to make it work. I test it on an adhoc network with android and pc, also in local on my computer. Hope it can help.

using System.Net.Sockets;
using System.Threading;
using System.Net;
using System;
using System.Diagnostics;

class ConnexionParameter : Guardian
{
    public TcpClient client;
    public string address;
    public int port;
    public Thread principale;
    public Thread thisthread = null;
    public int timeout;

    private EventWaitHandle wh = new AutoResetEvent(false);

    public ConnexionParameter(TcpClient client, string address, int port, int timeout, Thread principale)
    {
        this.client = client;
        this.address = address;
        this.port = port;
        this.principale = principale;
        this.timeout = timeout;
        thisthread = new Thread(Connect);
    }


    public void Connect()
    {
        WatchDog.Start(timeout, this);
        try
        {
            client.Connect(IPAddress.Parse(address), port);

        }
        catch (Exception)
        {
            UnityEngine.Debug.LogWarning("Unable to connect service (Training mode? Or not running?)");
        }
        OnTimeOver();
        //principale.Resume();
    }

    public bool IsConnected = true;
    public void OnTimeOver()
    {
        try
        {
            if (!client.Connected)
            {
                    /*there is the trick. The abort method from thread doesn't
 make the connection stop immediately(I think it's because it rise an exception
 that make time to stop). Instead I close the socket while it's trying to
 connect , that make the connection method return faster*/
                IsConnected = false;

                client.Close();
            }
            wh.Set();

        }
        catch(Exception)
        {
            UnityEngine.Debug.LogWarning("Connexion already closed, or forcing connexion thread to end. Ignore.");
        }
    }


    public void Start()
    {

        thisthread.Start();
        wh.WaitOne();
        //principale.Suspend();
    }

    public bool Get()
    {
        Start();
        return IsConnected;
    }
}


public static class Connexion
{


    public static bool Connect(this TcpClient client, string address, int port, int timeout)
    {
        ConnexionParameter cp = new ConnexionParameter(client, address, port, timeout, Thread.CurrentThread);
        return cp.Get();
    }

//http://stackoverflow.com/questions/19653588/timeout-at-acceptsocket
    public static Socket AcceptSocket(this TcpListener tcpListener, int timeoutms, int pollInterval = 10)
    {
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutms);
        var stopWatch = new Stopwatch();
        stopWatch.Start();
        while (stopWatch.Elapsed < timeout)
        {
            if (tcpListener.Pending())
                return tcpListener.AcceptSocket();

            Thread.Sleep(pollInterval);
        }
        return null;
    }


}

and there a very simple watchdog on C# to make it work:

using System.Threading;

public interface Guardian
{
    void OnTimeOver();
}

public class WatchDog {

    int m_iMs;
    Guardian m_guardian;

    public WatchDog(int a_iMs, Guardian a_guardian)
    {
        m_iMs = a_iMs;
        m_guardian = a_guardian;
        Thread thread = new Thread(body);
        thread.Start(this);
    }


    private void body(object o)
    {
        WatchDog watchdog = (WatchDog)o;
        Thread.Sleep(watchdog.m_iMs);
        watchdog.m_guardian.OnTimeOver();
    }

    public static void Start(int a_iMs, Guardian a_guardian)
    {
        new WatchDog(a_iMs, a_guardian);
    }
}

Open Cygwin at a specific folder

based on @LindseyD answer I created a simple BAT file, that opens cygwin in current directory, it may be useful (for me it is). Assuming that You have cygwin's bin directory in PATH.

FOR /F %%x IN ('sh -c pwd') DO bash -l -i -c 'cd %%x; exec bash'

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

You could convert it to an array and then print that out with Arrays.toString(Object[]):

System.out.println(Arrays.toString(stack.toArray()));

How to return the output of stored procedure into a variable in sql server

You can use the return statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success.

If no return is explicitly set, then the stored procedure returns zero.

   CREATE PROCEDURE GetImmediateManager
      @employeeID INT,
      @managerID INT OUTPUT
   AS
   BEGIN
     SELECT @managerID = ManagerID 
     FROM HumanResources.Employee 
     WHERE EmployeeID = @employeeID

     if @@rowcount = 0 -- manager not found?
       return 1;
   END

And you call it this way:

DECLARE @return_status int;
DECLARE @managerID int;

EXEC @return_status = GetImmediateManager 2, @managerID output;
if @return_status = 1
  print N'Immediate manager not found!';
else 
  print N'ManagerID is ' + @managerID;
go

You should use the return value for status codes only. To return data, you should use output parameters.

If you want to return a dataset, then use an output parameter of type cursor.

more on RETURN statement

How to disable and then enable onclick event on <div> with javascript

I'm confused by your question, seems to me that the question title and body are asking different things. If you want to disable/enable a click event on a div simply do:

$("#id").on('click', function(){ //enables click event
    //do your thing here
});

$("#id").off('click'); //disables click event

If you want to disable a div, use the following code:

$("#id").attr('disabled','disabled');

Hope this helps.

edit: oops, didn't see the other bind/unbind answer. Sorry. Those methods are also correct, though they've been deprecated in jQuery 1.7, and replaced by on()/off()

Getting XML Node text value with Java DOM

I'd print out the result of an2.getNodeName() as well for debugging purposes. My guess is that your tree crawling code isn't crawling to the nodes that you think it is. That suspicion is enhanced by the lack of checking for node names in your code.

Other than that, the javadoc for Node defines "getNodeValue()" to return null for Nodes of type Element. Therefore, you really should be using getTextContent(). I'm not sure why that wouldn't give you the text that you want.

Perhaps iterate the children of your tag node and see what types are there?

Tried this code and it works for me:

String xml = "<add job=\"351\">\n" +
             "    <tag>foobar</tag>\n" +
             "    <tag>foobar2</tag>\n" +
             "</add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
Document doc = db.parse(bis);
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;

for (int i=0; i < nl.getLength(); i++) {
    an = nl.item(i);
    if(an.getNodeType()==Node.ELEMENT_NODE) {
        NodeList nl2 = an.getChildNodes();

        for(int i2=0; i2<nl2.getLength(); i2++) {
            an2 = nl2.item(i2);
            // DEBUG PRINTS
            System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getTextContent());
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getNodeValue());
            System.out.println(an2.getTextContent());
            System.out.println(an2.getNodeValue());
        }
    }
}

Output was:

#text: type (3): foobar foobar
#text: type (3): foobar2 foobar2

Accessing an SQLite Database in Swift

This is by far the best SQLite library that I've used in Swift: https://github.com/stephencelis/SQLite.swift

Look at the code examples. So much cleaner than the C API:

import SQLite

let db = try Connection("path/to/db.sqlite3")

let users = Table("users")
let id = Expression<Int64>("id")
let name = Expression<String?>("name")
let email = Expression<String>("email")

try db.run(users.create { t in
    t.column(id, primaryKey: true)
    t.column(name)
    t.column(email, unique: true)
})
// CREATE TABLE "users" (
//     "id" INTEGER PRIMARY KEY NOT NULL,
//     "name" TEXT,
//     "email" TEXT NOT NULL UNIQUE
// )

let insert = users.insert(name <- "Alice", email <- "[email protected]")
let rowid = try db.run(insert)
// INSERT INTO "users" ("name", "email") VALUES ('Alice', '[email protected]')

for user in try db.prepare(users) {
    print("id: \(user[id]), name: \(user[name]), email: \(user[email])")
    // id: 1, name: Optional("Alice"), email: [email protected]
}
// SELECT * FROM "users"

let alice = users.filter(id == rowid)

try db.run(alice.update(email <- email.replace("mac.com", with: "me.com")))
// UPDATE "users" SET "email" = replace("email", 'mac.com', 'me.com')
// WHERE ("id" = 1)

try db.run(alice.delete())
// DELETE FROM "users" WHERE ("id" = 1)

try db.scalar(users.count) // 0
// SELECT count(*) FROM "users"

The documentation also says that "SQLite.swift also works as a lightweight, Swift-friendly wrapper over the C API," and follows with some examples of that.

How to check radio button is checked using JQuery?


//the following code checks if your radio button having name like 'yourRadioName' 
//is checked or not
$(document).ready(function() {
  if($("input:radio[name='yourRadioName']").is(":checked")) {
      //its checked
  }
});

Read a HTML file into a string variable in memory

Use File.ReadAllText(path_to_file) to read

SQLite3 database or disk is full / the database disk image is malformed

I use the following script for repairing malformed sqlite files:

#!/bin/bash

cat <( sqlite3 "$1" .dump | grep "^ROLLBACK" -v ) <( echo "COMMIT;" ) | sqlite3 "fix_$1"

Most of the time when a sqlite database is malformed it is still possible to make a dump. This dump is basically a lot of SQL statements that rebuild the database.

Some rows might be missing from the dump (probably becasue they are corrupted). If this is the case the INSERT statements of the missing rows will be replaced with some comments and the script will end with a ROLLBACK TRANSACTION.

So what we do here is we make the dump (malformed rows are excluded) and we replace the ROLLBACK with a COMMIT so that the entire dump script will be committed in stead of rolled back.

This method saved my life a couple of 100 times already \o/

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

How to put php inside JavaScript?

The only proper way to put server side data into generated javascript code:

<?php $jsString= 'testing'; ?>
<html>
  <body>
    <script type="text/javascript">      
      var jsStringFromPhp=<?php echo json_encode($jsString); ?>;
      alert(jsStringFromPhp);
    </script>
  </body>
</html>

With simple quotes the content of your variable is not escaped against HTML and javascript, so it is vulnerable by XSS attacks...

For similar reasons I recommend to use document.createTextNode() instead of setting the innerHTML. Ofc. it is slower, but more secure...

How to add the text "ON" and "OFF" to toggle button

try this

_x000D_
_x000D_
.switch {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 34px;_x000D_
}_x000D_
_x000D_
.switch input {display:none;}_x000D_
_x000D_
.slider {_x000D_
  position: absolute;_x000D_
  cursor: pointer;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  background-color: #ccc;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
.slider:before {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  height: 26px;_x000D_
  width: 26px;_x000D_
  left: 4px;_x000D_
  bottom: 4px;_x000D_
  background-color: white;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
input:checked + .slider {_x000D_
  background-color: #2196F3;_x000D_
}_x000D_
_x000D_
input:focus + .slider {_x000D_
  box-shadow: 0 0 1px #2196F3;_x000D_
}_x000D_
_x000D_
input:checked + .slider:before {_x000D_
  -webkit-transform: translateX(26px);_x000D_
  -ms-transform: translateX(26px);_x000D_
  transform: translateX(26px);_x000D_
}_x000D_
_x000D_
/* Rounded sliders */_x000D_
.slider.round {_x000D_
  border-radius: 34px;_x000D_
}_x000D_
_x000D_
.slider.round:before {_x000D_
  border-radius: 50%;_x000D_
}
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Untitled Document</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<h2>Toggle Switch</h2>_x000D_
_x000D_
<label class="switch">_x000D_
  <input type="checkbox">_x000D_
  <div class="slider"></div>_x000D_
</label>_x000D_
_x000D_
<label class="switch">_x000D_
  <input type="checkbox" checked>_x000D_
  <div class="slider"></div>_x000D_
</label><br><br>_x000D_
_x000D_
<label class="switch">_x000D_
  <input type="checkbox">_x000D_
  <div class="slider round"></div>_x000D_
</label>_x000D_
_x000D_
<label class="switch">_x000D_
  <input type="checkbox" checked>_x000D_
  <div class="slider round"></div>_x000D_
</label>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I get a platform-dependent new line character?

If you're trying to write a newline to a file, you could simply use BufferedWriter's newLine() method.

How to concatenate columns in a Postgres SELECT?

As i was also stuck in this, think i should share the solution that worked best for me. I also think that this is much simpler.

If you use Capitalized table name.

SELECT CONCAT("firstName", ' ', "lastName") FROM "User"

If you use lowercase table name

SELECT CONCAT(firstName, ' ', lastName) FROM user

That's it!. As PGSQL counts Double Quote for column declaration and Single Quote for string, this works like a charm.

Redefine tab as 4 spaces

Put your desired settings in the ~/.vimrc file -- See below for some guidelines and best practices.

There are four main ways to use tabs in Vim:

  1. Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4 (or 3 or whatever you prefer) and use 'noexpandtab'. Then Vim will use a mix of tabs and spaces, but typing and will behave like a tab appears every 4 (or 3) characters.

    Note: Setting 'tabstop' to any other value than 8 can make your file appear wrong in many places (e.g., when printing it).

  2. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use 'expandtab'. This way you will always insert spaces. The formatting will never be messed up when 'tabstop' is changed.

  3. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a |modeline| to set these values when editing the file again. Only works when using Vim to edit the file.

  4. Always set 'tabstop' and 'shiftwidth' to the same value, and 'noexpandtab'. This should then work (for initial indents only) for any tabstop setting that people use. It might be nice to have tabs after the first non-blank inserted as spaces if you do this though. Otherwise aligned comments will be wrong when 'tabstop' ischanged.

Source:

Why can't I see the "Report Data" window when creating reports?

I had to go through a bit more to force a refresh in VS 2008.

First, there is a Data Sources pane/toolbox (menu trail = Data > Show Data Sources), and a Report Data Sources dialog (menu trail = Report > Data Sources). I had trouble with the Data Sources pane reverting to an earlier property list every time I opened a certain report; it was as if the report designer was overwriting the data definition with the report's cached version thereof.

To remedy this, I had to:

  1. Exclude the report from my project to stop the build errors
  2. Clean & rebuild my project
  3. Refresh the Data Sources pane & confirm I could see the new fields
  4. Re-include the report and open the report designer with the Data Sources pane pinned in view
  5. (This is the key) Drag one of the new fields anywhere onto the report surface

Number 5 forced the report's internal XML copy of the data definition to refresh. Immediately after that, I could build again.

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

I am using such code in config.php:

$lang = 'ru'; // this language will be used if there is no any lang information from useragent (for example, from command line, wget, etc...

if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);
$tmp_value = $_COOKIE['language'];
if (!empty($tmp_value)) $lang = $tmp_value;
switch ($lang)
{
    case 'ru':
        $config['language'] = 'russian';
        setlocale(LC_ALL,'ru_RU.UTF-8'); 
        break;
        case 'uk':
        $config['language'] = 'ukrainian';
        setlocale(LC_ALL,'uk_UA.UTF-8'); 
                break;
        case 'foo':
        $config['language'] = 'foo';
        setlocale(LC_ALL,'foo_FOO.UTF-8'); 
                break;
        default:
        $config['language'] = 'english';
        setlocale(LC_ALL,'en_US.UTF-8'); 
        break;
}

.... and then i'm using usualy internal mechanizm of CI

o, almost forget! in views i using buttons, which seting cookie 'language' with language, prefered by user.

So, first this code try to detect "preffered language" setted in user`s useragent (browser). Then code try to read cookie 'language'. And finaly - switch sets language for CI-application

CSS get height of screen resolution

You can bind the current height and width of the screen to css variables: var(--screen-x) and var(--screen-y) with this javascript:

var root = document.documentElement;

document.addEventListener('resize', () => {
  root.style.setProperty('--screen-x', window.screenX)
  root.style.setProperty('--screen-y', window.screenY)
})

This was directly adapted from lea verou's example in her talk on css variables here: https://leaverou.github.io/css-variables/#slide31

TypeError: $.browser is undefined

Just include this script

http://code.jquery.com/jquery-migrate-1.0.0.js

after you include your jquery javascript file.

How to get all registered routes in Express?

Here is a one-line function to pretty-print the routes in an Express app:

const getAppRoutes = (app) => app._router.stack.reduce(
  (acc, val) => acc.concat(
    val.route ? [val.route.path] :
      val.name === "router" ? val.handle.stack.filter(
        x => x.route).map(
          x => val.regexp.toString().match(/\/[a-z]+/)[0] + (
            x.route.path === '/' ? '' : x.route.path)) : []) , []).sort();

jQuery UI Dialog with ASP.NET button postback

The exact solution is;

$("#dialogDiv").dialog({ other options...,
    open: function (type, data) {
        $(this).parent().appendTo("form");
    }
});

jQuery callback on image load (even when the image is cached)

Just re-add the src argument on a separate line after the img oject is defined. This will trick IE into triggering the lad-event. It is ugly, but it is the simplest workaround I've found so far.

jQuery('<img/>', {
    src: url,
    id: 'whatever'
})
.load(function() {
})
.appendTo('#someelement');
$('#whatever').attr('src', url); // trigger .load on IE

How to stop execution after a certain time in Java?

you should try the new Java Executor Services. http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

With this you don't need to program the loop the time measuring by yourself.

public class Starter {

    public static void main(final String[] args) {
        final ExecutorService service = Executors.newSingleThreadExecutor();

        try {
            final Future<Object> f = service.submit(() -> {
                // Do you long running calculation here
                Thread.sleep(1337); // Simulate some delay
                return "42";
            });

            System.out.println(f.get(1, TimeUnit.SECONDS));
        } catch (final TimeoutException e) {
            System.err.println("Calculation took to long");
        } catch (final Exception e) {
            throw new RuntimeException(e);
        } finally {
            service.shutdown();
        }
    }
}

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

I made a solution that works very nice for me:

function shadeColor(color, percent) {

    var R = parseInt(color.substring(1,3),16);
    var G = parseInt(color.substring(3,5),16);
    var B = parseInt(color.substring(5,7),16);

    R = parseInt(R * (100 + percent) / 100);
    G = parseInt(G * (100 + percent) / 100);
    B = parseInt(B * (100 + percent) / 100);

    R = (R<255)?R:255;  
    G = (G<255)?G:255;  
    B = (B<255)?B:255;  

    var RR = ((R.toString(16).length==1)?"0"+R.toString(16):R.toString(16));
    var GG = ((G.toString(16).length==1)?"0"+G.toString(16):G.toString(16));
    var BB = ((B.toString(16).length==1)?"0"+B.toString(16):B.toString(16));

    return "#"+RR+GG+BB;
}

Example Lighten:

shadeColor("#63C6FF",40);

Example Darken:

shadeColor("#63C6FF",-40);

Java - Convert integer to string

The way I know how to convert an integer into a string is by using the following code:

Integer.toString(int);

and

String.valueOf(int);

If you had an integer i, and a string s, then the following would apply:

int i;
String s = Integer.toString(i); or
String s = String.valueOf(i);

If you wanted to convert a string "s" into an integer "i", then the following would work:

i = Integer.valueOf(s).intValue();