Programs & Examples On #Offline caching

Offline caching typically means storing locally the data obtained from a remote service to make it possible to browse the data even when there is no connection to the storage.

What is the difference between "expose" and "publish" in Docker?

Basically, you have three options:

  1. Neither specify EXPOSE nor -p
  2. Only specify EXPOSE
  3. Specify EXPOSE and -p

1) If you specify neither EXPOSE nor -p, the service in the container will only be accessible from inside the container itself.

2) If you EXPOSE a port, the service in the container is not accessible from outside Docker, but from inside other Docker containers. So this is good for inter-container communication.

3) If you EXPOSE and -p a port, the service in the container is accessible from anywhere, even outside Docker.

The reason why both are separated is IMHO because:

  • choosing a host port depends on the host and hence does not belong to the Dockerfile (otherwise it would be depending on the host),
  • and often it's enough if a service in a container is accessible from other containers.

The documentation explicitly states:

The EXPOSE instruction exposes ports for use within links.

It also points you to how to link containers, which basically is the inter-container communication I talked about.

PS: If you do -p, but do not EXPOSE, Docker does an implicit EXPOSE. This is because if a port is open to the public, it is automatically also open to other Docker containers. Hence -p includes EXPOSE. That's why I didn't list it above as a fourth case.

Angular 2 Checkbox Two Way Data Binding

I have done a custom component tried two way binding

Mycomponent: <input type="checkbox" [(ngModel)]="model" >

_model:  boolean;   

@Output() checked: EventEmitter<boolean> = new EventEmitter<boolean>();

@Input('checked')
set model(checked: boolean) {

  this._model = checked;
  this.checked.emit(this._model);
  console.log('@Input(setmodel'+checked);
}

get model() {
  return this._model;
}

strange thing is this works

<mycheckbox  [checked]="isChecked" (checked)="isChecked = $event">

while this wont

<mycheckbox  [(checked)]="isChecked">

How to check if an array value exists?

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

Another use of in_array in_array() with an array as needle

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was found\n";
}

if (in_array(array('f', 'i'), $a)) {
    echo "'fi' was found\n";
}

if (in_array('o', $a)) {
    echo "'o' was found\n";
}
?>

Not unique table/alias

Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.

Try

    SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
      FROM Project_Assigned pa
INNER JOIN Account a
        ON pa.AccountID = a.Account_ID
INNER JOIN Project p
        ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
        ON a.Account_ID = c.Account_ID
     WHERE a.Access_Type = 'Client';

How to run jenkins as a different user

If you really want to run Jenkins as you, I suggest you check out my Jenkins.app. An alternative, easy way to run Jenkins on Mac.

See https://github.com/stisti/jenkins-app/

Download it from https://github.com/stisti/jenkins-app/downloads

Dependency injection with Jersey 2.0

Dependency required for jersey restful service and Tomcat is the server. where ${jersey.version} is 2.29.1

    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>2.0.SP1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
        <version>${jersey.version}</version>
    </dependency>

The basic code will be as follows:

@RequestScoped
@Path("test")
public class RESTEndpoint {

   @GET
   public String getMessage() {

AngularJS - Access to child scope

You can try this:

$scope.child = {} //declare it in parent controller (scope)

then in child controller (scope) add:

var parentScope = $scope.$parent;
parentScope.child = $scope;

Now the parent has access to the child's scope.

Javascript decoding html entities

Using jQuery the easiest will be:

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';

var output = $("<div />").html(text).text();
console.log(output);

DEMO: http://jsfiddle.net/LKGZx/

Vue.js getting an element within a component

vuejs 2

v-el:el:uniquename has been replaced by ref="uniqueName". The element is then accessed through this.$refs.uniqueName.

Python datetime strptime() and strftime(): how to preserve the timezone information

Try this:

import pytz
import datetime

fmt = '%Y-%m-%d %H:%M:%S %Z'

d = datetime.datetime.now(pytz.timezone("America/New_York"))
d_string = d.strftime(fmt)
d2 = pytz.timezone('America/New_York').localize(d.strptime(d_string,fmt), is_dst=None)
print(d_string)
print(d2.strftime(fmt))

Add legend to ggplot2 line plot

Since @Etienne asked how to do this without melting the data (which in general is the preferred method, but I recognize there may be some cases where that is not possible), I present the following alternative.

Start with a subset of the original data:

datos <-
structure(list(fecha = structure(c(1317452400, 1317538800, 1317625200, 
1317711600, 1317798000, 1317884400, 1317970800, 1318057200, 1318143600, 
1318230000, 1318316400, 1318402800, 1318489200, 1318575600, 1318662000, 
1318748400, 1318834800, 1318921200, 1319007600, 1319094000), class = c("POSIXct", 
"POSIXt"), tzone = ""), TempMax = c(26.58, 27.78, 27.9, 27.44, 
30.9, 30.44, 27.57, 25.71, 25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 
26.58, 26.18, 25.19, 24.19, 27.65, 23.92), TempMedia = c(22.88, 
22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52, 19.71, 20.73, 
23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 20.45, 19.42, 19.97, 
19.61), TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 
16.88, 16.82, 14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 
16.95, 17.55, 15.21, 14.22, 16.42)), .Names = c("fecha", "TempMax", 
"TempMedia", "TempMin"), row.names = c(NA, 20L), class = "data.frame")

You can get the desired effect by (and this also cleans up the original plotting code):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMax", "TempMedia", "TempMin"),
                      values = c("red", "green", "blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

The idea is that each line is given a color by mapping the colour aesthetic to a constant string. Choosing the string which is what you want to appear in the legend is the easiest. The fact that in this case it is the same as the name of the y variable being plotted is not significant; it could be any set of strings. It is very important that this is inside the aes call; you are creating a mapping to this "variable".

scale_colour_manual can now map these strings to the appropriate colors. The result is enter image description here

In some cases, the mapping between the levels and colors needs to be made explicit by naming the values in the manual scale (thanks to @DaveRGP for pointing this out):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

(giving the same figure as before). With named values, the breaks can be used to set the order in the legend and any order can be used in the values.

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMedia", "TempMax", "TempMin"),
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

Python read JSON file and modify

Set item using data['id'] = ....

import json

with open('data.json', 'r+') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.
    f.seek(0)        # <--- should reset file position to the beginning.
    json.dump(data, f, indent=4)
    f.truncate()     # remove remaining part

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

The problem is that you're calling List<T>.Reverse() which returns void.

You could either do:

List<string> names = "Tom,Scott,Bob".Split(',').ToList<string>();
names.Reverse();

or:

IList<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>();

The latter is more expensive, as reversing an arbitrary IEnumerable<T> involves buffering all of the data and then yielding it all - whereas List<T> can do all the reversing "in-place". (The difference here is that it's calling the Enumerable.Reverse<T>() extension method, instead of the List<T>.Reverse() instance method.)

More efficient yet, you could use:

string[] namesArray = "Tom,Scott,Bob".Split(',');
List<string> namesList = new List<string>(namesArray.Length);
namesList.AddRange(namesArray);
namesList.Reverse();

This avoids creating any buffers of an inappropriate size - at the cost of taking four statements where one will do... As ever, weigh up readability against performance in the real use case.

Count how many files in directory PHP

You should have :

<div id="header">
<?php 
    // integer starts at 0 before counting
    $i = 0; 
    $dir = 'uploads/';
    if ($handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false){
            if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) 
                $i++;
        }
    }
    // prints out how many were in the directory
    echo "There were $i files";
?>
</div>

How to draw a graph in PHP?

You can use google's chart api to generate charts.

How to output messages to the Eclipse console when developing for Android

i use below log format for print my content in logCat

Log.e("Msg","What you have to print");

Implementation difference between Aggregation and Composition in Java

Aggregation vs Composition

Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist.

whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human.

Aggregation relation is “has-a” and composition is “part-of” relation.

Composition is a strong Association whereas Aggregation is a weak Association.

Rails 3 execute custom sql query without a model

I'd recommend using ActiveRecord::Base.connection.exec_query instead of ActiveRecord::Base.connection.execute which returns a ActiveRecord::Result (available in rails 3.1+) which is a bit easier to work with.

Then you can access it in various the result in various ways like .rows, .each, or .to_hash

From the docs:

result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>


# Get the column names of the result:
result.columns
# => ["id", "title", "body"]

# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
      [2, "title_2", "body_2"],
      ...
     ]

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

# ActiveRecord::Result also includes Enumerable.
result.each do |row|
  puts row['title'] + " " + row['body']
end

note: copied my answer from here

iPhone/iPad browser simulator?

There's no good substitute to testing on an actual device.

Real devices have higher display densities, meaning that pixels are smaller. If you don't test on a real device, you may not realise that your design includes text that is too small to read or buttons that are too small to tap.

You use real devices with your fingers, not a mouse. This means that the accuracy of your taps is much lower and what you are tapping is obscured by your finger. If you don't test on a real device, you may not realise you've introduced usability problems into your design.

Android Failed to install HelloWorld.apk on device (null) Error

I get this from time to time, but it's usually related to the emulator being slow to start. Try again without closing the emulator between the retries. And if it still fails, please post the client logs (logcat).

Another reason can be a ghost Eclipse process running in background and still bound to the debugging port. Close eclipse, look at process list and see if there's still an Eclipse running. Kill all of them and restart Eclipse again.

How to make a Bootstrap accordion collapse when clicking the header div?

Another way is make your <a> full fill all the space of the panel-heading. Use this style to do so:

.panel-title a {
    display: block;
    padding: 10px 15px;
    margin: -10px -15px;
}

Check this demo (http://jsfiddle.net/KbQyx/).

Then when you clicking on the heading, you are actually clicking on the <a>.

Set textarea width to 100% in bootstrap modal

I had the same problem. I fixed it by adding this piece of code inside the text area's style.

resize: vertical;

You can check the Bootstrap reference here

How to access html form input from asp.net code behind

It should normally be done with Request.Form["elementName"].

For example, if you have <input type="text" name="email" /> then you can use Request.Form["email"] to access its value.

Changing iframe src with Javascript

Here's the jQuery way to do it:

$('#calendar').attr('src', loc);

How to change maven logging level to display only warning and errors?

The simplest way is to upgrade to Maven 3.3.1 or higher to take advantage of the ${maven.projectBasedir}/.mvn/jvm.config support.

Then you can use any options from Maven's SL4FJ's SimpleLogger support to configure all loggers or particular loggers. For example, here is a how to make all warning at warn level, except for a the PMD which is configured to log at error:

cat .mvn/jvm.config
-Dorg.slf4j.simpleLogger.defaultLogLevel=warn -Dorg.slf4j.simpleLogger.log.net.sourceforge.pmd=error

See here for more details on logging with Maven.

convert string to number node.js

Not a full answer Ok so this is just to supplement the information about parseInt, which is still very valid. Express doesn't allow the req or res objects to be modified at all (immutable). So if you want to modify/use this data effectively, you must copy it to another variable (var year = req.params.year).

java.lang.OutOfMemoryError: Java heap space in Maven

In order to resolve java.lang.OutOfMemoryError: Java heap space in Maven, try to configure below configuration in pom

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>${maven-surefire-plugin.version}</version>
     <configuration>
        <verbose>true</verbose>
        <fork>true</fork>
        <argLine>-XX:MaxPermSize=500M</argLine>
    </configuration>
</plugin>

Error You must specify a region when running command aws ecs list-container-instances

#1- Run this to configure the region once and for all:

aws configure set region us-east-1 --profile admin
  • Change admin next to the profile if it's different.

  • Change us-east-1 if your region is different.

#2- Run your command again:

aws ecs list-container-instances --cluster default

Android studio takes too much memory

You can speed up your Eclipse or Android Studio work, you just follow these:

  • Use/open single project at a time
  • clean your project after running your app in emulator every time
  • use mobile/external device instead of emulator
  • don't close emulator after using once, use same emulator for running app each time
  • Disable VCS by using File->Settings->Plugins and disable the following things :
    1.CVS Integration
    2.Git Integration
    3.GitHub
    4.Google Cloud Tools for Android Studio
    5.Subversion Integration

I am also using Android Studio with 4-GB installed main memory but following these statements really boost my Android Studio performance.

Python 3 Float Decimal Points/Precision

The comments state the objective is to print to 2 decimal places.

There's a simple answer for Python 3:

>>> num=3.65
>>> "The number is {:.2f}".format(num)
'The number is 3.65'

or equivalently with f-strings (Python 3.6+):

>>> num = 3.65
>>> f"The number is {num:.2f}"
'The number is 3.65'

As always, the float value is an approximation:

>>> "{}".format(num)
'3.65'
>>> "{:.10f}".format(num)
'3.6500000000'
>>> "{:.20f}".format(num)
'3.64999999999999991118'

I think most use cases will want to work with floats and then only print to a specific precision.

Those that want the numbers themselves to be stored to exactly 2 decimal digits of precision, I suggest use the decimal type. More reading on floating point precision for those that are interested.

cannot be cast to java.lang.Comparable

  • the object which implements Comparable is Fegan.

The method compareTo you are overidding in it should have a Fegan object as a parameter whereas you are casting it to a FoodItems. Your compareTo implementation should describe how a Fegan compare to another Fegan.

  • To actually do your sorting, you might want to make your FoodItems implement Comparable aswell and copy paste your actual compareTo logic in it.

Auto logout with Angularjs based on idle user

I think Buu's digest cycle watch is genius. Thanks for sharing. As others have noted $interval also causes the digest cycle to run. We could for the purpose of auto logging the user out use setInterval which will not cause a digest loop.

app.run(function($rootScope) {
    var lastDigestRun = new Date();
    setInterval(function () {
        var now = Date.now();
        if (now - lastDigestRun > 10 * 60 * 1000) {
          //logout
        }
    }, 60 * 1000);

    $rootScope.$watch(function() {
        lastDigestRun = new Date();
    });
});

How to disable spring security for particular url

When using permitAll it means every authenticated user, however you disabled anonymous access so that won't work.

What you want is to ignore certain URLs for this override the configure method that takes WebSecurity object and ignore the pattern.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/v1/signup");
}

And remove that line from the HttpSecurity part. This will tell Spring Security to ignore this URL and don't apply any filters to them.

Declare a variable as Decimal

You can't declare a variable as Decimal - you have to use Variant (you can use CDec to populate it with a Decimal type though).

Get top most UIViewController

I loved @dianz's answer, and so here is the swift 3's version of it. It's basically the same thing but his was missing a curly brace and some of the syntax/variable/method names have changed. So here it is!

extension UIApplication {
    class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return topViewController(base: nav.visibleViewController)
        }
        if let tab = base as? UITabBarController {
            if let selected = tab.selectedViewController {
                return topViewController(base: selected)
            }
        }
        if let presented = base?.presentedViewController {
            return topViewController(base: presented)
        }
        return base
    }
}

Usage is still the exact same though:

if let topController = UIApplication.topViewController() {
    print("The view controller you're looking at is: \(topController)")
}

Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

Remove the starting slash ('\') in the second parameter (path2) of Path.Combine.

How to generate JAXB classes from XSD?

You can also generate source code from schema using jaxb2-maven-plugin plugin:

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jaxb2-maven-plugin</artifactId>
            <version>2.2</version>
            <executions>
                <execution>
                    <goals>
                        <goal>xjc</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <sources>
                    <source>src/main/resources/your_schema.xsd</source>
                </sources>
                <xjbSources>
                    <xjbSource>src/main/resources/bindings.xjb</xjbSource>
                </xjbSources>
                <packageName>some_package</packageName>
                <outputDirectory>src/main/java</outputDirectory>
                <clearOutputDir>false</clearOutputDir>
                <generateEpisode>false</generateEpisode>
                <noGeneratedHeaderComments>true</noGeneratedHeaderComments>
            </configuration>
        </plugin>

How can I remove all files in my git repo and update/push from my local git repo?

Do a git add -A from the top of the working copy, take a look at git status and/or git diff --cached to review what you're about to do, then git commit the result.

CodeIgniter: Create new helper?

Just define a helper in application helper directory then call from your controller just function name like

helper name = new_helper.php
function test_method($data){
 return $data
}   

in controller load the helper

$this->load->new_helper();
$result =  test_method('Hello world!');
if($result){
 echo $result
}

output will be

Hello World!

AJAX cross domain call

after doing some research, the only "solution" to this problem is to call:

if($.browser.mozilla)
   netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');

this will ask an user if he allows a website to continue. After he confirmed that, all ajax calls regardless of it's datatype will get executed.

This works for mozilla browsers, in IE < 8, an user has to allow a cross domain call in a similar way, some version need to get configured within browser options.

chrome/safari: I didn't find a config flag for those browsers so far.

using JSONP as datatype would be nice, but in my case I don't know if a domain I need to access supports data in that format.

Another shot is to use HTML5 postMessage which works cross-domain aswell, but I can't afford to doom my users to HTML5 browsers.

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:

<location path="YourWebservice.asmx">
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</location>

Eclipse error: R cannot be resolved to a variable

In addition to install the build tools and restart the update manager I also had to restart Eclipse to make this work.

Tree data structure in C#

The generally excellent C5 Generic Collection Library has several different tree-based data structures, including sets, bags and dictionaries. Source code is available if you want to study their implementation details. (I have used C5 collections in production code with good results, although I haven't used any of the tree structures specifically.)

Get only part of an Array in Java?

You can use subList(int fromIndex, int toIndex) method on your integers arr, something like this:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
        List<Integer> partialArr = arr.subList(1, 3);

        // print the subArr
        for (Integer i: partialArr)
            System.out.println(i + " ");
    }
}

Output will be: 2 3.

Note that subList(int fromIndex, int toIndex) method performs minus 1 on the 2nd variable it receives (var2 - 1), i don't know exactly why, but that's what happens, maybe to reduce the chance of exceeding the size of the array.

Eclipse hangs on loading workbench

None of the solution helped me for my case.

I found the working solution though. I read that this happens when ADT plugin is not updated properly in Eclipse.

Solution
From Eclipse. . .
1. Go to Help Tap
2. Click Check for Updates

Update everything and whoa! No longer freezing at starting Eclipse!

Create a folder and sub folder in Excel VBA

There are some good answers on here, so I will just add some process improvements. A better way of determining if the folder exists (does not use FileSystemObjects, which not all computers are allowed to use):

Function FolderExists(FolderPath As String) As Boolean
     FolderExists = True
     On Error Resume Next
     ChDir FolderPath
     If Err <> 0 Then FolderExists = False
     On Error GoTo 0
End Function

Likewise,

Function FileExists(FileName As String) As Boolean
     If Dir(FileName) <> "" Then FileExists = True Else FileExists = False
EndFunction

array_push() with key value pair

$data['cat'] = 'wagon';

That's all you need to add the key and value to the array.

Convert char array to string use C

You're saying you have this:

char array[20]; char string[100];
array[0]='1'; 
array[1]='7'; 
array[2]='8'; 
array[3]='.'; 
array[4]='9';

And you'd like to have this:

string[0]= "178.9"; // where it was stored 178.9 ....in position [0]

You can't have that. A char holds 1 character. That's it. A "string" in C is an array of characters followed by a sentinel character (NULL terminator).

Now if you want to copy the first x characters out of array to string you can do that with memcpy():

memcpy(string, array, x);
string[x] = '\0'; 

Make div fill remaining space along the main axis in flexbox

Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex on the row container and at least making sure your middle container on the row has a flex-grow value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow properties applied, middle container only needs 1 for flex-grow).

Here's a pic of what I was trying to do and sample code for how I solved it.

enter image description here

_x000D_
_x000D_
.row {
  background: lightgray;
  height: 30px;
  width: 100%;
  display: flex;
  align-items:flex-end;
  margin-top:5px;
}
.left {
  background:lightblue;
}
.separator{
  flex-grow:1;
  border-bottom:dotted 2px black;
}
.right {
  background:coral;
}
_x000D_
<div class="row">
  <div class="left">Left</div>
  <div class="separator"></div>
  <div class="right">Right With Text</div>
</div>
<div class="row">
  <div class="left">Left With More Text</div>
  <div class="separator"></div>
  <div class="right">Right</div>
</div>
<div class="row">
  <div class="left">Left With Text</div>
  <div class="separator"></div>
  <div class="right">Right With More Text</div>
</div>
_x000D_
_x000D_
_x000D_

How to import a SQL Server .bak file into MySQL?

I highly doubt it. You might want to use DTS/SSIS to do this as Levi says. One think that you might want to do is start the process without actually importing the data. Just do enough to get the basic table structures together. Then you are going to want to change around the resulting table structure, because whatever structure tat will likely be created will be shaky at best.

You might also have to take this a step further and create a staging area that takes in all the data first n a string (varchar) form. Then you can create a script that does validation and conversion to get it into the "real" database, because the two databases don't always work well together, especially when dealing with dates.

PHP: Read Specific Line From File

This question is quite old by now, but for anyone dealing with very large files, here is a solution that does not involve reading every preceding line. This was also the only solution that worked in my case for a file with ~160 million lines.

<?php
function rand_line($fileName) {
    do{
        $fileSize=filesize($fileName);
        $fp = fopen($fileName, 'r');
        fseek($fp, rand(0, $fileSize));
        $data = fread($fp, 4096);  // assumes lines are < 4096 characters
        fclose($fp);
        $a = explode("\n",$data);
    }while(count($a)<2);
    return $a[1];
}

echo rand_line("file.txt");  // change file name
?>

It works by opening the file without reading anything, then moving the pointer instantly to a random position, reading up to 4096 characters from that point, then grabbing the first complete line from that data.

Why can't I set text to an Android TextView?

You set the text to a field that was rendered in another instance of your activity residing in cash,say when it was landscape oriented. Then it was recreated due to some reason. You need to set the text in an unusual way by saving the string to SharedPreferences and force relaunch the activity using recreate(), say for mOutputText:

@Override
protected void onResume() {
    super.onResume();
    String sLcl=mPreferences.getString("response","");
    if(!sLcl.isEmpty()){
        mOutputText.setText(sLcl);
        mPreferences.edit().putString("response","").commit();
    }
}

private void changeText() {
    mPreferences.edit().putString("response",responseText).commit();
    recreate();
}
@Override
protected void onActivityResult(
        int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case CAPTURE_MEDIA_RESULT_CODE:
            if (null == data || null == data.getData()) {
               showMessage("Sorry. You didn't save any video");
            } else {
                videoUri = data.getData();
                mProgress = new ProgressDialog(this);
                mProgress.setMessage("Uploading onYoutube ...");

                authorizeIt();// SAY YOU CALL THE changeText() at the end of this method
            }
            break;
    }
}

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Can you get the number of lines of code from a GitHub repository?

If the question is "can you quickly get NUMBER OF LINES of a github repo", the answer is no as stated by the other answers.

However, if the question is "can you quickly check the SCALE of a project", I usually gauge a project by looking at its size. Of course the size will include deltas from all active commits, but it is a good metric as the order of magnitude is quite close.

E.g.

How big is the "docker" project?

In your browser, enter api.github.com/repos/ORG_NAME/PROJECT_NAME i.e. api.github.com/repos/docker/docker

In the response hash, you can find the size attribute:

{
    ...
    size: 161432,
    ...
}

This should give you an idea of the relative scale of the project. The number seems to be in KB, but when I checked it on my computer it's actually smaller, even though the order of magnitude is consistent. (161432KB = 161MB, du -s -h docker = 65MB)

How can I URL encode a string in Excel VBA?

No, nothing built-in (until Excel 2013 - see this answer).

There are three versions of URLEncode() in this answer.

  • A function with UTF-8 support. You should probably use this one (or the alternative implementation by Tom) for compatibility with modern requirements.
  • For reference and educational purposes, two functions without UTF-8 support:
    • one found on a third party website, included as-is. (This was the first version of the answer)
    • one optimized version of that, written by me

A variant that supports UTF-8 encoding and is based on ADODB.Stream (include a reference to a recent version of the "Microsoft ActiveX Data Objects" library in your project):

Public Function URLEncode( _
   ByVal StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String
  Dim bytes() As Byte, b As Byte, i As Integer, space As String

  If SpaceAsPlus Then space = "+" Else space = "%20"

  If Len(StringVal) > 0 Then
    With New ADODB.Stream
      .Mode = adModeReadWrite
      .Type = adTypeText
      .Charset = "UTF-8"
      .Open
      .WriteText StringVal
      .Position = 0
      .Type = adTypeBinary
      .Position = 3 ' skip BOM
      bytes = .Read
    End With

    ReDim result(UBound(bytes)) As String

    For i = UBound(bytes) To 0 Step -1
      b = bytes(i)
      Select Case b
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Chr(b)
        Case 32
          result(i) = space
        Case 0 To 15
          result(i) = "%0" & Hex(b)
        Case Else
          result(i) = "%" & Hex(b)
      End Select
    Next i

    URLEncode = Join(result, "")
  End If
End Function

This function was found on freevbcode.com:

Public Function URLEncode( _
   StringToEncode As String, _
   Optional UsePlusRatherThanHexForSpace As Boolean = False _
) As String

  Dim TempAns As String
  Dim CurChr As Integer
  CurChr = 1

  Do Until CurChr - 1 = Len(StringToEncode)
    Select Case Asc(Mid(StringToEncode, CurChr, 1))
      Case 48 To 57, 65 To 90, 97 To 122
        TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
      Case 32
        If UsePlusRatherThanHexForSpace = True Then
          TempAns = TempAns & "+"
        Else
          TempAns = TempAns & "%" & Hex(32)
        End If
      Case Else
        TempAns = TempAns & "%" & _
          Right("0" & Hex(Asc(Mid(StringToEncode, _
          CurChr, 1))), 2)
    End Select

    CurChr = CurChr + 1
  Loop

  URLEncode = TempAns
End Function

I've corrected a little bug that was in there.


I would use more efficient (~2× as fast) version of the above:

Public Function URLEncode( _
   StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String

  Dim StringLen As Long: StringLen = Len(StringVal)

  If StringLen > 0 Then
    ReDim result(StringLen) As String
    Dim i As Long, CharCode As Integer
    Dim Char As String, Space As String

    If SpaceAsPlus Then Space = "+" Else Space = "%20"

    For i = 1 To StringLen
      Char = Mid$(StringVal, i, 1)
      CharCode = Asc(Char)
      Select Case CharCode
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Char
        Case 32
          result(i) = Space
        Case 0 To 15
          result(i) = "%0" & Hex(CharCode)
        Case Else
          result(i) = "%" & Hex(CharCode)
      End Select
    Next i
    URLEncode = Join(result, "")
  End If
End Function

Note that neither of these two functions support UTF-8 encoding.

number of values in a list greater than a certain number

You can do like this using function:

l = [34,56,78,2,3,5,6,8,45,6]  
print ("The list : " + str(l))   
def count_greater30(l):  
    count = 0  
    for i in l:  
        if i > 30:  
            count = count + 1.  
    return count
print("Count greater than 30 is : " + str(count)).  
count_greater30(l)

Redirect all output to file using Bash on Linux?

Though not POSIX, bash 4 has the &> operator:

command &> alloutput.txt

How do I build JSON dynamically in javascript?

As myJSON is an object you can just set its properties, for example:

myJSON.list1 = ["1","2"];

If you dont know the name of the properties, you have to use the array access syntax:

myJSON['list'+listnum] = ["1","2"];

If you want to add an element to one of the properties, you can do;

myJSON.list1.push("3");

In excel how do I reference the current row but a specific column?

To static either a row or a column, put a $ sign in front of it. So if you were to use the formula =AVERAGE($A1,$C1) and drag it down the entire sheet, A and C would remain static while the 1 would change to the current row

If you're on Windows, you can achieve the same thing by repeatedly pressing F4 while in the formula editing bar. The first F4 press will static both (it will turn A1 into $A$1), then just the row (A$1) then just the column ($A1)

Although technically with the formulas that you have, dragging down for the entirety of the column shouldn't be a problem without putting a $ sign in front of the column. Setting the column as static would only come into play if you're dragging ACROSS columns and want to keep using the same column, and setting the row as static would be for dragging down rows but wanting to use the same row.

Convert a object into JSON in REST service by Spring MVC

Another simple solution is to add jackson-databind dependency in POM.

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.1</version>
    </dependency>

Keep Rest of the code as it is.

What is the most useful script you've written for everyday life?

Best real-life script?

Me: (Enters room) "Boss, I want a raise."

Boss: (Offers chair from behind desk) "A raise? Please, take my job!"

Then again, that may be the worst script!

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

AngularJS: ng-model not binding to ng-checked for checkboxes

You don't need ng-checked when you use ng-model. If you're performing CRUD on your HTML Form, just create a model for CREATE mode that is consistent with your EDIT mode during the data-binding:

CREATE Mode: Model with default values only

$scope.dataModel = {
   isItemSelected: true,
   isApproved: true,
   somethingElse: "Your default value"
}

EDIT Mode: Model from database

$scope.dataModel = getFromDatabaseWithSameStructure()

Then whether EDIT or CREATE mode, you can consistently make use of your ng-model to sync with your database.

How to remove td border with html?

simple solution from my end is to keep another Table with border and insert your table in the outer table.

<table border="1">
<tr>
    <td>
        <table border="0">
            <tr>
                <td>one</td>
                <td>two</td>
            </tr>
            <tr>
                <td>one</td>
                <td>two</td>
            </tr>
        </table>
    </td>
</tr>

</table>

Changing color of Twitter bootstrap Nav-Pills

The most voted solution did not work for me.(Bootstrap 3.0.0) However, this did:

.nav-pills > li.active > a, .nav-pills > li.active > a:hover, .nav-pills > li.active > a:focus {
    color:black;
    background-color:#fcd900;
    }

including this on the page <style></style> tags serves for the per page basis well

and mixing it on two shades gives a brilliant effect like:

<style>
    .nav-pills > li.active > a, .nav-pills > li.active > a:focus {
        color: black;
        background-color: #fcd900;
    }

        .nav-pills > li.active > a:hover {
            background-color: #efcb00;
            color:black;
        }
</style>

JavaScript hard refresh of current page

window.location.href = window.location.href

What is a raw type and why shouldn't we use it?

What is a raw type and why do I often hear that they shouldn't be used in new code?

A "raw type" is the use of a generic class without specifying a type argument(s) for its parameterized type(s), e.g. using List instead of List<String>. When generics were introduced into Java, several classes were updated to use generics. Using these class as a "raw type" (without specifying a type argument) allowed legacy code to still compile.

"Raw types" are used for backwards compatibility. Their use in new code is not recommended because using the generic class with a type argument allows for stronger typing, which in turn may improve code understandability and lead to catching potential problems earlier.

What is the alternative if we can't use raw types, and how is it better?

The preferred alternative is to use generic classes as intended - with a suitable type argument (e.g. List<String>). This allows the programmer to specify types more specifically, conveys more meaning to future maintainers about the intended use of a variable or data structure, and it allows compiler to enforce better type-safety. These advantages together may improve code quality and help prevent the introduction of some coding errors.

For example, for a method where the programmer wants to ensure a List variable called 'names' contains only Strings:

List<String> names = new ArrayList<String>();
names.add("John");          // OK
names.add(new Integer(1));  // compile error

sqlite database default time value 'now'

This alternative example stores the local time as Integer to save the 20 bytes. The work is done in the field default, Update-trigger, and View. strftime must use '%s' (single-quotes) because "%s" (double-quotes) threw a 'Not Constant' error on me.

Create Table Demo (
   idDemo    Integer    Not Null Primary Key AutoIncrement
  ,DemoValue Text       Not Null Unique
  ,DatTimIns Integer(4) Not Null Default (strftime('%s', DateTime('Now', 'localtime'))) -- get Now/UTC, convert to local, convert to string/Unix Time, store as Integer(4)
  ,DatTimUpd Integer(4)     Null
);

Create Trigger trgDemoUpd After Update On Demo Begin
  Update Demo Set
    DatTimUpd  =                          strftime('%s', DateTime('Now', 'localtime'))  -- same as DatTimIns
  Where idDemo = new.idDemo;
End;

Create View If Not Exists vewDemo As Select -- convert Unix-Times to DateTimes so not every single query needs to do so
   idDemo
  ,DemoValue
  ,DateTime(DatTimIns, 'unixepoch') As DatTimIns -- convert Integer(4) (treating it as Unix-Time)
  ,DateTime(DatTimUpd, 'unixepoch') As DatTimUpd --   to YYYY-MM-DD HH:MM:SS
From Demo;

Insert Into Demo (DemoValue) Values ('One');                      -- activate the field Default
-- WAIT a few seconds --    
Insert Into Demo (DemoValue) Values ('Two');                      -- same thing but with
Insert Into Demo (DemoValue) Values ('Thr');                      --   later time values

Update Demo Set DemoValue = DemoValue || ' Upd' Where idDemo = 1; -- activate the Update-trigger

Select * From    Demo;                                            -- display raw audit values
idDemo  DemoValue  DatTimIns   DatTimUpd
------  ---------  ----------  ----------
1       One Upd    1560024902  1560024944
2       Two        1560024944
3       Thr        1560024944

Select * From vewDemo;                                            -- display automatic audit values
idDemo  DemoValue  DatTimIns            DatTimUpd
------  ---------  -------------------  -------------------
1       One Upd    2019-06-08 20:15:02  2019-06-08 20:15:44
2       Two        2019-06-08 20:15:44
3       Thr        2019-06-08 20:15:44

submit form on click event using jquery

If you have a form action and an input type="submit" inside form tags, it's going to submit the old fashioned way and basically refresh the page. When doing AJAX type transactions this isn't the desired effect you are after.

Remove the action. Or remove the form altogether, though in cases it does come in handy to serialize to cut your workload. If the form tags remain, move the button outside the form tags, or alternatively make it a link with an onclick or click handler as opposed to an input button. Jquery UI Buttons works great in this case because you can mimic an input button with an a tag element.

OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

As you can see from this example: http://jsfiddle.net/UTwGS/

HTML:

<label><input type="radio" value="1" name="my-radio">Radio One</label>
<label><input type="radio" value="2" name="my-radio">Radio One</label>

jQuery:

$('input[type="radio"]').on('click change', function(e) {
    console.log(e.type);
});

both the click and change events are fired when selecting a radio button option (at least in some browsers).

I should also point out that in my example the click event is still fired when you use tab and the keyboard to select an option.

So, my point is that even though the change event is fired is some browsers, the click event should supply the coverage you need.

What represents a double in sql server?

It sounds like you can pick and choose. If you pick float, you may lose 11 digits of precision. If that's acceptable, go for it -- apparently the Linq designers thought this to be a good tradeoff.

However, if your application needs those extra digits, use decimal. Decimal (implemented correctly) is way more accurate than a float anyway -- no messy translation from base 10 to base 2 and back.

How do I create a self-signed certificate for code signing on Windows?

As of PowerShell 4.0 (Windows 8.1/Server 2012 R2) it is possible to make a certificate in Windows without makecert.exe.

The commands you need are New-SelfSignedCertificate and Export-PfxCertificate.

Instructions are in Creating Self Signed Certificates with PowerShell.

DateTimePicker: pick both date and time

Set the Format to Custom and then specify the format:

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss";  

or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May)

Don't know about the picker for date and time together. Sounds like a custom control to me.

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

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

Another easy way to do this is to place your UIImageView within a UIScrollView. As I describe here, you need to set the scroll view's contentSize to be the same as your UIImageView's size. Set your controller instance to be the delegate of the scroll view and implement the viewForZoomingInScrollView: and scrollViewDidEndZooming:withView:atScale: methods to allow for pinch-zooming and image panning. This is effectively what Ben's solution does, only in a slightly more lightweight manner, as you don't have the overhead of a full web view.

One issue you may run into is that the scaling within the scroll view comes in the form of transforms applied to the image. This may lead to blurriness at high zoom factors. For something that can be redrawn, you can follow my suggestions here to provide a crisper display after the pinch gesture is finished. hniels' solution could be used at that point to rescale your image.

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

node.js string.replace doesn't work?

Isn't string.replace returning a value, rather than modifying the source string?

So if you wanted to modify variableABC, you'd need to do this:

var variableABC = "A B C";

variableABC = variableABC.replace('B', 'D') //output: 'A D C'

IE8 support for CSS Media Query

css3-mediaqueries-js is probably what you are looking for: this script emulates media queries. However (from the script's site) it "doesn't work on @imported stylesheets (which you shouldn't use anyway for performance reasons). Also won't listen to the media attribute of the <link> and <style> elements".

In the same vein you have the simpler Respond.js, which enables only min-width and max-width media queries.

Angular, content type is not being sent with $http

$http({
    url: 'http://localhost:8080/example/teste',
    dataType: 'json',
    method: 'POST',
    data: '',
    headers: {
        "Content-Type": "application/json"
    }

}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});

Try like this.

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

All of these options work depending on your situation, but you may not see any of them work if you're using SSMS (as mentioned in some comments SSMS hides CR/LFs)

So rather than driving yourself round the bend, Check this setting in

Tools | Options

which will replace the

Send email with PHPMailer - embed image in body

I found the answer:

$mail->AddEmbeddedImage('img/2u_cs_mini.jpg', 'logo_2u');

and on the <img> tag put src='cid:logo_2u'

Set up adb on Mac OS X

After trying all the solutions, none of them where working for me.

In my case I had the Android Studio and the adb was correctly working but the Android Studio was not capable to detect the adb. These was because I installed it with homebrew in another directory, not the /Users/$USER/Library/Android/sdk but Usr/Library blabla

Apparently AS needed to have it in his route /Users/$USER/Library/Android/sdk (same place as in preferences SDK installation route)

So I deleted all the adb from my computer (I installed several) and executed these terminal commands:

echo 'export ANDROID_HOME=/Users/$USER/Library/Android/sdk' >> ~/.bash_profile
echo 'export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools' >> ~/.bash_profile
source ~/.bash_profile
adb devices

Well, after that, still wasn't working, because for some reason the route for the adb was /Users/$USER/Library/Android/sdk/platform-tools/platform-tools (yes, repeated) so I just copied the last platform-tools into the first directory with all the license files and started working.

Weird but true

How do I change the default library path for R packages

After a couple of hours of trying to solve the issue in several ways, some of which are described here, for me (on Win 10) the option of creating a Renviron file worked, but a little different from what was written here above. The task is to change the value of the variable R_LIBS_USER. To do this two steps needed:

  1. Create the file named Renviron (without dot) in the folder \Program\etc\ (Programm is the directory where the R installed, for example for me it was c:\Program Files\R\R-4.0.0\etc)
  2. Insert a line in Renviron with new path: R_LIBS_USER=c:/R/Library

It's been working for a few days already.

SQL SELECT everything after a certain character

I've been working on something similar and after a few tries and fails came up with this:

Example: STRING-TO-TEST-ON = 'ab,cd,ef,gh'

I wanted to extract everything after the last occurrence of "," (comma) from the string... resulting in "gh".

My query is:

SELECT SUBSTR('ab,cd,ef,gh' FROM (LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1)) AS `wantedString`

Now let me try and explain what I did ...

  1. I had to find the position of the last "," from the string and to calculate the wantedString length, using LOCATE(",",REVERSE('ab,cd,ef,gh'))-1 by reversing the initial string I actually had to find the first occurrence of the "," in the string ... which wasn't hard to do ... and then -1 to actually find the string length without the ",".

  2. calculate the position of my wantedString by subtracting the string length I've calculated at 1st step from the initial string length:

    LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1

I have (+1) because I actually need the string position after the last "," .. and not containing the ",". Hope it makes sense.

  1. all it remain to do is running a SUBSTR on my initial string FROM the calculated position.

I haven't tested the query on large strings so I do not know how slow it is. So if someone actually tests it on a large string I would very happy to know the results.

SQL query to group by day

actually this depends on what DBMS you are using but in regular SQL convert(varchar,DateColumn,101) will change the DATETIME format to date (one day)

so:

SELECT 
    sum(amount) 
FROM 
    sales 
GROUP BY 
    convert(varchar,created,101)

the magix number 101 is what date format it is converted to

Converting Milliseconds to Minutes and Seconds?

To convert time in millis directly to minutes: second format you can use this

String durationText = DateUtils.formatElapsedTime(timeInMillis / 1000));

This will return a string with time in proper formatting. It worked for me.

How to find the Windows version from the PowerShell command line

Since PowerShell 5:

Get-ComputerInfo
Get-ComputerInfo -Property Windows*

I think this command pretty much tries the 1001 different ways so far discovered to collect system information...

C# : changing listbox row color?

I think you have to draw the listitems yourself to achieve this.

Here's a post with the same kind of question.

Current Subversion revision command

I think I have to do svn info and then retrieve the number with a string manipulation from "Revision: xxxxxx" It would be just nice, if there were a command that returns just the number :)

Validating an XML against referenced XSD in C#

You need to create an XmlReaderSettings instance and pass that to your XmlReader when you create it. Then you can subscribe to the ValidationEventHandler in the settings to receive validation errors. Your code will end up looking like this:

using System.Xml;
using System.Xml.Schema;
using System.IO;

public class ValidXSD
{
    public static void Main()
    {

        // Set the validation settings.
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
        settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

        // Create the XmlReader object.
        XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);

        // Parse the file. 
        while (reader.Read()) ;

    }
    // Display any warnings or errors.
    private static void ValidationCallBack(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred." + args.Message);
        else
            Console.WriteLine("\tValidation error: " + args.Message);

    }
}

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

Simple answer: a lot longer than two months. Learning to program competently will take longer than that, no matter what. It took me years to learn to be a competent object-oriented programmer, and I'm good at this stuff.

More detailed answers: it doesn't really matter whether you learn C# or SQL first, as they're very different. I'd probably suggest SQL, as it's easier to learn and more independently useful.

You will have a hard time getting used to the on-the-job realities at home, much as if you were studying plumbing or quantitative finance.

You're going to have a hard time putting all the information together without one or more projects you try to do. You're going to need to have other people to tell you when you're being stupid, when you're being overclever and will pay for it later, and when you're actually getting it.

Try to find an open source project you find vaguely interesting. Study their code. Figure out why they do what they do. Look at the bug list, and try to find something as trivial as possible to fix. Work from there. Learning to contribute is going to teach you things that are useful in the work world, and it will give you something to point at. It will be far easier to get your first job if you have some experience to point to.

Combine several images horizontally with Python

I would try this:

import numpy as np
import PIL
from PIL import Image

list_im = ['Test1.jpg', 'Test2.jpg', 'Test3.jpg']
imgs    = [ PIL.Image.open(i) for i in list_im ]
# pick the image which is the smallest, and resize the others to match it (can be arbitrary image shape here)
min_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1]
imgs_comb = np.hstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )

# save that beautiful picture
imgs_comb = PIL.Image.fromarray( imgs_comb)
imgs_comb.save( 'Trifecta.jpg' )    

# for a vertical stacking it is simple: use vstack
imgs_comb = np.vstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )
imgs_comb = PIL.Image.fromarray( imgs_comb)
imgs_comb.save( 'Trifecta_vertical.jpg' )

It should work as long as all images are of the same variety (all RGB, all RGBA, or all grayscale). It shouldn't be difficult to ensure this is the case with a few more lines of code. Here are my example images, and the result:

Test1.jpg

Test1.jpg

Test2.jpg

Test2.jpg

Test3.jpg

Test3.jpg

Trifecta.jpg:

combined images

Trifecta_vertical.jpg

enter image description here

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

Suppose you face this issue while running your go binary with in alpine container. Export the following variable before building your bin

# CGO has to be disabled for alpine
export CGO_ENABLED=0

Then go build

Vibrate and Sound defaults on notification

Notification Vibrate

mBuilder.setVibrate(new long[] { 1000, 1000});

Sound

mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);

for more sound option

Call php function from JavaScript

The only way to execute PHP from JS is AJAX. You can send data to server (for eg, GET /ajax.php?do=someFunction) then in ajax.php you write:

function someFunction() {
    echo 'Answer';
}

if ($_GET['do'] === "someFunction") {
    someFunction();
}

and then, catch the answer with JS (i'm using jQuery for making AJAX requests)

Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.

C# DropDownList with a Dictionary as DataSource

When a dictionary is enumerated, it will yield KeyValuePair<TKey,TValue> objects... so you just need to specify "Value" and "Key" for DataTextField and DataValueField respectively, to select the Value/Key properties.

Thanks to Joe's comment, I reread the question to get these the right way round. Normally I'd expect the "key" in the dictionary to be the text that's displayed, and the "value" to be the value fetched. Your sample code uses them the other way round though. Unless you really need them to be this way, you might want to consider writing your code as:

list.Add(cul.DisplayName, cod);

(And then changing the binding to use "Key" for DataTextField and "Value" for DataValueField, of course.)

In fact, I'd suggest that as it seems you really do want a list rather than a dictionary, you might want to reconsider using a dictionary in the first place. You could just use a List<KeyValuePair<string, string>>:

string[] languageCodsList = service.LanguagesAvailable();
var list = new List<KeyValuePair<string, string>>();

foreach (string cod in languageCodsList)
{
    CultureInfo cul = new CultureInfo(cod);
    list.Add(new KeyValuePair<string, string>(cul.DisplayName, cod));
}

Alternatively, use a list of plain CultureInfo values. LINQ makes this really easy:

var cultures = service.LanguagesAvailable()
                      .Select(language => new CultureInfo(language));
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();

If you're not using LINQ, you can still use a normal foreach loop:

List<CultureInfo> cultures = new List<CultureInfo>();
foreach (string cod in service.LanguagesAvailable())
{
    cultures.Add(new CultureInfo(cod));
}
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();

How do I check if a property exists on a dynamic anonymous type in c#?

    public static void Test()
    {
        int LOOP_LENGTH = 100000000;
        {
            long first_memory = GC.GetTotalMemory(true);
            var stopWatch = Stopwatch.StartNew();

            Console.WriteLine("doesPropertyExist");

            dynamic testdo = new { A = 1, B = (string)null, C = "A" };
            for (int i = 0; i < LOOP_LENGTH; i++)
            {
                if (!TestDynamic.doesPropertyExist(testdo, "A"))
                {
                    Console.WriteLine("throw find");
                    break;
                }

                if (TestDynamic.doesPropertyExist(testdo, "ABC"))
                {
                    Console.WriteLine("throw not find");
                    break;
                }
            }
            stopWatch.Stop();
            var last_memory = GC.GetTotalMemory(true);
            Console.WriteLine($" Time:{stopWatch.Elapsed.TotalSeconds}s\t Memory:{last_memory - first_memory}");
        }

        {
            long first_memory = GC.GetTotalMemory(true);
            var stopWatch = Stopwatch.StartNew();

            Console.WriteLine("HasProperty");

            dynamic testdo = new { A = 1, B = (string)null, C = "A" };
            for (int i = 0; i < LOOP_LENGTH; i++)
            {
                if (!TestDynamic.HasProperty(testdo, "A"))
                {
                    Console.WriteLine("throw find");
                    break;
                }

                if (TestDynamic.HasProperty(testdo, "ABC"))
                {
                    Console.WriteLine("throw not find");
                    break;
                }
            }
            stopWatch.Stop();
            var last_memory = GC.GetTotalMemory(true);
            Console.WriteLine($" Time:{stopWatch.Elapsed.TotalSeconds}s\t Memory:{last_memory - first_memory}");
        }


        {
            long first_memory = GC.GetTotalMemory(true);
            var stopWatch = Stopwatch.StartNew();

            Console.WriteLine("IsPropertyExist");

            dynamic testdo = new { A = 1, B = (string)null, C = "A" };
            for (int i = 0; i < LOOP_LENGTH; i++)
            {
                if (!TestDynamic.IsPropertyExist(testdo, "A"))
                {
                    Console.WriteLine("throw find");
                    break;
                }

                if (TestDynamic.IsPropertyExist(testdo, "ABC"))
                {
                    Console.WriteLine("throw not find");
                    break;
                }
            }
            stopWatch.Stop();
            var last_memory = GC.GetTotalMemory(true);
            Console.WriteLine($" Time:{stopWatch.Elapsed.TotalSeconds}s\t Memory:{last_memory - first_memory}");
        }

        {
            long first_memory = GC.GetTotalMemory(true);
            var stopWatch = Stopwatch.StartNew();

            Console.WriteLine("IsPropertyExistBinderException");

            dynamic testdo = new { A = 1, B = (string)null, C = "A" };
            for (int i = 0; i < LOOP_LENGTH; i++)
            {
                if (!TestDynamic.IsPropertyExistBinderException(testdo, "A"))
                {
                    Console.WriteLine("throw find");
                    break;
                }

                if (TestDynamic.IsPropertyExistBinderException(testdo, "ABC"))
                {
                    Console.WriteLine("throw not find");
                    break;
                }
            }
            stopWatch.Stop();
            var last_memory = GC.GetTotalMemory(true);
            Console.WriteLine($" Time:{stopWatch.Elapsed.TotalSeconds}s\t Memory:{last_memory - first_memory}");
        }


        {
            long first_memory = GC.GetTotalMemory(true);
            var stopWatch = Stopwatch.StartNew();

            Console.WriteLine("PropertyExists");

            dynamic testdo = new { A = 1, B = (string)null, C = "A" };
            for (int i = 0; i < LOOP_LENGTH; i++)
            {
                if (!TestDynamic.PropertyExists(testdo, "A"))
                {
                    Console.WriteLine("throw find");
                    break;
                }

                if (TestDynamic.PropertyExists(testdo, "ABC"))
                {
                    Console.WriteLine("throw not find");
                    break;
                }
            }
            stopWatch.Stop();
            var last_memory = GC.GetTotalMemory(true);
            Console.WriteLine($" Time:{stopWatch.Elapsed.TotalSeconds}s\t Memory:{last_memory - first_memory}");
        }


        {
            long first_memory = GC.GetTotalMemory(true);
            var stopWatch = Stopwatch.StartNew();

            Console.WriteLine("PropertyExistsJToken");

            dynamic testdo = new { A = 1, B = (string)null, C = "A" };
            for (int i = 0; i < LOOP_LENGTH; i++)
            {
                if (!TestDynamic.PropertyExistsJToken(testdo, "A"))
                {
                    Console.WriteLine("throw find");
                    break;
                }

                if (TestDynamic.PropertyExistsJToken(testdo, "ABC"))
                {
                    Console.WriteLine("throw not find");
                    break;
                }
            }
            stopWatch.Stop();
            var last_memory = GC.GetTotalMemory(true);
            Console.WriteLine($" Time:{stopWatch.Elapsed.TotalSeconds}s\t Memory:{last_memory - first_memory}");
        }




    }

    public static bool IsPropertyExist(dynamic settings, string name)
    {
        if (settings is ExpandoObject)
            return ((IDictionary<string, object>)settings).ContainsKey(name);

        return settings.GetType().GetProperty(name) != null;
    }

    public static bool HasProperty(dynamic obj, string name)
    {
        Type objType = obj.GetType();

        if (objType == typeof(ExpandoObject))
        {
            return ((IDictionary<string, object>)obj).ContainsKey(name);
        }

        return objType.GetProperty(name) != null;
    }


    public static bool PropertyExists(dynamic obj, string name)
    {
        if (obj == null) return false;
        if (obj is IDictionary<string, object> dict)
        {
            return dict.ContainsKey(name);
        }
        return obj.GetType().GetProperty(name) != null;
    }

    // public static bool HasPropertyExist(dynamic settings, string name)
    // {
    //     if (settings is System.Dynamic.ExpandoObject)
    //         return ((IDictionary<string, object>)settings).ContainsKey(name);
    //     if (settings is DynamicJsonObject)
    //         try
    //         {
    //             return settings[name] != null;
    //         }
    //         catch (KeyNotFoundException)
    //         {
    //             return false;
    //         }
    //     return settings.GetType().GetProperty(name) != null;
    // }

    public static bool IsPropertyExistBinderException(dynamic dynamicObj, string property)
    {
        try
        {
            var value = dynamicObj[property].Value;
            return true;
        }
        catch (RuntimeBinderException)
        {

            return false;
        }

    }

    public static bool HasPropertyFoundException(dynamic obj, string name)
    {
        try
        {
            var value = obj[name];
            return true;
        }
        catch (KeyNotFoundException)
        {
            return false;
        }
    }


    public static bool doesPropertyExist(dynamic obj, string property)
    {
        return ((Type)obj.GetType()).GetProperties().Where(p => p.Name.Equals(property)).Any();
    }

    public static bool PropertyExistsJToken(dynamic obj, string name)
    {
        if (obj == null) return false;
        if (obj is ExpandoObject)
            return ((IDictionary<string, object>)obj).ContainsKey(name);
        if (obj is IDictionary<string, object> dict1)
            return dict1.ContainsKey(name);
        if (obj is IDictionary<string, JToken> dict2)
            return dict2.ContainsKey(name);
        return obj.GetType().GetProperty(name) != null;
    }

    // public static bool PropertyExistsJsonObject(dynamic settings, string name)
    // {
    //     if (settings is ExpandoObject)
    //         return ((IDictionary<string, object>)settings).ContainsKey(name);
    //     else if (settings is DynamicJsonObject)
    //         return ((DynamicJsonObject)settings).GetDynamicMemberNames().Contains(name);

    //     return settings.GetType().GetProperty(name) != null;
    // }
}

doesPropertyExist

Time:59.5907507s Memory:403680

HasProperty

Time:30.8231781s Memory:14968

IsPropertyExist

Time:39.6179575s Memory:97000

IsPropertyExistBinderException throw find

PropertyExists

Time:56.009761s Memory:13464

PropertyExistsJToken

Time:61.6146953s Memory:15952

How do I configure the proxy settings so that Eclipse can download new plugins?

For me, I go to \eclipse\configuration.settings\org.eclipse.core.net.prefs set the property systemProxiesEnabled to true manually and restart eclipse.

Jenkins, specifying JAVA_HOME

This is an old thread but for more recent Jenkins versions (in my case Jenkins 2.135) that require a particular java JDK the following should help:

Note: This is for Centos 7 , other distros may have differing directory locations although I believe they are correct for ubuntu also.

Modify /etc/sysconfig/jenkins and set variable JENKINS_JAVA_CMD="/<your desired jvm>/bin/java" (root access require)

Example:

JENKINS_JAVA_CMD="/usr/lib/jvm/java-1.8.0-openjdk/bin/java"

Restart Jenkins (if jenkins is run as a service sudo service jenkins stop then sudo service jenkins start)

The above fixed my Jenkins install not starting after I upgraded to Java 10 and Jenkins to 2.135

How to change a nullable column to not nullable in a Rails migration?

You can't use add_timestamps and null:false if you have existing records, so here is the solution :

def change
  add_timestamps(:buttons, null: true)

  Button.find_each { |b| b.update(created_at: Time.zone.now, updated_at: Time.zone.now) }

  change_column_null(:buttons, :created_at, false)
  change_column_null(:buttons, :updated_at, false)
end

excel VBA run macro automatically whenever a cell is changed

I was creating a form in which the user enters an email address used by another macro to email a specific cell group to the address entered. I patched together this simple code from several sites and my limited knowledge of VBA. This simply watches for one cell (In my case K22) to be updated and then kills any hyperlink in that cell.

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("K22")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

        Range("K22").Select
        Selection.Hyperlinks.Delete

    End If 
End Sub

Is there a format code shortcut for Visual Studio?

To align the text in the proper format -

  • Ctrl + K + D for front end pages like .aspx or .cshtml

  • Ctrl + K + F for a .cs page

But observe to press all buttons in sequence...

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

Is there a way to remove unused imports and declarations from Angular 2+?

Edit (as suggested in comments and other people), Visual Studio Code has evolved and provides this functionality in-built as the command "Organize imports", with the following default keyboard shortcuts:

option+Shift+O for Mac

Alt + Shift + O for Windows


Original answer:

I hope this visual studio code extension will suffice your need: https://marketplace.visualstudio.com/items?itemName=rbbit.typescript-hero

It provides following features:

  • Add imports of your project or libraries to your current file
  • Add an import for the current name under the cursor
  • Add all missing imports of a file with one command
  • Intellisense that suggests symbols and automatically adds the needed imports "Light bulb feature" that fixes code you wrote
  • Sort and organize your imports (sort and remove unused)
  • Code outline view of your open TS / TSX document
  • All the cool stuff for JavaScript as well! (experimental stage though, better description below.)

For Mac: control+option+o

For Win: Ctrl+Alt+o

"A lambda expression with a statement body cannot be converted to an expression tree"

It means that a Lambda expression of type TDelegate which contains a ([parameters]) => { some code }; cannot be converted to an Expression<TDelegate>. It's the rule.

Simplify your query. The one you provided can be rewritten as the following and will compile:

Arr[] myArray = objects.Select(o => new Obj()
                {
                   Var1 = o.someVar,
                   Var2 = o.var2
                } ).ToArray();

What does PermGen actually stand for?

If I remember correctly, the gen stands for generation, as in a generational garbage collector (that treats younger objects differently than mid-life and "permanent" objects). Principle of locality suggests that recently created objects will be wiped out first.

C/C++ NaN constant (literal)?

As others have pointed out you are looking for std::numeric_limits<double>::quiet_NaN() although I have to say I prefer the cppreference.com documents. Especially because this statement is a little vague:

Only meaningful if std::numeric_limits::has_quiet_NaN == true.

and it was simple to figure out what this means on this site, if you check their section on std::numeric_limits::has_quiet_NaN it says:

This constant is meaningful for all floating-point types and is guaranteed to be true if std::numeric_limits::is_iec559 == true.

which as explained here if true means your platform supports IEEE 754 standard. This previous thread explains this should be true for most situations.

Which is better: <script type="text/javascript">...</script> or <script>...</script>

Both will work but xhtml standard requires you to specify the type too:

<script type="text/javascript">..</script> 

<!ELEMENT SCRIPT - - %Script;          -- script statements -->
<!ATTLIST SCRIPT
  charset     %Charset;      #IMPLIED  -- char encoding of linked resource --
  type        %ContentType;  #REQUIRED -- content type of script language --
  src         %URI;          #IMPLIED  -- URI for an external script --
  defer       (defer)        #IMPLIED  -- UA may defer execution of script --
  >

type = content-type [CI] This attribute specifies the scripting language of the element's contents and overrides the default scripting language. The scripting language is specified as a content type (e.g., "text/javascript"). Authors must supply a value for this attribute. There is no default value for this attribute.

Notices the emphasis above.

http://www.w3.org/TR/html4/interact/scripts.html

Note: As of HTML5 (far away), the type attribute is not required and is default.

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Using true and false in C

I prefer the third solution, i.e. using 1 and 0, because it is particularly useful when you have to test if a condition is true or false: you can simply use a variable for the if argument.
If you use other methods, I think that, to be consistent with the rest of the code, I should use a test like this:

if (variable == TRUE)
{
   ...
}

instead of:

if (variable)
{
   ...
}

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

Suppress the @JoinColumn(name="categoria") on the ID field of the Categoria class and I think it will work.

Asyncio.gather vs asyncio.wait

In addition to all the previous answers, I would like to tell about the different behavior of gather() and wait() in case they are cancelled.

Gather cancellation

If gather() is cancelled, all submitted awaitables (that have not completed yet) are also cancelled.

Wait cancellation

If the wait() task is cancelled, it simply throws an CancelledError and the waited tasks remain intact.

Simple example:

import asyncio


async def task(arg):
    await asyncio.sleep(5)
    return arg


async def cancel_waiting_task(work_task, waiting_task):
    await asyncio.sleep(2)
    waiting_task.cancel()
    try:
        await waiting_task
        print("Waiting done")
    except asyncio.CancelledError:
        print("Waiting task cancelled")

    try:
        res = await work_task
        print(f"Work result: {res}")
    except asyncio.CancelledError:
        print("Work task cancelled")


async def main():
    work_task = asyncio.create_task(task("done"))
    waiting = asyncio.create_task(asyncio.wait({work_task}))
    await cancel_waiting_task(work_task, waiting)

    work_task = asyncio.create_task(task("done"))
    waiting = asyncio.gather(work_task)
    await cancel_waiting_task(work_task, waiting)


asyncio.run(main())

Output:

asyncio.wait()
Waiting task cancelled
Work result: done
----------------
asyncio.gather()
Waiting task cancelled
Work task cancelled

Sometimes it becomes necessary to combine wait() and gather() functionality. For example, we want to wait for the completion of at least one task and cancel the rest pending tasks after that, and if the waiting itself was canceled, then also cancel all pending tasks.

As real examples, let's say we have a disconnect event and a work task. And we want to wait for the results of the work task, but if the connection was lost, then cancel it. Or we will make several parallel requests, but upon completion of at least one response, cancel all others.

It could be done this way:

import asyncio
from typing import Optional, Tuple, Set


async def wait_any(
        tasks: Set[asyncio.Future], *, timeout: Optional[int] = None,
) -> Tuple[Set[asyncio.Future], Set[asyncio.Future]]:
    tasks_to_cancel: Set[asyncio.Future] = set()
    try:
        done, tasks_to_cancel = await asyncio.wait(
            tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED
        )
        return done, tasks_to_cancel
    except asyncio.CancelledError:
        tasks_to_cancel = tasks
        raise
    finally:
        for task in tasks_to_cancel:
            task.cancel()


async def task():
    await asyncio.sleep(5)


async def cancel_waiting_task(work_task, waiting_task):
    await asyncio.sleep(2)
    waiting_task.cancel()
    try:
        await waiting_task
        print("Waiting done")
    except asyncio.CancelledError:
        print("Waiting task cancelled")

    try:
        res = await work_task
        print(f"Work result: {res}")
    except asyncio.CancelledError:
        print("Work task cancelled")


async def check_tasks(waiting_task, working_task, waiting_conn_lost_task):
    try:
        await waiting_task
        print("waiting is done")
    except asyncio.CancelledError:
        print("waiting is cancelled")

    try:
        await waiting_conn_lost_task
        print("connection is lost")
    except asyncio.CancelledError:
        print("waiting connection lost is cancelled")

    try:
        await working_task
        print("work is done")
    except asyncio.CancelledError:
        print("work is cancelled")


async def work_done_case():
    working_task = asyncio.create_task(task())
    connection_lost_event = asyncio.Event()
    waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
    waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
    await check_tasks(waiting_task, working_task, waiting_conn_lost_task)


async def conn_lost_case():
    working_task = asyncio.create_task(task())
    connection_lost_event = asyncio.Event()
    waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
    waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
    await asyncio.sleep(2)
    connection_lost_event.set()  # <---
    await check_tasks(waiting_task, working_task, waiting_conn_lost_task)


async def cancel_waiting_case():
    working_task = asyncio.create_task(task())
    connection_lost_event = asyncio.Event()
    waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
    waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
    await asyncio.sleep(2)
    waiting_task.cancel()  # <---
    await check_tasks(waiting_task, working_task, waiting_conn_lost_task)


async def main():
    print("Work done")
    print("-------------------")
    await work_done_case()
    print("\nConnection lost")
    print("-------------------")
    await conn_lost_case()
    print("\nCancel waiting")
    print("-------------------")
    await cancel_waiting_case()


asyncio.run(main())

Output:

Work done
-------------------
waiting is done
waiting connection lost is cancelled
work is done

Connection lost
-------------------
waiting is done
connection is lost
work is cancelled

Cancel waiting
-------------------
waiting is cancelled
waiting connection lost is cancelled
work is cancelled

Converting from hex to string

Your reference to "0x31 = 1" makes me think you're actually trying to convert ASCII values to strings - in which case you should be using something like Encoding.ASCII.GetString(Byte[])

Javascript | Set all values of an array

There's no built-in way, you'll have to loop over all of them:

function setAll(a, v) {
    var i, n = a.length;
    for (i = 0; i < n; ++i) {
        a[i] = v;
    }
}

http://jsfiddle.net/alnitak/xG88A/

If you really want, do this:

Array.prototype.setAll = function(v) {
    var i, n = this.length;
    for (i = 0; i < n; ++i) {
        this[i] = v;
    }
};

and then you could actually do cool.setAll(42) (see http://jsfiddle.net/alnitak/ee3hb/).

Some people frown upon extending the prototype of built-in types, though.

EDIT ES5 introduced a way to safely extend both Object.prototype and Array.prototype without breaking for ... in ... enumeration:

Object.defineProperty(Array.prototype, 'setAll', {
    value: function(v) {
        ...
    }
});

EDIT 2 In ES6 draft there's also now Array.prototype.fill, usage cool.fill(42)

SQL Server Profiler - How to filter trace to only display events from one database?

In the Trace properties, click the Events Selection tab at the top next to General. Then click Column Filters... at the bottom right. You can then select what to filter, such as TextData or DatabaseName.

Expand the Like node and enter your filter with the percentage % signs like %MyDatabaseName% or %TextDataToFilter%. Without the %% signs the filter will not work.

Also, make sure to check the checkbox Exclude rows that do not contain values' If you cannot find the field you are looking to filter such as DatabaseName go to the General tab and change your Template, blank one should contain all the fields.

Accessing dictionary value by index in python

Let us take an example of dictionary:

numbers = {'first':0, 'second':1, 'third':3}

When I did

numbers.values()[index]

I got an error:'dict_values' object does not support indexing

When I did

numbers.itervalues()

to iterate and extract the values it is also giving an error:'dict' object has no attribute 'iteritems'

Hence I came up with new way of accessing dictionary elements by index just by converting them to tuples.

tuple(numbers.items())[key_index][value_index]

for example:

tuple(numbers.items())[0][0] gives 'first'

if u want to edit the values or sort the values the tuple object does not allow the item assignment. In this case you can use

list(list(numbers.items())[index])

How to initialize log4j properly?

I've created file log4j.properties in resources folder next to hibernate.cfg.xml file and filled it with text below:

log4j.rootLogger=INFO, CONSOLE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}:%L] %m%n

now I got rid of warnings and errors

What is the default encoding of the JVM?

You can use this to print out the JVM defaults

import java.nio.charset.Charset;
import java.io.InputStreamReader;
import java.io.FileInputStream;

public class PrintCharSets {
        public static void main(String[] args) throws Exception {
                System.out.println("file.encoding=" + System.getProperty("file.encoding"));
                System.out.println("Charset.defaultCharset=" + Charset.defaultCharset());
                System.out.println("InputStreamReader.getEncoding=" + new InputStreamReader(new FileInputStream("./PrintCharSets.java")).getEncoding());
        }
}

Compile and Run

javac PrintCharSets.java && java PrintCharSets

How to limit the maximum files chosen when using multiple file input

Another possible solution with JS

function onSelect(e) {
    if (e.files.length > 5) {
        alert("Only 5 files accepted.");
        e.preventDefault();
    }
}

Outputting data from unit test in Python

I think I might have been overthinking this. One way I've come up with that does the job, is simply to have a global variable, that accumulates the diagnostic data.

Somthing like this:

log1 = dict()
class TestBar(unittest.TestCase):
    def runTest(self):
        for t1, t2 in testdata:
            f = Foo(t1) 
            if f.bar(t2) != 2: 
                log1("TestBar.runTest") = (f, t1, t2)
                self.fail("f.bar(t2) != 2")

Thanks for the replies. They have given me some alternative ideas for how to record information from unit tests in python.

Tokenizing strings in C

strtok can be very dangerous. It is not thread safe. Its intended use is to be called over and over in a loop, passing in the output from the previous call. The strtok function has an internal variable that stores the state of the strtok call. This state is not unique to each thread - it is global. If any other code uses strtok in another thread, you get problems. Not the kind of problems you want to track down either!

I'd recommend looking for a regex implementation, or using sscanf to pull apart the string.

Try this:

char strprint[256];
char text[256];
strcpy(text, "My string to test");
while ( sscanf( text, "%s %s", strprint, text) > 0 ) {
   printf("token: %s\n", strprint);
}

Note: The 'text' string is destroyed as it's separated. This may not be the preferred behaviour =)

Undefined reference to sqrt (or other mathematical functions)

Just adding the #include <math.h> in c source file and -lm in Makefile at the end will work for me.

    gcc -pthread -o p3 p3.c -lm

How to execute the start script with Nodemon

To avoid a global install, add Nodemon as a dependency, then...

package.json

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

pros and cons between os.path.exists vs os.path.isdir

Most of the time, it is the same.

But, path can exist physically whereas path.exists() returns False. This is the case if os.stat() returns False for this file.

If path exists physically, then path.isdir() will always return True. This does not depend on platform.

adding x and y axis labels in ggplot2

since the data ex1221new was not given, so I have created a dummy data and added it to a data frame. Also, the question which was asked has few changes in codes like then ggplot package has deprecated the use of

"scale_area()" and nows uses scale_size_area()
"opts()" has changed to theme()

In my answer,I have stored the plot in mygraph variable and then I have used

mygraph$labels$x="Discharge of materials" #changes x axis title
       mygraph$labels$y="Area Affected" # changes y axis title

And the work is done. Below is the complete answer.

install.packages("Sleuth2")
library(Sleuth2)
library(ggplot2)

ex1221new<-data.frame(Discharge<-c(100:109),Area<-c(120:129),NO3<-seq(2,5,length.out = 10))
discharge<-ex1221new$Discharge
area<-ex1221new$Area
nitrogen<-ex1221new$NO3
p <- ggplot(ex1221new, aes(discharge, area), main="Point")
mygraph<-p + geom_point(aes(size= nitrogen)) + 
  scale_size_area() + ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")+
theme(
 plot.title =  element_text(color="Blue", size=30, hjust = 0.5), 

 # change the styling of both the axis simultaneously from this-
 axis.title = element_text(color = "Green", size = 20, family="Courier",)
 

   # you can change the  axis title from the code below
   mygraph$labels$x="Discharge of materials" #changes x axis title
   mygraph$labels$y="Area Affected" # changes y axis title
   mygraph



   

Also, you can change the labels title from the same formula used above -

mygraph$labels$size= "N2" #size contains the nitrogen level 

Difference between thread's context class loader and normal classloader

There is an article on javaworld.com that explains the difference => Which ClassLoader should you use

(1)

Thread context classloaders provide a back door around the classloading delegation scheme.

Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.

(2) from the same source:

This confusion will probably stay with Java for some time. Take any J2SE API with dynamic resource loading of any kind and try to guess which loading strategy it uses. Here is a sampling:

  • JNDI uses context classloaders
  • Class.getResource() and Class.forName() use the current classloader
  • JAXP uses context classloaders (as of J2SE 1.4)
  • java.util.ResourceBundle uses the caller's current classloader
  • URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only
  • Java Serialization API uses the caller's current classloader by default

How to use moment.js library in angular 2 typescript app?

for angular2 with systemjs and jspm had to do:

import * as moment_ from 'moment';
export const moment =  moment_["default"];

var a = moment.now();
var b = moment().format('dddd');
var c = moment().startOf('day').fromNow();

Razor MVC Populating Javascript array with Model Array

The valid syntax with named fields:

  var array = [];

     @foreach (var item in model.List)
     {
        @:array.push({ 
                       "Project": "@item.Project",
                       "ProjectOrgUnit": "@item.ProjectOrgUnit"
                     });
     }

git: fatal unable to auto-detect email address

Steps to solve this problem

note: This problem mainly occurs due to which we haven't assigned our user name and email id in git so what we gonna do is assigning it in git

  1. Open git that you have installed

  2. Now we have to assign our user name and email id

  3. Just type git config --user.name <your_name> and click enter (you can mention or type any name you want)

  4. Similarly type git config --user.email <[email protected]> and click enter (you have to type your primary mail id)

  5. And that's it.

    Have a Good Day!!!.

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

With appFuse framework, you can create an Spring MVC archetype with jpa support, etc ...

Take a look at it's quickStart guide to see how to create an archetype based on this Framework.

Foundational frameworks in AppFuse:

  • Bootstrap and jQuery
  • Maven, Hibernate, Spring and Spring Security
  • Java 7, Annotations, JSP 2.1, Servlet 3.0
  • Web Frameworks: JSF, Struts 2, Spring MVC, Tapestry 5, Wicket
  • JPA Support

For example to create an appFuse light archetype :

mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes 
-DarchetypeArtifactId=appfuse-light-struts-archetype -DarchetypeVersion=2.2.1 
-DgroupId=com.mycompany -DartifactId=myproject

Difference between MongoDB and Mongoose

One more difference I found with respect to both is that it is fairly easy to connect to multiple databases with mongodb native driver while you have to use work arounds in mongoose which still have some drawbacks.

So if you wanna go for a multitenant application, go for mongodb native driver.

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

How to simple shade color in PHP?

<?php
function shadeColor ($color='#cccccc', $percent=-25) {

  $color = Str_Replace("#",Null,$color);

  $r = Hexdec(Substr($color,0,2));
  $g = Hexdec(Substr($color,2,2));
  $b = Hexdec(Substr($color,4,2));

  $r = (Int)($r*(100+$percent)/100);
  $g = (Int)($g*(100+$percent)/100);
  $b = (Int)($b*(100+$percent)/100);

  $r = Trim(Dechex(($r<255)?$r:255));  
  $g = Trim(Dechex(($g<255)?$g:255));  
  $b = Trim(Dechex(($b<255)?$b:255));

  $r = ((Strlen($r)==1)?"0{$r}":$r);
  $g = ((Strlen($g)==1)?"0{$g}":$g);
  $b = ((Strlen($b)==1)?"0{$b}":$b);

  return (String)("#{$r}{$g}{$b}");
}

echo shadeColor(); // #999999

How to run shell script on host from docker container?

If you are not worried about security and you're simply looking to start a docker container on the host from within another docker container like the OP, you can share the docker server running on the host with the docker container by sharing it's listen socket.

Please see https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface and see if your personal risk tolerance allows this for this particular application.

You can do this by adding the following volume args to your start command

docker run -v /var/run/docker.sock:/var/run/docker.sock ...

or by sharing /var/run/docker.sock within your docker compose file like this:

version: '3'

services:
   ci:
      command: ...
      image: ...
      volumes
         - /var/run/docker.sock:/var/run/docker.sock

When you run the docker start command within your docker container, the docker server running on your host will see the request and provision the sibling container.

credit: http://jpetazzo.github.io/2015/09/03/do-not-use-docker-in-docker-for-ci/

How to increase editor font size?

I have the latest version of Android Studio installed (3.6.1).

I navigated to: File->Settings->Editor->Font. The dialog displays a warning message (yellow triangle) indicating that the Font is defined in the color scheme.

(Editing the Font here had no effect.)

Editor Font

I clicked on the dialog's warning message link.

This navigated to: File->Settings->Editor->Color Scheme->Color Scheme Font.

(Now I could edit the Font for my current scheme.)

Editor Color Scheme Color Scheme Font

how do I initialize a float to its max/min value?

There's no real need to initialize to smallest/largest possible to find the smallest/largest in the array:

double largest = smallest = array[0];
for (int i=1; i<array_size; i++) {
    if (array[i] < smallest)
        smallest = array[i];
    if (array[i] > largest0
        largest= array[i];
}

Or, if you're doing it more than once:

#include <utility>

template <class iter>
std::pair<typename iter::value_type, typename iter::value_type> find_extrema(iter begin, iter end) {
    std::pair<typename iter::value_type, typename iter::value_type> ret;
    ret.first = ret.second = *begin;
    while (++begin != end) {
        if (*begin < ret.first)
           ret.first = *begin;
        if (*begin > ret.second)
           ret.second = *begin;
   }
   return ret;
}

The disadvantage of providing sample code -- I see others have already suggested the same idea.

Note that while the standard has a min_element and max_element, using these would require scanning through the data twice, which could be a problem if the array is large at all. Recent standards have addressed this by adding a std::minmax_element, which does the same as the find_extrema above (find both the minimum and maximum elements in a collection in a single pass).

Edit: Addressing the problem of finding the smallest non-zero value in an array of unsigned: observe that unsigned values "wrap around" when they reach an extreme. To find the smallest non-zero value, we can subtract one from each for the comparison. Any zero values will "wrap around" to the largest possible value for the type, but the relationship between other values will be retained. After we're done, we obviously add one back to the value we found.

unsigned int min_nonzero(std::vector<unsigned int> const &values) { 
    if (vector.size() == 0)
        return 0;
    unsigned int temp = values[0]-1;
    for (int i=1; i<values.size(); i++)
        if (values[i]-1 < temp)
            temp = values[i]-1;
    return temp+1;
}

Note this still uses the first element for the initial value, but we still don't need any "special case" code -- since that will wrap around to the largest possible value, any non-zero value will compare as being smaller. The result will be the smallest nonzero value, or 0 if and only if the vector contained no non-zero values.

Converting JSONarray to ArrayList

public static List<JSONObject> getJSONObjectListFromJSONArray(JSONArray array) 
        throws JSONException {
  ArrayList<JSONObject> jsonObjects = new ArrayList<>();
  for (int i = 0; 
           i < (array != null ? array.length() : 0);           
           jsonObjects.add(array.getJSONObject(i++))
       );
  return jsonObjects;
}

How to convert local time string to UTC?

For getting around day-light saving, etc.

None of the above answers particularly helped me. The code below works for GMT.

def get_utc_from_local(date_time, local_tz=None):
    assert date_time.__class__.__name__ == 'datetime'
    if local_tz is None:
        local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, "Europe/London"
    local_time = local_tz.normalize(local_tz.localize(date_time))
    return local_time.astimezone(pytz.utc)

import pytz
from datetime import datetime

summer_11_am = datetime(2011, 7, 1, 11)
get_utc_from_local(summer_11_am)
>>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=<UTC>)

winter_11_am = datetime(2011, 11, 11, 11)
get_utc_from_local(winter_11_am)
>>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=<UTC>)

psql: FATAL: Ident authentication failed for user "postgres"

You can set the environment variable PGHOST=localhost:

$ psql -U db_user db_name
psql: FATAL:  Peer authentication failed for user "db_user"

$ export PGHOST=localhost
$ psql -U db_user db_name

Password for user mfonline:

How to check if the docker engine and a docker container are running?

container status: true/false

# docker inspect --format '{{json .State.Running}}' container-name
true
#

Where do I get servlet-api.jar from?

You may want to consider using Java EE, which includes the javax.servlet.* packages. If you require a specific version of the servlet api, for instance to target a specific web application server, you will probably want the Java EE version which matches, see this version table.

How do you monitor network traffic on the iPhone?

You didnt specify the platform you use, so I assume it's a Mac ;-)

What I do is use a proxy. I use SquidMan, a standalone implementation of Squid

I start SquidMan on the Mac, then on the iPhone I enter the Proxy params in the General/Wifi Settings.

Then I can watch the HTTP trafic in the Console App, looking at the squid-access.log

If I need more infos, I switch to tcpdump, but I suppose WireShark should work too.

cordova Android requirements failed: "Could not find an installed version of Gradle"

I tried many but it didnt work finally ,

  1. I installed gradle using macos port
  2. I set GRADLE_HOME path as it told after installing gradle
  3. I executed ::

sudo chmod -R a+rwx /Library/Java/JavaVirtualMachines *

sudo chmod -R a+rwx *

sudo chmod 777 {your-gradle-path}

It immediately started working

How to use jQuery to show/hide divs based on radio button selection?

I wrote a simple code to unterstand you to how to make a show and hide radio buttons in jquery its very simple

<div id="myRadioGroup">

    Value Based<input type="radio" name="cars" checked="checked" value="2"  />

    Percent Based<input type="radio" name="cars" value="3" />
    <br>
    <div id="Cars2" class="desc" style="display: none;">
        <br>
        <label for="txtPassportNumber">Commission Value</label>
       <input type="text" id="txtPassportNumber" class="form-control" />
    </div>
    <div id="Cars3" class="desc" style="display: none;">
        <br>
        <label for="txtPassportNumber">Commission Percent</label>
       <input type="text" id="txtPassportNumber" class="form-control" />
    </div>
</div>
</div>

Jquery code

$(document).ready(function() {
    $("input[name$='cars']").click(function() {
        var test = $(this).val();

        $("div.desc").hide();
        $("#Cars" + test).show();
    });
});

give me comments

How to test an SQL Update statement before running it?

In addition to using a transaction as Imad has said (which should be mandatory anyway) you can also do a sanity check which rows are affected by running a select using the same WHERE clause as the UPDATE.

So if you UPDATE is

UPDATE foo
  SET bar = 42
WHERE col1 = 1
  AND col2 = 'foobar';

The following will show you which rows will be updated:

SELECT *
FROM foo
WHERE col1 = 1
  AND col2 = 'foobar';

Log exception with traceback

This is how I do it.

try:
    do_something()
except:
    # How can I log my exception here, complete with its traceback?
    import traceback
    traceback.format_exc() # this will print a complete trace to stout.

how to delete files from amazon s3 bucket?

It's worked for me try it.

import boto
import sys
from boto.s3.key import Key
import boto.s3.connection

AWS_ACCESS_KEY_ID = '<access_key>'
AWS_SECRET_ACCESS_KEY = '<secret_access_key>'
Bucketname = 'bucket_name' 

conn = boto.s3.connect_to_region('us-east-2',
        aws_access_key_id=AWS_ACCESS_KEY_ID,
        aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
        is_secure=True,              
        calling_format = boto.s3.connection.OrdinaryCallingFormat(),
        )
bucket = conn.get_bucket(Bucketname)

k = Key(bucket)

k.key = 'filename to delete'
bucket.delete_key(k)   

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

Update

Official standard dialogs are coming to JavaFX in release 8u40, as part of the implemenation of RT-12643. These should be available in final release form around March of 2015 and in source code form in the JavaFX development repository now.

In the meantime, you can use the ControlsFX solution below...


ControlsFX is the defacto standard 3rd party library for common dialog support in JavaFX (error, warning, confirmation, etc).

There are numerous other 3rd party libraries available which provide common dialog support as pointed out in some other answers and you can create your own dialogs easily enough using the sample code in Sergey's answer.

However, I believe that ControlsFX easily provide the best quality standard JavaFX dialogs available at the moment. Here are some samples from the ControlsFX documentation.

standard dialog

command links

How to use type: "POST" in jsonp ajax call

You can't POST using JSONP...it simply doesn't work that way, it creates a <script> element to fetch data...which has to be a GET request. There's not much you can do besides posting to your own domain as a proxy which posts to the other...but user's not going to be able to do this directly and see a response though.

Replace first occurrence of string in Python

Use re.sub directly, this allows you to specify a count:

regex.sub('', url, 1)

(Note that the order of arguments is replacement, original not the opposite, as might be suspected.)

How to determine if a number is positive or negative?

I think there is a very simple solution:

public boolean isPositive(int|float|double|long i){
    return (((i-i)==0)? true : false);
}

tell me if I'm wrong!

CORS - How do 'preflight' an httprequest?

During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.

For example, suppose the browser makes a request with the following headers:

Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header

Your server should then respond with the following headers:

Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header

Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.

Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/

Batch script loop

Here is a template script I will use.

@echo off
goto Loop

:Loop
<EXTRA SCRIPTING HERE!!!!>
goto Loop

exit

What this does is when it starts it turns off echo then after that it runs the "Loop" but in that place it keeps going to "Loop" (I hope this helps.)

Get an OutputStream into a String

baos.toString(StandardCharsets.UTF_8);

Converts the buffer's contents into a string by decoding the bytes using the named charset.

Java 14 - https://docs.oracle.com/

How do I get the name of the active user via the command line in OS X?

If you want to know who's currently logged in to the system:

$ w
 15:56:14 up 5 days, 20:58,  6 users,  load average: 0.43, 0.53, 0.50
USER     TTY        LOGIN@   IDLE   JCPU   PCPU WHAT
me       pts/2     Fri19    1:03m  0.98s  0.98s -/bin/bash
me       pts/3     09:55    6:00m  0.43s  0.43s /bin/bash
me       pts/5     15:56    0.00s  0.23s  0.00s w

(This is from a Linux system; the formatting on OS X may be slightly different, but the information should be about the same.)

There may be multiple login sessions; UNIX is designed to be a multi-user system, after all.

How to import/include a CSS file using PHP code and not HTML code?

This is an older post, however as the info is still relevant today an additional option may help others.

  • Define a constant for the file path per Stefan's answer. The definition can be placed at the top of the PHP page itself, or within an included/required external file such as config.php. (http://php.net/manual/en/function.include.php)

  • Echo the constant in PHP tags, then add the filename directly after. That's it!
    Works for other linked files such as JavaScript as well.

<?php
define('CSS_PATH', 'template/css/'); //define CSS path 
define('JS_PATH', 'template/js/'); //define JavaScript path 
?>
<!-- Doctype should be declared, even in PHP file -->
<!DOCTYPE html> 
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo CSS_PATH; ?>main.css">
<script type="text/javascript" src="<?php echo JS_PATH; ?>main.js"></script>
</head>
<body>
</body>
</html>

How to override Bootstrap's Panel heading background color?

You can simply add an id attribute to the panel. Like this

<div class="panel-heading" id="mypanelId">Hello world </div>

Then in your custom CSS file:

#mypanelId{
    background-image: none;
    background: rgba(22, 20, 100, 0.8);
    color: white;
     }

URL encoding in Android

I'm going to add one suggestion here. You can do this which avoids having to get any external libraries.

Give this a try:

String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();

You can see that in this particular URL, I need to have those spaces encoded so that I can use it for a request.

This takes advantage of a couple features available to you in Android classes. First, the URL class can break a url into its proper components so there is no need for you to do any string search/replace work. Secondly, this approach takes advantage of the URI class feature of properly escaping components when you construct a URI via components rather than from a single string.

The beauty of this approach is that you can take any valid url string and have it work without needing any special knowledge of it yourself.

Excel telling me my blank cells aren't blank

This works with numbers.

If your range is O8:O20, then in a nearby empty range (e.g. T8:T20) enter =O8/1 and fill down. This will give you a result of #VALUE for the 'empty' cells and your original number will remain as it was.

Then with the range T8:20 selected (CTL-* if it's not already) hit F5 and choose Special. From the Special dialogue, choose Errors and click OK. This will deselect your actual numbers leaving only the #VALUE cells selected. Delete them and you will have actual empty cells. Copy T8:T20 and paste back over O8:O20.

Essentially, since blank cells doesn't work, you need to convert the 'empty' cells into something that the Go To Special can latch on to. Any action that would convert into #VALUE would work, and other 'error' types should be supported as well.

What is class="mb-0" in Bootstrap 4?

m - sets margin

p - sets padding

t - sets margin-top or padding-top

b - sets margin-bottom or padding-bottom

l - sets margin-left or padding-left

r - sets margin-right or padding-right

x - sets both padding-left and padding-right or margin-left and margin-right

y - sets both padding-top and padding-bottom or margin-top and margin-bottom

blank - sets a margin or padding on all 4 sides of the element

0 - sets margin or padding to 0

1 - sets margin or padding to .25rem (4px if font-size is 16px)

2 - sets margin or padding to .5rem (8px if font-size is 16px)

3 - sets margin or padding to 1rem (16px if font-size is 16px)

4 - sets margin or padding to 1.5rem (24px if font-size is 16px)

5 - sets margin or padding to 3rem (48px if font-size is 16px)

auto - sets margin to auto

Select rows from a data frame based on values in a vector

Have a look at ?"%in%".

dt[dt$fct %in% vc,]
   fct X
1    a 2
3    c 3
5    c 5
7    a 7
9    c 9
10   a 1
12   c 2
14   c 4

You could also use ?is.element:

dt[is.element(dt$fct, vc),]

C++ templates that accept only certain types

Executive summary: Don't do that.

j_random_hacker's answer tells you how to do this. However, I would also like to point out that you should not do this. The whole point of templates is that they can accept any compatible type, and Java style type constraints break that.

Java's type constraints are a bug not a feature. They are there because Java does type erasure on generics, so Java can't figure out how to call methods based on the value of type parameters alone.

C++ on the other hand has no such restriction. Template parameter types can be any type compatible with the operations they are used with. There doesn't have to be a common base class. This is similar to Python's "Duck Typing," but done at compile time.

A simple example showing the power of templates:

// Sum a vector of some type.
// Example:
// int total = sum({1,2,3,4,5});
template <typename T>
T sum(const vector<T>& vec) {
    T total = T();
    for (const T& x : vec) {
        total += x;
    }
    return total;
}

This sum function can sum a vector of any type that support the correct operations. It works with both primitives like int/long/float/double, and user defined numeric types that overload the += operator. Heck, you can even use this function to join strings, since they support +=.

No boxing/unboxing of primitives is necessary.

Note that it also constructs new instances of T using T(). This is trivial in C++ using implicit interfaces, but not really possible in Java with type constraints.

While C++ templates don't have explicit type constraints, they are still type safe, and will not compile with code that does not support the correct operations.

Index of duplicates items in a python list

from collections import Counter, defaultdict

def duplicates(lst):
    cnt= Counter(lst)
    return [key for key in cnt.keys() if cnt[key]> 1]

def duplicates_indices(lst):
    dup, ind= duplicates(lst), defaultdict(list)
    for i, v in enumerate(lst):
        if v in dup: ind[v].append(i)
    return ind

lst= ['a', 'b', 'a', 'c', 'b', 'a', 'e']
print duplicates(lst) # ['a', 'b']
print duplicates_indices(lst) # ..., {'a': [0, 2, 5], 'b': [1, 4]})

A slightly more orthogonal (and thus more useful) implementation would be:

from collections import Counter, defaultdict

def duplicates(lst):
    cnt= Counter(lst)
    return [key for key in cnt.keys() if cnt[key]> 1]

def indices(lst, items= None):
    items, ind= set(lst) if items is None else items, defaultdict(list)
    for i, v in enumerate(lst):
        if v in items: ind[v].append(i)
    return ind

lst= ['a', 'b', 'a', 'c', 'b', 'a', 'e']
print indices(lst, duplicates(lst)) # ..., {'a': [0, 2, 5], 'b': [1, 4]})

Regex to match only letters

Depending on your meaning of "character":

[A-Za-z] - all letters (uppercase and lowercase)

[^0-9] - all non-digit characters

How to get numbers after decimal point?

5.55 % 1

Keep in mind this won't help you with floating point rounding problems. I.e., you may get:

0.550000000001

Or otherwise a little off the 0.55 you are expecting.

Send Post Request with params using Retrofit

Post data to backend using retrofit

 implementation 'com.squareup.retrofit2:retrofit:2.8.1'
 implementation 'com.squareup.retrofit2:converter-gson:2.8.1'
 implementation 'com.google.code.gson:gson:2.8.6'
 implementation 'com.squareup.okhttp3:logging-interceptor:4.5.0'

public interface UserService {
  @POST("users/")
  Call<UserResponse> userRegistration(@Body UserRegistration 
    userRegistration);
}



public class ApiClient {

    private static Retrofit getRetrofit(){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .addInterceptor(httpLoggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.larntech.net/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();



        return retrofit;

    }


    public static UserService getService(){
        UserService userService = getRetrofit().create(UserService.class);
        return userService;
    }

}

Calculating Pearson correlation and significance in Python

This is a implementation of Pearson Correlation function using numpy:


def corr(data1, data2):
    "data1 & data2 should be numpy arrays."
    mean1 = data1.mean() 
    mean2 = data2.mean()
    std1 = data1.std()
    std2 = data2.std()

#     corr = ((data1-mean1)*(data2-mean2)).mean()/(std1*std2)
    corr = ((data1*data2).mean()-mean1*mean2)/(std1*std2)
    return corr

Best equivalent VisualStudio IDE for Mac to program .NET/C#

Whilst more of a workaround, if you're running an Intel Mac, you could go the virtualisation route - at least then you can run the same tools.

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

You've encountered a local time discontinuity:

When local standard time was about to reach Sunday, 1. January 1928, 00:00:00 clocks were turned backward 0:05:52 hours to Saturday, 31. December 1927, 23:54:08 local standard time instead

This is not particularly strange and has happened pretty much everywhere at one time or another as timezones were switched or changed due to political or administrative actions.

right click context menu for datagridview

Use the CellMouseDown event on the DataGridView. From the event handler arguments you can determine which cell was clicked. Using the PointToClient() method on the DataGridView you can determine the relative position of the pointer to the DataGridView, so you can pop up the menu in the correct location.

(The DataGridViewCellMouseEvent parameter just gives you the X and Y relative to the cell you clicked, which isn't as easy to use to pop up the context menu.)

This is the code I used to get the mouse position, then adjust for the position of the DataGridView:

var relativeMousePosition = DataGridView1.PointToClient(Cursor.Position);
this.ContextMenuStrip1.Show(DataGridView1, relativeMousePosition);

The entire event handler looks like this:

private void DataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    // Ignore if a column or row header is clicked
    if (e.RowIndex != -1 && e.ColumnIndex != -1)
    {
        if (e.Button == MouseButtons.Right)
        {
            DataGridViewCell clickedCell = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];

            // Here you can do whatever you want with the cell
            this.DataGridView1.CurrentCell = clickedCell;  // Select the clicked cell, for instance

            // Get mouse position relative to the vehicles grid
            var relativeMousePosition = DataGridView1.PointToClient(Cursor.Position);

            // Show the context menu
            this.ContextMenuStrip1.Show(DataGridView1, relativeMousePosition);
        }
    }
}

Convert time in HH:MM:SS format to seconds only?

    $time = 00:06:00;
    $timeInSeconds = strtotime($time) - strtotime('TODAY');

Default values for Vue component props & how to check if a user did not set the prop?

Also something important to add here, in order to set default values for arrays and objects we must use the default function for props:

propE: {
      type: Object,
      // Object or array defaults must be returned from
      // a factory function
      default: function () {
        return { message: 'hello' }
      }
    },

How to cast from List<Double> to double[] in Java?

You can use the ArrayUtils class from commons-lang to obtain a double[] from a Double[].

Double[] ds = frameList.toArray(new Double[frameList.size()]);
...
double[] d = ArrayUtils.toPrimitive(ds);

adb command not found in linux environment

NOTE: while using adb on Linux you'll need to type ./adb to execute adb commands unless you create a path in ~/.bashrc. In a terminal write:

sudo gedit ~/.bashrc

Add the following line at the end of the file. Once you're done, save and exit.

Android tools

export PATH=~/Development/adt-bundle-linux/sdk/platform-tools:~/Development/adt-bundle-linux/sdk/tools:$PATH

Then in a Terminal run this command to reload your .bashrc: Code:

source ~/.bashrc

Now you can just run adb without put ./ before every command.

How do I detect a page refresh using jquery?

if you want to bookkeep some variable before page refresh

$(window).on('beforeunload', function(){
    // your logic here
});

if you want o load some content base on some condition

$(window).on('load', function(){
    // your logic here`enter code here`
});

System.MissingMethodException: Method not found?

In my case, there was no code change at all and suddenly one of the servers started getting this and only this exception (all servers have the same code, but only one started having issues):

System.MissingMethodException: Method not found: '?'.

Stack:

Server stack trace: 
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at myAccountSearch.AccountSearch.searchtPhone(searchtPhoneRequest request)
   at myAccountSearch.AccountSearchClient.myAccountSearch.AccountSearch.searchtPhone(searchtPhoneRequest request)
   at myAccountSearch.AccountSearchClient.searchtPhone(String ID, String HashID, searchtPhone Phone1)
   at WS.MyValidation(String AccountNumber, String PhoneNumber)

The issue I believe was corrupted AppPool - we have automated AppPool recycling going on every day at 3 am and the issue started at 3 am and then ended on its own at 3 am the next day.

Get all inherited classes of an abstract class

typeof(AbstractDataExport).Assembly tells you an assembly your types are located in (assuming all are in the same).

assembly.GetTypes() gives you all types in that assembly or assembly.GetExportedTypes() gives you types that are public.

Iterating through the types and using type.IsAssignableFrom() gives you whether the type is derived.

Logarithmic returns in pandas dataframe

@poulter7: I cannot comment on the other answers, so I post it as new answer: be careful with

np.log(df.price).diff() 

as this will fail for indices which can become negative as well as risk factors e.g. negative interest rates. In these cases

np.log(df.price/df.price.shift(1)).dropna()

is preferred and based on my experience generally the safer approach. It also evaluates the logarithm only once.

Whether you use +1 or -1 depends on the ordering of your time series. Use -1 for descending and +1 for ascending dates - in both cases the shift provides the preceding date's value.

C - error: storage size of ‘a’ isn’t known

In this case the user has done mistake in definition and its usage. If someone has done a typedef to a structure the same should be used without using struct following is the example.

typedef struct
{
   int a;
}studyT;

When using in a function

int main()
{
   struct studyT study; // This will give above error.
   studyT stud; // This will eliminate the above error.
   return 0;
}

javac option to compile all java files under a given directory recursively

javac command does not follow a recursive compilation process, so you have either specify each directory when running command, or provide a text file with directories you want to include:

javac -classpath "${CLASSPATH}" @java_sources.txt

Iterating through a list in reverse order in java

Create a custom reverseIterable.

calling a function from class in python - different way

class MathsOperations:
    def __init__ (self, x, y):
        self.a = x
        self.b = y
    def testAddition (self):
        return (self.a + self.b)

    def testMultiplication (self):
        return (self.a * self.b)

then

temp = MathsOperations()
print(temp.testAddition())

How do I get a button to open another activity?

If you declared your button in the xml file similar to this:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="next activity"
        android:onClick="goToActivity2"
        />

then you can use it to change the activity by putting this at the java file:

public void goToActivity2 (View view){
    Intent intent = new Intent (this, Main2Activity.class);
    startActivity(intent);
}

Note that my second activity is called "Main2Activity"

SVN change username

Also, for those who happened to realize too late, that they committed with the wrong credentials, the solution (after the fact) is to change the svn author of that revision: see this question

Basically the syntax is:

svn propset --revprop -r (revision_number) svn:author (new username)

Correct way to initialize HashMap and can HashMap hold different value types?

In answer to your second question: Yes a HashMap can hold different types of objects. Whether that's a good idea or not depends on the problem you're trying to solve.

That said, your example won't work. The int value is not an Object. You have to use the Integer wrapper class to store an int value in a HashMap

How to pass a list from Python, by Jinja2 to JavaScript

You can do this with Jinja's tojson filter, which

Dumps a structure to JSON so that it’s safe to use in <script> tags [and] in any place in HTML with the notable exception of double quoted attributes.

For example, in your Python, write:

some_template.render(list_of_items=list_of_items)

... or, in the context of a Flask endpoint:

return render_template('your_template.html', list_of_items=list_of_items)

Then in your template, write this:

{% for item in list_of_items %}
<span onclick='somefunction({{item | tojson}})'>{{item}}</span><br>
{% endfor %}

(Note that the onclick attribute is single-quoted. This is necessary since |tojson escapes ' characters but not " characters in its output, meaning that it can be safely used in single-quoted HTML attributes but not double-quoted ones.)

Or, to use list_of_items in an inline script instead of an HTML attribute, write this:

<script>
const jsArrayOfItems = {{list_of_items | tojson}};
// ... do something with jsArrayOfItems in JavaScript ...
</script>

DON'T use json.dumps to JSON-encode variables in your Python code and pass the resulting JSON text to your template. This will produce incorrect output for some string values, and will expose you to XSS if you're trying to encode user-provided values. This is because Python's built-in json.dumps doesn't escape characters like < and > (which need escaping to safely template values into inline <script>s, as noted at https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements) or single quotes (which need escaping to safely template values into single-quoted HTML attributes).

If you're using Flask, note that Flask injects a custom tojson filter instead of using Jinja's version. However, everything written above still applies. The two versions behave almost identically; Flask's just allows for some app-specific configuration that isn't available in Jinja's version.

recursion versus iteration

Recursion is usually much slower because all function calls must be stored in a stack to allow the return back to the caller functions. In many cases, memory has to be allocated and copied to implement scope isolation.

Some optimizations, like tail call optimization, make recursions faster but aren't always possible, and aren't implemented in all languages.

The main reasons to use recursion are

  • that it's more intuitive in many cases when it mimics our approach of the problem
  • that some data structures like trees are easier to explore using recursion (or would need stacks in any case)

Of course every recursion can be modeled as a kind of loop : that's what the CPU will ultimately do. And the recursion itself, more directly, means putting the function calls and scopes in a stack. But changing your recursive algorithm to a looping one might need a lot of work and make your code less maintainable : as for every optimization, it should only be attempted when some profiling or evidence showed it to be necessary.

How to set table name in dynamic SQL query?

Try this:

/* Variable Declaration */
DECLARE @EmpID AS SMALLINT
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @TableName AS NVARCHAR(100)
/* set the parameter value */
SET @EmpID = 1001
SET @TableName = 'tblEmployees'
/* Build Transact-SQL String by including the parameter */
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID' 
/* Specify Parameter Format */
SET @ParameterDefinition =  '@EmpID SMALLINT'
/* Execute Transact-SQL String */
EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID

How do I get and set Environment variables in C#?

If the purpose of reading environment variable is to override the values in the appsetting.json or any other config file, you can archive it through EnvironmentVariablesExtensions.

var builder = new ConfigurationBuilder()
                .AddJsonFile("appSettings.json")
                .AddEnvironmentVariables(prefix: "ABC_")

var config = builder.Build();

enter image description here

According to this example, Url for the environment is read from the appsettings.json. but when the AddEnvironmentVariables(prefix: "ABC_") line is added to the ConfigurationBuilder the value appsettings.json will be override by in the environement varibale value.

How to import classes defined in __init__.py

If lib/__init__.py defines the Helper class then in settings.py you can use:

from . import Helper

This works because . is the current directory, and acts as a synonym for the lib package from the point of view of the settings module. Note that it is not necessary to export Helper via __all__.

(Confirmed with python 2.7.10, running on Windows.)

Can I force a page break in HTML printing?

@Chris Doggett makes perfect sense. Although, I found one funny trick on lvsys.com, and it actually works on firefox and chrome. Just put this comment anywhere you want the page-break to be inserted. You can also replace the <p> tag with any block element.

<p><!-- pagebreak --></p>

Why can't I center with margin: 0 auto?

You need to define the width of the element you are centering, not the parent element.

#header ul {
    margin: 0 auto;
    width: 90%;
}

Edit: Ok, I've seen the testpage now, and here is how I think you want it:

#header ul {
    list-style:none;
    margin:0 auto;
    width:90%;
}

/* Remove the float: left; property, it interferes with display: inline and 
 * causes problems. (float: left; makes the element implicitly a block-level
 * element. It is still good to use display: inline on it to overcome a bug
 * in IE6 and below that doubles horizontal margins for floated elements)
 * The styles below is the full style for the list-items. 
 */
#header ul li {
    color:#CCCCCC;
    display:inline;
    font-size:20px;
    padding-right:20px;
}

Is it possible to send a variable number of arguments to a JavaScript function?

With ES6 you can use rest parameters for varagrs. This takes the argument list and converts it to an array.

function logArgs(...args) {
    console.log(args.length)
    for(let arg of args) {
        console.log(arg)
    }
}

How to minify php page html output?

Turn on gzip if you want to do it properly. You can also just do something like this:

$this->output = preg_replace(
    array(
        '/ {2,}/',
        '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
    ),
    array(
        ' ',
        ''
    ),
    $this->output
);

This removes about 30% of the page size by turning your html into one line, no tabs, no new lines, no comments. Mileage may vary