Programs & Examples On #Bigint

Arbitrary-precision arithmetic (also called bignum arithmetic, multiple precision arithmetic, or infinite-precision arithmetic) indicates that calculations are performed on numbers which digits of precision are limited only by the available memory of the host system. This contrasts with the faster fixed-precision arithmetic found in most arithmetic logic unit (ALU) hardware, which typically offers between 8 and 64 bits of precision.

What is the equivalent of bigint in C#?

I was handling a bigint datatype to be shown in a DataGridView and made it like this

something = (int)(Int64)data_reader[0];

What is Func, how and when is it used

Aforementioned answers are great, just putting few points I see might be helpful:

  • Func is built-in delegate type

  • Func delegate type must return a value. Use Action delegate if no return type needed.

  • Func delegate type can have zero to 16 input parameters.

  • Func delegate does not allow ref and out parameters.

  • Func delegate type can be used with an anonymous method or lambda expression.

    Func<int, int, int> Sum = (x, y) => x + y;

How to ensure that there is a delay before a service is started in systemd?

This answer on super user I think is a better answer. From https://superuser.com/a/573761/67952

"But since you asked for a way without using Before and After, you can use:

Type=idle

which as man systemd.service explains

Behavior of idle is very similar to simple; however, actual execution of the service program is delayed until all active jobs are dispatched. This may be used to avoid interleaving of output of shell services with the status output on the console. Note that this type is useful only to improve console output, it is not useful as a general unit ordering tool, and the effect of this service type is subject to a 5s time-out, after which the service program is invoked anyway. "

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

It's because the name column on the bar table does not have the UNIQUE constraint.

So imagine you have 2 rows on the bar table that contain the name 'ams' and you insert a row on baz with 'ams' on bar_fk, which row on bar would it be referring since there are two rows matching?

Binary Search Tree - Java Implementation

According to Collections Framework Overview you have two balanced tree implementations:

How to use UIPanGestureRecognizer to move object? iPhone/iPad

swift 2 version of the @MS AppTech answer

func handlePan(panGest : UIPanGestureRecognizer) {
let velocity : CGPoint = panGest.velocityInView(self.view);
        let magnitude : CGFloat = CGFloat(sqrtf((Float(velocity.x) * Float(velocity.x)) + (Float(velocity.y) * Float(velocity.y))));
        let slideMult :CGFloat = magnitude / 200;
        //NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);

        let slideFactor : CGFloat = 0.1 * slideMult; // Increase for more of a slide
        var finalPoint : CGPoint = CGPointMake(panGest.view!.center.x + (velocity.x * slideFactor),
                                         panGest.view!.center.y + (velocity.y * slideFactor));
        finalPoint.x = min(max(finalPoint.x, 0), self.view.bounds.size.width);
        finalPoint.y = min(max(finalPoint.y, 0), self.view.bounds.size.height);

        UIView.animateWithDuration(Double(slideFactor*2), delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
            panGest.view!.center = finalPoint;
            }, completion: nil)
}

UITableView - change section header color

SWIFT 2

I was able to successfully change the section background color with an added blur effect (which is really cool). To change the background color of section easily:

  1. First go to Storyboard and select the Table View
  2. Go to Attributes Inspector
  3. List item
  4. Scroll down to View
  5. Change "Background"

Then for blur effect, add to code:

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    // This is the blur effect

    let blurEffect = UIBlurEffect(style: .Light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)

    // Gets the header view as a UITableViewHeaderFooterView and changes the text colour and adds above blur effect
    let headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    headerView.textLabel!.textColor = UIColor.darkGrayColor()
    headerView.textLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 13)
    headerView.tintColor = .groupTableViewBackgroundColor()
    headerView.backgroundView = blurEffectView

}

How to animate button in android?


Class.Java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_with_the_button);

    final Animation myAnim = AnimationUtils.loadAnimation(this, R.anim.milkshake);
    Button myButton = (Button) findViewById(R.id.new_game_btn);
    myButton.setAnimation(myAnim);
}

For onClick of the Button

myButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        v.startAnimation(myAnim);
    }
});

Create the anim folder in res directory

Right click on, res -> New -> Directory

Name the new Directory anim

create a new xml file name it milkshake


milkshake.xml

<?xml version="1.0" encoding="utf-8"?>
    <rotate xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="100"
        android:fromDegrees="-5"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatCount="10"
        android:repeatMode="reverse"
        android:toDegrees="5" />

laravel 5.4 upload image

i think better to do this

    if ( $request->hasFile('file')){
        if ($request->file('file')->isValid()){
            $file = $request->file('file');
            $name = $file->getClientOriginalName();
            $file->move('images' , $name);
            $inputs = $request->all();
            $inputs['path'] = $name;
        }
    }
    Post::create($inputs);

actually images is folder that laravel make it automatic and file is name of the input and here we store name of the image in our path column in the table and store image in public/images directory

Is there a PowerShell "string does not contain" cmdlet or syntax?

You can use the -notmatch operator to get the lines that don't have the characters you are interested in.

     Get-Content $FileName | foreach-object { 
     if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

I want to add to the answers posted on above that none of the solutions proposed here worked for me. My WAMP, is working on port 3308 instead of 3306 which is what it is installed by default. I found out that when working in a local environment, if you are using mysqladmin in your computer (for testing environment), and if you are working with port other than 3306, you must define your variable DB_SERVER with the value localhost:NumberOfThePort, so it will look like the following: define("DB_SERVER", "localhost:3308"). You can obtain this value by right-clicking on the WAMP icon in your taskbar (on the hidden icons section) and select Tools. You will see the section: "Port used by MySQL: NumberOfThePort"

This will fix your connection to your database.

This was the error I got: Error: SQLSTATE[HY1045] Access denied for user 'username'@'localhost' on line X.

I hope this helps you out.

:)

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

You might want to add the following to your pom and try compiling

   <repositories>
        <repository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/libs-snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/libs-snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

Are there constants in JavaScript?

Checkout https://www.npmjs.com/package/constjs, which provides three functions to create enum, string const and bitmap. The returned result is either frozen or sealed thus you can't change/delete the properties after they are created, you can neither add new properties to the returned result

create Enum:

var ConstJs = require('constjs');

var Colors = ConstJs.enum("blue red");

var myColor = Colors.blue;

console.log(myColor.isBlue()); // output true 
console.log(myColor.is('blue')); // output true 
console.log(myColor.is('BLUE')); // output true 
console.log(myColor.is(0)); // output true 
console.log(myColor.is(Colors.blue)); // output true 

console.log(myColor.isRed()); // output false 
console.log(myColor.is('red')); // output false 

console.log(myColor._id); // output blue 
console.log(myColor.name()); // output blue 
console.log(myColor.toString()); // output blue 

// See how CamelCase is used to generate the isXxx() functions 
var AppMode = ConstJs.enum('SIGN_UP, LOG_IN, FORGOT_PASSWORD');
var curMode = AppMode.LOG_IN;

console.log(curMode.isLogIn()); // output true 
console.log(curMode.isSignUp()); // output false 
console.log(curMode.isForgotPassword()); // output false 

Create String const:

var ConstJs = require('constjs');

var Weekdays = ConstJs.const("Mon, Tue, Wed");
console.log(Weekdays); // output {Mon: 'Mon', Tue: 'Tue', Wed: 'Wed'} 

var today = Weekdays.Wed;
console.log(today); // output: 'Wed'; 

Create Bitmap:

var ConstJs = require('constjs');

var ColorFlags = ConstJs.bitmap("blue red");
console.log(ColorFlags.blue); // output false 

var StyleFlags = ConstJs.bitmap(true, "rustic model minimalist");
console.log(StyleFlags.rustic); // output true 

var CityFlags = ConstJs.bitmap({Chengdu: true, Sydney: false});
console.log(CityFlags.Chengdu); //output true 
console.log(CityFlags.Sydney); // output false 

var DayFlags = ConstJs.bitmap(true, {Mon: false, Tue: true});
console.log(DayFlags.Mon); // output false. Default val wont override specified val if the type is boolean  

For more information please checkout

Disclaim: I am the author if this tool.

How to create a self-signed certificate for a domain name for development?

I ran into this same problem when I wanted to enable SSL to a project hosted on IIS 8. Finally the tool I used was OpenSSL, after many days fighting with makecert commands.The certificate is generated in Debian, but I could import it seamlessly into IIS 7 and 8.

Download the OpenSSL compatible with your OS and this configuration file. Set the configuration file as default configuration of OpenSSL.

First we will generate the private key and certificate of Certification Authority (CA). This certificate is to sign the certificate request (CSR).

You must complete all fields that are required in this process.

  1. openssl req -new -x509 -days 3650 -extensions v3_ca -keyout root-cakey.pem -out root-cacert.pem -newkey rsa:4096

You can create a configuration file with default settings like this: Now we will generate the certificate request, which is the file that is sent to the Certification Authorities.

The Common Name must be set the domain of your site, for example: public.organization.com.

  1. openssl req -new -nodes -out server-csr.pem -keyout server-key.pem -newkey rsa:4096

Now the certificate request is signed with the generated CA certificate.

  1. openssl x509 -req -days 365 -CA root-cacert.pem -CAkey root-cakey.pem -CAcreateserial -in server-csr.pem -out server-cert.pem

The generated certificate must be exported to a .pfx file that can be imported into the IIS.

  1. openssl pkcs12 -export -out server-cert.pfx -inkey server-key.pem -in server-cert.pem -certfile root-cacert.pem -name "Self Signed Server Certificate"

In this step we will import the certificate CA.

  1. In your server must import the CA certificate to the Trusted Root Certification Authorities, for IIS can trust the certificate to be imported. Remember that the certificate to be imported into the IIS, has been signed with the certificate of the CA.

    • Open Command Prompt and type mmc.
    • Click on File.
    • Select Add/Remove Snap in....
    • Double click on Certificates.
    • Select Computer Account and Next ->.
    • Select Local Computer and Finish.
    • Ok.
    • Go to Certificates -> Trusted Root Certification Authorities -> Certificates, rigth click on Certificates and select All Tasks -> Import ...

enter image description here

  • Select Next -> Browse ...
  • You must select All Files to browse the location of root-cacert.pem file.
  • Click on Next and select Place all certificates in the following store: Trusted Root Certification Authorities.
  • Click on Next and Finish.

enter image description here

With this step, the IIS trust on the authenticity of our certificate.

  1. In our last step we will import the certificate to IIS and add the binding site.

    • Open Internet Information Services (IIS) Manager or type inetmgr on command prompt and go to Server Certificates.
    • Click on Import....
    • Set the path of .pfx file, the passphrase and Select certificate store on Web Hosting.

enter image description here

  • Click on OK.
  • Now go to your site on IIS Manager and select Bindings... and Add a new binding.

  • Select https as the type of binding and you should be able to see the imported certificate.

  • Click on OK and all is done.

enter image description here

how to insert value into DataGridView Cell?

You can use this function if you want to add the data into database, with a button. I hope it will help.

// dgvBill is name of DataGridView

string StrQuery;
try
{
    using (SqlConnection conn = new SqlConnection(ConnectingString))
    {
        using (SqlCommand comm = new SqlCommand())
        {
            comm.Connection = conn;
            conn.Open();
            for (int i = 0; i < dgvBill.Rows.Count; i++) 
            {
                StrQuery = @"INSERT INTO tblBillDetails (IdBill, productID, quantity, price,  total) VALUES ('" + IdBillVar+ "','" + dgvBill.Rows[i].Cells[0].Value + "', '" + dgvBill.Rows[i].Cells[4].Value + "', '" + dgvBill.Rows[i].Cells[3].Value + "', '" + dgvBill.Rows[i].Cells[2].Value + "');";
                comm.CommandText = StrQuery;
                comm.ExecuteNonQuery();         
             }
         }
     }
 }
 catch (Exception err)
 {
     MessageBox.Show(err.Message  , "Error !");
 }

How to find array / dictionary value using key?

It's as simple as this :

$array[$key];

Using custom fonts using CSS?

Today there are four font container formats in use on the web: EOT, TTF, WOFF,andWOFF2.

Unfortunately, despite the wide range of choices, there isn't a single universal format that works across all old and new browsers:

  • EOT is IE only,
  • TTF has partial IE support,
  • WOFF enjoys the widest support but is not available in some older browsers
  • WOFF 2.0 support is a work in progress for many browsers.

If you want your web app to have the same font across all browsers then you might want to provide all 4 font type in CSS

 @font-face {
      font-family: 'besom'; !important
      src: url('fonts/besom/besom.eot');
      src: url('fonts/besom/besom.eot?#iefix') format('embedded-opentype'),
           url('fonts/besom/besom.woff2') format('woff2'),
           url('fonts/besom/besom.woff') format('woff'),
           url('fonts/besom/besom.ttf') format('truetype'),
           url('fonts/besom/besom.svg#besom_2regular') format('svg');
      font-weight: normal;
      font-style: normal;
  }

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

What does HTTP/1.1 302 mean exactly?

302 is a response indicating change of resource location - "Found".

The url where the resource should be now located should be in the response 'Location' header.

The "jump" should be done by the requesting client (make a new request to the resource url in the response Location header field).

MySQL - Operand should contain 1 column(s)

COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by,
    users.id AS posted_by_id
    FROM users
    WHERE users.id = posts.posted_by)

Well, you can’t get multiple columns from one subquery like that. Luckily, the second column is already posts.posted_by! So:

SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
posts.posted_by
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by_username
    FROM users
    WHERE users.id = posts.posted_by)
...

jQuery get the rendered height of an element?

I made a simple code that doesn't even need JQuery and probably gonna help some people. It gets the total height of 'ID1' after loaded and use it on 'ID2'

function anyName(){
    var varname=document.getElementById('ID1').offsetHeight;
    document.getElementById('ID2').style.height=varname+'px';
}

Then just set the body to load it

<body onload='anyName()'>

Property 'value' does not exist on type 'EventTarget'

Here is the simple approach I used:

const element = event.currentTarget as HTMLInputElement
const value = element.value

The error shown by TypeScript compiler is gone and the code works.

C# How to determine if a number is a multiple of another?

Try

public bool IsDivisible(int x, int n)
{
   return (x % n) == 0;
}

The modulus operator % returns the remainder after dividing x by n which will always be 0 if x is divisible by n.

For more information, see the % operator on MSDN.

Add views in UIStackView programmatically

In my case the thing that was messing with I would expect was that I was missing this line:

stackView.translatesAutoresizingMaskIntoConstraints = false;

After that no need to set constraints to my arranged subviews whatsoever, the stackview is taking care of that.

Mutex example / tutorial?

I stumbled upon this post recently and think that it needs an updated solution for the standard library's c++11 mutex (namely std::mutex).

I've pasted some code below (my first steps with a mutex - I learned concurrency on win32 with HANDLE, SetEvent, WaitForMultipleObjects etc).

Since it's my first attempt with std::mutex and friends, I'd love to see comments, suggestions and improvements!

#include <condition_variable>
#include <mutex>
#include <algorithm>
#include <thread>
#include <queue>
#include <chrono>
#include <iostream>


int _tmain(int argc, _TCHAR* argv[])
{   
    // these vars are shared among the following threads
    std::queue<unsigned int>    nNumbers;

    std::mutex                  mtxQueue;
    std::condition_variable     cvQueue;
    bool                        m_bQueueLocked = false;

    std::mutex                  mtxQuit;
    std::condition_variable     cvQuit;
    bool                        m_bQuit = false;


    std::thread thrQuit(
        [&]()
        {
            using namespace std;            

            this_thread::sleep_for(chrono::seconds(5));

            // set event by setting the bool variable to true
            // then notifying via the condition variable
            m_bQuit = true;
            cvQuit.notify_all();
        }
    );


    std::thread thrProducer(
        [&]()
        {
            using namespace std;

            int nNum = 13;
            unique_lock<mutex> lock( mtxQuit );

            while ( ! m_bQuit )
            {
                while( cvQuit.wait_for( lock, chrono::milliseconds(75) ) == cv_status::timeout )
                {
                    nNum = nNum + 13 / 2;

                    unique_lock<mutex> qLock(mtxQueue);
                    cout << "Produced: " << nNum << "\n";
                    nNumbers.push( nNum );
                }
            }
        }   
    );

    std::thread thrConsumer(
        [&]()
        {
            using namespace std;
            unique_lock<mutex> lock(mtxQuit);

            while( cvQuit.wait_for(lock, chrono::milliseconds(150)) == cv_status::timeout )
            {
                unique_lock<mutex> qLock(mtxQueue);
                if( nNumbers.size() > 0 )
                {
                    cout << "Consumed: " << nNumbers.front() << "\n";
                    nNumbers.pop();
                }               
            }
        }
    );

    thrQuit.join();
    thrProducer.join();
    thrConsumer.join();

    return 0;
}

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

What are dex files: Android app (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app.

Reason for this exception: The DEX specification limits the total number of methods that can be referenced within a single DEX file to 65,536 (64K reference limit) —including Android framework methods, library methods, and methods in your own code.

Step 01. Add the following dependency as follows

For Non-Androidx Users,

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}
defaultConfig {
    minSdkVersion 16
    targetSdkVersion 28
    multiDexEnabled true  //ADD THIS LINE
}

For Androidx Users,

dependencies {
  implementation 'androidx.multidex:multidex:2.0.1'
}
    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 28
        multiDexEnabled true  //ADD THIS LINE
    }

Step 02:

After adding those Sync projects and before you run the project make sure to Build a project before the run. otherwise, you will get an exception.

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

This error

docker: Error response from daemon: OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"/bin/sh\": stat /bin/sh: no such file or directory": unknown.

occurs when creating a docker image from base image eg. scratch. This is because the resulting image does not have a shell to execute the image. If your use:

ENV EXECUTABLE hello
cmd [$EXECUTABLE]

in your docker file, docker uses /bin/sh to parse the input string. and hence the error. Inspecting on the image, your will find:

$docker inspect <image-name>
"Entrypoint": [
                "/bin/sh",
                "-c",
                "[$HM_APP]"
            ]

This means that the ENTRYPOINT or CMD arguments will be parsed using /bin/sh -c. The solution that worked for me is to parse the command as a JSON array of string e.g.

cmd ["hello"]

and inspecting the image again:

"Entrypoint": [
                "hello"
            ]

This removes the dependence on /bin/sh the docker app can now execute the binary file. Example:

FROM scratch

# Environmental variables

# Copy files
ADD . /
# Home dir
WORKDIR /bin

EXPOSE 8083
ENTRYPOINT ["hospitalms"]

Hope this helps someone in future.

Extract number from string with Oracle function

This works for me, I only need first numbers in string:

TO_NUMBER(regexp_substr(h.HIST_OBSE, '\.*[[:digit:]]+\.*[[:digit:]]*'))

the field had the following string: "(43 Paginas) REGLAS DE PARTICIPACION".

result field: 43

How do I close a tkinter window?

The easiest way would be to click the red button (leftmost on macOS and rightmost on Windows). If you want to bind a specific function to a button widget, you can do this:

class App:
    def __init__(self, master)
        frame = Tkinter.Frame(master)
        frame.pack()
        self.quit_button = Tkinter.Button(frame, text = 'Quit', command = frame.quit)
        self.quit_button.pack()

Or, to make things a little more complex, use protocol handlers and the destroy() method.

import tkMessageBox

def confirmExit():
    if tkMessageBox.askokcancel('Quit', 'Are you sure you want to exit?'):
        root.destroy()
root = Tk()
root.protocol('WM_DELETE_WINDOW', confirmExit)
root.mainloop()

How do I get the height of a div's full content with jQuery?

Element.scrollHeight is a property, not a function, as noted here. As noted here, the scrollHeight property is only supported after IE8. If you need it to work before that, temporarily set the CSS overflow and height to auto, which will cause the div to take the maximum height it needs. Then get the height, and change the properties back to what they were before.

Converting ArrayList to Array in java

package com.v4common.shared.beans.audittrail;

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

public class test1 {
    public static void main(String arg[]){
        List<String> list = new ArrayList<String>();
        list.add("abcd#xyz");
        list.add("mnop#qrs");

        Object[] s = list.toArray();
        String[] s1= new String[list.size()];
        String[] s2= new String[list.size()];

        for(int i=0;i<s.length;i++){
            if(s[i] instanceof String){
                String temp = (String)s[i];
                if(temp.contains("#")){
                    String[] tempString = temp.split("#");
                    for(int j=0;j<tempString.length;j++) {
                        s1[i] = tempString[0];
                        s2[i] = tempString[1];
                    }

                }
            }   
        }
        System.out.println(s1.length);
        System.out.println(s2.length);
        System.out.println(s1[0]);
        System.out.println(s1[1]);
    }
}

How to set layout_weight attribute dynamically from code?

If the constructor with width, height and weight is not working, try using the constructor with width and height. And then manually set the weight.

And if you want the width to be set according to the weight, set width as 0 in the constructor. Same applies for height. Below code works for me.

LinearLayout.LayoutParams childParam1 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam1.weight = 0.3f;
child1.setLayoutParams(childParam1);

LinearLayout.LayoutParams childParam2 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam2.weight = 0.7f;
child2.setLayoutParams(childParam2);

parent.setWeightSum(1f);
parent.addView(child1);
parent.addView(child2);

How do I use the includes method in lodash to check if an object is in the collection?

You could use find to solve your problem

https://lodash.com/docs/#find

const data = [{"a": 1}, {"b": 2}]
const item = {"b": 2}


find(data, item)
// > true

Delete all the queues from RabbitMQ?

If you don't have rabbitmqadmin installed, try to purge queues with rabbitmqctl:

rabbitmqctl list_queues | awk '{ print $1 }' | xargs -L1 rabbitmqctl purge_queue

Reading in from System.in - Java

You can use System.in to read from the standard input. It works just like entering it from a keyboard. The OS handles going from file to standard input.

class MyProg {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Printing the file passed in:");
        while(sc.hasNextLine()) System.out.println(sc.nextLine());
    }
}

Python subprocess/Popen with a modified environment

you might use my_env.get("PATH", '') instead of my_env["PATH"] in case PATH somehow not defined in the original environment, but other than that it looks fine.

Checking for an empty field with MySQL

An empty field can be either an empty string or a NULL.

To handle both, use:

email > ''

which can benefit from the range access if you have lots of empty email record (both types) in your table.

Run exe file with parameters in a batch file

If you need to see the output of the execute, use CALL together with or instead of START.

Example:

CALL "C:\Program Files\Certain Directory\file.exe" -param PAUSE

This will run the file.exe and print back whatever it outputs, in the same command window. Remember the PAUSE after the call or else the window may close instantly.

How to count check-boxes using jQuery?

There are multiple methods to do that:

Method 1:

alert($('.checkbox_class_here:checked').size());

Method 2:

alert($('input[name=checkbox_name]').attr('checked'));

Method 3:

alert($(":checkbox:checked").length);

How long to brute force a salted SHA-512 hash? (salt provided)

I want to know the time to brute force for when the password is a dictionary word and also when it is not a dictionary word.

Dictionary password

Ballpark figure: there are about 1,000,000 English words, and if a hacker can compute about 10,000 SHA-512 hashes a second (update: see comment by CodesInChaos, this estimate is very low), 1,000,000 / 10,000 = 100 seconds. So it would take just over a minute to crack a single-word dictionary password for a single user. If the user concatenates two dictionary words, you're in the area of a few days, but still very possible if the attacker is cares enough. More than that and it starts getting tough.

Random password

If the password is a truly random sequence of alpha-numeric characters, upper and lower case, then the number of possible passwords of length N is 60^N (there are 60 possible characters). We'll do the calculation the other direction this time; we'll ask: What length of password could we crack given a specific length of time? Just use this formula:

N = Log60(t * 10,000) where t is the time spent calculating hashes in seconds (again assuming 10,000 hashes a second).

1 minute:    3.2
5 minute:    3.6
30 minutes:  4.1
2 hours:     4.4
3 days:      5.2

So given a 3 days we'd be able to crack the password if it's 5 characters long.

This is all very ball-park, but you get the idea. Update: see comment below, it's actually possible to crack much longer passwords than this.

What's going on here?

Let's clear up some misconceptions:

  • The salt doesn't make it slower to calculate hashes, it just means they have to crack each user's password individually, and pre-computed hash tables (buzz-word: rainbow tables) are made completely useless. If you don't have a precomputed hash-table, and you're only cracking one password hash, salting doesn't make any difference.

  • SHA-512 isn't designed to be hard to brute-force. Better hashing algorithms like BCrypt, PBKDF2 or SCrypt can be configured to take much longer to compute, and an average computer might only be able to compute 10-20 hashes a second. Read This excellent answer about password hashing if you haven't already.

  • update: As written in the comment by CodesInChaos, even high entropy passwords (around 10 characters) could be bruteforced if using the right hardware to calculate SHA-512 hashes.


Notes on accepted answer:

The accepted answer as of September 2014 is incorrect and dangerously wrong:

In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack)... Finding a collision using a birthday attack takes O(2^n/2) time, where n is the output length of the hash function in bits.

The birthday attack is completely irrelevant to cracking a given hash. And this is in fact a perfect example of a preimage attack. That formula and the next couple of paragraphs result in dangerously high and completely meaningless values for an attack time. As demonstrated above it's perfectly possible to crack salted dictionary passwords in minutes.

The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords...

That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5...

Yes, please use an algorithm that is slow to compute, but what is "entropy-enducing"? Putting a low entropy password through a hash doesn't increase entropy. It should preserve entropy, but you can't make a rubbish password better with a hash, it doesn't work like that. A weak password put through PBKDF2 is still a weak password.

Dynamic WHERE clause in LINQ

You can also use the PredicateBuilder from LinqKit to chain multiple typesafe lambda expressions using Or or And.

http://www.albahari.com/nutshell/predicatebuilder.aspx

Could not find folder 'tools' inside SDK

In my case i was using Ubuntu. Where the was two directories one was /android-sdks and /android-sdk-linux. I used the second one it works for me :)

How to downgrade tensorflow, multiple versions possible?

Click to green checkbox on installed tensorflow and choose needed versionscreenshot Anaconda navigator

here-document gives 'unexpected end of file' error

Here is a flexible way to do deal with multiple indented lines without using heredoc.

  echo 'Hello!'
  sed -e 's:^\s*::' < <(echo '
    Some indented text here.
    Some indented text here.
  ')
  if [[ true ]]; then
    sed -e 's:^\s\{4,4\}::' < <(echo '
      Some indented text here.
        Some extra indented text here.
      Some indented text here.
    ')
  fi

Some notes on this solution:

  • if the content is expected to have simple quotes, either escape them using \ or replace the string delimiters with double quotes. In the latter case, be careful that construction like $(command) will be interpreted. If the string contains both simple and double quotes, you'll have to escape at least of kind.
  • the given example print a trailing empty line, there are numerous way to get rid of it, not included here to keep the proposal to a minimum clutter
  • the flexibility comes from the ease with which you can control how much leading space should stay or go, provided that you know some sed REGEXP of course.

Checking if element exists with Python Selenium

You could also do it more concisely using

driver.find_element_by_id("some_id").size != 0

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

You can add an onchange event on the textarea (or any other fields) that set a variable in JS. When the user attempts to close the page (window.onunload) you check the value of that variable and show the alert accordingly.

How to detect if a browser is Chrome using jQuery?

Sadly due to Opera's latest update !!window.chrome (and other tests on the window object) when testing in Opera returns true.

Conditionizr takes care of this for you and solves the Opera issue:

conditionizr.add('chrome', [], function () {
    return !!window.chrome && !/opera|opr/i.test(navigator.userAgent);
});

I'd highly suggest using it as none of the above are now valid.

This allows you to do:

if (conditionizr.chrome) {...}

Conditionizr takes care of other browser detects and is much faster and reliable than jQuery hacks.

How to have image and text side by side

HTML

<div class='containerBox'>
    <div>
       <img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails'>
       <div>
       <h4>Facebook</h4>  
       <div style="font-size:.6em;float:left; margin-left:5px;color:white;">fine location, GPS, coarse location</div>
       <div style="float:right;font-size:.6em; margin-right:5px; color:white;">0 mins ago</div>
       </div>
   </div> 
</div>

CSS

 .iconDetails {
 margin-left:2%;
 float:left; 
 height:40px;
 width:40px;
 } 

.containerBox {
width:300px;
height:60px;
padding:1px;
background-color:#303030;
}
h4{
margin:0px;
margin-top:3%;
margin-left:50px;
color:white;
}

adb uninstall failed

Open your application Manifest and check the application's package first.

After that, be sure that your device is set into debugger mode.

Check if ADB can interact with your device:

adb devices

If your device is listed, then run:

adb uninstall PACKAGE_WRITTEN_IN_MANIFEST

How to automatically redirect HTTP to HTTPS on Apache servers?

This worked for me:

RewriteCond %{HTTPS} =off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L,R=301]

numpy: most efficient frequency counts for unique values in an array

To count unique non-integers - similar to Eelco Hoogendoorn's answer but considerably faster (factor of 5 on my machine), I used weave.inline to combine numpy.unique with a bit of c-code;

import numpy as np
from scipy import weave

def count_unique(datain):
  """
  Similar to numpy.unique function for returning unique members of
  data, but also returns their counts
  """
  data = np.sort(datain)
  uniq = np.unique(data)
  nums = np.zeros(uniq.shape, dtype='int')

  code="""
  int i,count,j;
  j=0;
  count=0;
  for(i=1; i<Ndata[0]; i++){
      count++;
      if(data(i) > data(i-1)){
          nums(j) = count;
          count = 0;
          j++;
      }
  }
  // Handle last value
  nums(j) = count+1;
  """
  weave.inline(code,
      ['data', 'nums'],
      extra_compile_args=['-O2'],
      type_converters=weave.converters.blitz)
  return uniq, nums

Profile info

> %timeit count_unique(data)
> 10000 loops, best of 3: 55.1 µs per loop

Eelco's pure numpy version:

> %timeit unique_count(data)
> 1000 loops, best of 3: 284 µs per loop

Note

There's redundancy here (unique performs a sort also), meaning that the code could probably be further optimized by putting the unique functionality inside the c-code loop.

Truncate a SQLite table if it exists?

"sqllite" dosn't have "TRUNCATE " order like than mysql, then we have to get other way... this function (reset_table) frist delete all data in table and then reset AUTOINCREMENT key in table.... now you can use this function every where you want...

example :

private SQLiteDatabase mydb;
private final String dbPath = "data/data/your_project_name/databases/";
private final String dbName = "your_db_name";


public void reset_table(String table_name){
    open_db();

    mydb.execSQL("Delete from "+table_name);
    mydb.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE name='"+table_name+"';");

    close_db();
}

public void open_db(){

    mydb = SQLiteDatabase.openDatabase(dbPath + dbName + ".db", null, SQLiteDatabase.OPEN_READWRITE);
}
public void close_db(){

    mydb.close();
}

How do I check if a given Python string is a substring of another one?

string.find("substring") will help you. This function returns -1 when there is no substring.

Generate random password string with requirements in javascript

As @RobW notes, restricting the password to a fixed number of characters as proposed in the OP scheme is a bad idea. But worse, answers that propose code based on Math.random are, well, a really bad idea.

Let's start with the bad idea. The OP code is randomly selecting a string of 8 characters from a set of 62. Restricting the random string to 5 letters and 3 numbers means the resulting passwords will have, at best, 28.5 bits of entropy (as opposed to a potential of 47.6 bits if the distribution restriction of 5 letters and 3 numbers were removed). That's not very good. But in reality, the situation is even worse. The at best aspect of the code is destroyed by the use of Math.random as the means of generating entropy for the passwords. Math.random is a pseudo random number generator. Due to the deterministic nature of pseudo random number generators the entropy of the resulting passwords is really bad , rendering any such proposed solution a really bad idea. Assuming these passwords are being doled out to end users (o/w what's the point), an active adversary that receives such a password has very good chance of predicting future passwords doled out to other users, and that's probably not a good thing.

But back to the just bad idea. Assume a cryptographically strong pseudo random number generator is used instead of Math.random. Why would you restrict the passwords to 28.5 bits? As noted, that's not very good. Presumably the 5 letters, 3 numbers scheme is to assist users in managing randomly doled out passwords. But let's face it, you have to balance ease of use against value of use, and 28.5 bits of entropy isn't much value in defense against an active adversary.

But enough of the bad. Let's propose a path forward. I'll use the JavaScript EntropyString library which "efficiently generates cryptographically strong random strings of specified entropy from various character sets". Rather than the OP 62 characters, I'll use a character set with 32 characters chosen to reduce the use of easily confused characters or the formation of English words. And rather than the 5 letter, 3 number scheme (which has too little entropy), I'll proclaim the password will have 60 bits of entropy (this is the balance of ease versus value).

import { Entropy, charSet32 } from 'entropy-string'
const random = new Entropy({ bits: 60, charset: charset32 })
const string = random.string()

"Q7LfR8Jn7RDp"

Note the arguments to Entropy specify the desired bits of entropy as opposed to more commonly seen solutions to random string generation that specify passing in a string length (which is both misguided and typically underspecified, but that's another story).

AngularJS Multiple ng-app within a page

You can use angular.bootstrap() directly... the problem is you lose the benefits of directives.

First you need to get a reference to the HTML element in order to bootstrap it, which means your code is now coupled to your HTML.

Secondly the association between the two is not as apparent. With ngApp you can clearly see what HTML is associated with what module and you know where to look for that information. But angular.bootstrap() could be invoked from anywhere in your code.

If you are going to do it at all the best way would be by using a directive. Which is what I did. It's called ngModule. Here is what your code would look like using it:

<!DOCTYPE html>
<html>
    <head>
        <script src="angular.js"></script>
        <script src="angular.ng-modules.js"></script>
        <script>
          var moduleA = angular.module("MyModuleA", []);
          moduleA.controller("MyControllerA", function($scope) {
              $scope.name = "Bob A";
          });

          var moduleB = angular.module("MyModuleB", []);
          moduleB.controller("MyControllerB", function($scope) {
              $scope.name = "Steve B";
          });
        </script>
    </head>
    <body>
        <div ng-modules="MyModuleA, MyModuleB">
            <h1>Module A, B</h1>
            <div ng-controller="MyControllerA">
                {{name}}
            </div>
            <div ng-controller="MyControllerB">
                {{name}}
            </div>
        </div>

        <div ng-module="MyModuleB">
            <h1>Just Module B</h1>
            <div ng-controller="MyControllerB">
                {{name}}
            </div>
        </div>
    </body>
</html>

You can get the source code for it at:

http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/

It's implemented in the same way as ngApp. It simply calls angular.bootstrap() behind the scenes.

Assert a function/method was not called using Mock

This should work for your case;

assert not my_var.called, 'method should not have been called'

Sample;

>>> mock=Mock()
>>> mock.a()
<Mock name='mock.a()' id='4349129872'>
>>> assert not mock.b.called, 'b was called and should not have been'
>>> assert not mock.a.called, 'a was called and should not have been'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: a was called and should not have been

SQL Error: ORA-00942 table or view does not exist

Either the user doesn't have privileges needed to see the table, the table doesn't exist or you are running the query in the wrong schema

Does the table exist?

    select owner, 
           object_name 
    from dba_objects 
    where object_name = any ('CUSTOMER','customer');

What privileges did you grant?

    grant select, insert on customer to user;

Are you running the query against the owner from the first query?

How can I disable the Maven Javadoc plugin from the command line?

You can use the maven.javadoc.skip property to skip execution of the plugin, going by the Mojo's javadoc. You can specify the value as a Maven property:

<properties>
    <maven.javadoc.skip>true</maven.javadoc.skip>
</properties>

or as a command-line argument: -Dmaven.javadoc.skip=true, to skip generation of the Javadocs.

Window.open and pass parameters by post method

I've used this in the past, since we typically use razor syntax for coding

@using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { target = "_blank" }))

{

// add hidden and form filed here

}

Setting java locale settings

If you ever want to check what locale or character set java is using this is built into the JVM:

java -XshowSettings -version

and it will dump out loads of the settings it's using. This way you can check your LANG and LC_* values are getting picked up correctly.

JQuery - $ is not defined

That error can only be caused by one of three things:

  1. Your JavaScript file is not being properly loaded into your page
  2. You have a botched version of jQuery. This could happen because someone edited the core file, or a plugin may have overwritten the $ variable.
  3. You have JavaScript running before the page is fully loaded, and as such, before jQuery is fully loaded.

First of all, ensure, what script is call properly, it should looks like

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

and shouldn't have attributes async or defer.

Then you should check the Firebug net panel to see if the file is actually being loaded properly. If not, it will be highlighted red and will say "404" beside it. If the file is loading properly, that means that the issue is number 2.

Make sure all jQuery javascript code is being run inside a code block such as:

$(document).ready(function () {
  //your code here
});

This will ensure that your code is being loaded after jQuery has been initialized.

One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described.

Note: If you're loading code which does not require jQuery to run it does not need to be placed inside the jQuery ready handler. That code may be separated using document.readyState.

List to array conversion to use ravel() function

If all you want is calling ravel on your (nested, I s'pose?) list, you can do that directly, numpy will do the casting for you:

L = [[1,None,3],["The", "quick", object]]
np.ravel(L)
# array([1, None, 3, 'The', 'quick', <class 'object'>], dtype=object)

Also worth mentioning that you needn't go through numpy at all.

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

Running the script like this (cron case for example): php5 /pathToScript/info.php produces the same error.

The correct way: php5 -cli /pathToScript/info.php

How to export JavaScript array info to csv (on client side)?

In Chrome 35 update, download attribute behavior was changed.

https://code.google.com/p/chromium/issues/detail?id=373182

to work this in chrome, use this

var pom = document.createElement('a');
var csvContent=csv; //here we load our csv data 
var blob = new Blob([csvContent],{type: 'text/csv;charset=utf-8;'});
var url = URL.createObjectURL(blob);
pom.href = url;
pom.setAttribute('download', 'foo.csv');
pom.click();

What is the meaning of single and double underscore before an object name?

  • _var: variables with a leading single underscore in python are classic variables, intended to inform others using your code that this variable should be reserved for internal use. They differ on one point from classic variables: they are not imported when doing a wildcard import of an object/module where they are defined (exceptions when defining the __all__ variable). Eg:

    # foo.py
    
    var = "var"
    _var = "_var"
    
    # bar.py
    
    from foo import *
    
    print(dir())  # list of defined objects, contains 'var' but not '_var'
    print(var)    # var
    print(_var)   # NameError: name '_var' is not defined
    
  • _ : the single underscore is a special case of the leading single underscore variables. It is used by convention as a trash variable, to store a value that is not intended to be later accessed. It is also not imported by wildcard imports. Eg: this for loop prints "I must not talk in class" 10 times, and never needs to access the _ variable.

    for _ in range(10):
        print("I must not talk in class")
    
  • __var: double leading underscore variables (at least two leading underscores, at most one trailing underscore). When used as class attributes (variables and methods), these variables are subject to name mangling: outside of the class, python will rename the attribute to _<Class_name>__<attribute_name>. Example:

    class MyClass:
        __an_attribute = "attribute_value"
    
    my_class = MyClass()
    print(my_class._MyClass__an_attribute)  # "attribute_value"
    print(my_class.__an_attribute)  # AttributeError: 'MyClass' object has no attribute '__an_attribute'
    

    When used as variables outside a class, they behave like single leading underscore variables.

  • __var__: double leading and trailing underscore variables (at least two leading and trailing underscores). Also called dunders. This naming convention is used by python to define variables internally. Avoid using this convention to prevent name conflicts that could arise with python updates. Dunder variables behave like single leading underscore variables: they are not subject to name mangling when used inside classes, but are not imported in wildcard imports.

Excel select a value from a cell having row number calculated

You could use the INDIRECT function. This takes a string and converts it into a range

More info here

=INDIRECT("K"&A2)

But it's preferable to use INDEX as it is less volatile.

=INDEX(K:K,A2)

This returns a value or the reference to a value from within a table or range

More info here

Put either function into cell B2 and fill down.

gpg: no valid OpenPGP data found

Managed to resolve it. separated the command in to two commands and used directly the file name which was downloaded example -

wget -q -O - https://pkg.jenkins.io/debian/jenkins-ci.org.key | sudo apt-key    add -

can be separated into

  1. wget -q -O - https://pkg.jenkins.io/debian/jenkins-ci.org.key
  2. sudo apt-key add jenkins-ci.org.key

ViewPager PagerAdapter not updating the View

This is a horrible problem and I'm happy to present an excellent solution; simple, efficient, and effective !

See below, the code shows using a flag to indicate when to return POSITION_NONE

public class ViewPagerAdapter extends PagerAdapter
{
    // Members
    private boolean mForceReinstantiateItem = false;

    // This is used to overcome terrible bug that Google isn't fixing
    // We know that getItemPosition() is called right after notifyDataSetChanged()
    // Therefore, the fix is to return POSITION_NONE right after the notifyDataSetChanged() was called - but only once
    @Override
    public int getItemPosition(Object object)
    {
        if (mForceReinstantiateItem)
        {
            mForceReinstantiateItem = false;
            return POSITION_NONE;
        }
        else
        {
            return super.getItemPosition(object);
        }
    }

    public void setData(ArrayList<DisplayContent> newContent)
    {
        mDisplayContent = newContent;
        mForceReinstantiateItem = true;
        notifyDataSetChanged();
    }

}

Adding quotes to a string in VBScript

You have to use double double quotes to escape the double quotes (lol):

g = "abcd """ & a & """"

Position a div container on the right side

Just wanna update this for beginners now you should definitly use flexbox to do that, it's more appropriate and work for responsive try this : http://jsfiddle.net/x5vyC/3957/

#wrapper{
  display:flex;
  justify-content:space-between;
  background:red;
}


#c1{
   background:blue;
}


#c2{
    background:green;
}

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You have an error in you script tag construction, this:

<script language="JavaScript" type="text/javascript" script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

Should look like this:

<script language="JavaScript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

You have a 'script' word lost in the middle of your script tag. Also you should remove the http:// to let the browser decide whether to use HTTP or HTTPS.

UPDATE

But your main error is that you are including jQuery UI (ONLY) you must include jQuery first! jQuery UI and jQuery are used together, not in separate. jQuery UI depends on jQuery. You should put this line before jQuery UI:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

UIScrollView Scrollable Content Size Ambiguity

Check out this really quick and to the point tutorial on how to get the scroll view working and fully scrollable with auto layout. Now, the only thing that is still leaving me puzzled is why the scroll view content size is always larger then necessary..

http://samwize.com/2014/03/14/how-to-use-uiscrollview-with-autolayout/

How to create correct JSONArray in Java using JSONObject

Small reusable method can be written for creating person json object to avoid duplicate code

JSONObject  getPerson(String firstName, String lastName){
   JSONObject person = new JSONObject();
   person .put("firstName", firstName);
   person .put("lastName", lastName);
   return person ;
} 

public JSONObject getJsonResponse(){

    JSONArray employees = new JSONArray();
    employees.put(getPerson("John","Doe"));
    employees.put(getPerson("Anna","Smith"));
    employees.put(getPerson("Peter","Jones"));

    JSONArray managers = new JSONArray();
    managers.put(getPerson("John","Doe"));
    managers.put(getPerson("Anna","Smith"));
    managers.put(getPerson("Peter","Jones"));

    JSONObject response= new JSONObject();
    response.put("employees", employees );
    response.put("manager", managers );
    return response;
  }

Simulating Key Press C#

Simple one, add before Main

[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

Code inside Main/Method:

string className = "IEFrame";
string windowName = "New Tab - Windows Internet Explorer";
IntPtr IE = FindWindow(className, windowName);
if (IE == IntPtr.Zero)
{
   return;
}
SetForegroundWindow(IE);
InputSimulator.SimulateKeyPress(VirtualKeyCode.F5);

Note:

  1. Add InputSimulator as reference. To download Click here

  2. To find Class & Window name, use WinSpy++. To download Click here

Count number of objects in list

length(x)

Get or set the length of vectors (including lists) and factors, and of any other R object for which a method has been defined.

lengths(x)

Get the length of each element of a list or atomic vector (is.atomic) as an integer or numeric vector.

Launching a website via windows commandline

You can start web pages using command line in any browser typing this command

cd %your chrome directory%
start /max http://google.com

save it as bat and run it :)

How to Logout of an Application Where I Used OAuth2 To Login With Google?

If any one want it in Java, Here is my Answer, For this you have to call Another Thread.

How to use python numpy.savetxt to write strings and float number to an ASCII file?

The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.

import numpy as np

names  = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 ,  0.5678 ,  0.9123 ])

ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats

np.savetxt('test.txt', ab, fmt="%10s %10.3f")

Update: This example also works properly in Python 3 by using the 'U6' Unicode string dtype, when creating the ab structured array, instead of the 'S6' byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1' in Python 3.

how to git commit a whole folder?

To stage an entire folder, you'd enter this command:

    $git add .

The period will add all files in the folder.

Python strptime() and timezones?

The datetime module documentation says:

Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])).

See that [0:6]? That gets you (year, month, day, hour, minute, second). Nothing else. No mention of timezones.

Interestingly, [Win XP SP2, Python 2.6, 2.7] passing your example to time.strptime doesn't work but if you strip off the " %Z" and the " EST" it does work. Also using "UTC" or "GMT" instead of "EST" works. "PST" and "MEZ" don't work. Puzzling.

It's worth noting this has been updated as of version 3.2 and the same documentation now also states the following:

When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.

Note that this doesn't work with %Z, so the case is important. See the following example:

In [1]: from datetime import datetime

In [2]: start_time = datetime.strptime('2018-04-18-17-04-30-AEST','%Y-%m-%d-%H-%M-%S-%Z')

In [3]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: None

In [4]: start_time = datetime.strptime('2018-04-18-17-04-30-+1000','%Y-%m-%d-%H-%M-%S-%z')

In [5]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: UTC+10:00

ContractFilter mismatch at the EndpointDispatcher exception

A "ContractFilter mismatch at the EndpointDispatcher" means the receiver could not process the message because it did not match any of the contracts the receiver has configured for the endpoint which received the message.

This can be because:

  • You have different contracts between client and sender.
  • You're using a different binding between client and sender.
  • The message security settings are not consistent between client and sender.

Have at look at the EndpointDispatcher class for more information on the subject.

So:

Make certain that your client and server contracts match.

  • If you've generated your client from a WSDL, is the WSDL up-to-date?
  • If you've made a recent change to the contract, have you deployed the right version of both client and server?
  • If you've hand-crafted your client contract classes, make sure the namespaces, elements names and action names match the ones expected by the server.

Check the bindings are the same between client and server.

  • If you're using a .config file to manage your endpoints, make sure the binding elements match.

Check the security settings are the same between client and server.

  • If you're using a .config file to manage your endpoints, make sure the security elements match.

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

I have come to share an solution. The error happened to me after forcing the notbook to hang up. possible solution clean preject.

Unexpected token < in first line of HTML

Check your encoding, i got something similar once because of the BOM.

Make sure the core.js file is encoded in utf-8 without BOM

The representation of if-elseif-else in EL using JSF

You can use EL if you want to work as IF:

<h:outputLabel value="#{row==10? '10' : '15'}"/>

Changing styles or classes:

style="#{test eq testMB.test? 'font-weight:bold' : 'font-weight:normal'}"

class="#{test eq testMB.test? 'divRred' : 'divGreen'}"

Python: Is there an equivalent of mid, right, and left from BASIC?

There are built-in functions in Python for "right" and "left", if you are looking for a boolean result.

str = "this_is_a_test"
left = str.startswith("this")
print(left)
> True

right = str.endswith("test")
print(right)
> True

How to put a text beside the image?

If you or some other fox who need to have link with Icon Image and text as link text beside the image see bellow code:

CSS

.linkWithImageIcon{

    Display:inline-block;
}
.MyLink{
  Background:#FF3300;
  width:200px;
  height:70px;
  vertical-align:top;
  display:inline-block; font-weight:bold;
} 

.MyLinkText{
  /*---The margin depends on how the image size is ---*/
  display:inline-block; margin-top:5px;
}

HTML

<a href="#" class="MyLink"><img src="./yourImageIcon.png" /><span class="MyLinkText">SIGN IN</span></a>

enter image description here

if you see the image the white portion is image icon and other is style this way you can create different buttons with any type of Icons you want to design

ios simulator: how to close an app

For closing (not quit) the running application in Simulator the keyboard shortcut is "shift+command+h".

Unexpected character encountered while parsing value

When I encountered a similar problem, I fixed it by substituting &mode=xml for &mode=json in the request.

Create an array of strings

As already mentioned by Amro, the most concise way to do this is using cell arrays. However, Budo touched on the new string class introduced in version R2016b of MATLAB. Using this new object, you can very easily create an array of strings in a loop as follows:

for i = 1:10
  Names(i) = string('Sample Text');
end

keyCode values for numeric keypad?

Little bit cleared @A.Morel's answer. You might beware of keyboard language layout. Some keyboard layouts changed default numeric keys to symbols.

let key = parseInt(e.key)
if (isNaN(key)) {
  console.log("is not numeric")
}
else {
  console.log("is numeric")
}

An implementation of the fast Fourier transform (FFT) in C#

For a multi-threaded implementation tuned for Intel processors I'd check out Intel's MKL library. It's not free, but it's afforable (less than $100) and blazing fast - but you'd need to call it's C dll's via P/Invokes. The Exocortex project stopped development 6 years ago, so I'd be careful using it if this is an important project.

How can I strip first X characters from string using sed?

Another way, using cut instead of sed.

result=`echo $pid | cut -c 5-`

In Android EditText, how to force writing uppercase?

You can add the android:textAllCaps="true" property to your xml file in the EditText. This will enforce the softinput keyboard to appear in all caps mode. The value you enter will appear in Uppercase. However, this won't ensure that the user can only enter in UpperCase letters. If they want, they can still fall back to the lower case letters. If you want to ensure that the output of the Edittext is in All caps, then you have to manually convert the input String using toUpperCase() method of String class.

Refresh image with a new one at the same url

After creating the new image, are you removing the old image from the DOM and replacing it with the new one?

You could be grabbing new images every updateImage call, but not adding them to the page.

There are a number of ways to do it. Something like this would work.

function updateImage()
{
    var image = document.getElementById("theText");
    if(image.complete) {
        var new_image = new Image();
        //set up the new image
        new_image.id = "theText";
        new_image.src = image.src;           
        // insert new image and remove old
        image.parentNode.insertBefore(new_image,image);
        image.parentNode.removeChild(image);
    }

    setTimeout(updateImage, 1000);
}

After getting that working, if there are still problems it is probably a caching issue like the other answers talk about.

What does "collect2: error: ld returned 1 exit status" mean?

Try running task manager to determine if your program is still running.

If it is running then stop it and run it again. the [Error] ld returned 1 exit status will not come back

How to run binary file in Linux

:-) If not typo, why are you using ./commonRT instead of ./commonKT ??

Add image in pdf using jspdf

You defined Base64? If you not defined, occurs this error:

ReferenceError: Base64 is not defined

Stacked Bar Plot in R

A somewhat different approach using ggplot2:

dat <- read.table(text = "A   B   C   D   E   F    G
1 480 780 431 295 670 360  190
2 720 350 377 255 340 615  345
3 460 480 179 560  60 735 1260
4 220 240 876 789 820 100   75", header = TRUE)

library(reshape2)

dat$row <- seq_len(nrow(dat))
dat2 <- melt(dat, id.vars = "row")

library(ggplot2)

ggplot(dat2, aes(x = variable, y = value, fill = row)) + 
  geom_bar(stat = "identity") +
  xlab("\nType") +
  ylab("Time\n") +
  guides(fill = FALSE) +
  theme_bw()

this gives:

enter image description here

When you want to include a legend, delete the guides(fill = FALSE) line.

How do I list all cron jobs for all users?

To get list from ROOT user.

for user in $(cut -f1 -d: /etc/passwd); do echo $user; sudo crontab -u $user -l; done

ASP.NET Display "Loading..." message while update panel is updating

You can use code as below when

using Image as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

using Text as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <span style="border-width: 0px; position: fixed; padding: 50px; background-color: #FFFFFF; font-size: 36px; left: 40%; top: 40%;">Loading ...</span>
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

How do I convert a String to a BigInteger?

For a loop where you want to convert an array of strings to an array of bigIntegers do this:

String[] unsorted = new String[n]; //array of Strings
BigInteger[] series = new BigInteger[n]; //array of BigIntegers

for(int i=0; i<n; i++){
    series[i] = new BigInteger(unsorted[i]); //convert String to bigInteger
}

Using NotNull Annotation in method argument

To test your method validation in a test, you have to wrap it a proxy in the @Before method.

@Before
public void setUp() {
    this.classAutowiredWithFindStuffMethod = MethodValidationProxyFactory.createProxy(this.classAutowiredWithFindStuffMethod);
}

With MethodValidationProxyFactory as :

import org.springframework.context.support.StaticApplicationContext;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

public class MethodValidationProxyFactory {

private static final StaticApplicationContext ctx = new StaticApplicationContext();

static {
    MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
    processor.afterPropertiesSet(); // init advisor
    ctx.getBeanFactory()
            .addBeanPostProcessor(processor);
}

@SuppressWarnings("unchecked")
public static <T> T createProxy(T instance) {

    return (T) ctx.getAutowireCapableBeanFactory()
            .applyBeanPostProcessorsAfterInitialization(instance, instance.getClass()
                    .getName());
}

}

And then, add your test :

@Test
public void findingNullStuff() {
 assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> this.classAutowiredWithFindStuffMethod.findStuff(null));

}

Django: multiple models in one template using forms

The MultiModelForm from django-betterforms is a convenient wrapper to do what is described in Gnudiff's answer. It wraps regular ModelForms in a single class which is transparently (at least for basic usage) used as a single form. I've copied an example from their docs below.

# forms.py
from django import forms
from django.contrib.auth import get_user_model
from betterforms.multiform import MultiModelForm
from .models import UserProfile

User = get_user_model()

class UserEditForm(forms.ModelForm):
    class Meta:
        fields = ('email',)

class UserProfileForm(forms.ModelForm):
    class Meta:
        fields = ('favorite_color',)

class UserEditMultiForm(MultiModelForm):
    form_classes = {
        'user': UserEditForm,
        'profile': UserProfileForm,
    }

# views.py
from django.views.generic import UpdateView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.contrib.auth import get_user_model
from .forms import UserEditMultiForm

User = get_user_model()

class UserSignupView(UpdateView):
    model = User
    form_class = UserEditMultiForm
    success_url = reverse_lazy('home')

    def get_form_kwargs(self):
        kwargs = super(UserSignupView, self).get_form_kwargs()
        kwargs.update(instance={
            'user': self.object,
            'profile': self.object.profile,
        })
        return kwargs

How to put a component inside another component in Angular2?

If you remove directives attribute it should work.

@Component({
    selector: 'parent',
    template: `
            <h1>Parent Component</h1>
            <child></child>
        `
    })
    export class ParentComponent{}


@Component({
    selector: 'child',    
    template: `
            <h4>Child Component</h4>
        `
    })
    export class ChildComponent{}

Directives are like components but they are used in attributes. They also have a declarator @Directive. You can read more about directives Structural Directives and Attribute Directives.

There are two other kinds of Angular directives, described extensively elsewhere: (1) components and (2) attribute directives.

A component manages a region of HTML in the manner of a native HTML element. Technically it's a directive with a template.


Also if you are open the glossary you can find that components are also directives.

Directives fall into one of the following categories:

  • Components combine application logic with an HTML template to render application views. Components are usually represented as HTML elements. They are the building blocks of an Angular application.

  • Attribute directives can listen to and modify the behavior of other HTML elements, attributes, properties, and components. They are usually represented as HTML attributes, hence the name.

  • Structural directives are responsible for shaping or reshaping HTML layout, typically by adding, removing, or manipulating elements and their children.


The difference that components have a template. See Angular Architecture overview.

A directive is a class with a @Directive decorator. A component is a directive-with-a-template; a @Component decorator is actually a @Directive decorator extended with template-oriented features.


The @Component metadata doesn't have directives attribute. See Component decorator.

Handling JSON Post Request in Go

type test struct {
    Test string `json:"test"`
}

func test(w http.ResponseWriter, req *http.Request) {
    var t test_struct

    body, _ := ioutil.ReadAll(req.Body)
    json.Unmarshal(body, &t)

    fmt.Println(t)
}

Getting all types that implement an interface

This worked for me. It loops though the classes and checks to see if they are derrived from myInterface

 foreach (Type mytype in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
                 .Where(mytype => mytype .GetInterfaces().Contains(typeof(myInterface)))) {
    //do stuff
 }

PHP: How to remove all non printable characters in a string?

All of the solutions work partially, and even below probably does not cover all of the cases. My issue was in trying to insert a string into a utf8 mysql table. The string (and its bytes) all conformed to utf8, but had several bad sequences. I assume that most of them were control or formatting.

function clean_string($string) {
  $s = trim($string);
  $s = iconv("UTF-8", "UTF-8//IGNORE", $s); // drop all non utf-8 characters

  // this is some bad utf-8 byte sequence that makes mysql complain - control and formatting i think
  $s = preg_replace('/(?>[\x00-\x1F]|\xC2[\x80-\x9F]|\xE2[\x80-\x8F]{2}|\xE2\x80[\xA4-\xA8]|\xE2\x81[\x9F-\xAF])/', ' ', $s);

  $s = preg_replace('/\s+/', ' ', $s); // reduce all multiple whitespace to a single space

  return $s;
}

To further exacerbate the problem is the table vs. server vs. connection vs. rendering of the content, as talked about a little here

Java Minimum and Maximum values in Array

Imho one of the simplest Solutions is: -

//MIN NUMBER
Collections.sort(listOfNumbers);
listOfNumbers.get(0);

//MAX NUMBER
Collections.sort(listOfNumbers);
Collections.reverse(listOfNumbers);
listOfNumbers.get(0);

Pointer to class data member "::*"

Another application are intrusive lists. The element type can tell the list what its next/prev pointers are. So the list does not use hard-coded names but can still use existing pointers:

// say this is some existing structure. And we want to use
// a list. We can tell it that the next pointer
// is apple::next.
struct apple {
    int data;
    apple * next;
};

// simple example of a minimal intrusive list. Could specify the
// member pointer as template argument too, if we wanted:
// template<typename E, E *E::*next_ptr>
template<typename E>
struct List {
    List(E *E::*next_ptr):head(0), next_ptr(next_ptr) { }

    void add(E &e) {
        // access its next pointer by the member pointer
        e.*next_ptr = head;
        head = &e;
    }

    E * head;
    E *E::*next_ptr;
};

int main() {
    List<apple> lst(&apple::next);

    apple a;
    lst.add(a);
}

How to find difference between two Joda-Time DateTimes in minutes

This will get you the difference between two DateTime objects in milliseconds:

DateTime d1 = new DateTime();
DateTime d2 = new DateTime();

long diffInMillis = d2.getMillis() - d1.getMillis();

How to find a whole word in a String in java

You can use regular expressions. Use Matcher and Pattern methods to get the desired output

Saving excel worksheet to CSV files with filename+worksheet name using VB

I think this is what you want...

Sub SaveWorksheetsAsCsv()

Dim WS As Excel.Worksheet
Dim SaveToDirectory As String

Dim CurrentWorkbook As String
Dim CurrentFormat As Long

CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook
SaveToDirectory = "H:\test\"

For Each WS In Application.ActiveWorkbook.Worksheets
    WS.SaveAs SaveToDirectory & WS.Name, xlCSV
Next

Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
Application.DisplayAlerts = True
' Temporarily turn alerts off to prevent the user being prompted
'  about overwriting the original file.

End Sub

Relative imports - ModuleNotFoundError: No module named x

Setting PYTHONPATH can also help with this problem.

Here is how it can be done on Windows

set PYTHONPATH=.

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

How can I solve equations in Python?

Python may be good, but it isn't God...

There are a few different ways to solve equations. SymPy has already been mentioned, if you're looking for analytic solutions.

If you're happy to just have a numerical solution, Numpy has a few routines that can help. If you're just interested in solutions to polynomials, numpy.roots will work. Specifically for the case you mentioned:

>>> import numpy
>>> numpy.roots([2,-6])
array([3.0])

For more complicated expressions, have a look at scipy.fsolve.

Either way, you can't escape using a library.

How do I use StringUtils in Java?

StringUtils is an Apache Commons project. You need to download and add the library to your classpath.

To use:

import org.apache.commons.lang3.StringUtils;

Python 3.6 install win32api?

Information provided by @Gord

As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

pip install pywin32

If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

pip install pywin32==xxx

This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.


Probably now undesirable solutions but certainly still valid as of September 2019

There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/

The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


EDIT

Since I posted my answer there are other alternatives to downloading the win32api module.

It is now available to download through pip using this command;

pip install pypiwin32

Also it can be installed from this GitHub repository as provided in comments by @Heath

What's the difference between a single precision and double precision floating point operation?

Basically single precision floating point arithmetic deals with 32 bit floating point numbers whereas double precision deals with 64 bit.

The number of bits in double precision increases the maximum value that can be stored as well as increasing the precision (ie the number of significant digits).

How to instantiate, initialize and populate an array in TypeScript?

There isn't a field initialization syntax like that for objects in JavaScript or TypeScript.

Option 1:

class bar {
    // Makes a public field called 'length'
    constructor(public length: number) { }
}

bars = [ new bar(1) ];

Option 2:

interface bar {
    length: number;
}

bars = [ {length: 1} ];

Perl - If string contains text?

If you just need to search for one string within another, use the index function (or rindex if you want to start scanning from the end of the string):

if (index($string, $substring) != -1) {
   print "'$string' contains '$substring'\n";
}

To search a string for a pattern match, use the match operator m//:

if ($string =~ m/pattern/) {
    print "'$string' matches the pattern\n";       
}

How do search engines deal with AngularJS applications?

Let's get definitive about AngularJS and SEO

Google, Yahoo, Bing, and other search engines crawl the web in traditional ways using traditional crawlers. They run robots that crawl the HTML on web pages, collecting information along the way. They keep interesting words and look for other links to other pages (these links, the amount of them and the number of them come into play with SEO).

So why don't search engines deal with javascript sites?

The answer has to do with the fact that the search engine robots work through headless browsers and they most often do not have a javascript rendering engine to render the javascript of a page. This works for most pages as most static pages don't care about JavaScript rendering their page, as their content is already available.

What can be done about it?

Luckily, crawlers of the larger sites have started to implement a mechanism that allows us to make our JavaScript sites crawlable, but it requires us to implement a change to our site.

If we change our hashPrefix to be #! instead of simply #, then modern search engines will change the request to use _escaped_fragment_ instead of #!. (With HTML5 mode, i.e. where we have links without the hash prefix, we can implement this same feature by looking at the User Agent header in our backend).

That is to say, instead of a request from a normal browser that looks like:

http://www.ng-newsletter.com/#!/signup/page

A search engine will search the page with:

http://www.ng-newsletter.com/?_escaped_fragment_=/signup/page

We can set the hash prefix of our Angular apps using a built-in method from ngRoute:

angular.module('myApp', [])
.config(['$location', function($location) {
  $location.hashPrefix('!');
}]);

And, if we're using html5Mode, we will need to implement this using the meta tag:

<meta name="fragment" content="!">

Reminder, we can set the html5Mode() with the $location service:

angular.module('myApp', [])
.config(['$location', 
function($location) {
  $location.html5Mode(true);
}]);

Handling the search engine

We have a lot of opportunities to determine how we'll deal with actually delivering content to search engines as static HTML. We can host a backend ourselves, we can use a service to host a back-end for us, we can use a proxy to deliver the content, etc. Let's look at a few options:

Self-hosted

We can write a service to handle dealing with crawling our own site using a headless browser, like phantomjs or zombiejs, taking a snapshot of the page with rendered data and storing it as HTML. Whenever we see the query string ?_escaped_fragment_ in a search request, we can deliver the static HTML snapshot we took of the page instead of the pre-rendered page through only JS. This requires us to have a backend that delivers our pages with conditional logic in the middle. We can use something like prerender.io's backend as a starting point to run this ourselves. Of course, we still need to handle the proxying and the snippet handling, but it's a good start.

With a paid service

The easiest and the fastest way to get content into search engine is to use a service Brombone, seo.js, seo4ajax, and prerender.io are good examples of these that will host the above content rendering for you. This is a good option for the times when we don't want to deal with running a server/proxy. Also, it's usually super quick.

For more information about Angular and SEO, we wrote an extensive tutorial on it at http://www.ng-newsletter.com/posts/serious-angular-seo.html and we detailed it even more in our book ng-book: The Complete Book on AngularJS. Check it out at ng-book.com.

How do I compile the asm generated by GCC?

You can embed the assembly code in a normal C program. Here's a good introduction. Using the appropriate syntax, you can also tell GCC you want to interact with variables declared in C. The program below instructs gcc that:

  • eax shall be foo
  • ebx shall be bar
  • the value in eax shall be stored in foo after the assembly code executed

\n

int main(void)
{
        int foo = 10, bar = 15;
        __asm__ __volatile__("addl  %%ebx,%%eax"
                             :"=a"(foo)
                             :"a"(foo), "b"(bar)
                             );
        printf("foo+bar=%d\n", foo);
        return 0;
}

Reading and writing to serial port in C on Linux

I've solved my problems, so I post here the correct code in case someone needs similar stuff.

Open Port

int USB = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY );

Set parameters

struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);

/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 ) {
   std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}

/* Save old tty parameters */
tty_old = tty;

/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);

/* Setting other Port Stuff */
tty.c_cflag     &=  ~PARENB;            // Make 8n1
tty.c_cflag     &=  ~CSTOPB;
tty.c_cflag     &=  ~CSIZE;
tty.c_cflag     |=  CS8;

tty.c_cflag     &=  ~CRTSCTS;           // no flow control
tty.c_cc[VMIN]   =  1;                  // read doesn't block
tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines

/* Make raw */
cfmakeraw(&tty);

/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
   std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}

Write

unsigned char cmd[] = "INIT \r";
int n_written = 0,
    spot = 0;

do {
    n_written = write( USB, &cmd[spot], 1 );
    spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);

It was definitely not necessary to write byte per byte, also int n_written = write( USB, cmd, sizeof(cmd) -1) worked fine.

At last, read:

int n = 0,
    spot = 0;
char buf = '\0';

/* Whole response*/
char response[1024];
memset(response, '\0', sizeof response);

do {
    n = read( USB, &buf, 1 );
    sprintf( &response[spot], "%c", buf );
    spot += n;
} while( buf != '\r' && n > 0);

if (n < 0) {
    std::cout << "Error reading: " << strerror(errno) << std::endl;
}
else if (n == 0) {
    std::cout << "Read nothing!" << std::endl;
}
else {
    std::cout << "Response: " << response << std::endl;
}

This one worked for me. Thank you all!

Duplicate AssemblyVersion Attribute

I came across the same when tried add GitVersion tool to update my version in AssemblyInfo.cs. Use VS2017 and .NET Core project. So I just mixed both worlds. My AssemblyInfo.cs contains only version info that was generated by GitVersion tool, my csproj contains remaingin things. Please note I don't use <GenerateAssemblyInfo>false</GenerateAssemblyInfo> I use attributes related to version only (see below). More details here AssemblyInfo properties.

AssemblyInfo.cs

[assembly: AssemblyVersion("0.2.1.0")]
[assembly: AssemblyFileVersion("0.2.1.0")]
[assembly: AssemblyInformationalVersion("0.2.1+13.Branch.master.Sha.119c35af0f529e92e0f75a5e6d8373912d457818")]

my.csproj contains all related to other assemblyu attributes:

<PropertyGroup>
...
<Company>SOME Company </Company>
<Authors>Some Authors</Authors>
<Product>SOME Product</Product>
...
<GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
<GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute><GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>

csproj maps to package tab at project properties

Responsive width Facebook Page Plugin

As of Graph API 2.3 Facebook provides code similar to the following for the comments plugin:

<div class="fb-comments"
    data-href="http://absolute.url"
    data-numposts="5">
</div>

Add a data-width="100%" to make it semi-responsive as follows:

<div class="fb-comments"
    data-href="http://absolute.url"
    data-numposts="5"
    data-width="100%">
</div>


Semi-responsive because, the plugin doesn't resize itself on page resize. The size depends on the size of the screen when the plugin loads.

Create an empty data.frame

If you already have an existent data frame, let's say df that has the columns you want, then you can just create an empty data frame by removing all the rows:

empty_df = df[FALSE,]

Notice that df still contains the data, but empty_df doesn't.

I found this question looking for how to create a new instance with empty rows, so I think it might be helpful for some people.

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I've tried these solutions and many others, but none of them quite worked out. Since this is the first answer on google, I'll add my solution here.

The method that worked well for me was to take relationships out of the picture during commits, so there was nothing for EF to screw up. I did this by re-finding the parent object in the DBContext, and deleting that. Since the re-found object's navigation properties are all null, the childrens' relationships are ignored during the commit.

var toDelete = db.Parents.Find(parentObject.ID);
db.Parents.Remove(toDelete);
db.SaveChanges();

Note that this assumes the foreign keys are setup with ON DELETE CASCADE, so when the parent row is removed, the children will be cleaned up by the database.

Why do I have ORA-00904 even when the column is present?

check the position of Column annotation in java class for the field For Example,consider one table with name STUDENT with 3 column(Name,Roll_No,Marks).

Then make sure you have added below annotation of column before Getter Method instead of Setter method. It will solve ur problem @Column(name = "Name", length = 100)

**@Column(name = "NAME", length = 100)
public String getName() {**
    return name;
}

    public void setName(String name) {
    this.name= name;
}

How to Get a Specific Column Value from a DataTable?

foreach (DataRow row in Datatable.Rows) 
{
    if (row["CountryName"].ToString() == userInput) 
    {
        return row["CountryID"];
    }
}

While this may not compile directly you should get the idea, also I'm sure it would be vastly superior to do the query through SQL as a huge datatable will take a long time to run through all the rows.

How can I tell jackson to ignore a property for which I don't have control over the source code?

Using Java Class

new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

Using Annotation

@JsonIgnoreProperties(ignoreUnknown=true)

Jquery change background color

This is how it should be:

Code:

$(function(){
  $("button").mouseover(function(){
    var $p = $("#P44");
    $p.stop()
      .css("background-color","yellow")
      .hide(1500, function() {
          $p.css("background-color","red")
            .show(1500);
      });
  });
});

Demo: http://jsfiddle.net/p7w9W/2/

Explanation:

You have to wait for the callback on the animating functions before you switch background color. You should also not use only numeric ID:s, and if you have an ID of your <p> there you shouldn't include a class in your selector.

I also enhanced your code (caching of the jQuery object, chaining, etc.)

Update: As suggested by VKolev the color is now changing when the item is hidden.

How to write trycatch in R

Since I just lost two days of my life trying to solve for tryCatch for an irr function, I thought I should share my wisdom (and what is missing). FYI - irr is an actual function from FinCal in this case where got errors in a few cases on a large data set.

  1. Set up tryCatch as part of a function. For example:

    irr2 <- function (x) {
      out <- tryCatch(irr(x), error = function(e) NULL)
      return(out)
    }
    
  2. For the error (or warning) to work, you actually need to create a function. I originally for error part just wrote error = return(NULL) and ALL values came back null.

  3. Remember to create a sub-output (like my "out") and to return(out).

gridview data export to excel in asp.net

Your sheet is blank because your string writer in null. Here is what may help

System.Web.UI.HtmlTextWriter htmlWrite =
    new HtmlTextWriter(stringWrite);

    GridView1.RenderControl(htmlWrite);

Here is the full code

protected void Button1_Click(object sender, EventArgs e)
{
    Response.Clear();

    Response.AddHeader("content-disposition", "attachment;
    filename=FileName.xls");


    Response.ContentType = "application/vnd.xls";

    System.IO.StringWriter stringWrite = new System.IO.StringWriter();

    System.Web.UI.HtmlTextWriter htmlWrite =
    new HtmlTextWriter(stringWrite);

    GridView1.RenderControl(htmlWrite);

    Response.Write(stringWrite.ToString());

    Response.End();

}

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

ASP.net using a form to insert data into an sql server table

Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </p>
    </form>
</body>

Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

The button is a web control Button Add a Click event to the button call it Button1Click:

void Button1Click(Object sender,EventArgs e) { }

Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

String firstBox = TextBox1.Text;

In the same way you can populate the objects when event occur.

Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.

Where is android_sdk_root? and how do I set it.?

I received the same error after installing android studio and trying to run hello world. I think you need to use the SDK Manager inside Android Studio to install some things first.

android_sdk_root error

Open up Android Studio, and click on the SDK Manager in the toolbar.

SDK Manager

Now install the SDK tools you need.

  • Tools -> Android SDK Tools
  • Tools -> Android SDK Platform-tools
  • Tools -> Android SDK Build-tools (highest version)

For each Android release you are targeting, hit the appropriate Android X.X folder and select (at a minimum):

  • SDK Platform
  • A system image for the emulator, such as ARM EABI v7a System Image

The SDK Manager will run (this can take a while) and download and install the various SDKs.

Inside Android Studio, File->Project Structure will show you where your Android sdks are installed. As you can see mine is c:\users\Joe\AppData\Local\Android\sdk1.

enter image description here

If I navigate to C:\Users\Joe\AppData\Local\Android\sdk1\sources you can see the various Android SDKs installed there...

SDK Directories

How to create dictionary and add key–value pairs dynamically?

You could create a class Dictionary so you can interact with the Dictionary list easily:

_x000D_
_x000D_
class Dictionary {_x000D_
  constructor() {_x000D_
    this.items = {};_x000D_
  }_x000D_
  has(key) {_x000D_
    return key in this.items;_x000D_
  }_x000D_
  set(key,value) {_x000D_
    this.items[key] = value;_x000D_
  }_x000D_
  delete(key) {_x000D_
    if( this.has(key) ){_x000D_
      delete this.items[key]_x000D_
      return true;_x000D_
    }_x000D_
    return false;_x000D_
  }_x000D_
}_x000D_
_x000D_
var d = new Dictionary();_x000D_
d.set(1, "value1")_x000D_
d.set(2, "value2")_x000D_
d.set(3, "value3")_x000D_
console.log(d.has(2));_x000D_
d.delete(2);_x000D_
console.log(d.has(2));
_x000D_
_x000D_
_x000D_

How to convert char to int?

You can try something like this:

int val = Convert.ToInt32("" + '1');

jQuery: Adding two attributes via the .attr(); method

Should work:

.attr({
    target:"nw", 
    title:"Opens in a new window",
    "data-value":"internal link" // attributes which contain dash(-) should be covered in quotes.
});

Note:

" When setting multiple attributes, the quotes around attribute names are optional.

WARNING: When setting the 'class' attribute, you must always use quotes!

From the jQuery documentation (Sep 2016) for .attr:

Attempting to change the type attribute on an input or button element created via document.createElement() will throw an exception on Internet Explorer 8 or older.

Edit:
For future reference... To get a single attribute you would use

var strAttribute = $(".something").attr("title");

To set a single attribute you would use

$(".something").attr("title","Test");

To set multiple attributes you need to wrap everything in { ... }

$(".something").attr( { title:"Test", alt:"Test2" } );

Edit - If you're trying to get/set the 'checked' attribute from a checkbox...

You will need to use prop() as of jQuery 1.6+

the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

...the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does

So to get the checked status of a checkbox, you should use:

$('#checkbox1').prop('checked'); // Returns true/false

Or to set the checkbox as checked or unchecked you should use:

$('#checkbox1').prop('checked', true); // To check it
$('#checkbox1').prop('checked', false); // To uncheck it

What is the recommended way to delete a large number of items from DynamoDB?

According to the DynamoDB documentation you could just delete the full table.

See below:

"Deleting an entire table is significantly more efficient than removing items one-by-one, which essentially doubles the write throughput as you do as many delete operations as put operations"

If you wish to delete only a subset of your data, then you could make separate tables for each month, year or similar. This way you could remove "last month" and keep the rest of your data intact.

This is how you delete a table in Java using the AWS SDK:

DeleteTableRequest deleteTableRequest = new DeleteTableRequest()
  .withTableName(tableName);
DeleteTableResult result = client.deleteTable(deleteTableRequest);

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

The website was running fine then suddenly it started to display this same error 404 message (The origin server did not find a current representation for the target resource or is not willing to disclose that one exists), Perhaps because of switching servers back and forward from Tomcat 9 to 8 and 7

In my case, i only had to update the project which was causing this error then restart the specific tomcat version. You may also need to Maven Clean and Maven Install after the "Maven Update Project"

Select Maven Update ProjectUpdate and Refresh Workspace

Double quotes within php script echo

You need to escape ", so it won't be interpreted as end of string. Use \ to escape it:

echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";

Read more: strings and escape sequences

Tri-state Check box in HTML?

You can use radio groups to achieve that functionality:

<input type="radio" name="choice" value="yes" />Yes
<input type="radio" name="choice" value="No" />No
<input type="radio" name="choice" value="null" />null

How to check if a variable is empty in python?

See also this previous answer which recommends the not keyword

How to check if a list is empty in Python?

It generalizes to more than just lists:

>>> a = ""
>>> not a
True

>>> a = []
>>> not a
True

>>> a = 0
>>> not a
True

>>> a = 0.0
>>> not a
True

>>> a = numpy.array([])
>>> not a
True

Notably, it will not work for "0" as a string because the string does in fact contain something - a character containing "0". For that you have to convert it to an int:

>>> a = "0"
>>> not a
False

>>> a = '0'
>>> not int(a)
True

Check if a key exists inside a json object

I change your if statement slightly and works (also for inherited obj - look on snippet)

if(!("merchant_id" in thisSession)) alert("yeah");

_x000D_
_x000D_
var sessionA = {_x000D_
  amt: "10.00",_x000D_
  email: "[email protected]",_x000D_
  merchant_id: "sam",_x000D_
  mobileNo: "9874563210",_x000D_
  orderID: "123456",_x000D_
  passkey: "1234",_x000D_
}_x000D_
_x000D_
var sessionB = {_x000D_
  amt: "10.00",_x000D_
  email: "[email protected]",_x000D_
  mobileNo: "9874563210",_x000D_
  orderID: "123456",_x000D_
  passkey: "1234",_x000D_
}_x000D_
_x000D_
_x000D_
var sessionCfromA = Object.create(sessionA); // inheritance_x000D_
sessionCfromA.name = 'john';_x000D_
_x000D_
_x000D_
if (!("merchant_id" in sessionA)) alert("merchant_id not in sessionA");_x000D_
if (!("merchant_id" in sessionB)) alert("merchant_id not in sessionB");_x000D_
if (!("merchant_id" in sessionCfromA)) alert("merchant_id not in sessionCfromA");_x000D_
_x000D_
if ("merchant_id" in sessionA) alert("merchant_id in sessionA");_x000D_
if ("merchant_id" in sessionB) alert("merchant_id in sessionB");_x000D_
if ("merchant_id" in sessionCfromA) alert("merchant_id in sessionCfromA");
_x000D_
_x000D_
_x000D_

Javascript string/integer comparisons

You can use Number() function also since it converts the object argument to a number that represents the object's value.

Eg: javascript:alert( Number("2") > Number("10"))

Windows Scipy Install: No Lapack/Blas Resources Found

The solution to the absence of BLAS/LAPACK libraries for SciPy installations on Windows 7 64-bit is described here:

http://www.scipy.org/scipylib/building/windows.html

Installing Anaconda is much easier, but you still don't get Intel MKL or GPU support without paying for it (they are in the MKL Optimizations and Accelerate add-ons for Anaconda - I'm not sure if they use PLASMA and MAGMA either). With MKL optimization, numpy has outperformed IDL on large matrix computations by 10-fold. MATLAB uses the Intel MKL library internally and supports GPU computing, so one might as well use that for the price if they're a student ($50 for MATLAB + $10 for the Parallel Computing Toolbox). If you get the free trial of Intel Parallel Studio, it comes with the MKL library, as well as C++ and FORTRAN compilers that will come in handy if you want to install BLAS and LAPACK from MKL or ATLAS on Windows:

http://icl.cs.utk.edu/lapack-for-windows/lapack/

Parallel Studio also comes with the Intel MPI library, useful for cluster computing applications and their latest Xeon processsors. While the process of building BLAS and LAPACK with MKL optimization is not trivial, the benefits of doing so for Python and R are quite large, as described in this Intel webinar:

https://software.intel.com/en-us/articles/powered-by-mkl-accelerating-numpy-and-scipy-performance-with-intel-mkl-python

Anaconda and Enthought have built businesses out of making this functionality and a few other things easier to deploy. However, it is freely available to those willing to do a little work (and a little learning).

For those who use R, you can now get MKL optimized BLAS and LAPACK for free with R Open from Revolution Analytics.

EDIT: Anaconda Python now ships with MKL optimization, as well as support for a number of other Intel library optimizations through the Intel Python distribution. However, GPU support for Anaconda in the Accelerate library (formerly known as NumbaPro) is still over $10k USD! The best alternatives for that are probably PyCUDA and scikit-cuda, as copperhead (essentially a free version of Anaconda Accelerate) unfortunately ceased development five years ago. It can be found here if anybody wants to pick up where they left off.

How to update a single library with Composer?

To install doctrine/doctrine-fixtures-bundle with version 2.1.* and minimum stability @dev use this:

composer require doctrine/doctrine-fixtures-bundle:2.1.*@dev

then to update only this single package:

composer update doctrine/doctrine-fixtures-bundle

How do I read from parameters.yml in a controller in symfony2?

I send you an example with swiftmailer:

parameters.yml

recipients: [email1, email2, email3]

services:

your_service_name:
        class: your_namespace
        arguments: ["%recipients%"]

the class of the service:

protected $recipients;

public function __construct($recipients)
{
    $this->recipients = $recipients;
}

push() a two-dimensional array

The solution below uses a double loop to add data to the bottom of a 2x2 array in the Case 3. The inner loop pushes selected elements' values into a new row array. The outerloop then pushes the new row array to the bottom of an existing array (see Newbie: Add values to two-dimensional array with for loops, Google Apps Script).

In this example, I created a function that extracts a section from an existing array. The extracted section can be a row (full or partial), a column (full or partial), or a 2x2 section of the existing array. A new blank array (newArr) is filled by pushing the relevant section from the existing array (arr) into the new array.

 function arraySection(arr, r1, c1, rLength, cLength) {      
   rowMax = arr.length;
    if(isNaN(rowMax)){rowMax = 1};
   colMax = arr[0].length;
   if(isNaN(colMax)){colMax = 1};
   var r2 = r1 + rLength - 1;
   var c2 = c1 + cLength - 1;

   if ((r1< 0 || r1 > r2 || r1 > rowMax || (r1 | 0) != r1) || (r2 < 0 || 
     r2 > rowMax || (r2 | 0) != r2)|| (c1< 0 || c1 > c2 || c1 > colMax || 
   (c1 | 0) != c1) ||(c2 < 0 || c2 > colMax || (c2 | 0) != c2)){
        throw new Error(
        'arraySection: invalid input')       
        return;
     };
   var newArr = [];

// Case 1: extracted section is a column array, 
//          all elements are in the same column
 if (c1 == c2){
   for (var i = r1; i <= r2; i++){ 
         // Logger.log("arr[i][c1] for i = " + i);
         // Logger.log(arr[i][c1]);
     newArr.push([arr[i][c1]]); 
     };
    };  

// Case 2: extracted section is a row array, 
//          all elements are in the same row
  if (r1 == r2 && c1 != c2){
    for (var j = c1; j <= c2; j++){ 
      newArr.push(arr[r1][j]); 
      };
   };  

// Case 3: extracted section is a 2x2 section 
    if (r1 != r2 && c1 != c2){     
     for (var i = r1; i <= r2; i++) {
          rowi = [];
       for (var j = c1; j <= c2; j++) {
          rowi.push(arr[i][j]);
        }
       newArr.push(rowi)
      };
    };
   return(newArr);
  };

Find duplicate lines in a file and count how many time each line was duplicated?

To find duplicate counts use below command as requested by you :

sort filename | uniq -c | awk '{print $2, $1}'

Better way to revert to a previous SVN revision of a file?

svn merge will merge revisions, not revert them. i.e. if you have some addition in your HEAD version then merge that with a previous revision, then the change will persist.

I use svn cat then redirect it into the file:

svn cat -r 851 l3toks.dtx > l3toks.dtx

Then you have the 851 content in that file and can check it back in.

How to create a directory and give permission in single command

When the directory already exist:

mkdir -m 777 /path/to/your/dir

When the directory does not exist and you want to create the parent directories:

mkdir -m 777 -p /parent/dirs/to/create/your/dir

Passing environment-dependent variables in webpack

I'm not a huge fan of...

new webpack.DefinePlugin({
  'process.env': envVars
}),

...as it does not provides any type of security. instead, you end up boosting your secret stuff, unless you add a webpack to gitignore ??? there is a better solution.

Basically with this config once you compile your code all the process env variables will be removed from the entire code, there is not going to be a single process.env.VAR up thanks to the babel plugin transform-inline-environment-variables PS if you do not want to end up with a whole bunch of undefines, make sure you call the env.js before webpack calls babel-loader, that's why it is the first thing webpack calls. the array of vars in babel.config.js file must match the object on env.js. now there is only one mow thing to do. add a .env file put all your env variables there, the file must be at the root of the project or feel free to add it where ever u want, just make sure to set the same location on the env.js file and also add it to gitignore

const dotFiles = ['.env'].filter(Boolean);

if (existsSync(dotFiles)) {
    require("dotenv-expand")(require("dotenv").config((dotFiles)));
}

If you want to see the whole babel + webpack + ts get it from heaw https://github.com/EnetoJara/Node-typescript-babel-webpack.git

and same logic applies to react and all the other

config
---webpack.js
---env.js
src
---source code world
.env
bunch of dotFiles

env.js

"use strict";
/***
I took the main idea from CRA, but mine is more cooler xD
*/
const {realpathSync, existsSync} = require('fs');
const {resolve, isAbsolute, delimiter} = require('path');

const NODE_ENV = process.env.NODE_ENV || "development";

const appDirectory = realpathSync(process.cwd());

if (typeof NODE_ENV !== "string") {
    throw new Error("falle and stuff");
}

const dotFiles = ['.env'].filter(Boolean);

if (existsSync(dotFiles)) {
    require("dotenv-expand")(require("dotenv").config((dotFiles)));
}

process.env.NODE_PATH = (process.env.NODE_PATH || "")
    .split(delimiter)
    .filter(folder => folder && isAbsolute(folder))
    .map(folder => resolve(appDirectory, folder))
    .join(delimiter);

const ENETO_APP = /^ENETO_APP_/i;

module.exports = (function () {
    const raw = Object.keys ( process.env )
        .filter ( key => ENETO_APP.test ( key ) )
        .reduce ( ( env, key ) => {
                env[ key ] = process.env[ key ];
                return env;
            },
            {
                BABEL_ENV: process.env.ENETO_APP_BABEL_ENV,
                ENETO_APP_DB_NAME: process.env.ENETO_APP_DB_NAME,
                ENETO_APP_DB_PASSWORD: process.env.ENETO_APP_DB_PASSWORD,
                ENETO_APP_DB_USER: process.env.ENETO_APP_DB_USER,
                GENERATE_SOURCEMAP: process.env.ENETO_APP_GENERATE_SOURCEMAP,
                NODE_ENV: process.env.ENETO_APP_NODE_ENV,
                PORT: process.env.ENETO_APP_PORT,
                PUBLIC_URL: "/"
            } );

    const stringyField = {
        "process.env": Object.keys(raw).reduce((env, key)=> {
            env[key]=JSON.stringify(raw[key]);
            return env;
        },{}),

    };

    return {
        raw, stringyField
    }
})();

webpack file with no plugins troll

"use strict";

require("core-js");
require("./env.js");

const path = require("path");
const nodeExternals = require("webpack-node-externals");

module.exports = env => {
    return {
        devtool: "source-map",
        entry: path.join(__dirname, '../src/dev.ts'),
        externals: [nodeExternals()],
        module: {
            rules: [
                {
                    exclude: /node_modules/,
                    test: /\.ts$/,
                    use: [
                        {
                            loader: "babel-loader",
                        },
                        {
                            loader: "ts-loader"
                        }
                    ],
                },
                {
                    test: /\.(png|jpg|gif)$/,
                    use: [
                        {
                            loader: "file-loader",
                        },
                    ],
                },
            ],
        },
        node: {
            __dirname: false,
            __filename: false,
        },
        optimization: {
            splitChunks: {
                automaticNameDelimiter: "_",
                cacheGroups: {
                    vendor: {
                        chunks: "initial",
                        minChunks: 2,
                        name: "vendor",
                        test: /[\\/]node_modules[\\/]/,
                    },
                },
            },
        },
        output: {
            chunkFilename: "main.chunk.js",
            filename: "name-bundle.js",
            libraryTarget: "commonjs2",
        },
        plugins: [],
        resolve: {
            extensions: ['.ts', '.js']
        }   ,
        target: "node"
    };
};

babel.config.js

module.exports = api => {

    api.cache(() => process.env.NODE_ENV);

    return {

        plugins: [
            ["@babel/plugin-proposal-decorators", { legacy: true }],
            ["@babel/plugin-transform-classes", {loose: true}],
            ["@babel/plugin-external-helpers"],
            ["@babel/plugin-transform-runtime"],
            ["@babel/plugin-transform-modules-commonjs"],
            ["transform-member-expression-literals"],
            ["transform-property-literals"],
            ["@babel/plugin-transform-reserved-words"],
            ["@babel/plugin-transform-property-mutators"],
            ["@babel/plugin-transform-arrow-functions"],
            ["@babel/plugin-transform-block-scoped-functions"],
            [
                "@babel/plugin-transform-async-to-generator",
                {
                    method: "coroutine",
                    module: "bluebird",
                },
            ],
            ["@babel/plugin-proposal-async-generator-functions"],
            ["@babel/plugin-transform-block-scoping"],
            ["@babel/plugin-transform-computed-properties"],
            ["@babel/plugin-transform-destructuring"],
            ["@babel/plugin-transform-duplicate-keys"],
            ["@babel/plugin-transform-for-of"],
            ["@babel/plugin-transform-function-name"],
            ["@babel/plugin-transform-literals"],
            ["@babel/plugin-transform-object-super"],
            ["@babel/plugin-transform-shorthand-properties"],
            ["@babel/plugin-transform-spread"],
            ["@babel/plugin-transform-template-literals"],
            ["@babel/plugin-transform-exponentiation-operator"],
            ["@babel/plugin-proposal-object-rest-spread"],
            ["@babel/plugin-proposal-do-expressions"],
            ["@babel/plugin-proposal-export-default-from"],
            ["@babel/plugin-proposal-export-namespace-from"],
            ["@babel/plugin-proposal-logical-assignment-operators"],
            ["@babel/plugin-proposal-throw-expressions"],
            [
                "transform-inline-environment-variables",
                {
                    include: [
                        "ENETO_APP_PORT",
                        "ENETO_APP_NODE_ENV",
                        "ENETO_APP_BABEL_ENV",
                        "ENETO_APP_DB_NAME",
                        "ENETO_APP_DB_USER",
                        "ENETO_APP_DB_PASSWORD",
                    ],
                },
            ],
        ],
        presets: [["@babel/preset-env",{
            targets: {
                node: "current",
                esmodules: true
            },
            useBuiltIns: 'entry',
            corejs: 2,
            modules: "cjs"
        }],"@babel/preset-typescript"],
    };
};

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

What does the 'static' keyword do in a class?

Static means that you don't have to create an instance of the class to use the methods or variables associated with the class. In your example, you could call:

Hello.main(new String[]()) //main(...) is declared as a static function in the Hello class

directly, instead of:

Hello h = new Hello();
h.main(new String[]()); //main(...) is a non-static function linked with the "h" variable

From inside a static method (which belongs to a class) you cannot access any members which are not static, since their values depend on your instantiation of the class. A non-static Clock object, which is an instance member, would have a different value/reference for each instance of your Hello class, and therefore you could not access it from the static portion of the class.

Find closing HTML tag in Sublime Text

It's built in from Sublime Editor 2 at least. Just press the following and it balances the HTML-tag

Shortcut (Mac): Shift + Command + A

Shortcut (Windows): Control + Alt + A

How to toggle font awesome icon on click?

Simply call jQuery's toggleClass() on the i element contained within your a element(s) to toggle either the plus and minus icons:

...click(function() {
    $(this).find('i').toggleClass('fa-minus-circle fa-plus-circle');
});

Note that this assumes that a class of fa-plus-circle is added to your i element by default.

JSFiddle demo.

Merge Cell values with PHPExcel - PHP

$this->excel->setActiveSheetIndex(0)->mergeCells("A".($p).":B".($p)); for dynamic merging of cells

How do I download code using SVN/Tortoise from Google Code?

See my answer to a very similar question here: How to download/checkout a project from Google Code in Windows?

In brief: If you don't want to install anything but do want to download an SVN or GIT repository, then you can use this: http://downloadsvn.codeplex.com

How to assign an exec result to a sql variable?

I had the same question. While there are good answers here I decided to create a table-valued function. With a table (or scalar) valued function you don't have to change your stored proc. I simply did a select from the table-valued function. Note that the parameter (MyParameter is optional).

CREATE FUNCTION [dbo].[MyDateFunction] 
(@MyParameter varchar(max))
RETURNS TABLE 
AS
RETURN 
(
    --- Query your table or view or whatever and select the results.
    SELECT DateValue FROM MyTable WHERE ID = @MyParameter;
)

To assign to your variable you simply can do something like:

Declare @MyDate datetime;
SET @MyDate = (SELECT DateValue FROM MyDateFunction(@MyParameter));

You can also use a scalar valued function:

CREATE FUNCTION TestDateFunction()  
RETURNS datetime  
BEGIN  
    RETURN (SELECT GetDate());
END

Then you can simply do

Declare @MyDate datetime;
SET @MyDate = (Select dbo.TestDateFunction());
SELECT @MyDate;

Align <div> elements side by side

Beware float: left

…there are many ways to align elements side-by-side.

Below are the most common ways to achieve two elements side-by-side…

Demo: View/edit all the below examples on Codepen


Basic styles for all examples below…

Some basic css styles for parent and child elements in these examples:

.parent {
  background: mediumpurple;
  padding: 1rem;
}
.child {
  border: 1px solid indigo;
  padding: 1rem;
}

float:left

Using the float solution my have unintended affect on other elements. (Hint: You may need to use a clearfix.)

html

<div class='parent'>
  <div class='child float-left-child'>A</div>
  <div class='child float-left-child'>B</div>
</div>

css

.float-left-child {
  float: left;
}

display:inline-block

html

<div class='parent'>
  <div class='child inline-block-child'>A</div>
  <div class='child inline-block-child'>B</div>
</div>

css

.inline-block-child {
  display: inline-block;
}

Note: the space between these two child elements can be removed, by removing the space between the div tags:

display:inline-block (no space)

html

<div class='parent'>
  <div class='child inline-block-child'>A</div><div class='child inline-block-child'>B</div>
</div>

css

.inline-block-child {
  display: inline-block;
}

display:flex

html

<div class='parent flex-parent'>
  <div class='child flex-child'>A</div>
  <div class='child flex-child'>B</div>
</div>

css

.flex-parent {
  display: flex;
}
.flex-child {
  flex: 1;
}

display:inline-flex

html

<div class='parent inline-flex-parent'>
  <div class='child'>A</div>
  <div class='child'>B</div>
</div>

css

.inline-flex-parent {
  display: inline-flex;
}

display:grid

html

<div class='parent grid-parent'>
  <div class='child'>A</div>
  <div class='child'>B</div>
</div>

css

.grid-parent {
  display: grid;
  grid-template-columns: 1fr 1fr
}

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

Python, add items from txt file into a list

Read the documentation:

with open('names.txt', 'r') as f:
    myNames = f.readlines()

The others already provided answers how to get rid of the newline character.

Update:

Fred Larson provides a nice solution in his comment:

with open('names.txt', 'r') as f:
    myNames = [line.strip() for line in f]

Dictionary text file

There's also WordNet. Its data files format are well-documented.
I used it for building an embeddable dictionary library for iOS developers (www.lexicontext.com) and also in one of my apps.

How do I get the resource id of an image if I know its name?

You can use this function to get a Resource ID:

public static int getResourseId(Context context, String pVariableName, String pResourcename, String pPackageName) throws RuntimeException {
    try {
        return context.getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
    } catch (Exception e) {
        throw new RuntimeException("Error getting Resource ID.", e)
    } 
}


So if you want to get a Drawable Resource ID, you can call the method like this:

getResourseId(MyActivity.this, "myIcon", "drawable", getPackageName());

(or from a fragment):

getResourseId(getActivity(), "myIcon", "drawable", getActivity().getPackageName());


For a String Resource ID you can call it like this:

getResourseId(getActivity(), "myAppName", "string", getActivity().getPackageName());

etc...


Careful: It throws a RuntimeException if it fails to find the Resource ID. Be sure to recover properly in production.

Read this

Launch Android application without main Activity and start Service on launching application

You said you didn't want to use a translucent Activity, but that seems to be the best way to do this:

  1. In your Manifest, set the Activity theme to Theme.Translucent.NoTitleBar.
  2. Don't bother with a layout for your Activity, and don't call setContentView().
  3. In your Activity's onCreate(), start your Service with startService().
  4. Exit the Activity with finish() once you've started the Service.

In other words, your Activity doesn't have to be visible; it can simply make sure your Service is running and then exit, which sounds like what you want.

I would highly recommend showing at least a Toast notification indicating to the user that you are launching the Service, or that it is already running. It is very bad user experience to have a launcher icon that appears to do nothing when you press it.

JavaScript: Is there a way to get Chrome to break on all errors?

Edit: The original link I answered with is now invalid.The newer URL would be https://developers.google.com/web/tools/chrome-devtools/javascript/add-breakpoints#exceptions as of 2016-11-11.

I realize this question has an answer, but it's no longer accurate. Use the link above ^


(link replaced by edited above) - you can now set it to break on all exceptions or just unhandled ones. (Note that you need to be in the Sources tab to see the button.)

Chrome's also added some other really useful breakpoint capabilities now, such as breaking on DOM changes or network events.

Normally I wouldn't re-answer a question, but I had the same question myself, and I found this now-wrong answer, so I figured I'd put this information in here for people who came along later in searching. :)

Windows equivalent of linux cksum command

In the year 2019, Microsoft offers the following solution for Windows 10. This solution works for SHA256 checksum.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-filehash?view=powershell-6

Press the Windows key. Type PowerShell. Select Windows Powershell. Press Enter key. Paste the command

Get-FileHash C:\Users\Donald\Downloads\File-to-be-checked-by-sha256.exe | Format-List

Replace File-to-be-checked-by-sha256.exe by the name of your file to be checked.

Replace the path to your path where the file is. Press Enter key. Powershell shows then the following

Algorithm : SHA256 Hash : 123456789ABCDEFGH1234567890... Path : C:\Users\Donald\Downloads\File-to-be-checked-by-sha256.exe

how to properly display an iFrame in mobile safari

If the iFrame content is not yours then the solution below will not work.

With Android all you need to do is to surround the iframe with a DIV and set the height on the div to document.documentElement.clientHeight. IOS, however, is a different animal. Although I have not yet tried Sharon's solution it does seem like a good solution. I did find a simpler solution but it only works with IOS 5.+.

Surround your iframe element with a DIV (lets call it scroller), set the height of the DIV and make sure that the new DIV has the following styling:

$('#scroller').css({'overflow' : 'auto', '-webkit-overflow-scrolling' : 'touch'});

This alone will work but you will notice that in most implementations the content in the iframe goes blank when scrolling and is basically rendered useless. My understanding is that this behavior has been reported as a bug to Apple as early as iOS 5.0. To get around that problem, find the body element in the iframe and add -webkit-transform', 'translate3d(0, 0, 0) like so:

$('#contentIframe').contents().find('body').css('-webkit-transform', 'translate3d(0, 0, 0)');

If your app or iframe is heavy on memory usage you might get a hitchy scroll for which you might need to use Sharon's solution.

How can you test if an object has a specific property?

Real similar to a javascript check:

foreach($member in $members)
{
    if($member.PropertyName)
    {
        Write $member.PropertyName
    }
    else
    {
        Write "Nope!"
    }
}

How to add an element to the beginning of an OrderedDict?

This is now possible with move_to_end(key, last=True)

>>> d = OrderedDict.fromkeys('abcde')
>>> d.move_to_end('b')
>>> ''.join(d.keys())
'acdeb'
>>> d.move_to_end('b', last=False)
>>> ''.join(d.keys())
'bacde'

https://docs.python.org/3/library/collections.html#collections.OrderedDict.move_to_end

User Authentication in ASP.NET Web API

I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.

The client side code (CoffeeScript) to get the token is:

getAuthenticationToken = (username, password) ->
    dataToSend = "username=" + username + "&password=" + password
    dataToSend += "&grant_type=password"
    $.post("/token", dataToSend).success saveAccessToken

If successful the following is called, which saves the authentication token locally:

saveAccessToken = (response) ->
    window.authenticationToken = response.access_token

Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:

{ "Authorization": "Bearer " + window.authenticationToken }

What is 'Context' on Android?

Context is an interface to global information about an application environment. It's an abstract class whose implementation is provided by the Android system.

Context allows access to application-specific resources and classes, as well as calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

Here is Example

 public class MyActivity extends Activity {

      public void Testing() {

      Context actContext = this; /*returns the Activity Context since   Activity extends Context.*/

      Context appContext = getApplicationContext();    /*returns the context of the single, global Application object of the current process. */

      Button BtnShowAct1 = (Button) findViewById(R.id.btnGoToAct1);
      Context BtnContext = BtnShowAct1.getContext();   /*returns the context of the View. */

For more details you can visit http://developer.android.com/reference/android/content/Context.html

Downloading folders from aws s3, cp or sync?

In case you need to use another profile, especially cross account. you need to add the profile in the config file

[profile profileName]
region = us-east-1
role_arn = arn:aws:iam::XXX:role/XXXX
source_profile = default

and then if you are accessing only a single file

aws s3 cp s3://crossAccountBucket/dir localdir --profile profileName

Combining two expressions (Expression<Func<T, bool>>)

I suggest one more improvement to PredicateBuilder and ExpressionVisitor solutions. I called it UnifyParametersByName and you can find it in MIT library of mine: LinqExprHelper. It allows for combining arbitary lambda expressions. Usually the questions are asked about predicate expression, but this idea extends to projection expressions as well.

The following code employs a method ExprAdres which creates a complicated parametrized expression, using inline lambda. This complicated expression is coded only once, and then reused, thanks to the LinqExprHelper mini-library.

public IQueryable<UbezpExt> UbezpFull
{
    get
    {
        System.Linq.Expressions.Expression<
            Func<UBEZPIECZONY, UBEZP_ADRES, UBEZP_ADRES, UbezpExt>> expr =
            (u, parAdrM, parAdrZ) => new UbezpExt
            {
                Ub = u,
                AdrM = parAdrM,
                AdrZ = parAdrZ,
            };

        // From here an expression builder ExprAdres is called.
        var expr2 = expr
            .ReplacePar("parAdrM", ExprAdres("M").Body)
            .ReplacePar("parAdrZ", ExprAdres("Z").Body);
        return UBEZPIECZONY.Select((Expression<Func<UBEZPIECZONY, UbezpExt>>)expr2);
    }
}

And this is the subexpression building code:

public static Expression<Func<UBEZPIECZONY, UBEZP_ADRES>> ExprAdres(string sTyp)
{
    return u => u.UBEZP_ADRES.Where(a => a.TYP_ADRESU == sTyp)
        .OrderByDescending(a => a.DATAOD).FirstOrDefault();
}

What I tried to achieve was to perform parametrized queries without need to copy-paste and with ability to use inline lambdas, which are so pretty. Without all these helper-expression stuff, I would be forced to create whole query in one go.

Get a CSS value with JavaScript

If you're into libraries, why not MyLibrary and getStyle.

The jQuery css method is misnamed, CSS is just one way of setting styles and doesn't necessarily represent the actual values of an element's style properties.

How to resize an image to a specific size in OpenCV?

Make a useful function like this:

IplImage* img_resize(IplImage* src_img, int new_width,int new_height)
{
    IplImage* des_img;
    des_img=cvCreateImage(cvSize(new_width,new_height),src_img->depth,src_img->nChannels);
    cvResize(src_img,des_img,CV_INTER_LINEAR);
    return des_img;
} 

Set ImageView width and height programmatically?

The best and easiest way to set a button dynamically is

 Button index=new Button(this);
 int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, getResources().getDisplayMetrics());             
 int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 42, getResources().getDisplayMetrics());

The above height and width are in pixels px. 45 being the height in dp and 42 being the width in dp.

 index.setLayoutParams(new <Parent>.LayoutParams(width, height));

So, for example, if you've placed your button within a TableRow within a TableLayout, you should have it as TableRow.LayoutParams

 index.setLayoutParams(new TableRow.LayoutParams(width, height));

c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)

If you will place your definitions in this order then the code will be compiled

class Ball;

class Player {
public:
    void doSomething(Ball& ball);
private:
};

class Ball {
public:
    Player& PlayerB;
    float ballPosX = 800;
private:

};

void Player::doSomething(Ball& ball) {
    ball.ballPosX += 10;                   // incomplete type error occurs here.
}

int main()
{
}

The definition of function doSomething requires the complete definition of class Ball because it access its data member.

In your code example module Player.cpp has no access to the definition of class Ball so the compiler issues an error.

Best way to change the background color for an NSView

In swift you can subclass NSView and do this

class MyView:NSView {
    required init?(coder: NSCoder) {
        super.init(coder: coder);

        self.wantsLayer = true;
        self.layer?.backgroundColor = NSColor.redColor().CGColor;
    }
}

varbinary to string on SQL Server

For a VARBINARY(MAX) column, I had to use NVARCHAR(MAX):

cast(Content as nvarchar(max))

Or

CONVERT(NVARCHAR(MAX), Content, 0)
VARCHAR(MAX) didn't show the entire value

How do I draw a shadow under a UIView?

If you would like to use StoryBoard and wouldnt like to keep typing in runtime attributes, you can easily create an extension to views and make them usable in storyboard.

Step 1. create extension

extension UIView {

@IBInspectable var shadowRadius: CGFloat {
    get {
        return layer.shadowRadius
    }
    set {
        layer.shadowRadius = newValue
    }
}

@IBInspectable var shadowOpacity: Float {
    get {
        return layer.shadowOpacity
    }
    set {
        layer.shadowOpacity = newValue
    }
}

@IBInspectable var shadowOffset: CGSize {
    get {
        return layer.shadowOffset
    }
    set {
        layer.shadowOffset = newValue
    }
}

@IBInspectable var maskToBound: Bool {
    get {
        return layer.masksToBounds
    }
    set {
        layer.masksToBounds = newValue
    }
}
}

step 2. you can now use these attributes in storyboardstoryboard image

get number of columns of a particular row in given excel using Java

There are two Things you can do

use

int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();

or

int noOfColumns = sh.getRow(0).getLastCellNum();

There is a fine difference between them

  1. Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)
  2. Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'

Implement division with bit-wise operator

For integers:

public class Division {

    public static void main(String[] args) {
        System.out.println("Division: " + divide(100, 9));
    }

    public static int divide(int num, int divisor) {
        int sign = 1;
        if((num > 0 && divisor < 0) || (num < 0 && divisor > 0))
            sign = -1;

        return divide(Math.abs(num), Math.abs(divisor), Math.abs(divisor)) * sign;
    }

    public static int divide(int num, int divisor, int sum) {
        if (sum > num) {
            return 0;
        }

        return 1 + divide(num, divisor, sum + divisor);
    }
}

Casting to string in JavaScript

In addition to all the above, one should note that, for a defined value v:

  • String(v) calls v.toString()
  • '' + v calls v.valueOf() prior to any other type cast

So we could do something like:

var mixin = {
  valueOf:  function () { return false },
  toString: function () { return 'true' }
};
mixin === false;  // false
mixin == false;    // true
'' + mixin;       // "false"
String(mixin)     // "true"

Tested in FF 34.0 and Node 0.10

Regex Match all characters between two strings

Try This is[\s\S]*sentence, works in javascript

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

Detect IE version (prior to v9) in JavaScript

Don't over complicate such simple things. Just use a plain and simple JScript conditional comment. It is the fastest because it adds zero code to non-IE browsers for the detection, and it has compatibility dating back to versions of IE before HTML conditional comments were supported. In short,

var IE_version=(-1/*@cc_on,@_jscript_version@*/);

Beware of minifiers: most (if not all) will mistake the special conditional comment for a regular comment, and remove it

Basically, then above code sets the value of IE_version to the version of IE you are using, or -1 f you are not using IE. A live demonstration:

_x000D_
_x000D_
var IE_version=(-1/*@cc_on,@_jscript_version@*/);_x000D_
if (IE_version!==-1){_x000D_
    document.write("<h1>You are using Internet Explorer " + IE_version + "</h1>");_x000D_
} else {_x000D_
    document.write("<h1>You are not using a version of Internet Explorer less than 11</h1>");_x000D_
}
_x000D_
_x000D_
_x000D_

This works based on the fact that conditional comments are only visible in older versions of Internet Explorer, and IE sets @_jscript_version to the version of the browser. For example, if you are using Internet Explorer 7, then @_jscript_version will be set to 7, thus, the postprocessed javascript that will be executed will actually look like this:

var IE_version=(-1,7);

which gets evaluated to 7.

Custom style to jquery ui dialogs

See http://jsfiddle.net/qP8DY/24/

You can add a class (such as "success-dialog" in my example) to div#success, either directly in your HTML, or in your JavaScript by adding to the dialogClass option, as I've done.

$('#success').dialog({
    height: 50,
    width: 350,
    modal: true,
    resizable: true,
    dialogClass: 'no-close success-dialog'
});

Then just add the success-dialog class to your CSS rules as appropriate. To indicate an element with two (or more) classes applied to it, just write them all together, with no spaces in between. For example:

.ui-dialog.success-dialog {
    font-family: Verdana,Arial,sans-serif;
    font-size: .8em;
}

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

How to concatenate strings in windows batch file for loop?

In batch you could do it like this:

@echo off

setlocal EnableDelayedExpansion

set "string_list=str1 str2 str3 ... str10"

for %%s in (%string_list%) do (
  set "var=%%sxyz"
  svn co "!var!"
)

If you don't need the variable !var! elsewhere in the loop, you could simplify that to

@echo off

setlocal

set "string_list=str1 str2 str3 ... str10"

for %%s in (%string_list%) do svn co "%%sxyz"

However, like C.B. I'd prefer PowerShell if at all possible:

$string_list = 'str1', 'str2', 'str3', ... 'str10'

$string_list | ForEach-Object {
  $var = "${_}xyz"   # alternatively: $var = $_ + 'xyz'
  svn co $var
}

Again, this could be simplified if you don't need $var elsewhere in the loop:

$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object { svn co "${_}xyz" }

How many parameters are too many?

It's a known fact that, on average, people can keep 7 +/- 2 things in their head at a time. I like to use that principle with parameters. Assuming that programmers are all above-average intelligent people, I'd say everything 10+ is too many.

BTW, if parameters are similar in any way, I'd put them in a vector or list rather than a struct or class.

Error:Cause: unable to find valid certification path to requested target

This problem might be due to some restricted internet connections... If you are installing build tools on some restricted network, the required certificates might not install... So try changing the network connection.... Worked for me.....

JavaFX - create custom button with image

There are a few different ways to accomplish this, I'll outline my favourites.

Use a ToggleButton and apply a custom style to it. I suggest this because your required control is "like a toggle button" but just looks different from the default toggle button styling.

My preferred method is to define a graphic for the button in css:

.toggle-button {
  -fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
}

.toggle-button:selected {
  -fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}

OR use the attached css to define a background image.

// file imagetogglebutton.css deployed in the same package as ToggleButtonImage.class
.toggle-button {
  -fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
  -fx-background-repeat: no-repeat;
  -fx-background-position: center;
}

.toggle-button:selected {
  -fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}

I prefer the -fx-graphic specification over the -fx-background-* specifications as the rules for styling background images are tricky and setting the background does not automatically size the button to the image, whereas setting the graphic does.

And some sample code:

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;

public class ToggleButtonImage extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  @Override public void start(final Stage stage) throws Exception {
    final ToggleButton toggle = new ToggleButton();
    toggle.getStylesheets().add(this.getClass().getResource(
      "imagetogglebutton.css"
    ).toExternalForm());
    toggle.setMinSize(148, 148); toggle.setMaxSize(148, 148);
    stage.setScene(new Scene(
      StackPaneBuilder.create()
        .children(toggle)
        .style("-fx-padding:10; -fx-background-color: cornsilk;")
        .build()
    ));
    stage.show();
  }
}

Some advantages of doing this are:

  1. You get the default toggle button behavior and don't have to re-implement it yourself by adding your own focus styling, mouse and key handlers etc.
  2. If your app gets ported to different platform such as a mobile device, it will work out of the box responding to touch events rather than mouse events, etc.
  3. Your styling is separated from your application logic so it is easier to restyle your application.

An alternate is to not use css and still use a ToggleButton, but set the image graphic in code:

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.image.*;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;

public class ToggleButtonImageViaGraphic extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  @Override public void start(final Stage stage) throws Exception {
    final ToggleButton toggle      = new ToggleButton();
    final Image        unselected  = new Image(
      "http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png"
    );
    final Image        selected    = new Image(
      "http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png"
    );
    final ImageView    toggleImage = new ImageView();
    toggle.setGraphic(toggleImage);
    toggleImage.imageProperty().bind(Bindings
      .when(toggle.selectedProperty())
        .then(selected)
        .otherwise(unselected)
    );

    stage.setScene(new Scene(
      StackPaneBuilder.create()
        .children(toggle)
        .style("-fx-padding:10; -fx-background-color: cornsilk;")
        .build()
    ));
    stage.show();
  }
}

The code based approach has the advantage that you don't have to use css if you are unfamilar with it.

For best performance and ease of porting to unsigned applet and webstart sandboxes, bundle the images with your app and reference them by relative path urls rather than downloading them off the net.

How to add element into ArrayList in HashMap

#i'm also maintaining insertion order here
Map<Integer,ArrayList> d=new LinkedHashMap<>();
for( int i=0; i<2; i++)
{
int id=s.nextInt();
ArrayList al=new ArrayList<>();
al.add(s.next());  //name
al.add(s.next());  //category
al.add(s.nextInt()); //fee
d.put(id, al);
 }

How to add 10 minutes to my (String) time?

Use Calendar.add(int field,int amount) method.