Programs & Examples On #Agavi

Agavi is a scalable PHP MVC application framework that enables developers to create clean, maintainable and extensible code for all kinds of applications (CLI, WEB, SOAP etc.)

How to produce an csv output file from stored procedure in SQL Server

I think it is possible to use bcp command. I am also new to this command but I followed this link and it worked for me.

How do you specify a different port number in SQL Management Studio?

Using the client manager affects all connections or sets a client machine specific alias.

Use the comma as above: this can be used in an app.config too

It's probably needed if you have firewalls between you and the server too...

How can I change an element's class with JavaScript?

classList DOM API:

A very convenient manner of adding and removing classes is the classList DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using javascript. For example:

_x000D_
_x000D_
const el = document.getElementById("main");_x000D_
console.log(el.classList);
_x000D_
<div class="content wrapper animated" id="main"></div>
_x000D_
_x000D_
_x000D_

We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).

Example:

_x000D_
_x000D_
const el = document.getElementById('container');_x000D_
_x000D_
_x000D_
function addClass () {_x000D_
   el.classList.add('newclass');_x000D_
}_x000D_
_x000D_
_x000D_
function replaceClass () {_x000D_
     el.classList.replace('foo', 'newFoo');_x000D_
}_x000D_
_x000D_
_x000D_
function removeClass () {_x000D_
       el.classList.remove('bar');_x000D_
}
_x000D_
button{_x000D_
  margin: 20px;_x000D_
}_x000D_
_x000D_
.foo{_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
.newFoo {_x000D_
  color: blue;_x000D_
}_x000D_
_x000D_
.bar{_x000D_
  background-color:powderblue;_x000D_
}_x000D_
_x000D_
.newclass{_x000D_
  border: 2px solid green;_x000D_
}
_x000D_
<div class="foo bar" id="container">_x000D_
  "Sed ut perspiciatis unde omnis _x000D_
  iste natus error sit voluptatem accusantium doloremque laudantium, _x000D_
  totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et _x000D_
  quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam _x000D_
  voluptatem quia voluptas _x000D_
 </div>_x000D_
  _x000D_
<button onclick="addClass()">AddClass</button>_x000D_
  _x000D_
<button onclick="replaceClass()">ReplaceClass</button>_x000D_
  _x000D_
<button onclick="removeClass()">removeClass</button>_x000D_
  
_x000D_
_x000D_
_x000D_

How to export data as CSV format from SQL Server using sqlcmd?

You can run something like this:

sqlcmd -S MyServer -d myDB -E -Q "select col1, col2, col3 from SomeTable" 
       -o "MyData.csv" -h-1 -s"," -w 700
  • -h-1 removes column name headers from the result
  • -s"," sets the column seperator to ,
  • -w 700 sets the row width to 700 chars (this will need to be as wide as the longest row or it will wrap to the next line)

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

Yes , Jared and Kelly Orr are right. I use the following code like in edit exception.

foreach (var issue in dinner.GetRuleViolations())
{
    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}

in stead of

ModelState.AddRuleViolations(dinner.GetRuleViolations());

What's wrong with overridable method calls in constructors?

Here is an example that reveals the logical problems that can occur when calling an overridable method in the super constructor.

class A {

    protected int minWeeklySalary;
    protected int maxWeeklySalary;

    protected static final int MIN = 1000;
    protected static final int MAX = 2000;

    public A() {
        setSalaryRange();
    }

    protected void setSalaryRange() {
        throw new RuntimeException("not implemented");
    }

    public void pr() {
        System.out.println("minWeeklySalary: " + minWeeklySalary);
        System.out.println("maxWeeklySalary: " + maxWeeklySalary);
    }
}

class B extends A {

    private int factor = 1;

    public B(int _factor) {
        this.factor = _factor;
    }

    @Override
    protected void setSalaryRange() {
        this.minWeeklySalary = MIN * this.factor;
        this.maxWeeklySalary = MAX * this.factor;
    }
}

public static void main(String[] args) {
    B b = new B(2);
    b.pr();
}

The result would actually be:

minWeeklySalary: 0

maxWeeklySalary: 0

This is because the constructor of class B first calls the constructor of class A, where the overridable method inside B gets executed. But inside the method we are using the instance variable factor which has not yet been initialized (because the constructor of A has not yet finished), thus factor is 0 and not 1 and definitely not 2 (the thing that the programmer might think it will be). Imagine how hard would be to track an error if the calculation logic was ten times more twisted.

I hope that would help someone.

How to get history on react-router v4?

In the specific case of react-router, using context is a valid case scenario, e.g.

class MyComponent extends React.Component {
  props: PropsType;

  static contextTypes = {
    router: PropTypes.object
  };

  render () {
    this.context.router;
  }
}

You can access an instance of the history via the router context, e.g. this.context.router.history.

Links not going back a directory?

There are two type of paths: absolute and relative. This is basically the same for files in your hard disc and directories in a URL.

Absolute paths start with a leading slash. They always point to the same location, no matter where you use them:

  • /pages/en/faqs/faq-page1.html

Relative paths are the rest (all that do not start with slash). The location they point to depends on where you are using them

  • index.html is:
    • /pages/en/faqs/index.html if called from /pages/en/faqs/faq-page1.html
    • /pages/index.html if called from /pages/example.html
    • etc.

There are also two special directory names: . and ..:

  • . means "current directory"
  • .. means "parent directory"

You can use them to build relative paths:

  • ../index.html is /pages/en/index.html if called from /pages/en/faqs/faq-page1.html
  • ../../index.html is /pages/index.html if called from /pages/en/faqs/faq-page1.html

Once you're familiar with the terms, it's easy to understand what it's failing and how to fix it. You have two options:

  • Use absolute paths
  • Fix your relative paths

Scale image to fit a bounding box

Today, just say object-fit: contain. Support is everything but IE: http://caniuse.com/#feat=object-fit

Data truncated for column?

I had the same problem because of an table column which was defined as ENUM('x','y','z') and later on I was trying to save the value 'a' into this column, thus I got the mentioned error.

Solved by altering the table column definition and added value 'a' into the enum set.

.gitignore all the .DS_Store files in every folder and subfolder

You can also add the --cached flag to auco's answer to maintain local .DS_store files, as Edward Newell mentioned in his original answer. The modified command looks like this: find . -name .DS_Store -print0 | xargs -0 git rm --cached --ignore-unmatch ..cheers and thanks!

Change a Django form field to a hidden field

If you want the field to always be hidden, use the following:

class MyForm(forms.Form):
    hidden_input = forms.CharField(widget=forms.HiddenInput(), initial="value")

If you want the field to be conditionally hidden, you can do the following:

form = MyForm()
if condition:
    form.fields["field_name"].widget = forms.HiddenInput()
    form.fields["field_name"].initial = "value"

Convert string to number and add one

Parse the Id as it would be string and then add.

e.g.

$('.load_more').live("click",function() { //When user clicks
    var newcurrentpageTemp = parseInt($(this).attr("id")) + 1;//Get the id from the hyperlink
    alert(newcurrentpageTemp);
    dosomething();
});

How do I remove documents using Node.js Mongoose?

This worked for me, just try this:

const id = req.params.id;
      YourSchema
      .remove({_id: id})
      .exec()
      .then(result => {
        res.status(200).json({
          message: 'deleted',
          request: {
            type: 'POST',
            url: 'http://localhost:3000/yourroutes/'
          }
        })
      })
      .catch(err => {
        res.status(500).json({
          error: err
        })
      });

SpringMVC RequestMapping for GET parameters

This will get ALL parameters from the request. For Debugging purposes only:

@RequestMapping (value = "/promote", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView renderPromotePage (HttpServletRequest request) {
    Map<String, String[]> parameters = request.getParameterMap();

    for(String key : parameters.keySet()) {
        System.out.println(key);
        String[] vals = parameters.get(key);
        for(String val : vals)
            System.out.println(" -> " + val);
    }

    ModelAndView mv = new ModelAndView();
    mv.setViewName("test");
    return mv;
}

How do I make an attributed string using Swift?

Swift 2.1 - Xcode 7

let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :[String:AnyObject] = [NSFontAttributeName : labelFont!]
let attrString = NSAttributedString(string:"foo", attributes: attributes)
myLabel.attributedText = attrString

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

you can use this option for call soap with wdsl :

$opts = array(
            'http' => array(
                'user_agent' => 'PHPSoapClient'
            )
        );
        $context = stream_context_create($opts);

        $soapClientOptions = array(
            'stream_context' => $context,
            'cache_wsdl' => WSDL_CACHE_NONE
        );

        $wsdlUrl = 'your wsdl url';
        $soapClient = new SoapClient($wsdlUrl, $soapClientOptions);

        $result = $soapClient->VerifyTransaction($refNum, $MerchantCode);

Check whether variable is number or string in JavaScript

XOR operation can be used to detect number or string. number ^ 0 will always give the number as output and string ^ 0 will give 0 as output.

Example: 
   1)  2 ^ 0 = 2
   2)  '2' ^ 0  = 2
   3)  'Str' ^ 0 = 0

how to run mysql in ubuntu through terminal

If you want to run your scripts, then

mysql -u root -p < yourscript.sql

Change Default branch in gitlab

For GitLab 11.5.0-ee, go to https://gitlab.com/<username>/<project name>/settings/repository.

You should see:

Default Branch

Select the branch you want to set as the default for this project. All merge requests and commits will automatically be made against this branch unless you specify a different one.

Click Expand, select a branch, and click Save Changes.

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

i got the same error. it worked with df.fillna(-99999, inplace=True) before doing any replacement, substitution etc

Visual Studio: LINK : fatal error LNK1181: cannot open input file

I don't know why, but changing the Linker->Input->Additional Dependencies reference from "dxguid.lib" to "C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Lib\x86\dxguid.lib" (in my case) was the only thing that worked.

Insert php variable in a href

Try using printf function or the concatination operator

http://php.net/manual/en/function.printf.php

CSS background-size: cover replacement for Mobile Safari

I have had a similar issue recently and realised that it's not due to background-size:cover but background-attachment:fixed.

I solved the issue by using a media query for iPhone and setting background-attachment property to scroll.

For my case:

.cover {
    background-size: cover;
    background-attachment: fixed;
    background-position: center center;

    @media (max-width: @iphone-screen) {
        background-attachment: scroll;
    }
}

Edit: The code block is in LESS and assumes a pre-defined variable for @iphone-screen. Thanks for the notice @stephband.

Changing tab bar item image and text color iOS

You may also do by this way:

override func viewWillLayoutSubviews() {  
  if let items = self.tabBar.items {
    for item in 0..<items.count {
      items[item].image = items[item].image?.withRenderingMode(.alwaysOriginal)
            items[item].selectedImage = items[item].selectedImage?.withRenderingMode(.alwaysTemplate)
    }

Optional:

 UITabBar.appearance().tintColor = UIColor.red

I hope it will help you.

Trigger an action after selection select2

//when a Department selecting
$('#department_id').on('select2-selecting', function (e) {
    console.log("Action Before Selected");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});

//when a Department removing
$('#department_id').on('select2-removing', function (e) {
    console.log("Action Before Deleted");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});

Determine if Python is running inside virtualenv

Easiest way is to just run: which python, if you are in a virtualenv it will point to its python instead of the global one

HTML table sort

Here is another library.

Changes required are -

  1. Add sorttable js

  2. Add class name sortable to table.

Click the table headers to sort the table accordingly:

_x000D_
_x000D_
<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>

<table class="sortable">
  <tr>
    <th>Name</th>
    <th>Address</th>
    <th>Sales Person</th>
  </tr>

  <tr class="item">
    <td>user:0001</td>
    <td>UK</td>
    <td>Melissa</td>
  </tr>
  <tr class="item">
    <td>user:0002</td>
    <td>France</td>
    <td>Justin</td>
  </tr>
  <tr class="item">
    <td>user:0003</td>
    <td>San Francisco</td>
    <td>Judy</td>
  </tr>
  <tr class="item">
    <td>user:0004</td>
    <td>Canada</td>
    <td>Skipper</td>
  </tr>
  <tr class="item">
    <td>user:0005</td>
    <td>Christchurch</td>
    <td>Alex</td>
  </tr>

</table>
_x000D_
_x000D_
_x000D_

How do I get the path of the assembly the code is in?

I got the same behaviour in the NUnit in the past. By default NUnit copies your assembly into the temp directory. You can change this behaviour in the NUnit settings:

enter image description here

Maybe TestDriven.NET and MbUnit GUI have the same settings.

What is the difference between a process and a thread?

Thread is a light weight process while, the process is a self contained execution environment.

What is meant by "self contained execution process"? Private set of basic runtime resources.

What is meant by "private set of basic runtime resources"? The space allocated from memory to run the the process.(Simply a memory space.)

JNI and Gradle in Android Studio

Android Studio 2.2 came out with the ability to use ndk-build and cMake. Though, we had to wait til 2.2.3 for the Application.mk support. I've tried it, it works...though, my variables aren't showing up in the debugger. I can still query them via command line though.

You need to do something like this:

externalNativeBuild{
   ndkBuild{
        path "Android.mk"
    }
}

defaultConfig {
  externalNativeBuild{
    ndkBuild {
      arguments "NDK_APPLICATION_MK:=Application.mk"
      cFlags "-DTEST_C_FLAG1"  "-DTEST_C_FLAG2"
      cppFlags "-DTEST_CPP_FLAG2"  "-DTEST_CPP_FLAG2"
      abiFilters "armeabi-v7a", "armeabi"
    }
  } 
}

See http://tools.android.com/tech-docs/external-c-builds

NB: The extra nesting of externalNativeBuild inside defaultConfig was a breaking change introduced with Android Studio 2.2 Preview 5 (July 8, 2016). See the release notes at the above link.

Attempt to set a non-property-list object as an NSUserDefaults

Swift with @propertyWrapper

Save Codable object to UserDefault

@propertyWrapper
    struct UserDefault<T: Codable> {
        let key: String
        let defaultValue: T

        init(_ key: String, defaultValue: T) {
            self.key = key
            self.defaultValue = defaultValue
        }

        var wrappedValue: T {
            get {

                if let data = UserDefaults.standard.object(forKey: key) as? Data,
                    let user = try? JSONDecoder().decode(T.self, from: data) {
                    return user

                }

                return  defaultValue
            }
            set {
                if let encoded = try? JSONEncoder().encode(newValue) {
                    UserDefaults.standard.set(encoded, forKey: key)
                }
            }
        }
    }




enum GlobalSettings {

    @UserDefault("user", defaultValue: User(name:"",pass:"")) static var user: User
}

Example User model confirm Codable

struct User:Codable {
    let name:String
    let pass:String
}

How to use it

//Set value 
 GlobalSettings.user = User(name: "Ahmed", pass: "Ahmed")

//GetValue
print(GlobalSettings.user)

R color scatter plot points based on values

Also it'd work to just specify ifelse() twice:

plot(pos,cn, col= ifelse(cn >= 3, "red", ifelse(cn <= 1,"blue", "black")), ylim = c(0, 10))

Where are my postgres *.conf files?

nantha=# SHOW config_file;

config_file

/var/lib/postgresql/data/postgresql.conf (1 row)

nantha=# SHOW hba_file;

hba_file

/var/lib/postgresql/data/pg_hba.conf (1 row)

How to get single value of List<object>

Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

How to fill 100% of remaining height?

To get a div to 100% height on a page, you will need to set each object on the hierarchy above the div to 100% as well. for instance:

html { height:100%; }
body { height:100%; }
#full { height: 100%; }
#someid { height: 100%; }

Although I cannot fully understand your question, I'm assuming this is what you mean.

This is the example I am working from:

<html style="height:100%">
    <body style="height:100%">
        <div style="height:100%; width: 300px;">
            <div style="height:100%; background:blue;">

            </div>
        </div>
    </body>
</html>

Style is just a replacement for the CSS which I haven't externalised.

How to update data in one table from corresponding data in another table in SQL Server 2005

update t2
set t2.deptid = t1.deptid
from test1 t1, test2 t2
where t2.employeeid = t1.employeeid

Android Studio gradle takes too long to build

I was facing the same problem for a long time but I solved it by adjusting the settings in gradle.

Step 1:In Module app add dependency in BuildScript

buildscript {
 dependencies {
         classpath 'com.android.tools.build:gradle:2.0.0-alpha9'
}
}

Step 2: Add dexOption and give the following heapSize

  dexOptions {
    incremental = true;
    preDexLibraries = false
    javaMaxHeapSize "4g"
}

Step 3: Add productFlavors

    productFlavors {
    dev {
        minSdkVersion 23
        applicationId = "com.Reading.home"
    }
    prod {
        minSdkVersion 15
        applicationId = "com.Reading.home" // you don't need it, but can be useful

    }
}

This should reduce your build time.

Certificate is trusted by PC but not by Android

I had the same error because I didn't issued a Let's Encrypt cert for the www.my-domain.com, only for my-domain.com

Issuing also for the www. and configuring the vhost to load certificates for www.my-domain.com before redirecting to https://my-domain.com did the trick.

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

In my case I had to include several additional exclusions. It appears it doesn't like Regular expressions which would've made this a nice one-liner.

android {
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/notice.txt'
    }
}

When should I really use noexcept?

When can I realistically except to observe a performance improvement after using noexcept? In particular, give an example of code for which a C++ compiler is able to generate better machine code after the addition of noexcept.

Um, never? Is never a time? Never.

noexcept is for compiler performance optimizations in the same way that const is for compiler performance optimizations. That is, almost never.

noexcept is primarily used to allow "you" to detect at compile-time if a function can throw an exception. Remember: most compilers don't emit special code for exceptions unless it actually throws something. So noexcept is not a matter of giving the compiler hints about how to optimize a function so much as giving you hints about how to use a function.

Templates like move_if_noexcept will detect if the move constructor is defined with noexcept and will return a const& instead of a && of the type if it is not. It's a way of saying to move if it is very safe to do so.

In general, you should use noexcept when you think it will actually be useful to do so. Some code will take different paths if is_nothrow_constructible is true for that type. If you're using code that will do that, then feel free to noexcept appropriate constructors.

In short: use it for move constructors and similar constructs, but don't feel like you have to go nuts with it.

Android Studio - Unable to find valid certification path to requested target

I got it because I'm behind a proxy. I had set the http but not the https proxy in gradle.properties. Https was needed in this case:

systemProp.http.proxyHost=<host>
systemProp.http.proxyPort=<port>
systemProp.https.proxyHost=<host>
systemProp.https.proxyPort=<port>

Also, take a look at the Android Studio logs for where the error could be.

Updating .class file in jar

Editing properties/my_app.properties file inside jar:

"zip -u /var/opt/my-jar-with-dependencies.jar properties/my_app.properties". Basically "zip -u <source> <dest>", where dest is relative to the jar extract folder.

Python reading from a file and saving to utf-8

You can also get through it by the code below:

file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()

Dynamically Add Variable Name Value Pairs to JSON Object

I'm assuming each entry in "ips" can have multiple name value pairs - so it's nested. You can achieve this data structure as such:

var ips = {}

function addIpId(ipID, name, value) {
    if (!ips[ipID]) ip[ipID] = {};
    var entries = ip[ipID];
    // you could add a check to ensure the name-value par's not already defined here
    var entries[name] = value;
}

Is it fine to have foreign key as primary key?

Yes, a foreign key can be a primary key in the case of one to one relationship between those tables

Change :hover CSS properties with JavaScript

Had some same problems, used addEventListener for events "mousenter", "mouseleave":

let DOMelement = document.querySelector('CSS selector for your HTML element');

// if you want to change e.g color: 
let origColorStyle = DOMelement.style.color;

DOMelement.addEventListener("mouseenter", (event) => { event.target.style.color = "red" });

DOMelement.addEventListener("mouseleave", (event) => { event.target.style.color = origColorStyle })

Or something else for style when cursor is above the DOMelement. DOMElement can be chosen by various ways.

Composer: how can I install another dependency without updating old ones?

My use case is simpler, and fits simply your title but not your further detail.

That is, I want to install a new package which is not yet in my composer.json without updating all the other packages.

The solution here is composer require x/y

How to stop a goroutine

You can't kill a goroutine from outside. You can signal a goroutine to stop using a channel, but there's no handle on goroutines to do any sort of meta management. Goroutines are intended to cooperatively solve problems, so killing one that is misbehaving would almost never be an adequate response. If you want isolation for robustness, you probably want a process.

Create <div> and append <div> dynamically

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

iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

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

div2.className = 'block-2';
iDiv.appendChild(div2);

Iterating over Typescript Map

Just a simple explanation to use it in an HTML document.

If you have a Map of types (key, array) then you initialise the array this way:

public cityShop: Map<string, Shop[]> = new Map();

And to iterate over it, you create an array from key values.

Just use it as an array as in:

keys = Array.from(this.cityShop.keys());

Then, in HTML, you can use:

*ngFor="let key of keys"

Inside this loop, you just get the array value with:

this.cityShop.get(key)

Done!

Android studio logcat nothing to show

I tried the suggestions above. However, none of them worked. I then did the following which surprisingly worked:

  1. Disconnect the USB from the device
  2. Connected the device via Wi-Fi using the commands adb tcpip 5555 and adb connect <device ip>
  3. Disconnected the device from the adb using adb kill-server
  4. Connected the device back via USB

The LogCat then showed the logs. Even though the logs were available at step 2, the following steps resolved the issue for me when connecting via USB.

Increasing (or decreasing) the memory available to R processes

In RStudio, to increase:

file.edit(file.path("~", ".Rprofile"))

then in .Rprofile type this and save

invisible(utils::memory.limit(size = 60000))

To decrease: open .Rprofile

invisible(utils::memory.limit(size = 30000))

save and restart RStudio.

Managing SSH keys within Jenkins for Git

According to this article, you may try following command:

   ssh-add -l

If your key isn't in the list, then

   ssh-add /var/lib/jenkins/.ssh/id_rsa_project

Function inside a function.?

Not sure what the author of that code wanted to achieve. Definining a function inside another function does NOT mean that the inner function is only visible inside the outer function. After calling x() the first time, the y() function will be in global scope as well.

"NoClassDefFoundError: Could not initialize class" error

I had this:

 class Util {
  static boolean isNeverAsync = System.getenv().get("asyncc_exclude_redundancy").equals("yes");
}

you can probably see the problem, the env var might return null instead of string. So just to test my theory, I changed it to:

 class Util {
  static boolean isNeverAsync = false;
}

and the problem went away. Too bad that Java can't give you the exact stack trace of the error though, kinda weird.

How to pass props to {this.props.children}

Cleaner way considering one or more children

<div>
   { React.Children.map(this.props.children, child => React.cloneElement(child, {...this.props}))}
</div>

Oracle JDBC intermittent Connection Issue

I faced the same problem when a liquibase was executed from jenkins. Sporadically this error was thrown to the output and the liquibase change logs were not executed at all.

Solution provided: In the jenkin's maven project, the jdk was updated from jdk8-131 to any newer version (eg java8-162).

ReferenceError: $ is not defined

Use Google CDN for fast loading:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

FIFO class in Java

if you want to have a pipe to write/read data, you can use the http://docs.oracle.com/javase/6/docs/api/java/io/PipedWriter.html

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

Check if a string is a date value

I know it's an old question but I faced the same problem and saw that none of the answers worked properly - specifically weeding out numbers (1,200,345,etc..) from dates, which is the original question. Here is a rather unorthodox method I could think of and it seems to work. Please point out if there are cases where it will fail.

if(sDate.toString() == parseInt(sDate).toString()) return false;

This is the line to weed out numbers. Thus, the entire function could look like:

_x000D_
_x000D_
function isDate(sDate) {  _x000D_
  if(sDate.toString() == parseInt(sDate).toString()) return false; _x000D_
  var tryDate = new Date(sDate);_x000D_
  return (tryDate && tryDate.toString() != "NaN" && tryDate != "Invalid Date");  _x000D_
}_x000D_
_x000D_
console.log("100", isDate(100));_x000D_
console.log("234", isDate("234"));_x000D_
console.log("hello", isDate("hello"));_x000D_
console.log("25 Feb 2018", isDate("25 Feb 2018"));_x000D_
console.log("2009-11-10T07:00:00+0000", isDate("2009-11-10T07:00:00+0000"));
_x000D_
_x000D_
_x000D_

How do you decrease navbar height in Bootstrap 3?

In Bootstrap 4

In my case I have just changed the .navbar min-height and the links font-size and it decreased the navbar.

For example:

.navbar{
    min-height:12px;
}
.navbar  a {
    font-size: 11.2px;
}

And this also worked for increasing the navbar height.

This also helps to change the navbar size when scrolling down the browser.

Header and footer in CodeIgniter

Or more complex, but makes life easy is to use more constants in boot. So subclasses can be defined freely, and a single method to show view. Also selected constants can be passed to javascript in the header.

<?php
/*
 * extends codeigniter main controller
 */

class CH_Controller extends CI_Controller {

    protected $viewdata;

public function __construct() {
    parent::__construct();
            //hard code / override and transfer only required constants (for security) server constants
            //such as domain name to client - this is for code porting and no passwords or database details
            //should be used - ajax is for this

    $this->viewdata = array(
                "constants_js" => array(
                    "TOP_DOMAIN"=>TOP_DOMAIN,
                    "C_UROOT" => C_UROOT,
                    "UROOT" => UROOT,
                    "DOMAIN"=> DOMAIN
                )
            );

}

public function show($viewloc) {
            $this->load->view('templates/header', $this->viewdata);
    $this->load->view($viewloc, $this->viewdata);
    $this->load->view('templates/footer', $this->viewdata);
}

//loads custom class objects if not already loaded
public function loadplugin($newclass) {
    if (!class_exists("PL_" . $newclass)) {
        require(CI_PLUGIN . "PL_" . $newclass . ".php");
    }
}

then simply:

$this->show("<path>/views/viewname/whatever_V.php");

will load header, view and footer.

Local package.json exists, but node_modules missing

npm start runs a script that the app maker built for easy starting of the app npm install installs all the packages in package.json

run npm install first

then run npm start

CSS to hide INPUT BUTTON value text

well:

font-size: 0; line-height: 0;

work awesome for me!

Cannot read property 'addEventListener' of null

Thanks to @Rob M. for his help. This is what the final block of code looked like:

function swapper() {
  toggleClass(document.getElementById('overlay'), 'open');
}

var el = document.getElementById('overlayBtn');
if (el){
  el.addEventListener('click', swapper, false);

  var text = document.getElementById('overlayBtn');
  text.onclick = function(){
    this.innerHTML = (this.innerHTML === "Menu") ? "Close" : "Menu";
    return false;
  };
}

How to remove word wrap from textarea?

If you can use JavaScript, the following might be the most portable option today (tested Firefox 31, Chrome 36):

http://jsfiddle.net/cirosantilli/eaxgesoq/

<style>
  div#editor {
    white-space: pre;
    word-wrap: normal;
    overflow-x: scroll;
  }
<style>
<div contenteditable="true"></div>

There seems to be no standard, portable CSS solution:

Also, if you can use Javascript, you might as well use the ACE editor:

http://jsfiddle.net/cirosantilli/bL9vr8o8/

<script src="http://cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/ace.js"></script>
<div id="editor">content</div>
<script>
  var editor = ace.edit('editor')
  editor.renderer.setShowGutter(false)
</script>

Probably works with ACE because it does not use a textarea either which is underspecified / incoherently implemented, but not sure if it is uses contenteditable.

Escape text for HTML

If you're using .NET 4 or above and you don't want to reference System.Web, you can use WebUtility.HtmlEncode from System

var encoded = WebUtility.HtmlEncode(unencoded);

This has the same effect as HttpUtility.HtmlEncode and should be preferred over System.Security.SecurityElement.Escape.

Update Jenkins from a war file

#on ubuntu, in /usr/share/jenkins:

sudo service jenkins stop
sudo mv jenkins.war jenkins.war.old
sudo wget https://updates.jenkins-ci.org/latest/jenkins.war
sudo service jenkins start

How to make an unaware datetime timezone aware in python

In general, to make a naive datetime timezone-aware, use the localize method:

import datetime
import pytz

unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)
aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC)

now_aware = pytz.utc.localize(unaware)
assert aware == now_aware

For the UTC timezone, it is not really necessary to use localize since there is no daylight savings time calculation to handle:

now_aware = unaware.replace(tzinfo=pytz.UTC)

works. (.replace returns a new datetime; it does not modify unaware.)

selecting unique values from a column

Use this query to get values

SELECT * FROM `buy` group by date order by date DESC

Appending to an object

How about storing the alerts as records in an array instead of properties of a single object ?

var alerts = [ 
    {num : 1, app:'helloworld',message:'message'},
    {num : 2, app:'helloagain',message:'another message'} 
]

And then to add one, just use push:

alerts.push({num : 3, app:'helloagain_again',message:'yet another message'});

How to change color of Toolbar back button in Android?

Use this:

<style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
  <item name="colorControlNormal">@color/white</item> 
</style>

How to get method parameter names?

In Python 3.+ with the Signature object at hand, an easy way to get a mapping between argument names to values, is using the Signature's bind() method!

For example, here is a decorator for printing a map like that:

import inspect

def decorator(f):
    def wrapper(*args, **kwargs):
        bound_args = inspect.signature(f).bind(*args, **kwargs)
        bound_args.apply_defaults()
        print(dict(bound_args.arguments))

        return f(*args, **kwargs)

    return wrapper

@decorator
def foo(x, y, param_with_default="bars", **kwargs):
    pass

foo(1, 2, extra="baz")
# This will print: {'kwargs': {'extra': 'baz'}, 'param_with_default': 'bars', 'y': 2, 'x': 1}

How to submit http form using C#

I had a similar issue in MVC (which lead me to this problem).

I am receiving a FORM as a string response from a WebClient.UploadValues() request, which I then have to submit - so I can't use a second WebClient or HttpWebRequest. This request returned the string.

using (WebClient client = new WebClient())
  {
    byte[] response = client.UploadValues(urlToCall, "POST", new NameValueCollection()
    {
        { "test", "value123" }
    });

    result = System.Text.Encoding.UTF8.GetString(response);
  }

My solution, which could be used to solve the OP, is to append a Javascript auto submit to the end of the code, and then using @Html.Raw() to render it on a Razor page.

result += "<script>self.document.forms[0].submit()</script>";
someModel.rawHTML = result;
return View(someModel);

Razor Code:

@model SomeModel

@{
    Layout = null;
}

@Html.Raw(@Model.rawHTML)

I hope this can help anyone who finds themselves in the same situation.

Using Linq to group a list of objects into a new grouped list of list of objects

For type

public class KeyValue
{
    public string KeyCol { get; set; }
    public string ValueCol { get; set; }
}

collection

var wordList = new Model.DTO.KeyValue[] {
    new Model.DTO.KeyValue {KeyCol="key1", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key2", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key3", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key4", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key5", ValueCol="value3" },
    new Model.DTO.KeyValue {KeyCol="key6", ValueCol="value4" }
};

our linq query look like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList() };

or for array instead of list like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList().ToArray<string>() };

Sending the bearer token with axios

By using Axios interceptor:

const service = axios.create({
  timeout: 20000 // request timeout
});

// request interceptor

service.interceptors.request.use(
  config => {
    // Do something before request is sent

    config.headers["Authorization"] = "bearer " + getToken();
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

How to get current PHP page name

You can use basename() and $_SERVER['PHP_SELF'] to get current page file name

echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */

How can I remove all objects but one from the workspace in R?

Here is a simple construct that will do it, by using setdiff:

rm(list=setdiff(ls(), "x"))

And a full example. Run this at your own risk - it will remove all variables except x:

x <- 1
y <- 2
z <- 3
ls()
[1] "x" "y" "z"

rm(list=setdiff(ls(), "x"))

ls()
[1] "x"

Remove blank attributes from an Object in Javascript

We can use JSON.stringify and JSON.parse to remove blank attributes from an object.

jsObject = JSON.parse(JSON.stringify(jsObject), (key, value) => {
               if (value == null || value == '' || value == [] || value == {})
                   return undefined;
               return value;
           });

"commence before first target. Stop." error

This means that there is a line which starts with a space, tab, or some other whitespace without having a target in front of it.

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

You need to run Set-ExecutionPolicy:

Set-ExecutionPolicy Unrestricted <-- Will allow unsigned PowerShell scripts to run.

Set-ExecutionPolicy Restricted <-- Will not allow unsigned PowerShell scripts to run.

Set-ExecutionPolicy RemoteSigned <-- Will allow only remotely signed PowerShell scripts to run.

How do you change the server header returned by nginx?

It’s very simple: Add these lines to server section:

server_tokens off;
more_set_headers 'Server: My Very Own Server';

Send push to Android by C# using FCM (Firebase Cloud Messaging)

I write this code and It's worked for me .

public static string ExcutePushNotification(string title, string msg, string fcmToken, object data) 
{

        var serverKey = "AAAA*******************";
        var senderId = "3333333333333";


        var result = "-1";

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://fcm.googleapis.com/fcm/send");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
        httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
        httpWebRequest.Method = "POST";


        var payload = new
        {
            notification = new
            {
                title = title,
                body = msg,
                sound = "default"
            },

            data = new
            {
                info = data
            },
            to = fcmToken,
            priority = "high",
            content_available = true,

        };


        var serializer = new JavaScriptSerializer();

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = serializer.Serialize(payload);
            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
        }
        return result;
}

How to find files recursively by file type and copy them to a directory while in ssh?

Try this:

find . -name "*.pdf" -type f -exec cp {} ./pdfsfolder \;

What is "origin" in Git?

The top answer is great.

I would just add, that it becomes easy to understand if you think about remotes as locations other than your computer that you may want to move your code to.

Some very good examples are:

  • GitHub
  • A server to host your app

So you can certainly have multiple remotes. A very common pattern is to use GitHub to store your code, and a server to host your application (if it's a web application). Then you would have 2 remotes (possibly more if you have other environments).

Try opening your git config by typing git config -e

Note: press escape, then :, then q then enter to quit out

Example

Here's what you might see in your git configs if you had 3 remotes. In this example, 1 remote (called 'origin') is GitHub, another remote (called 'staging') is a staging server, and the third (called 'heroku') is a production server.

[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
        ignorecase = true
        precomposeunicode = true
[remote "origin"]
        url = https://github.com/username/reponame.git
        fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
        remote = origin
        merge = refs/heads/master
[remote "heroku"]
        url = https://git.heroku.com/appname.git
        fetch = +refs/heads/*:refs/remotes/heroku/*
[remote "staging"]
        url = https://git.heroku.com/warm-bedlands-98000.git
        fetch = +refs/heads/*:refs/remotes/staging/*

The three lines starting with [remote ... show us the remotes we can push to.

Running git push origin will push to the url for '[remote "origin"]', i.e. to GitHub

But similarly, we could push to another remote, say, '[remote "staging"]', with git push staging, then it would push to https://git.heroku.com/warm-bedlands-98000.git.

In the example above, we can see the 3 remotes with git remote:

git remote   
heroku
origin
staging

Summary or origin

Remotes are simply places on the internet that you may have a reason to send your code to. GitHub is an obvious place, as are servers that host your app, and you may have other locations too. git push origin simply means it will push to 'origin', which is the name GitHub chooses to default to.

As for branchname

branchname is simply what you're pushing to the remote. According the git push help docs, the branchname argument is technically a refspec, which, for practical purposes, is the branch you want to push.

  • Read more in the docs for git push by running: git push --help

error: passing xxx as 'this' argument of xxx discards qualifiers

Member functions that do not modify the class instance should be declared as const:

int getId() const {
    return id;
}
string getName() const {
    return name;
}

Anytime you see "discards qualifiers", it's talking about const or volatile.

Jenkins not executing jobs (pending - waiting for next executor)

In my case I've to set Execute concurrent builds if necessary in job's General settings.

How to get previous month and year relative to today, using strtotime and date?

//return timestamp, use to format month, year as per requirement
function getMonthYear($beforeMonth = '') {
    if($beforeMonth !="" && $beforeMonth >= 1) {
        $date = date('Y')."-".date('m')."-15";
        $timestamp_before = strtotime( $date . ' -'.$beforeMonth.' month' );
        return $timestamp_before;
    } else {
        $time= time();
        return $time;
    }
}


//call function
$month_year = date("Y-m",getMonthYear(1));// last month before  current month
$month_year = date("Y-m",getMonthYear(2)); // second last month before current month

Font Awesome 5 font-family issue

The problem is in the font-weight.
For Font Awesome 5 you have to use {font-weight:900}

Curl command line for consuming webServices?

curl -H "Content-Type: text/xml; charset=utf-8" \
-H "SOAPAction:" \
-d @soap.txt -X POST http://someurl

How to add a bot to a Telegram Group?

Edit: now there is yet an easier way to do this - when creating your group, just mention the full bot name (eg. @UniversalAgent1Bot) and it will list it as you type. Then you can just tap on it to add it.

Old answer:

  1. Create a new group from the menu. Don't add any bots yet
  2. Find the bot (for instance you can go to Contacts and search for it)
  3. Tap to open
  4. Tap the bot name on the top bar. Your page becomes like this: Telegram bot settings
  5. Now, tap the triple ... and you will get the Add to Group button: Adding the bot
  6. Now select your group and add the bot - and confirm the addition

linq query to return distinct field values from a list of objects

Assuming you want the full object, but only want to deal with distinctness by typeID, there's nothing built into LINQ to make this easy. (If you just want the typeID values, it's easy - project to that with Select and then use the normal Distinct call.)

In MoreLINQ we have the DistinctBy operator which you could use:

var distinct = list.DistinctBy(x => x.typeID);

This only works for LINQ to Objects though.

You can use a grouping or a lookup, it's just somewhat annoying and inefficient:

var distinct = list.GroupBy(x => x.typeID, (key, group) => group.First());

How to set top-left alignment for UILabel for iOS application?

you can also just change your UILabel to UITextView, because they basically do the same thing except the advantage of UITextView is that text is automatically aligned to the top left

CSS Vertical align does not work with float

Vertical alignment doesn't work with floated elements, indeed. That's because float lifts the element from the normal flow of the document. You might want to use other vertical aligning techniques, like the ones based on transform, display: table, absolute positioning, line-height, js (last resort maybe) or even the plain old html table (maybe the first choice if the content is actually tabular). You'll find that there's a heated debate on this issue.

However, this is how you can vertically align YOUR 3 divs:

.wrap{
    width: 500px;
    overflow:hidden;    
    background: pink;
}

.left {
    width: 150px;       
    margin-right: 10px;
    background: yellow;  
    display:inline-block;
    vertical-align: middle; 
}

.left2 {
    width: 150px;    
    margin-right: 10px;
    background: aqua; 
    display:inline-block;
    vertical-align: middle; 
}

.right{
    width: 150px;
    background: orange;
    display:inline-block;
    vertical-align: middle; 
}

Not sure why you needed both fixed width, display: inline-block and floating.

Name node is in safe mode. Not able to leave

use below command to turn off the safe mode

$> hdfs dfsadmin -safemode leave

How to convert JSON string to array

If you are getting the JSON string from the form using $_REQUEST, $_GET, or $_POST the you will need to use the function html_entity_decode(). I didn't realize this until I did a var_dump of what was in the request vs. what I copied into and echo statement and noticed the request string was much larger.

Correct Way:

$jsonText = $_REQUEST['myJSON'];
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode($decodedText, true);

With Errors:

$jsonText = $_REQUEST['myJSON'];
$myArray = json_decode($jsonText, true);
echo json_last_error(); //Returns 4 - Syntax error;

python: restarting a loop

Just wanted to post an alternative which might be more genearally usable. Most of the existing solutions use a loop index to avoid this. But you don't have to use an index - the key here is that unlike a for loop, where the loop variable is hidden, the loop variable is exposed.

You can do very similar things with iterators/generators:

x = [1,2,3,4,5,6]
xi = iter(x)
ival = xi.next()
while not exit_condition(ival):
    # Do some ival stuff
    if ival == 4:
        xi = iter(x)
    ival = xi.next()

It's not as clean, but still retains the ability to write to the loop iterator itself.

Usually, when you think you want to do this, your algorithm is wrong, and you should rewrite it more cleanly. Probably what you really want to do is use a generator/coroutine instead. But it is at least possible.

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

If you have access to python, this is a helper that will get the yyyy-mm-dd date value for any arbitrary n days ago:

function get_n_days_ago {
  local days=$1
  python -c "import datetime; print (datetime.date.today() - datetime.timedelta(${days})).isoformat()"
}

# today is 2014-08-24

$ get_n_days_ago 1
2014-08-23

$ get_n_days_ago 2
2014-08-22

int to string in MySQL

select t2.* 
from t1 join t2 on t2.url='site.com/path/%' + cast(t1.id as varchar)  + '%/more' 
where t1.id > 9000

Using concat like suggested is even better though

How to set a text box for inputing password in winforms?

private void cbShowHide_CheckedChanged(object sender, EventArgs e)
{
    if (cbShowHide.Checked)
    {
        txtPin.UseSystemPasswordChar = PasswordPropertyTextAttribute.No.Password;
    }
    else
    {
        //Hides Textbox password
        txtPin.UseSystemPasswordChar = PasswordPropertyTextAttribute.Yes.Password;
    }
}

Copy this code to show and hide your textbox using a checkbox

How to show only next line after the matched one?

Great answer from raim, was very useful for me. It is trivial to extend this to print e.g. line 7 after the pattern

awk -v lines=7 '/blah/ {for(i=lines;i;--i)getline; print $0 }' logfile

How do I get the max ID with Linq to Entity?

The best way to get the id of the entity you added is like this:

public int InsertEntity(Entity factor)
{
    Db.Entities.Add(factor);
    Db.SaveChanges();
    var id = factor.id;
    return id;
}

Force an Android activity to always use landscape mode

In my OnCreate(Bundle), I generally do the following:

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

How to run a javascript function during a mouseover on a div

I'm assuming you want to display the welcome when you mouse over "some text".

As a message box, this will be:

<div id="sub1" onmouseover="javascript:alert('Welcome!');">some text</div>

As a tooltip, it should be:

<div id="sub1" title="Welcome!">some text</div>

As a new div, you can use:

<div id="sub1" onmouseover="javascript:var mydiv = document.createElement('div'); mydiv.height = 100; mydiv.width = 100; mydiv.zindex = 1000; mydiv.innerHTML = 'Welcome!'; mydiv.position = 'absolute'; mydiv.top = 0; mydiv.left = 0;">some text</div>

You should NEVER contain spaces in the id of an element.

Does Spring Data JPA have any way to count entites using method name resolving?

JpaRepository also extends QueryByExampleExecutor. So you don't even need to define custom methods on your interface:

public interface UserRepository extends JpaRepository<User, Long> {
    // no need of custom method
}

And then query like:

User probe = new User();
u.setName = "John";
long count = repo.count(Example.of(probe));

How to change file encoding in NetBeans?

This link answer your question: http://wiki.netbeans.org/FaqI18nProjectEncoding

You can change the sources encoding or runtime encoding.

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

Get current time in seconds since the Epoch on Linux, Bash

Just to add.

Get the seconds since epoch(Jan 1 1970) for any given date(e.g Oct 21 1973).

date -d "Oct 21 1973" +%s


Convert the number of seconds back to date

date --date @120024000


The command date is pretty versatile. Another cool thing you can do with date(shamelessly copied from date --help). Show the local time for 9AM next Friday on the west coast of the US

date --date='TZ="America/Los_Angeles" 09:00 next Fri'

Better yet, take some time to read the man page http://man7.org/linux/man-pages/man1/date.1.html

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

Run this script from SharePoint 2010 Management Shell as Administrator.

Invalid hook call. Hooks can only be called inside of the body of a function component

If all the above doesn't work, especially if having big size dependency (like my case), both building and loading were taking a minimum of 15 seconds, so it seems the delay gave a false message "Invalid hook call." So what you can do is give some time to ensure the build is completed before testing.

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

Make sure you clean your project in android studio (or eclipse),

It should solve your issues

Get max and min value from array in JavaScript

Why not store it as an array of prices instead of object?

prices = []
$(allProducts).each(function () {
    var price = parseFloat($(this).data('price'));
    prices.push(price);
});
prices.sort(function(a, b) { return a - b }); //this is the magic line which sort the array

That way you can just

prices[0]; // cheapest
prices[prices.length - 1]; // most expensive

Note that you can do shift() and pop() to get min and max price respectively, but it will take off the price from the array.

Even better alternative is to use Sergei solution below, by using Math.max and min respectively.

EDIT:

I realized that this would be wrong if you have something like [11.5, 3.1, 3.5, 3.7] as 11.5 is treated as a string, and would come before the 3.x in dictionary order, you need to pass in custom sort function to make sure they are indeed treated as float:

prices.sort(function(a, b) { return a - b });

How to call code behind server method from a client side JavaScript function?

I had to register my buttonid as a postbacktrigger...

RegisterPostbackTrigger(idOfButton)

Using GroupBy, Count and Sum in LINQ Lambda Expressions

    var ListByOwner = list.GroupBy(l => l.Owner)
                          .Select(lg => 
                                new { 
                                    Owner = lg.Key, 
                                    Boxes = lg.Count(),
                                    TotalWeight = lg.Sum(w => w.Weight), 
                                    TotalVolume = lg.Sum(w => w.Volume) 
                                });

How can I keep my branch up to date with master with git?

You can use the cherry-pick to get the particular bug fix commit(s)

$ git checkout branch
$ git cherry-pick bugfix

Kotlin Android start new Activity

Remember to add the activity you want to present, to your AndroidManifest.xml too :-) That was the issue for me.

hibernate: LazyInitializationException: could not initialize proxy

if you are using Lazy loading your method must be annotated with

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) for Stateless Session EJB

MySQL Insert with While Loop

You cannot use WHILE like that; see: mysql DECLARE WHILE outside stored procedure how?

You have to put your code in a stored procedure. Example:

CREATE PROCEDURE myproc()
BEGIN
    DECLARE i int DEFAULT 237692001;
    WHILE i <= 237692004 DO
        INSERT INTO mytable (code, active, total) VALUES (i, 1, 1);
        SET i = i + 1;
    END WHILE;
END

Fiddle: http://sqlfiddle.com/#!2/a4f92/1

Alternatively, generate a list of INSERT statements using any programming language you like; for a one-time creation, it should be fine. As an example, here's a Bash one-liner:

for i in {2376921001..2376921099}; do echo "INSERT INTO mytable (code, active, total) VALUES ($i, 1, 1);"; done

By the way, you made a typo in your numbers; 2376921001 has 10 digits, 237692200 only 9.

Getting the class of the element that fired an event using JQuery

This will contain the full class (which may be multiple space separated classes, if the element has more than one class). In your code it will contain either "konbo" or "kinta":

event.target.className

You can use jQuery to check for classes by name:

$(event.target).hasClass('konbo');

and to add or remove them with addClass and removeClass.

Python: printing a file to stdout

To improve on @bgporter's answer, with Python-3 you will probably want to operate on bytes instead of needlessly converting things to utf-8:

>>> import shutil
>>> import sys
>>> with open("test.txt", "rb") as f:
...    shutil.copyfileobj(f, sys.stdout.buffer)

What is the difference between declarations, providers, and import in NgModule?

Components are declared, Modules are imported, and Services are provided. An example I'm working with:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import {FormsModule} from '@angular/forms';
import { UserComponent } from './components/user/user.component';
import { StateService } from './services/state.service';    

@NgModule({
  declarations: [
    AppComponent,
    UserComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [ StateService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

How and where to use ::ng-deep?

Use ::ng-deep with caution. I used it throughout my app to set the material design toolbar color to different colors throughout my app only to find that when the app was in testing the toolbar colors step on each other. Come to find out it is because these styles becomes global, see this article Here is a working code solution that doesn't bleed into other components.

<mat-toolbar #subbar>
...
</mat-toolbar>

export class BypartSubBarComponent implements AfterViewInit {
  @ViewChild('subbar', { static: false }) subbar: MatToolbar;
  constructor(
    private renderer: Renderer2) { }
  ngAfterViewInit() {
    this.renderer.setStyle(
      this.subbar._elementRef.nativeElement, 'backgroundColor', 'red');
  }

}

Best data type for storing currency values in a MySQL database

Something like Decimal(19,4) usually works pretty well in most cases. You can adjust the scale and precision to fit the needs of the numbers you need to store. Even in SQL Server, I tend not to use "money" as it's non-standard.

How do I check if an object has a key in JavaScript?

Try the JavaScript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if key is available on myObj directly:

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.

remove space between paragraph and unordered list

You can use CSS selectors in a way similar to the following:

p + ul {
    margin-top: -10px;
}

This could be helpful because p + ul means select any <ul> element after a <p> element.

You'll have to adapt this to how much padding or margin you have on your <p> tags generally.

Original answer to original question:

p, ul {
    padding: 0;
    margin: 0;
}

That will take any EXTRA white space away.

p, ul {
    display: inline;
}

That will make all the elements inline instead of blocks. (So, for instance, the <p> won't cause a line break before and after it.)

PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused

Using MAMP ON Mac, I solve my problem by renaming

/Applications/MAMP/tmp/mysql/mysql.sock.lock

to

/Applications/MAMP/tmp/mysql/mysql.sock

What is the proper use of an EventEmitter?

When you want to have cross component interaction, then you need to know what are @Input , @Output , EventEmitter and Subjects.

If the relation between components is parent- child or vice versa we use @input & @output with event emitter..

@output emits an event and you need to emit using event emitter.

If it's not parent child relationship.. then you have to use subjects or through a common service.

Get all directories within directory nodejs

Another recursive approach

Thanks to Mayur for knowing me about withFileTypes. I written following code for getting files of particular folder recursively. It can be easily modified to get only directories.

const getFiles = (dir, base = '') => readdirSync(dir, {withFileTypes: true}).reduce((files, file) => {
    const filePath = path.join(dir, file.name)
    const relativePath = path.join(base, file.name)
    if(file.isDirectory()) {
        return files.concat(getFiles(filePath, relativePath))
    } else if(file.isFile()) {
        file.__fullPath = filePath
        file.__relateivePath = relativePath
        return files.concat(file)
    }
}, [])

Java Programming: call an exe from Java and passing parameters

Pass your arguments in constructor itself.

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();

Text to speech(TTS)-Android

MainActivity.class

import java.util.Locale;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences.Editor;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

    String text;
    EditText et;
    TextToSpeech tts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et=(EditText)findViewById(R.id.editText1);
        tts=new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int status) {
                // TODO Auto-generated method stub
                if(status == TextToSpeech.SUCCESS){
                    int result=tts.setLanguage(Locale.US);
                    if(result==TextToSpeech.LANG_MISSING_DATA ||
                            result==TextToSpeech.LANG_NOT_SUPPORTED){
                        Log.e("error", "This Language is not supported");
                    }
                    else{
                        ConvertTextToSpeech();
                    }
                }
                else
                    Log.e("error", "Initilization Failed!");
            }
        });


    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub

        if(tts != null){

            tts.stop();
            tts.shutdown();
        }
        super.onPause();
    }

    public void onClick(View v){

        ConvertTextToSpeech();

    }

    private void ConvertTextToSpeech() {
        // TODO Auto-generated method stub
        text = et.getText().toString();
        if(text==null||"".equals(text))
        {
            text = "Content not available";
            tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }else
            tts.speak(text+"is saved", TextToSpeech.QUEUE_FLUSH, null);
    }

}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="177dp"
        android:onClick="onClick"
        android:text="Button" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="81dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

</RelativeLayout>

Styling input radio with css

You should use some background image to your radio buttons and flip it with another image on change

.radio {
    background: url(customButton.png) no-repeat;
}

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

If you're using MVC 3 and Razor you can also use the following:

@Html.RadioButtonFor(model => model.blah, true) Yes
@Html.RadioButtonFor(model => model.blah, false) No

Java - Search for files in a directory

This method will recursively search thru each directory starting at the root, until the fileName is found, or all remaining results come back null.

public static String searchDirForFile(String dir, String fileName) {
    File[] files = new File(dir).listFiles();
    for(File f:files) {
        if(f.isDirectory()) {
            String loc = searchDirForFile(f.getPath(), fileName);
            if(loc != null)
                return loc;
        }
        if(f.getName().equals(fileName))
            return f.getPath();
    }
    return null;
}

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

Introduction

This can have a lot of causes which are broken down in following sections:

  • Put servlet class in a package
  • Set servlet URL in url-pattern
  • @WebServlet works only on Servlet 3.0 or newer
  • javax.servlet.* doesn't work anymore in Servlet 5.0 or newer
  • Make sure compiled *.class file is present in built WAR
  • Test the servlet individually without any JSP/HTML page
  • Use domain-relative URL to reference servlet from HTML
  • Use straight quotes in HTML attributes

Put servlet class in a package

First of all, put the servlet class in a Java package. You should always put publicly reuseable Java classes in a package, otherwise they are invisible to classes which are in a package, such as the server itself. This way you eliminiate potential environment-specific problems. Packageless servlets work only in specific Tomcat+JDK combinations and this should never be relied upon.

In case of a "plain" IDE project, the class needs to be placed in its package structure inside "Java Resources" folder and thus not "WebContent", this is for web files such as JSP. Below is an example of the folder structure of a default Eclipse Dynamic Web Project as seen in Navigator view:

EclipseProjectName
 |-- src
 |    `-- com
 |         `-- example
 |              `-- YourServlet.java
 |-- WebContent
 |    |-- WEB-INF
 |    |    `-- web.xml
 |    `-- jsps
 |         `-- page.jsp
 :

In case of a Maven project, the class needs to be placed in its package structure inside main/java and thus not main/resources, this is for non-class files and absolutely also not main/webapp, this is for web files. Below is an example of the folder structure of a default Maven webapp project as seen in Eclipse's Navigator view:

MavenProjectName
 |-- src
 |    `-- main
 |         |-- java
 |         |    `-- com
 |         |         `-- example
 |         |              `-- YourServlet.java
 |         |-- resources
 |         `-- webapp
 |              |-- WEB-INF
 |              |    `-- web.xml
 |              `-- jsps
 |                   `-- page.jsp
 :

Note that the /jsps subfolder is not strictly necessary. You can even do without it and put the JSP file directly in webcontent/webapp root, but I'm just taking over this from your question.

Set servlet URL in url-pattern

The servlet URL is specified as the "URL pattern" of the servlet mapping. It's absolutely not per definition the classname/filename of the servlet class. The URL pattern is to be specified as value of @WebServlet annotation.

package com.example; // Use a package!

@WebServlet("/servlet") // This is the URL of the servlet.
public class YourServlet extends HttpServlet { // Must be public and extend HttpServlet.
    // ...
}

In case you want to support path parameters like /servlet/foo/bar, then use an URL pattern of /servlet/* instead. See also Servlet and path parameters like /xyz/{value}/test, how to map in web.xml?

@WebServlet works only on Servlet 3.0 or newer

In order to use @WebServlet, you only need to make sure that your web.xml file, if any (it's optional since Servlet 3.0), is declared conform Servlet 3.0+ version and thus not conform e.g. 2.5 version or lower. Below is a Servlet 4.0 compatible one (which matches Tomcat 9+, WildFly 11+, Payara 5+, etc).

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0"
>
    <!-- Config here. -->
</web-app>

Or, in case you're not on Servlet 3.0+ yet (e.g. Tomcat 6 or older), then remove the @WebServlet annotation.

package com.example;

public class YourServlet extends HttpServlet {
    // ...
}

And register the servlet instead in web.xml like this:

<servlet>
    <servlet-name>yourServlet</servlet-name>
    <servlet-class>com.example.YourServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>yourServlet</servlet-name>
    <url-pattern>/servlet</url-pattern>  <!-- This is the URL of the servlet. -->
</servlet-mapping>

Note thus that you should not use both ways. Use either annotation based configuarion or XML based configuration. When you have both, then XML based configuration will override annotation based configuration.

javax.servlet.* doesn't work anymore in Servlet 5.0 or newer

Since Jakarta EE 9 / Servlet 5.0 (Tomcat 10, TomEE 9, WildFly 22 Preview, GlassFish 6, Payara 6, Liberty 22, etc), the javax.* package has been renamed to jakarta.* package.

In other words, please make absolutely sure that you don't randomly put JAR files of a different server in your WAR project such as tomcat-servlet-api-9.x.x.jar merely in order to get the javax.* package to compile. This will only cause trouble. Remove it altogether and edit the imports of your servlet class from

import javax.servlet.*;
import javax.servlet.http.*;

to

import jakarta.servlet.*;
import jakarta.servlet.http.*;

In case you're using Maven, you can find examples of proper pom.xml declarations for Tomcat 10+, Tomcat 9-, JEE 9+ and JEE 8- in this answer: Tomcat 9 casting servlets to javax.servlet.Servlet instead of jakarta.servlet.http.HttpServlet

Make sure compiled *.class file is present in built WAR

In case you're using a build tool such as Eclipse and/or Maven, then you need to make absolutely sure that the compiled servlet class file resides in its package structure in /WEB-INF/classes folder of the produced WAR file. In case of package com.example; public class YourServlet, it must be located in /WEB-INF/classes/com/example/YourServlet.class. Otherwise you will face in case of @WebServlet also a 404 error, or in case of <servlet> a HTTP 500 error like below:

HTTP Status 500

Error instantiating servlet class com.example.YourServlet

And find in the server log a java.lang.ClassNotFoundException: com.example.YourServlet, followed by a java.lang.NoClassDefFoundError: com.example.YourServlet, in turn followed by javax.servlet.ServletException: Error instantiating servlet class com.example.YourServlet.

An easy way to verify if the servlet is correctly compiled and placed in classpath is to let the build tool produce a WAR file (e.g. rightclick project, Export > WAR file in Eclipse) and then inspect its contents with a ZIP tool. If the servlet class is missing in /WEB-INF/classes, or if the export causes an error, then the project is badly configured or some IDE/project configuration defaults have been mistakenly reverted (e.g. Project > Build Automatically has been disabled in Eclipse).

You also need to make sure that the project icon has no red cross indicating a build error. You can find the exact error in Problems view (Window > Show View > Other...). Usually the error message is fine Googlable. In case you have no clue, best is to restart from scratch and do not touch any IDE/project configuration defaults. In case you're using Eclipse, you can find instructions in How do I import the javax.servlet API in my Eclipse project?

Test the servlet individually without any JSP/HTML page

Provided that the server runs on localhost:8080, and that the WAR is successfully deployed on a context path of /contextname (which defaults to the IDE project name, case sensitive!), and the servlet hasn't failed its initialization (read server logs for any deploy/servlet success/fail messages and the actual context path and servlet mapping), then a servlet with URL pattern of /servlet is available at http://localhost:8080/contextname/servlet.

You can just enter it straight in browser's address bar to test it invidivually. If its doGet() is properly overriden and implemented, then you will see its output in browser. Or if you don't have any doGet() or if it incorrectly calls super.doGet(), then a "HTTP 405: HTTP method GET is not supported by this URL" error will be shown (which is still better than a 404 as a 405 is evidence that the servlet itself is actually found).

Overriding service() is a bad practice, unless you're reinventing a MVC framework — which is very unlikely if you're just starting out with servlets and are clueless as to the problem described in the current question ;) See also Design Patterns web based applications.

Regardless, if the servlet already returns 404 when tested invidivually, then it's entirely pointless to try with a HTML form instead. Logically, it's therefore also entirely pointless to include any HTML form in questions about 404 errors from a servlet.

Use domain-relative URL to reference servlet from HTML

Once you've verified that the servlet works fine when invoked individually, then you can advance to HTML. As to your concrete problem with the HTML form, the <form action> value needs to be a valid URL. The same applies to <a href>. You need to understand how absolute/relative URLs work. You know, an URL is a web address as you can enter/see in the webbrowser's address bar. If you're specifying a relative URL as form action, i.e. without the http:// scheme, then it becomes relative to the current URL as you see in your webbrowser's address bar. It's thus absolutely not relative to the JSP/HTML file location in server's WAR folder structure as many starters seem to think.

So, assuming that the JSP page with the HTML form is opened by http://localhost:8080/contextname/jsps/page.jsp, and you need to submit to a servlet located in http://localhost:8080/contextname/servlet, here are several cases (note that you can safely substitute <form action> with <a href> here):

  • Form action submits to an URL with a leading slash.

      <form action="/servlet">
    

    The leading slash / makes the URL relative to the domain, thus the form will submit to

      http://localhost:8080/servlet
    

    But this will likely result in a 404 as it's in the wrong context.


  • Form action submits to an URL without a leading slash.

      <form action="servlet">
    

    This makes the URL relative to the current folder of the current URL, thus the form will submit to

      http://localhost:8080/contextname/jsps/servlet
    

    But this will likely result in a 404 as it's in the wrong folder.


  • Form action submits to an URL which goes one folder up.

      <form action="../servlet">
    

    This will go one folder up (exactly like as in local disk file system paths!), thus the form will submit to

      http://localhost:8080/contextname/servlet
    

    This one must work!


  • The canonical approach, however, is to make the URL domain-relative so that you don't need to fix the URLs once again when you happen to move the JSP files around into another folder.

      <form action="${pageContext.request.contextPath}/servlet">
    

    This will generate

      <form action="/contextname/servlet">
    

    Which will thus always submit to the right URL.


Use straight quotes in HTML attributes

You need to make absolutely sure you're using straight quotes in HTML attributes like action="..." or action='...' and thus not curly quotes like action=”...” or action=’...’. Curly quotes are not supported in HTML and they will simply become part of the value. Watch out when copy-pasting code snippets from blogs! Some blog engines, notably Wordpress, are known to by default use so-called "smart quotes" which thus also corrupts the quotes in code snippets this way. On the other hand, instead of copy-pasting code, try simply typing over the code yourself. Additional advantage of actually getting the code through your brain and fingers is that it will make you to remember and understand the code much better in long term and also make you a better developer.

See also:

Other cases of HTTP Status 404 error:

How to get the latest tag name in current branch in Git?

if your tags are sortable:

git tag --merged $YOUR_BRANCH_NAME | grep "prefix/" | sort | tail -n 1

How to print a debug log?

You can use:

<?php
echo '<script>console.log("debug log")</script>';
?>

grep --ignore-case --only

This is a known bug on the initial 2.5.1, and has been fixed in early 2007 (Redhat 2.5.1-5) according to the bug reports. Unfortunately Apple is still using 2.5.1 even on Mac OS X 10.7.2.

You could get a newer version via Homebrew (3.0) or MacPorts (2.26) or fink (3.0-1).


Edit: Apparently it has been fixed on OS X 10.11 (or maybe earlier), even though the grep version reported is still 2.5.1.

handling dbnull data in vb.net

The only way that i know of is to test for it, you can do a combined if though to make it easy.

If NOT IsDbNull(myItem("sID")) AndAlso myItem("sID") = sId Then
   'Do success
ELSE
   'Failure
End If

I wrote in VB as that is what it looks like you need, even though you mixed languages.

Edit

Cleaned up to use IsDbNull to make it more readable

What is the connection string for localdb for version 11

You need to install Dot Net 4.0.2 or above as mentioned here.
The 4.0 bits don't understand the syntax required by LocalDB

See this question here

You can dowload the update here

tmux set -g mouse-mode on doesn't work

Paste here in ~/.tmux.conf

set -g mouse on

and run on terminal

tmux source-file ~/.tmux.conf

Java, return if trimmed String in List contains String

You can use your own code. You don't need to use the looping structure, if you don't want to use the looping structure as you said above. Only you have to focus to remove space or trim the String of the list.

If you are using java8 you can simply trim the String using the single line of the code:

myList = myList.stream().map(String :: trim).collect(Collectors.toList());

The importance of the above line is, in the future, you can use a List or set as well. Now you can use your own code:

if(myList.contains("A")){
    //true
}else{
    // false
}

Is < faster than <=?

Assuming we're talking about internal integer types, there's no possible way one could be faster than the other. They're obviously semantically identical. They both ask the compiler to do precisely the same thing. Only a horribly broken compiler would generate inferior code for one of these.

If there was some platform where < was faster than <= for simple integer types, the compiler should always convert <= to < for constants. Any compiler that didn't would just be a bad compiler (for that platform).

Java JTable setting Column Width

No need for the option, just make the preferred width of the last column the maximum and it will take all the extra space.

table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(Integer.MAX_INT);

Asp Net Web API 2.1 get client IP address

If you're self-hosting with Asp.Net 2.1 using the OWIN Self-host NuGet package you can use the following code:

 private string getClientIp(HttpRequestMessage request = null)
    {
        if (request == null)
        {
            return null;
        }

        if (request.Properties.ContainsKey("MS_OwinContext"))
        {
            return ((OwinContext) request.Properties["MS_OwinContext"]).Request.RemoteIpAddress;
        }
        return null;
    }

How do I capture the output of a script if it is being ran by the task scheduler?

Use the cmd.exe command processor to build a timestamped file name to log your scheduled task's output

To build upon answers by others here, it may be that you want to create an output file that has the date and/or time embedded in the name of the file. You can use the cmd.exe command processor to do this for you.

Note: This technique takes the string output of internal Windows environment variables and slices them up based on character position. Because of this, the exact values supplied in the examples below may not be correct for the region of Windows you use. Also, with some regional settings, some components of the date or time may introduce a space into the constructed file name when their value is less than 10. To mitigate this issue, surround your file name with quotes so that any unintended spaces in the file name won't break the command-line you're constructing. Experiment and find what works best for your situation.

Be aware that PowerShell is more powerful than cmd.exe. One way it is more powerful is that it can deal with different Windows regions. But this answer is about solving this issue using cmd.exe, not PowerShell, so we continue.

Using cmd.exe

You can access different components of the date and time by slicing the internal environment variables %date% and %time%, as follows (again, the exact slicing values are dependent on the region configured in Windows):

  • Year (4 digits): %date:~10,4%
  • Month (2 digits): %date:~4,2%
  • Day (2 digits): %date:~7,2%
  • Hour (2 digits): %time:~0,2%
  • Minute (2 digits): %time:~3,2%
  • Second (2 digits): %time:~6,2%

Suppose you want your log file to be named using this date/time format: "Log_[yyyyMMdd]_[hhmmss].txt". You'd use the following:

Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt

To test this, run the following command line:

cmd.exe /c echo "Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt"

Putting it all together, to redirect both stdout and stderr from your script to a log file named with the current date and time, use might use the following as your command line:

cmd /c YourProgram.cmd > "Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt" 2>&1

Note the use of quotes around the file name to handle instances a date or time component may introduce a space character.

In my case, if the current date/time were 10/05/2017 9:05:34 AM, the above command-line would produce the following:

cmd /c YourProgram.cmd > "Log_20171005_ 90534.txt" 2>&1

Return value from nested function in Javascript

you have to call a function before it can return anything.

function mainFunction() {
      function subFunction() {
            var str = "foo";
            return str;
      }
      return subFunction();
}

var test = mainFunction();
alert(test);

Or:

function mainFunction() {
      function subFunction() {
            var str = "foo";
            return str;
      }
      return subFunction;
}

var test = mainFunction();
alert( test() );

for your actual code. The return should be outside, in the main function. The callback is called somewhere inside the getLocations method and hence its return value is not recieved inside your main function.

function reverseGeocode(latitude,longitude){
    var address = "";
    var country = "";
    var countrycode = "";
    var locality = "";

    var geocoder = new GClientGeocoder();
    var latlng = new GLatLng(latitude, longitude);

    geocoder.getLocations(latlng, function(addresses) {
     address = addresses.Placemark[0].address;
     country = addresses.Placemark[0].AddressDetails.Country.CountryName;
     countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
     locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
    });   
    return country
   }

How do you execute SQL from within a bash script?

As Bash doesn't have built in sql database connectivity... you will need to use some sort of third party tool.

How to name an object within a PowerPoint slide?

Yes. Click on the object (textbox, shape, etc.) to select the object and in the Drawing Tools | Format tab, click on Selection Pane in the Arrange group. From there, you'll see names of objects - you can double click (or press F2) on any name and rename it. By deselecting it, it becomes renamed. You can also get to this from the Home tab -> Drawing group -> Arrange drop-down -> Selection pane or by pressing ALT + F10.

How to iterate through a table rows and get the cell values using jQuery

Hello every one thanks for the help below is the working code for my question

$("#TableView tr.item").each(function() { 
    var quantity1=$(this).find("input.name").val(); 
    var quantity2=$(this).find("input.id").val(); 
});

JavaScript OR (||) variable assignment explanation

Javacript uses short-circuit evaluation for logical operators || and &&. However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true, or false value.

The following values are considered falsy in JavaScript.

  • false
  • null
  • "" (empty string)
  • 0
  • Nan
  • undefined

Ignoring the operator precedence rules, and keeping things simple, the following examples show which value halted the evaluation, and gets returned as a result.

false || null || "" || 0 || NaN || "Hello" || undefined // "Hello"

The first 5 values upto NaN are falsy so they are all evaluated from left to right, until it meets the first truthy value - "Hello" which makes the entire expression true, so anything further up will not be evaluated, and "Hello" gets returned as a result of the expression. Similarly, in this case:

1 && [] && {} && true && "World" && null && 2010 // null

The first 5 values are all truthy and get evaluated until it meets the first falsy value (null) which makes the expression false, so 2010 isn't evaluated anymore, and null gets returned as a result of the expression.

The example you've given is making use of this property of JavaScript to perform an assignment. It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "Hello" to b as it makes it easier to assign a default value, instead of doing if-else checks.

var a = false;
var b = a || "Hello";

You could call the below example an exploitation of this feature, and I believe it makes code harder to read.

var messages = 0;
var newMessagesText = "You have " + messages + " messages.";
var noNewMessagesText = "Sorry, you have no new messages.";
alert((messages && newMessagesText) || noNewMessagesText);

Inside the alert, we check if messages is falsy, and if yes, then evaluate and return noNewMessagesText, otherwise evaluate and return newMessagesText. Since it's falsy in this example, we halt at noNewMessagesText and alert "Sorry, you have no new messages.".

How to "add existing frameworks" in Xcode 4?

Another easy way to do it so that it is referenced in the project folder you want, like "Frameworks", is to:

  1. Select "Show the Project navigator"
  2. Right-click on the project folder you wish to add the framework to.
  3. Select 'Add Files to "YourProjectName"'
  4. Browse to the framework - generally under /Developer/SDKs/MacOSXversion.sdk/System/Library/Frameworks
  5. Select the one you want.
  6. Select "Add"

It will appear in both the project navigator where you want it, as well as in the "Link Binary With Libraries" area of the "Build Phases" pane of your target.

python save image from url

Python code snippet to download a file from an url and save with its name

import requests

url = 'http://google.com/favicon.ico'
filename = url.split('/')[-1]
r = requests.get(url, allow_redirects=True)
open(filename, 'wb').write(r.content)

Disabling Minimize & Maximize On WinForm?

public Form1()
{
InitializeComponent();
//this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
}

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

I've recently found a lib called ion that brings a little extra to the table.

ion has built-in support for image download integrated with ImageView, JSON (with the help of GSON), files and a very handy UI threading support.

I'm using it on a new project and so far the results have been good. Its use is much simpler than Volley or Retrofit.

How do I update a formula with Homebrew?

I think the correct way to do is

brew upgrade mongodb

It will upgrade the mongodb formula. If you want to upgrade all outdated formula, simply

brew upgrade

No line-break after a hyphen

Late to the party, but I think this is actually the most elegant. Use the WORD JOINER Unicode character &#8288; on either side of your hyphen, or em dash, or any character.

So, like so:

&#8288;—&#8288;

This will join the symbol on both ends to its neighbors (without adding a space) and prevent line breaking.

How do I revert a Git repository to a previous commit?

In GitKraken you can do this:

  1. Right click on the commit that you want to reset, choose: Reset to this commit/Hard:

    Enter image description here

  2. Right click on the commit again, choose: Current branch name/Push:

    Enter image description here

  3. Click on the Force Push:

    Enter image description here

Obs.: You need to be careful, because all the commit history after the hard reset are lost and this action is irreversible. You need to be sure what you doing.

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

To check online you can use

http://codebeautify.org/base64-to-image-converter

You can convert string to image like this way

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView image =(ImageView)findViewById(R.id.image);

        //encode image to base64 string
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

        //decode base64 string to image
        imageBytes = Base64.decode(imageString, Base64.DEFAULT);
        Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        image.setImageBitmap(decodedImage);
    }
}

http://www.thecrazyprogrammer.com/2016/10/android-convert-image-base64-string-base64-string-image.html

SimpleXML - I/O warning : failed to load external entity

this also works:

$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);

then I just run a forloop to grab the stuff from the nodes.

like this:`

for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;

***note that your node names will differ, obviously..and your HTML might be structured differently...also your loop might be set to higher or lower amount of results.

File Upload in WebView

This is work for me. Also work for Nougat and Marshmallow[2][3]

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private final static int FCR = 1;
    WebView webView;
    private String mCM;
    private ValueCallback<Uri> mUM;
    private ValueCallback<Uri[]> mUMA;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if (Build.VERSION.SDK_INT >= 21) {
            Uri[] results = null;

            //Check if response is positive
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == FCR) {

                    if (null == mUMA) {
                        return;
                    }
                    if (intent == null) {
                        //Capture Photo if no image available
                        if (mCM != null) {
                            results = new Uri[]{Uri.parse(mCM)};
                        }
                    } else {
                        String dataString = intent.getDataString();
                        if (dataString != null) {
                            results = new Uri[]{Uri.parse(dataString)};
                        }
                    }
                }
            }
            mUMA.onReceiveValue(results);
            mUMA = null;
        } else {

            if (requestCode == FCR) {
                if (null == mUM) return;
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                mUM.onReceiveValue(result);
                mUM = null;
            }
        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= 23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
        }

        webView = (WebView) findViewById(R.id.ifView);
        assert webView != null;

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);

        if (Build.VERSION.SDK_INT >= 21) {
            webSettings.setMixedContentMode(0);
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else if (Build.VERSION.SDK_INT >= 19) {
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else if (Build.VERSION.SDK_INT < 19) {
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }

        webView.setWebViewClient(new Callback());
        webView.loadUrl("https://infeeds.com/");
        webView.setWebChromeClient(new WebChromeClient() {

            //For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {

                mUM = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);
            }

            // For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {

                mUM = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                MainActivity.this.startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FCR);
            }

            //For Android 4.1+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {

                mUM = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FCR);
            }

            //For Android 5.0+
            public boolean onShowFileChooser(
                    WebView webView, ValueCallback<Uri[]> filePathCallback,
                    WebChromeClient.FileChooserParams fileChooserParams) {

                if (mUMA != null) {
                    mUMA.onReceiveValue(null);
                }

                mUMA = filePathCallback;
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {

                    File photoFile = null;

                    try {
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCM);
                    } catch (IOException ex) {
                        Log.e(TAG, "Image file creation failed", ex);
                    }
                    if (photoFile != null) {
                        mCM = "file:" + photoFile.getAbsolutePath();
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    } else {
                        takePictureIntent = null;
                    }
                }

                Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                contentSelectionIntent.setType("*/*");
                Intent[] intentArray;

                if (takePictureIntent != null) {
                    intentArray = new Intent[]{takePictureIntent};
                } else {
                    intentArray = new Intent[0];
                }

                Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                startActivityForResult(chooserIntent, FCR);

                return true;
            }
        });
    }

    // Create an image file
    private File createImageFile() throws IOException {

        @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "img_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(imageFileName, ".jpg", storageDir);
    }

    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {

        if (event.getAction() == KeyEvent.ACTION_DOWN) {

            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:

                    if (webView.canGoBack()) {
                        webView.goBack();
                    } else {
                        finish();
                    }

                    return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    public class Callback extends WebViewClient {
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
        }
    }
}

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

I have created this jquery that solved my problem.

public void ChangeClassIntoSelected(String name,String div) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("Array.from($(\"div." + div +" ul[name=" + name + "]\")[0].children).forEach((element, index) => {\n" +
                "   $(element).addClass('ui-selected');\n" +
                "});");
    }

With this script you are able to change the actual class name into some other thing.

How to enable production mode?

This worked for me, using the latest release of Angular 2 (2.0.0-rc.1):

main.ts

import {enableProdMode} from '@angular/core';

enableProdMode();
bootstrap(....);

Here is the function reference from their docs: https://angular.io/api/core/enableProdMode

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

Make sure you have access configured to the URL http://localhost/reports using the SQL Reporting Services Configuration. To do this:

  1. Open Reporting Services Configuration Manager -> then connect to the report server instance -> then click on Report Manager URL.
  2. In the Report Manager URL page, click the Advanced button -> then in the Multiple Identities for Report Manager, click Add.
  3. In the Add a Report Manager HTTP URL popup box, select Host Header and type in: localhost
  4. Click OK to save your changes.
  5. Now start/ run Internet Explorer using Run as Administator... (NOTE: If you don't see the 'Site Settings' link in the top left corner while at http://localhost/reports it is probably because you aren't running IE as an Administator or you haven't assigned your computers 'domain\username' to the reporting services roles, see how to do this in the next few steps.)
  6. Then go to: http://localhost/reports (you may have to login with your Computer's username and password)
  7. You should now be directed to the Home page of SQL Server Reporting Services here: http://localhost/Reports/Pages/Folder.aspx
  8. From the Home page, click the Properties tab, then click New Role Assignment
  9. In the Group or user name textbox, add the 'domain\username' which was in the error message (in my case, I added: DOUGDELL3-PC\DOUGDELL3 for the 'domain\username', in your case you can find the domain\username for your computer in the rsAccessDenied error message).
  10. Now check all the checkboxes; Browser, Content Manager, My Reports, Publisher, Report Builder, and then click OK.
  11. You're domain\username should now be assigned to the Roles that will give you access to deploy your reports to the Report Server. If you're using Visual Studio or SQL Server Business Intelligence Development Studio to deploy your reports to your local reports server, you should now be able to.
  12. Hopefully, that helps you solve your Reports Server rsAccessDenied error message...

Just to let you know this tutorial was done on a Windows 7 computer with SQL Server Reporting Services 2008.

Reference Article: http://techasp.blogspot.co.uk/2013/06/how-to-fix-reporting-services.html

Return multiple values from a function in swift

you should return three different values from this method and get these three in a single variable like this.

func getTime()-> (hour:Int,min:Int,sec:Int){
//your code
return (hour,min,sec)
}

get the value in single variable

let getTime = getTime()

now you can access the hour,min and seconds simply by "." ie.

print("hour:\(getTime.hour) min:\(getTime.min) sec:\(getTime.sec)")

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

So in general dll has to be placed in two places:

  1. GAC ( can have 32 and 64 versions of dll's)
  2. your project bin folder

Thus, you just need add reference to log4net.dll. (In your case 32-bit with PublicKeyToken=692fbea5521e1304)

You can achive that by

Convert txt to csv python script

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

How do I correct the character encoding of a file?

When you see character sequences like ç and é, it's usually an indication that a UTF-8 file has been opened by a program that reads it in as ANSI (or similar). Unicode characters such as these:

U+00C2 Latin capital letter A with circumflex
U+00C3 Latin capital letter A with tilde
U+0082 Break permitted here
U+0083 No break here

tend to show up in ANSI text because of the variable-byte strategy that UTF-8 uses. This strategy is explained very well here.

The advantage for you is that the appearance of these odd characters makes it relatively easy to find, and thus replace, instances of incorrect conversion.

I believe that, since ANSI always uses 1 byte per character, you can handle this situation with a simple search-and-replace operation. Or more conveniently, with a program that includes a table mapping between the offending sequences and the desired characters, like these:

“ -> “ # should be an opening double curly quote
â€? -> ” # should be a closing double curly quote

Any given text, assuming it's in English, will have a relatively small number of different types of substitutions.

Hope that helps.

How to check task status in Celery?

Creating an AsyncResult object from the task id is the way recommended in the FAQ to obtain the task status when the only thing you have is the task id.

However, as of Celery 3.x, there are significant caveats that could bite people if they do not pay attention to them. It really depends on the specific use-case scenario.

By default, Celery does not record a "running" state.

In order for Celery to record that a task is running, you must set task_track_started to True. Here is a simple task that tests this:

@app.task(bind=True)
def test(self):
    print self.AsyncResult(self.request.id).state

When task_track_started is False, which is the default, the state show is PENDING even though the task has started. If you set task_track_started to True, then the state will be STARTED.

The state PENDING means "I don't know."

An AsyncResult with the state PENDING does not mean anything more than that Celery does not know the status of the task. This could be because of any number of reasons.

For one thing, AsyncResult can be constructed with invalid task ids. Such "tasks" will be deemed pending by Celery:

>>> task.AsyncResult("invalid").status
'PENDING'

Ok, so nobody is going to feed obviously invalid ids to AsyncResult. Fair enough, but it also has for effect that AsyncResult will also consider a task that has successfully run but that Celery has forgotten as being PENDING. Again, in some use-case scenarios this can be a problem. Part of the issue hinges on how Celery is configured to keep the results of tasks, because it depends on the availability of the "tombstones" in the results backend. ("Tombstones" is the term use in the Celery documentation for the data chunks that record how the task ended.) Using AsyncResult won't work at all if task_ignore_result is True. A more vexing problem is that Celery expires the tombstones by default. The result_expires setting by default is set to 24 hours. So if you launch a task, and record the id in long-term storage, and more 24 hours later, you create an AsyncResult with it, the status will be PENDING.

All "real tasks" start in the PENDING state. So getting PENDING on a task could mean that the task was requested but never progressed further than this (for whatever reason). Or it could mean the task ran but Celery forgot its state.

Ouch! AsyncResult won't work for me. What else can I do?

I prefer to keep track of goals than keep track of the tasks themselves. I do keep some task information but it is really secondary to keeping track of the goals. The goals are stored in storage independent from Celery. When a request needs to perform a computation depends on some goal having been achieved, it checks whether the goal has already been achieved, if yes, then it uses this cached goal, otherwise it starts the task that will effect the goal, and sends to the client that made the HTTP request a response that indicates it should wait for a result.


The variable names and hyperlinks above are for Celery 4.x. In 3.x the corresponding variables and hyperlinks are: CELERY_TRACK_STARTED, CELERY_IGNORE_RESULT, CELERY_TASK_RESULT_EXPIRES.

jQuery ajax call to REST service

I think there is no need to specify

'http://localhost:8080`" 

in the URI part.. because. if you specify it, You'll have to change it manually for every environment.

Only

"/restws/json/product/get" also works

Change content of div - jQuery

You could subscribe for the .click event for the links and change the contents of the div using the .html method:

$('.click').click(function() {
    // get the contents of the link that was clicked
    var linkText = $(this).text();

    // replace the contents of the div with the link text
    $('#content-container').html(linkText);

    // cancel the default action of the link by returning false
    return false;
});

Note however that if you replace the contents of this div the click handler that you have assigned will be destroyed. If you intend to inject some new DOM elements inside the div for which you need to attach event handlers, this attachments should be performed inside the .click handler after inserting the new contents. If the original selector of the event is preserved you may also take a look at the .delegate method to attach the handler.

Using if elif fi in shell scripts

Use double brackets...

if [[ expression ]]

How to Configure SSL for Amazon S3 bucket

You can access your files via SSL like this:

https://s3.amazonaws.com/bucket_name/images/logo.gif

If you use a custom domain for your bucket, you can use S3 and CloudFront together with your own SSL certificate (or generate a free one via Amazon Certificate Manager): http://aws.amazon.com/cloudfront/custom-ssl-domains/

Set a variable if undefined in JavaScript

The 2018 ES6 answer is:

return Object.is(x, undefined) ? y : x;

If variable x is undefined, return variable y... otherwise if variable x is defined, return variable x.

Delete column from SQLite table

This option works only if you can open the DB in a DB Browser like DB Browser for SQLite.

In DB Browser for SQLite:

  1. Go to the tab, "Database Structure"
  2. Select you table Select Modify table (just under the tabs)
  3. Select the column you want to delete
  4. Click on Remove field and click OK

Unknown Column In Where Clause

Your defined alias are not welcomed by the WHERE clause you have to use the HAVING clause for this

SELECT u_name AS user_name FROM users HAVING user_name = "john";

OR you can directly use the original column name with the WHERE

SELECT u_name AS user_name FROM users WHERE u_name = "john";

Same as you have the result in user defined alias as a result of subquery or any calculation it will be accessed by the HAVING clause not by the WHERE

SELECT u_name AS user_name ,
(SELECT last_name FROM users2 WHERE id=users.id) as user_last_name
FROM users  WHERE u_name = "john" HAVING user_last_name ='smith'

How to SUM two fields within an SQL query

If you want to add two columns together, all you have to do is add them. Then you will get the sum of those two columns for each row returned by the query.

What your code is doing is adding the two columns together and then getting a sum of the sums. That will work, but it might not be what you are attempting to accomplish.

How do I select an element that has a certain class?

It should be this way:

h2.myClass looks for h2 with class myClass. But you actually want to apply style for h2 inside .myClass so you can use descendant selector .myClass h2.

h2 {
    color: red;
}

.myClass {
    color: green;
}

.myClass h2 {
    color: blue;
}

Demo

This ref will give you some basic idea about the selectors and have a look at descendant selectors

Shadow Effect for a Text in Android?

TextView textv = (TextView) findViewById(R.id.textview1);
textv.setShadowLayer(1, 0, 0, Color.BLACK);

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

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

How to auto import the necessary classes in Android Studio with shortcut?

You can also use Eclipse's keyboard shortcuts: just go on preferences > keymap and choose Eclipse from the drop-down menu. And all your Eclipse shortcuts will be used in here.

Generate a random number in a certain range in MATLAB

Generate values from the uniform distribution on the interval [a, b].

      r = a + (b-a).*rand(100,1);

JSON formatter in C#?

This version produces JSON that is more compact and in my opinion more readable since you can see more at one time. It does this by formatting the deepest layer inline or like a compact array structure.

The code has no dependencies but is more complex.

{ 
  "name":"Seller", 
  "schema":"dbo",
  "CaptionFields":["Caption","Id"],
  "fields":[ 
    {"name":"Id","type":"Integer","length":"10","autoincrement":true,"nullable":false}, 
    {"name":"FirstName","type":"Text","length":"50","autoincrement":false,"nullable":false}, 
    {"name":"LastName","type":"Text","length":"50","autoincrement":false,"nullable":false}, 
    {"name":"LotName","type":"Text","length":"50","autoincrement":false,"nullable":true}, 
    {"name":"LotDetailsURL","type":"Text","length":"255","autoincrement":false,"nullable":true} 
  ]
}

The code follows

private class IndentJsonInfo
{
    public IndentJsonInfo(string prefix, char openingTag)
    {
        Prefix = prefix;
        OpeningTag = openingTag;
        Data = new List<string>();
    }
    public string Prefix;
    public char OpeningTag;
    public bool isOutputStarted;
    public List<string> Data;
}
internal static string IndentJSON(string jsonString, int startIndent = 0, int indentSpaces = 2)
{
    if (String.IsNullOrEmpty(jsonString))
        return jsonString;

    try
    {
        var jsonCache = new List<IndentJsonInfo>();
        IndentJsonInfo currentItem = null;

        var sbResult = new StringBuilder();

        int curIndex = 0;
        bool inQuotedText = false;

        var chunk = new StringBuilder();

        var saveChunk = new Action(() =>
        {
            if (chunk.Length == 0)
                return;
            if (currentItem == null)
                throw new Exception("Invalid JSON: No container.");
            currentItem.Data.Add(chunk.ToString());
            chunk = new StringBuilder();
        });

        while (curIndex < jsonString.Length)
        {
            var cChar = jsonString[curIndex];
            if (inQuotedText)
            {
                // Get the rest of quoted text.
                chunk.Append(cChar);

                // Determine if the quote is escaped.
                bool isEscaped = false;
                var excapeIndex = curIndex;
                while (excapeIndex > 0 && jsonString[--excapeIndex] == '\\') isEscaped = !isEscaped;

                if (cChar == '"' && !isEscaped)
                    inQuotedText = false;
            }
            else if (Char.IsWhiteSpace(cChar))
            {
                // Ignore all whitespace outside of quotes.
            }
            else
            {
                // Outside of Quotes.
                switch (cChar)
                {
                    case '"':
                        chunk.Append(cChar);
                        inQuotedText = true;
                        break;
                    case ',':
                        chunk.Append(cChar);
                        saveChunk();
                        break;
                    case '{':
                    case '[':
                        currentItem = new IndentJsonInfo(chunk.ToString(), cChar);
                        jsonCache.Add(currentItem);
                        chunk = new StringBuilder();
                        break;
                    case '}':
                    case ']':
                        saveChunk();
                        for (int i = 0; i < jsonCache.Count; i++)
                        {
                            var item = jsonCache[i];
                            var isLast = i == jsonCache.Count - 1;
                            if (!isLast)
                            {
                                if (!item.isOutputStarted)
                                {
                                    sbResult.AppendLine(
                                        "".PadLeft((startIndent + i) * indentSpaces) +
                                        item.Prefix + item.OpeningTag);
                                    item.isOutputStarted = true;
                                }
                                var newIndentString = "".PadLeft((startIndent + i + 1) * indentSpaces);
                                foreach (var listItem in item.Data)
                                {
                                    sbResult.AppendLine(newIndentString + listItem);
                                }
                                item.Data = new List<string>();
                            }
                            else // If Last
                            {
                                if (!(
                                    (item.OpeningTag == '{' && cChar == '}') ||
                                    (item.OpeningTag == '[' && cChar == ']')
                                   ))
                                {
                                    throw new Exception("Invalid JSON: Container Mismatch, Open '" + item.OpeningTag + "', Close '" + cChar + "'.");
                                }

                                string closing = null;
                                if (item.isOutputStarted)
                                {
                                    var newIndentString = "".PadLeft((startIndent + i + 1) * indentSpaces);
                                    foreach (var listItem in item.Data)
                                    {
                                        sbResult.AppendLine(newIndentString + listItem);
                                    }
                                    closing = cChar.ToString();
                                }
                                else
                                {
                                    closing =
                                        item.Prefix + item.OpeningTag +
                                        String.Join("", currentItem.Data.ToArray()) +
                                        cChar;
                                }

                                jsonCache.RemoveAt(i);
                                currentItem = (jsonCache.Count > 0) ? jsonCache[jsonCache.Count - 1] : null;
                                chunk.Append(closing);
                            }
                        }
                        break;
                    default:
                        chunk.Append(cChar);
                        break;
                }
            }
            curIndex++;
        }

        if (inQuotedText)
            throw new Exception("Invalid JSON: Incomplete Quote");
        else if (jsonCache.Count != 0)
            throw new Exception("Invalid JSON: Incomplete Structure");
        else
        {
            if (chunk.Length > 0)
                sbResult.AppendLine("".PadLeft(startIndent * indentSpaces) + chunk);
            var result = sbResult.ToString();
            return result;
        }
    }
    catch (Exception ex)
    {
        throw;  // Comment out to return unformatted text if the format failed.
        // Invalid JSON, skip the formatting.
        return jsonString;
    }
}

The function allows you to specify a starting point for the indentation because I use this as part of a process that assembles very large JSON formatted backup files.

RSA encryption and decryption in Python

Here is my implementation for python 3 and pycrypto

from Crypto.PublicKey import RSA
key = RSA.generate(4096)
f = open('/home/john/Desktop/my_rsa_public.pem', 'wb')
f.write(key.publickey().exportKey('PEM'))
f.close()
f = open('/home/john/Desktop/my_rsa_private.pem', 'wb')
f.write(key.exportKey('PEM'))
f.close()

f = open('/home/john/Desktop/my_rsa_public.pem', 'rb')
f1 = open('/home/john/Desktop/my_rsa_private.pem', 'rb')
key = RSA.importKey(f.read())
key1 = RSA.importKey(f1.read())

x = key.encrypt(b"dddddd",32)

print(x)
z = key1.decrypt(x)
print(z)

Plot multiple boxplot in one graph

In base R a formula interface with interactions (:) can be used to achieve this.

df <- read.csv("~/Desktop/TestData.csv")
df <- data.frame(stack(df[,-1]), Label=df$Label) # reshape to long format

boxplot(values ~ Label:ind, data=df, col=c("red", "limegreen"), las=2)

example

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

By adding following code of line in bundle to config it works for me

bundles.IgnoreList.Clear();  

Follow the link for more explanation

Native query with named parameter fails with "Not all named parameters have been set"

This was a bug fixed in version 4.3.11 https://hibernate.atlassian.net/browse/HHH-2851

EDIT: Best way to execute a native query is still to use NamedParameterJdbcTemplate It allows you need to retrieve a result that is not a managed entity ; you can use a RowMapper and even a Map of named parameters!

private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

@Autowired
public void setDataSource(DataSource dataSource) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}

final List<Long> resultList = namedParameterJdbcTemplate.query(query, 
            mapOfNamedParamters, 
            new RowMapper<Long>() {
        @Override
        public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
            return rs.getLong(1);
        }
    });

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

Spring RestTemplate GET with parameters

Since at least Spring 3, instead of using UriComponentsBuilder to build the URL (which is a bit verbose), many of the RestTemplate methods accept placeholders in the path for parameters (not just exchange).

From the documentation:

Many of the RestTemplate methods accepts a URI template and URI template variables, either as a String vararg, or as Map<String,String>.

For example with a String vararg:

restTemplate.getForObject(
   "http://example.com/hotels/{hotel}/rooms/{room}", String.class, "42", "21");

Or with a Map<String, String>:

Map<String, String> vars = new HashMap<>();
vars.put("hotel", "42");
vars.put("room", "21");

restTemplate.getForObject("http://example.com/hotels/{hotel}/rooms/{room}", 
    String.class, vars);

Reference: https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#rest-resttemplate-uri

If you look at the JavaDoc for RestTemplate and search for "URI Template", you can see which methods you can use placeholders with.

Jenkins Slave port number for firewall

A slave isn't a server, it's a client type application. Network clients (almost) never use a specific port. Instead, they ask the OS for a random free port. This works much better since you usually run clients on many machines where the current configuration isn't known in advance. This prevents thousands of "client wouldn't start because port is already in use" bug reports every day.

You need to tell the security department that the slave isn't a server but a client which connects to the server and you absolutely need to have a rule which says client:ANY -> server:FIXED. The client port number should be >= 1024 (ports 1 to 1023 need special permissions) but I'm not sure if you actually gain anything by adding a rule for this - if an attacker can open privileged ports, they basically already own the machine.

If they argue, then ask them why they don't require the same rule for all the web browsers which people use in your company.

Upload a file to Amazon S3 with NodeJS

So it looks like there are a few things going wrong here. Based on your post it looks like you are attempting to support file uploads using the connect-multiparty middleware. What this middleware does is take the uploaded file, write it to the local filesystem and then sets req.files to the the uploaded file(s).

The configuration of your route looks fine, the problem looks to be with your items.upload() function. In particular with this part:

var params = {
  Key: file.name,
  Body: file
};

As I mentioned at the beginning of my answer connect-multiparty writes the file to the local filesystem, so you'll need to open the file and read it, then upload it, and then delete it on the local filesystem.

That said you could update your method to something like the following:

var fs = require('fs');
exports.upload = function (req, res) {
    var file = req.files.file;
    fs.readFile(file.path, function (err, data) {
        if (err) throw err; // Something went wrong!
        var s3bucket = new AWS.S3({params: {Bucket: 'mybucketname'}});
        s3bucket.createBucket(function () {
            var params = {
                Key: file.originalFilename, //file.name doesn't exist as a property
                Body: data
            };
            s3bucket.upload(params, function (err, data) {
                // Whether there is an error or not, delete the temp file
                fs.unlink(file.path, function (err) {
                    if (err) {
                        console.error(err);
                    }
                    console.log('Temp File Delete');
                });

                console.log("PRINT FILE:", file);
                if (err) {
                    console.log('ERROR MSG: ', err);
                    res.status(500).send(err);
                } else {
                    console.log('Successfully uploaded data');
                    res.status(200).end();
                }
            });
        });
    });
};

What this does is read the uploaded file from the local filesystem, then uploads it to S3, then it deletes the temporary file and sends a response.

There's a few problems with this approach. First off, it's not as efficient as it could be, as for large files you will be loading the entire file before you write it. Secondly, this process doesn't support multi-part uploads for large files (I think the cut-off is 5 Mb before you have to do a multi-part upload).

What I would suggest instead is that you use a module I've been working on called S3FS which provides a similar interface to the native FS in Node.JS but abstracts away some of the details such as the multi-part upload and the S3 api (as well as adds some additional functionality like recursive methods).

If you were to pull in the S3FS library your code would look something like this:

var fs = require('fs'),
    S3FS = require('s3fs'),
    s3fsImpl = new S3FS('mybucketname', {
        accessKeyId: XXXXXXXXXXX,
        secretAccessKey: XXXXXXXXXXXXXXXXX
    });

// Create our bucket if it doesn't exist
s3fsImpl.create();

exports.upload = function (req, res) {
    var file = req.files.file;
    var stream = fs.createReadStream(file.path);
    return s3fsImpl.writeFile(file.originalFilename, stream).then(function () {
        fs.unlink(file.path, function (err) {
            if (err) {
                console.error(err);
            }
        });
        res.status(200).end();
    });
};

What this will do is instantiate the module for the provided bucket and AWS credentials and then create the bucket if it doesn't exist. Then when a request comes through to upload a file we'll open up a stream to the file and use it to write the file to S3 to the specified path. This will handle the multi-part upload piece behind the scenes (if needed) and has the benefit of being done through a stream, so you don't have to wait to read the whole file before you start uploading it.

If you prefer, you could change the code to callbacks from Promises. Or use the pipe() method with the event listener to determine the end/errors.

If you're looking for some additional methods, check out the documentation for s3fs and feel free to open up an issue if you are looking for some additional methods or having issues.

Jquery post, response in new window

Accepted answer doesn't work with "use strict" as the "with" statement throws an error. So instead:

$.post(url, function (data) {
    var w = window.open('about:blank', 'windowname');
    w.document.write(data);
    w.document.close();
});

Also, make sure 'windowname' doesn't have any spaces in it because that will fail in IE :)

Simple 3x3 matrix inverse code (C++)

Why don't you try to code it yourself? Take it as a challenge. :)

For a 3×3 matrix

alt text
(source: wolfram.com)

the matrix inverse is

alt text
(source: wolfram.com)

I'm assuming you know what the determinant of a matrix |A| is.

Images (c) Wolfram|Alpha and mathworld.wolfram (06-11-09, 22.06)

SQL update query using joins

One of the easiest way is to use a common table expression (since you're already on SQL 2005):

with cte as (
select
    im.itemid
    ,im.sku as iSku
    ,gm.SKU as GSKU
    ,mm.ManufacturerId as ManuId
    ,mm.ManufacturerName
    ,im.mf_item_number
    ,mm.ManufacturerID
    , <your other field>
from 
    item_master im, group_master gm, Manufacturer_Master mm 
where
    im.mf_item_number like 'STA%'
    and im.sku=gm.sku
    and gm.ManufacturerID = mm.ManufacturerID
    and gm.manufacturerID=34)
update cte set mf_item_number = <your other field>

The query execution engine will figure out on its own how to update the record.

cannot download, $GOPATH not set

You can use the "export" solution just like what other guys have suggested. I'd like to provide you with another solution for permanent convenience: you can use any path as GOPATH when running Go commands.

Firstly, you need to download a small tool named gost : https://github.com/byte16/gost/releases . If you use ubuntu, you can download the linux version(https://github.com/byte16/gost/releases/download/v0.1.0/gost_linux_amd64.tar.gz).

Then you need to run the commands below to unpack it :

$ cd /path/to/your/download/directory 
$ tar -xvf gost_linux_amd64.tar.gz

You would get an executable gost. You can move it to /usr/local/bin for convenient use:

$ sudo mv gost /usr/local/bin

Run the command below to add the path you want to use as GOPATH into the pathspace gost maintains. It is required to give the path a name which you would use later.

$ gost add foo /home/foobar/bar     # 'foo' is the name and '/home/foobar/bar' is the path

Run any Go command you want in the format:

gost goCommand [-p {pathName}] -- [goFlags...] [goArgs...]

For example, you want to run go get github.com/go-sql-driver/mysql with /home/foobar/bar as the GOPATH, just do it as below:

$ gost get -p foo -- github.com/go-sql-driver/mysql  # 'foo' is the name you give to the path above.

It would help you to set the GOPATH and run the command. But remember that you have added the path into gost's pathspace. If you are under any level of subdirectories of /home/foobar/bar, you can even just run the command below which would do the same thing for short :

$ gost get -- github.com/go-sql-driver/mysql

gost is a Simple Tool of Go which can help you to manage GOPATHs and run Go commands. For more details about how to use it to run other Go commands, you can just run gost help goCmdName. For example you want to know more about install, just type words below in:

$ gost help install

You can also find more details in the README of the project: https://github.com/byte16/gost/blob/master/README.md

How to convert an address into a Google Maps Link (NOT MAP)

http://maps.google.com/maps?q=<?php echo urlencode($address); ?> 

the encode ur conver and adds all the extra elements like for spaces and all. so u can easily fetch plane text code from db and use it without worring about the special characters to be added