Programs & Examples On #Ora 00911

Oracle database error code ORA-00911: invalid character

How can I solve ORA-00911: invalid character error?

I encountered the same thing lately. it was just due to spaces when copying a script from a document to sql developer. I had to remove the spaces and the script ran.

Where's my invalid character (ORA-00911)

One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

You are single quoting your SQL statement which is making the variables text instead of variables.

$sql = "SELECT * 
    FROM $usertable 
    WHERE PartNumber = $partid";

How to handle command-line arguments in PowerShell

You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -, like script.ps1 -server http://devserver

Then you handle them in param section in the beginning of the file.

You can also assign default values to your params, read them from console if not available or stop script execution:

 param (
    [string]$server = "http://defaultserver",
    [Parameter(Mandatory=$true)][string]$username,
    [string]$password = $( Read-Host "Input password, please" )
 )

Inside the script you can simply

write-output $server

since all parameters become variables available in script scope.

In this example, the $server gets a default value if the script is called without it, script stops if you omit the -username parameter and asks for terminal input if -password is omitted.

Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.

The keyword for that is [switch] parameter type:

 param (
    [string]$server = "http://defaultserver",
    [string]$password = $( Read-Host "Input password, please" ),
    [switch]$force = $false
 )

Inside the script then you would work with it like this:

if ($force) {
  //deletes a file or does something "bad"
}

Now, when calling the script you'd set the switch/flag parameter like this:

.\yourscript.ps1 -server "http://otherserver" -force

If you explicitly want to state that the flag is not set, there is a special syntax for that

.\yourscript.ps1 -server "http://otherserver" -force:$false

Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):

Dump Mongo Collection into JSON format

From the Mongo documentation:

The mongoexport utility takes a collection and exports to either JSON or CSV. You can specify a filter for the query, or a list of fields to output

Read more here: http://www.mongodb.org/display/DOCS/mongoexport

how to make a div to wrap two float divs inside?

Here's another, I found helpful. It works even for Responsive CSS design too.

#wrap
{
   display: table;
   table-layout: fixed; /* it'll enable the div to be responsive */
   width: 100%; /* as display table will shrink the div to content-wide */
}

WARNING: But this theory won't work for holder contains inner elements with absolute positions. And it will create problem for fixed-width layout. But for responsive design, it's just excellent. :)

ADDITION TO Meep3D's ANSWER

With CSS3, in a dynamic portion, you can add clear float to the last element by:

#wrap [class*='my-div-class']:last-of-type {
  display: block;
  clear: both;
}

Where your divs are:

<div id="wrap">
<?php for( $i = 0; $i < 3; $i++ ) {
   <div class="my-div-class-<?php echo $i ?>>
      <p>content</p>
   </div> <!-- .my-div-class-<?php echo $i ?> -->
}
</div>

Reference:

jQuery get the location of an element relative to window

function getWindowRelativeOffset(parentWindow, elem) {
        var offset = {
            left : 0,
            top : 0
        };
        // relative to the target field's document
        offset.left = elem.getBoundingClientRect().left;
        offset.top = elem.getBoundingClientRect().top;
        // now we will calculate according to the current document, this current
        // document might be same as the document of target field or it may be
        // parent of the document of the target field
        var childWindow = elem.document.frames.window;
        while (childWindow != parentWindow) {
            offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
            offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
            childWindow = childWindow.parent;
        }
        return offset;
    };

you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus for IE only as per my requirement but similar can be done for other browsers

Using jQuery, Restricting File Size Before Uploading

Try below code:

var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;

if (sizeInKB >= sizeLimit) {
    alert("Max file size 30KB");
    return false;
}

C/C++ NaN constant (literal)?

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

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

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

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

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

How do I redirect in expressjs while passing some context?

 app.get('/category', function(req, res) {
  var string = query
  res.redirect('/?valid=' + string);
});

in the ejs you can directly use valid:

<% var k = valid %>

mysql is not recognised as an internal or external command,operable program or batch

enter image description hereHere what I DO on MY PC I install all software that i usually used in G: partian not C: if my operating system is fall (win 10) , Do not need to reinstall them again and lost time , Then How windows work it update PATH automatic if you install any new programe or pice of softwore ,

SO

I must update PATH like these HERE! all my software i usually used 1- I created folder called Programe Files 2- I install all my programe data in these folder 3-and then going to PATH and add it Dont forget ;

%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;G:\HashiCorp\Vagrant\bin;G:\xampp\php;G:\xampp\mysql\bin;G:\Program Files (x86)\heroku\bin;G:\Program Files (x86)\Git\bin;G:\Program Files (x86)\composer;G:\Program Files (x86)\nodejs;G:\Program Files (x86)\Sublime Text 3;G:\Program Files (x86)\Microsoft VS Code\bin;G:\Program Files (x86)\cygwin64\bin

enter image description here

Can you target <br /> with css?

My own tests conclusively show that br tags do not like to be targeted for css.

But if you can add style then you can probably also add a scrip tag to the header of the page? Link to an external .js that does something like this:

function replaceLineBreaksWithHorizontalRulesInElement( element )
{
    elems = element.getElementsByTagName( 'br' );
    for ( var i = 0; i < elems.length; i ++ )
    {
        br = elems.item( i );
        hr = document.createElement( 'hr' );
        br.parentNode.replaceChild( hr, br );
    }
}

So in short, it's not optimal, but here is my solution.

ListBox with ItemTemplate (and ScrollBar!)

I pasted your code into test project, added about 20 items and I get usable scroll bars, no problem, and they work as expected. When I only add a couple items (such that scrolling is unnecessary) I get no usable scrollbar. Could this be the case? that you are not adding enough items?

If you remove the ScrollViewer.VerticalScrollBarVisibility="Visible" then the scroll bars only appear when you have need of them.

Giving a border to an HTML table row, <tr>

Yes. I updated my answer DEMO

table td {
    border-top: thin solid; 
    border-bottom: thin solid;
}

table td:first-child {
     border-left: thin solid;
}

table td:last-child {
     border-right: thin solid;
}

If you want to style only one <tr> you can do it with a class: Second DEMO

Execute JavaScript code stored as a string

You can execute it using a function. Example:

var theInstructions = "alert('Hello World'); var x = 100";

var F=new Function (theInstructions);

return(F());

Remove ListView items in Android

You can use

adapter.clear() 

that will remove all item of your first adapter then you could either set another adapter or reuse the adapter and add the items to the old adapter. If you use

adapter.add()

to add data to your list you don't need to call notifyDataSetChanged

CSS - Overflow: Scroll; - Always show vertical scroll bar?

Please note on iPad Safari, NoviceCoding's solution won't work if you have -webkit-overflow-scrolling: touch; somewhere in your CSS. The solution is either removing all the occurrences of -webkit-overflow-scrolling: touch; or putting -webkit-overflow-scrolling: auto; with NoviceCoding's solution.

How to get history on react-router v4?

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

class MyComponent extends React.Component {
  props: PropsType;

  static contextTypes = {
    router: PropTypes.object
  };

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

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

C# Inserting Data from a form into an access Database

 private void Add_Click(object sender, EventArgs e) {
 OleDbConnection con = new OleDbConnection(@ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\HP\Desktop\DS Project.mdb");
 OleDbCommand cmd = con.CreateCommand();
 con.Open();
 cmd.CommandText = "Insert into DSPro (Playlist) values('" + textBox1.Text + "')";
 cmd.ExecuteNonQuery();
 MessageBox.Show("Record Submitted", "Congrats");
 con.Close();
} 

Allowed characters in filename

Here is the code to clean file name in python.

import unicodedata

def clean_name(name, replace_space_with=None):
    """
    Remove invalid file name chars from the specified name

    :param name: the file name
    :param replace_space_with: if not none replace space with this string
    :return: a valid name for Win/Mac/Linux
    """

    # ref: https://en.wikipedia.org/wiki/Filename
    # ref: https://stackoverflow.com/questions/4814040/allowed-characters-in-filename
    # No control chars, no: /, \, ?, %, *, :, |, ", <, >

    # remove control chars
    name = ''.join(ch for ch in name if unicodedata.category(ch)[0] != 'C')

    cleaned_name = re.sub(r'[/\\?%*:|"<>]', '', name)
    if replace_space_with is not None:
        return cleaned_name.replace(' ', replace_space_with)
    return cleaned_name

The difference between "require(x)" and "import x"

Not an answer here and more like a comment, sorry but I can't comment.

In node V10, you can use the flag --experimental-modules to tell Nodejs you want to use import. But your entry script should end with .mjs.

Note this is still an experimental thing and should not be used in production.

// main.mjs
import utils from './utils.js'
utils.print();
// utils.js
module.exports={
    print:function(){console.log('print called')}
}

Ref 1 - Nodejs Doc

Ref 2 - github issue

How to center body on a page?

You have to specify the width to the body for it to center on the page.

Or put all the content in the div and center it.

<body>
    <div>
    jhfgdfjh
    </div>
</body>?

div {
    margin: 0px auto;
    width:400px;
}

?

AngularJS - Create a directive that uses ng-model

This is a little late answer, but I found this awesome post about NgModelController, which I think is exactly what you were looking for.

TL;DR - you can use require: 'ngModel' and then add NgModelController to your linking function:

link: function(scope, iElement, iAttrs, ngModelCtrl) {
  //TODO
}

This way, no hacks needed - you are using Angular's built-in ng-model

Output to the same line overwriting previous output?

You can just add '\r' at the end of the string plus a comma at the end of print function. For example:

print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!\r'),

Removing index column in pandas when reading a csv

One thing that i do is df=df.reset_index() then df=df.drop(['index'],axis=1)

Which Python memory profiler is recommended?

I'm developing a memory profiler for Python called memprof:

http://jmdana.github.io/memprof/

It allows you to log and plot the memory usage of your variables during the execution of the decorated methods. You just have to import the library using:

from memprof import memprof

And decorate your method using:

@memprof

This is an example on how the plots look like:

enter image description here

The project is hosted in GitHub:

https://github.com/jmdana/memprof

HTML CSS How to stop a table cell from expanding

It's entirely possible if your code has enough relative logic to work with.

Simply use the viewport units though for some the math may be a bit more complicated. I used this to prevent list items from bloating certain table columns with much longer text.

ol {max-width: 10vw; padding: 0; overflow: hidden;}

Apparently max-width on colgroup elements do not work which is pretty lame to be dependent entirely on child elements to control something on the parent.

Javac is not found

You don't have jdk1.7.0_17 in your PATH - check again. There is only JRE which may not contain 'javac' compiler.

Besides it is best to set JAVA_HOME variable, and then include it in PATH.

GDB: break if variable equal value

There are hardware and software watchpoints. They are for reading and for writing a variable. You need to consult a tutorial:

http://www.unknownroad.com/rtfm/gdbtut/gdbwatch.html

To set a watchpoint, first you need to break the code into a place where the varianle i is present in the environment, and set the watchpoint.

watch command is used to set a watchpoit for writing, while rwatch for reading, and awatch for reading/writing.

How to get javax.comm API?

Another Simple way i found in Netbeans right click on your project>libraris click add jar/folder add your comm.jar and you done.

if you dont have comm.jar download it from >>> http://llk.media.mit.edu/projects/picdev/software/javaxcomm.zip

Redefine tab as 4 spaces

Add line
set ts=4
in
~/.vimrc file for per user
or
/etc/vimrc file for system wide

The endpoint reference (EPR) for the Operation not found is

On Websphere Application Server, in the same situation, it helped deleting the Temp folders while the server was stopped.

I ran into the situation when the package of the service changed.

How do I "commit" changes in a git submodule?

A submodule is its own repo/work-area, with its own .git directory.

So, first commit/push your submodule's changes:

$ cd path/to/submodule
$ git add <stuff>
$ git commit -m "comment"
$ git push

Then, update your main project to track the updated version of the submodule:

$ cd /main/project
$ git add path/to/submodule
$ git commit -m "updated my submodule"
$ git push

error, string or binary data would be truncated when trying to insert

Just want to contribute with additional information: I had the same issue and it was because of the field wasn't big enough for the incoming data and this thread helped me to solve it (the top answer clarifies it all).

BUT it is very important to know what are the possible reasons that may cause it.

In my case i was creating the table with a field like this:

Select '' as  Period, * From Transactions Into #NewTable

Therefore the field "Period" had a length of Zero and causing the Insert operations to fail. I changed it to "XXXXXX" that is the length of the incoming data and it now worked properly (because field now had a lentgh of 6).

I hope this help anyone with same issue :)

Cannot lower case button text in android studio

You could set like this

button.setAllCaps(false);

programmatically

How to pass parameters on onChange of html select

I found @Piyush's answer helpful, and just to add to it, if you programatically create a select, then there is an important way to get this behavior that may not be obvious. Let's say you have a function and you create a new select:

var changeitem = function (sel) {
  console.log(sel.selectedIndex);
}
var newSelect = document.createElement('select');
newSelect.id = 'newselect';

The normal behavior may be to say

newSelect.onchange = changeitem;

But this does not really allow you to specify that argument passed in, so instead you may do this:

newSelect.setAttribute('onchange', 'changeitem(this)');

And you are able to set the parameter. If you do it the first way, then the argument you'll get to your onchange function will be browser dependent. The second way seems to work cross-browser just fine.

How to set RelativeLayout layout params in code not in xml?

Just a basic example:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
Button button1;
button1.setLayoutParams(params);

params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, button1.getId());
Button button2;
button2.setLayoutParams(params);

As you can see, this is what you have to do:

  1. Create a RelativeLayout.LayoutParams object.
  2. Use addRule(int) or addRule(int, int) to set the rules. The first method is used to add rules that don't require values.
  3. Set the parameters to the view (in this case, to each button).

What is the difference between a Docker image and a container?

I couldn't understand the concept of image and layer in spite of reading all the questions here and then eventually stumbled upon this excellent documentation from Docker (duh!).

The example there is really the key to understand the whole concept. It is a lengthy post, so I am summarising the key points that need to be really grasped to get clarity.

  • Image: A Docker image is built up from a series of read-only layers

  • Layer: Each layer represents an instruction in the image’s Dockerfile.

Example: The below Dockerfile contains four commands, each of which creates a layer.

FROM ubuntu:15.04

COPY . /app

RUN make /app

CMD python /app/app.py

Importantly, each layer is only a set of differences from the layer before it.

  • Container. When you create a new container, you add a new writable layer on top of the underlying layers. This layer is often called the “container layer”. All changes made to the running container, such as writing new files, modifying existing files, and deleting files, are written to this thin writable container layer.

Hence, the major difference between a container and an image is the top writable layer. All writes to the container that add new or modify existing data are stored in this writable layer. When the container is deleted, the writable layer is also deleted. The underlying image remains unchanged.

Understanding images cnd Containers from a size-on-disk perspective

To view the approximate size of a running container, you can use the docker ps -s command. You get size and virtual size as two of the outputs:

  • Size: the amount of data (on disk) that is used for the writable layer of each container

  • Virtual Size: the amount of data used for the read-only image data used by the container. Multiple containers may share some or all read-only image data. Hence these are not additive. I.e. you can't add all the virtual sizes to calculate how much size on disk is used by the image

Another important concept is the copy-on-write strategy

If a file or directory exists in a lower layer within the image, and another layer (including the writable layer) needs read access to it, it just uses the existing file. The first time another layer needs to modify the file (when building the image or running the container), the file is copied into that layer and modified.

I hope that helps someone else like me.

How to send string from one activity to another?

TWO CASES

There are two situations possible when we talk about passing data between activities.

Let's say there are two activities A and B and there is a String X. and you are in Activity A.

Now let's see the two cases

  1. A-------->B
  2. A<--------B

CASE 1:
String X is in A and you want to get it in Activity B.

It is very straightforward.

In Activity A.

1) Create Intent
2) Put Extra value
3) startActivity

Intent i = new Intent(A.this, B.class);
i.putExtra("Your_KEY",X);
startActivity(i)

In Activity B

Inside onCreate() method retrieve string X using the key which you used while storing X (Your_KEY).

Intent i = getIntent();
String s = i.getStringExtra("Your_KEY");

Case 2:
This case is little tricky if u are new to Android development Because you are in Activity A, you move to Activity B, collect the string, move back to Activity A and retrieve the collected String or data. Let's see how to deal with this situation.

In Activity A
1) Create Intent
2) start an activity with a request code.

Intent i = new Intent(A.this, B.class);
startActivityForResult(i,your_req_code);

In Activity B
1) Put string X in intent
2) Set result
3) Finish activity

Intent returnIntent = new Intent();
returnIntent .putString("KEY",X);
setResult(resCode,returnIntent);   // for the first argument, you could set Activity.RESULT_OK or your custom rescode too
finish();

Again in Activity A
1) Override onActivityResult method

onActivityResult(int req_code, int res_code, Intent data)
{
       if(req_code==your_req_code)
       {
          String X = data.getStringExtra("KEY")
       }
}

Further understanding of Case 2

You might wonder what is the reqCode, resCode in the onActivityResult(int reqCode, resCode, Intent data)

reqCode is useful when you have to identify from which activity you are getting the result from.

Let's say you have two buttons, one button starts Camera (you click a photo and get the bitmap of that image in your Activity as a result), another button starts GoogleMap( you get back the current coordinates of your location as a result). So to distinguish between the results of both activities you start CameraActivty and MapActivity with different request codes.

resCode: is useful when you have to distinguish between how results are coming back to requesting activity.

For eg: You start Camera Activity. When the camera activity starts, you could either take a photo or just move back to requesting activity without taking a photo with the back button press. So in these two situations, your camera activity sends result with different resCode ACTIVITY.RESULT_OK and ACTIVITY.RESULT_CANCEL respectively.

Relevant Links

Read more on Getting result

C++ Array Of Pointers

What you want is:

Foo *array[10]; // array of 10 Foo pointers

Not to be confused with:

Foo (*array)[10]; // pointer to array of 10 Foos

In either case, nothing will be automatically initialized because these represent pointers to Foos that have yet to be assigned to something (e.g. with new).

I finally "got" pointer/array declaration syntax in C when I realized that it describes how you access the base type. Foo *array[5][10]; means that *array[0..4][0..9] (subscript on an array of 5 items, then subscript on an array of 10 items, then dereference as a pointer) will access a Foo object (note that [] has higher precedence than *).

This seems backwards. You would think that int array[5][10]; (a.k.a. int (array[5])[10];) is an array of 10 int array[5]. Suppose this were the case. Then you would access the last element of the array by saying array[9][4]. Doesn't that look backwards too? Because a C array declaration is a pattern indicating how to get to the base type (rather than a composition of array expressions like one might expect), array declarations and code using arrays don't have to be flipflopped.

PDO error message?

From the manual:

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.

$qry = '
    INSERT INTO non-existant-table (id, score) 
    SELECT id, 40 
    FROM another-non-existant-table
    WHERE description LIKE "%:search_string%"
    AND available = "yes"
    ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());

How to import a .cer certificate into a java keystore?

The certificate that you already have is probably the server's certificate, or the certificate used to sign the server's certificate. You will need it so that your web service client can authenticate the server.

But if additionally you need to perform client authentication with SSL, then you need to get your own certificate, to authenticate your web service client. For this you need to create a certificate request; the process involves creating your own private key, and the corresponding public key, and attaching that public key along with some of your info (email, name, domain name, etc) to a file that's called the certificate request. Then you send that certificate request to the company that's already asked you for it, and they will create your certificate, by signing your public key with their private key, and they'll send you back an X509 file with your certificate, which you can now add to your keystore, and you'll be ready to connect to a web service using SSL requiring client authentication.

To generate your certificate request, use "keytool -certreq -alias -file -keypass -keystore ". Send the resulting file to the company that's going to sign it.

When you get back your certificate, run "keytool -importcert -alias -keypass -keystore ".

You may need to used -storepass in both cases if the keystore is protected (which is a good idea).

What are Maven goals and phases and what is their difference?

I believe a good answer is already provided, but I would like to add an easy-to-follow diagram of the different 3 life-cycles (build, clean, and site) and the phases in each.

enter image description here

The phases in bold - are the main phases commonly used.

Eclipse CDT: no rule to make target all

If the above solutions did not work for you so -

Could be that you did not install C++ compiler packages properly, flow this: (Instructions for Win7, 32bit/64bit)

  1. Make sure you install properly one or more of the supporting C++ compiler packages:

    (I installed MinGW (HowTo Install Videos can be found on YouTube))

    In case you choose to install MinGW packages:

    • Download MinGW installer from the Install Page above
    • Run MinGW installer and make sure to choose the following packages:

      - mingw-developer-toolkit
      - mingw32-base
      - mingw32-gcc-g++
      - msys-base

    • Add MinGW and MSYS bin paths to your PATH environment variable , if you didn't change the default installation folders you should add:

    C:\MinGW\msys\1.0\bin;C:\MinGW\bin;
    • Logoff and log back in for making sure Environment vars kicked in
  2. Create a new C++ project in eclipse:

    • New -> C++ Projects
    • Choose Project type: Executables -> Hello World C++ project
      (Now on the right, under Toolchains you shall see MinGW GCC)
    • Select MinGW GCC from the Toolchains list
    • Hit Finish
  3. In you Hello World Project you shall see + src folder, and + Includes (If so you are probably good to go).

  4. Build project
  5. Run it!

CSS Animation onClick

Try this:

<div>
 <p onclick="startAnimation()">Start</p><!--O botão para iniciar (start)-->
 <div id="animation">Hello!</div> <!--O elemento que você quer animar-->
</div>

<style>
@keyframes animationName {
from {margin-left:-30%;}
}
</style>

<script>
function startAnimation() {
    document.getElementById("animation").style.animation = "animationName 2s linear 1";
}
</script>

How to delete file from public folder in laravel 5.1

this method worked for me
First, put the line below at the beginning of your controller:

use File;

below namespace in your php file Second:

 $destinationPath = 'your_path';
 File::delete($destinationPath.'/your_file');

$destinationPath --> the folder inside folder public.

VBA: How to delete filtered rows in Excel?

Use SpecialCells to delete only the rows that are visible after autofiltering:

ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:

ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

Combine two columns of text in pandas dataframe

Using zip could be even quicker:

df["period"] = [''.join(i) for i in zip(df["Year"].map(str),df["quarter"])]

Graph:

enter image description here

import pandas as pd
import numpy as np
import timeit
import matplotlib.pyplot as plt
from collections import defaultdict

df = pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']})

myfuncs = {
"df['Year'].astype(str) + df['quarter']":
    lambda: df['Year'].astype(str) + df['quarter'],
"df['Year'].map(str) + df['quarter']":
    lambda: df['Year'].map(str) + df['quarter'],
"df.Year.str.cat(df.quarter)":
    lambda: df.Year.str.cat(df.quarter),
"df.loc[:, ['Year','quarter']].astype(str).sum(axis=1)":
    lambda: df.loc[:, ['Year','quarter']].astype(str).sum(axis=1),
"df[['Year','quarter']].astype(str).sum(axis=1)":
    lambda: df[['Year','quarter']].astype(str).sum(axis=1),
    "df[['Year','quarter']].apply(lambda x : '{}{}'.format(x[0],x[1]), axis=1)":
    lambda: df[['Year','quarter']].apply(lambda x : '{}{}'.format(x[0],x[1]), axis=1),
    "[''.join(i) for i in zip(dataframe['Year'].map(str),dataframe['quarter'])]":
    lambda: [''.join(i) for i in zip(df["Year"].map(str),df["quarter"])]
}

d = defaultdict(dict)
step = 10
cont = True
while cont:
    lendf = len(df); print(lendf)
    for k,v in myfuncs.items():
        iters = 1
        t = 0
        while t < 0.2:
            ts = timeit.repeat(v, number=iters, repeat=3)
            t = min(ts)
            iters *= 10
        d[k][lendf] = t/iters
        if t > 2: cont = False
    df = pd.concat([df]*step)

pd.DataFrame(d).plot().legend(loc='upper center', bbox_to_anchor=(0.5, -0.15))
plt.yscale('log'); plt.xscale('log'); plt.ylabel('seconds'); plt.xlabel('df rows')
plt.show()

Quickest way to compare two generic lists for differences

I have used this code to compare two list which has million of records.

This method will not take much time

    //Method to compare two list of string
    private List<string> Contains(List<string> list1, List<string> list2)
    {
        List<string> result = new List<string>();

        result.AddRange(list1.Except(list2, StringComparer.OrdinalIgnoreCase));
        result.AddRange(list2.Except(list1, StringComparer.OrdinalIgnoreCase));

        return result;
    }

random number generator between 0 - 1000 in c#

Have you tried this

Random integer between 0 and 1000(1000 not included):

Random random = new Random();
int randomNumber = random.Next(0, 1000);

Loop it as many times you want

React.js, wait for setState to finish before triggering a function?

       this.setState(
        {
            originId: input.originId,
            destinationId: input.destinationId,
            radius: input.radius,
            search: input.search
        },
        function() { console.log("setState completed", this.state) }
       )

this might be helpful

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

In addition to Jhonson's list, also check library's folders

In visual studio, select Tools > Options from the main menu. select Projects and Solutions > VC++ Directories. Select x64 from the Platform dropdown.

$(VCInstallDir)lib\AMD64;
$(VCInstallDir)atlmfc\lib\amd64;
$(WindowsSdkDir)lib\x64;

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

To get the value of my drop down box on page load, I use

document.addEventListener('DOMContentLoaded',fnName);

Hope this helps some one.

Get fragment (value after hash '#') from a URL in php

A) already have url with #hash in PHP? Easy! Just parse it out !

if( strpos( $url, "#" ) === false ) echo "NO HASH !";
   else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0

Or in "old" PHP you must pre-store the exploded to access the array:

$exploded_url = explode( "#", $url ); $exploded_url[1]; 

B) You want to get a #hash by sending a form to PHP?
    => Use some JavaScript MAGIC! (To pre-process the form)

var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
    forms[i].addEventListener( // add a "listener"
        'submit', // for an on-submit "event"
        function () { //add a submit pre-processing function:
            var input_name = "fragment"; // name form will use to send the fragment
            // Try search whether we already done this or not
            // in current form, find every <input ... name="fragment" ...>
            var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
            if (hiddens.length < 1) { // if not there yet
                //create an extra input element
                var hidden = document.createElement("input");
                //set it to hidden so it doesn't break view 
                hidden.setAttribute('type', 'hidden');
                //set a name to get by it in PHP
                hidden.setAttribute('name', input_name);
                this.appendChild(hidden); //append it to the current form
            } else {
                var hidden = hiddens[0]; // use an existing one if already there
            }

            //set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
            hidden.setAttribute('value', window.location.hash);
        }
    );
}

Depending on your form's method attribute you get this hash in PHP by:
$_GET['fragment'] or $_POST['fragment']

Possible returns: 1. ""[empty string] (no hash) 2. whole hash INCLUDING the #[hash] sign (because we've used the window.location.hash in JavaScript which just works that way :) )

C) You want to get the #hash in PHP JUST from requested URL?

                                    YOU CAN'T !

...(not while considering regular HTTP requests)...

...Hope this helped :)

Incrementing a date in JavaScript

var myDate = new Date();

//add a day to the date
myDate.setDate(myDate.getDate() + 1);

How do I remove/delete a folder that is not empty?

You can use os.system command for simplicity:

import os
os.system("rm -rf dirname")

As obvious, it actually invokes system terminal to accomplish this task.

How to do a batch insert in MySQL

Load data infile query is much better option but some servers like godaddy restrict this option on shared hosting so , only two options left then one is insert record on every iteration or batch insert , but batch insert has its limitaion of characters if your query exceeds this number of characters set in mysql then your query will crash , So I suggest insert data in chunks withs batch insert , this will minimize number of connections established with database.best of luck guys

Rounding Bigdecimal values with 2 Decimal Places

You may try this:

public static void main(String[] args) {
    BigDecimal a = new BigDecimal("10.12345");
    System.out.println(toPrecision(a, 2));
}

private static BigDecimal toPrecision(BigDecimal dec, int precision) {
    String plain = dec.movePointRight(precision).toPlainString();
    return new BigDecimal(plain.substring(0, plain.indexOf("."))).movePointLeft(precision);
}

OUTPUT:

10.12

Setting cursor at the end of any text of a textbox

For Windows Forms you can control cursor position (and selection) with txtbox.SelectionStart and txtbox.SelectionLength properties. If you want to set caret to end try this:

txtbox.SelectionStart = txtbox.Text.Length;
txtbox.SelectionLength = 0;

For WPF see this question.

Checkout Jenkins Pipeline Git SCM with credentials?

For what it's worth adding to the discussion... what I did that ended up helping me... Since the pipeline is run within a workspace within a docker image that is cleaned up each time it runs. I grabbed the credentials needed to perform necessary operations on the repo within my pipeline and stored them in a .netrc file. this allowed me to authorize the git repo operations successfully.

withCredentials([usernamePassword(credentialsId: '<credentials-id>', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
    sh '''
        printf "machine github.com\nlogin $GIT_USERNAME\n password $GIT_PASSWORD" >> ~/.netrc
        // continue script as necessary working with git repo...
    '''
}

If...Then...Else with multiple statements after Then

Multiple statements are to be separated by a new line:

If SkyIsBlue Then
  StartEngines
  Pollute
ElseIf SkyIsRed Then
  StopAttack
  Vent
ElseIf SkyIsYellow Then
  If Sunset Then
    Sleep
  ElseIf Sunrise or IsMorning Then
    Smoke
    GetCoffee
  Else
    Error
  End If
Else
  Joke
  Laugh
End If

Mysql: Select all data between two dates

You can use as an alternate solution:

SELECT * FROM TABLE_NAME WHERE `date` >= '1-jan-2013' 
OR `date` <= '12-jan-2013'

How to assign a select result to a variable?

Why do you need a cursor at all? Your entire segment of code can be replaced by this, which will run a lot faster on large numbers of rows.

UPDATE tarinvoice set confirmtocntctkey = PrimaryCntctKey 
FROM tarinvoice INNER JOIN tarcustomer ON tarinvoice.custkey = tarcustomer.custkey
WHERE confirmtocntctkey is null and tranno like '%115876'

GSON - Date format

This won't really work at all. There is no date type in JSON. I would recommend to serialize to ISO8601 back and forth (for format agnostics and JS compat). Consider that you have to know which fields contain dates.

Generating a unique machine id

I had the same problem and after a little research I decided the best would be to read MachineGuid in registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography, as @Agnus suggested. It is generated during OS installation and won't change unless you make another fresh OS install. Depending on the OS version it may contain the network adapter MAC address embedded (plus some other numbers, including random), or a pseudorandom number, the later for newer OS versions (after XP SP2, I believe, but not sure). If it's a pseudorandom theoretically it can be forged - if two machines have the same initial state, including real time clock. In practice, this will be rare, but be aware if you expect it to be a base for security that can be attacked by hardcore hackers.

Of course a registry entry can also be easily changed by anyone to forge a machine GUID, but what I found is that this would disrupt normal operation of so many components of Windows that in most cases no regular user would do it (again, watch out for hardcore hackers).

How to add element in List while iterating in java?

You could iterate on a copy (clone) of your original list:

List<String> copy = new ArrayList<String>(list);
for (String s : copy) {
    // And if you have to add an element to the list, add it to the original one:
    list.add("some element");
}

Note that it is not even possible to add a new element to a list while iterating on it, because it will result in a ConcurrentModificationException.

How do I enable --enable-soap in php on linux?

As far as your question goes: no, if activating from .ini is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap, yum install php-soap). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).

In general, the double-dash --switches are designed to be used when recompiling PHP from scratch.

You would download the PHP source package (as a compressed .tgz tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script

./configure --prefix ...

The configure command used by your PHP may be shown with phpinfo(). Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap will then enable SOAP in addition to everything else.

That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype, gd, libjpeg, XML, expat, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg installed might not be enough, and you might need libjpeg-dev also).

I have to keep a separate virtual machine with everything installed for my recompilation purposes.

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

generate model using user:references vs user_id:integer

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

 belongs_to :something

is to look for something_id.

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

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

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

or (note the plural):

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

Check the current number of connections to MongoDb

Connect with your mongodb instance from local system

  1. sudo mongo "mongodb://MONGO_HOST_IP:27017" --authenticationDatabase admin

It ll let you know all connected clients and their details

  1. db.currentOp(true)

jQuery & CSS - Remove/Add display:none

In JavaScript:

getElementById("id").style.display = null;

In jQuery:

$("#id").css("display","");

How to redirect user's browser URL to a different page in Nodejs?

For those who (unlike OP) are using the express lib:

http.get('*',function(req,res){  
    res.redirect('http://exmple.com'+req.url)
})

Sorting A ListView By Column

i would recommend you to you datagridview, for heavy stuff.. it's include a lot of auto feature listviwe does not

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

The issue for me was trying to sign the application with the app store distribution certificate. Switching the cert to the Xcode generated Team provisioning profile fixed the issue.

Tests not running in Test Explorer

For me having a property called TestContext in a base class was causing this behavior. For example:

[TestClass]
public abstract class TestClassBase
{
    protected object TestContext { get; private set; }
}

[TestClass]
public class TestClass : TestClassBase
{
    // This method not found
    [TestMethod]
    public void TestCase() {}
}

A failure occurred while executing com.android.build.gradle.internal.tasks

I already had multidex enabled but the version was too old so upgraded and it fixed the issue:

// Old version
implementation 'com.android.support:multidex:1.0.3'
// New version
def multidex_version = "2.0.1"
implementation 'androidx.multidex:multidex:$multidex_version'

Bootstrap 3: How do you align column content to bottom of row

I don't know why but for me the solution proposed by Marius Stanescu is breaking the specificity of col (a col-md-3 followed by a col-md-4 will take all of the twelve row)

I found another working solution :

.bottom-column 
{
   display: inline-block;
   vertical-align: middle;
   float: none;
}

Fill background color left to right CSS

A single css code on hover can do the trick: box-shadow: inset 100px 0 0 0 #e0e0e0;

A complete demo can be found in my fiddle:

https://jsfiddle.net/shuvamallick/3o0h5oka/

How do I change the hover over color for a hover over table in Bootstrap?

Instead of changing the default table-hover class, make a new class ( anotherhover ) and apply it to the table that you need this effect for.

Code as below;

.anotherhover tbody tr:hover td { background: CornflowerBlue; }

Including another class in SCSS

@extend .myclass;
@extend #{'.my-class'};

Import a custom class in Java

In the same package you don't need to import the class.

Otherwise, it is very easy. In Eclipse or NetBeans just write the class you want to use and press on Ctrl + Space. The IDE will automatically import the class.

General information:

You can import a class with import keyword after package information:

Example:

package your_package;


import anotherpackage.anotherclass;

public class Your_Class {
    ...
    private Vector variable;
    ...
}

You can instance the class with:

Anotherclass foo = new Anotherclass();

Is there a .NET/C# wrapper for SQLite?

I'd definitely go with System.Data.SQLite (as previously mentioned: http://sqlite.phxsoftware.com/)

It is coherent with ADO.NET (System.Data.*), and is compiled into a single DLL. No sqlite3.dll - because the C code of SQLite is embedded within System.Data.SQLite.dll. A bit of managed C++ magic.

How do I clone a github project to run locally?

git clone git://github.com/ryanb/railscasts-episodes.git

Call a stored procedure with parameter in c#

The .NET Data Providers consist of a number of classes used to connect to a data source, execute commands, and return recordsets. The Command Object in ADO.NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.

A stored procedure is a pre-compiled executable object that contains one or more SQL statements. In many cases stored procedures accept input parameters and return multiple values . Parameter values can be supplied if a stored procedure is written to accept them. A sample stored procedure with accepting input parameter is given below :

  CREATE PROCEDURE SPCOUNTRY
  @COUNTRY VARCHAR(20)
  AS
  SELECT PUB_NAME FROM publishers WHERE COUNTRY = @COUNTRY
  GO

The above stored procedure is accepting a country name (@COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.

  command.CommandType = CommandType.StoredProcedure;
  param = new SqlParameter("@COUNTRY", "Germany");
  param.Direction = ParameterDirection.Input;
  param.DbType = DbType.String;
  command.Parameters.Add(param);

The above code passing country parameter to the stored procedure from C# application.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = null;
            SqlConnection connection ;
            SqlDataAdapter adapter ;
            SqlCommand command = new SqlCommand();
            SqlParameter param ;
            DataSet ds = new DataSet();

            int i = 0;

            connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword";
            connection = new SqlConnection(connetionString);

            connection.Open();
            command.Connection = connection;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "SPCOUNTRY";

            param = new SqlParameter("@COUNTRY", "Germany");
            param.Direction = ParameterDirection.Input;
            param.DbType = DbType.String;
            command.Parameters.Add(param);

            adapter = new SqlDataAdapter(command);
            adapter.Fill(ds);

            for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                MessageBox.Show (ds.Tables[0].Rows[i][0].ToString ());
            }

            connection.Close();
        }
    }
}

Write HTML to string

Use an XDocument to create the DOM, then write it out using an XmlWriter. This will give you a wonderfully concise and readable notation as well as nicely formatted output.

Take this sample program:

using System.Xml;
using System.Xml.Linq;

class Program {
    static void Main() {
        var xDocument = new XDocument(
            new XDocumentType("html", null, null, null),
            new XElement("html",
                new XElement("head"),
                new XElement("body",
                    new XElement("p",
                        "This paragraph contains ", new XElement("b", "bold"), " text."
                    ),
                    new XElement("p",
                        "This paragraph has just plain text."
                    )
                )
            )
        );

        var settings = new XmlWriterSettings {
            OmitXmlDeclaration = true, Indent = true, IndentChars = "\t"
        };
        using (var writer = XmlWriter.Create(@"C:\Users\wolf\Desktop\test.html", settings)) {
            xDocument.WriteTo(writer);
        }
    }
}

This generates the following output:

<!DOCTYPE html >
<html>
    <head />
    <body>
        <p>This paragraph contains <b>bold</b> text.</p>
        <p>This paragraph has just plain text.</p>
    </body>
</html>

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

I wanted to add that I was having the same issue and flexWrap, flex:1 (in the text components), nothing flex was working for me.

Eventually, I set the width of my text components' wrapper to the width of the device and the text started wrapping. const win = Dimensions.get('window');

      <View style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignSelf: 'center',
        width: win.width
      }}>
        <Text style={{ top: 0, alignSelf: 'center' }} >{image.title}</Text>
        <Text style={{ alignSelf: 'center' }}>{image.description}</Text>
      </View>

whitespaces in the path of windows filepath

Try putting double quotes in your filepath variable

"\"E:/ABC/SEM 2/testfiles/all.txt\""

Check the permissions of the file or in any case consider renaming the folder to remove the space

How to place a JButton at a desired location in a JFrame using Java

I have figured it out lol. for the button do .setBounds(0, 0, 220, 30) The .setBounds layout is like this (int x, int y, int width, int height)

Find where python is installed (if it isn't default dir)

Have a look at sys.path:

>>> import sys
>>> print(sys.path)

How do you fix a bad merge, and replay your good commits onto a fixed merge?

Intro: You Have 5 Solutions Available

The original poster states:

I accidentally committed an unwanted file...to my repository several commits ago...I want to completely delete the file from the repository history.

Is it possible to rewrite the change history such that filename.orig was never added to the repository in the first place?

There are many different ways to remove the history of a file completely from git:

  1. Amending commits.
  2. Hard resets (possibly plus a rebase).
  3. Non-interactive rebase.
  4. Interactive rebases.
  5. Filtering branches.

In the case of the original poster, amending the commit isn't really an option by itself, since he made several additional commits afterwards, but for the sake of completeness, I will also explain how to do it, for anyone else who justs wants to amend their previous commit.

Note that all of these solutions involve altering/re-writing history/commits in one way another, so anyone with old copies of the commits will have to do extra work to re-sync their history with the new history.


Solution 1: Amending Commits

If you accidentally made a change (such as adding a file) in your previous commit, and you don't want the history of that change to exist anymore, then you can simply amend the previous commit to remove the file from it:

git rm <file>
git commit --amend --no-edit

Solution 2: Hard Reset (Possibly Plus a Rebase)

Like solution #1, if you just want to get rid of your previous commit, then you also have the option of simply doing a hard reset to its parent:

git reset --hard HEAD^

That command will hard-reset your branch to the previous 1st parent commit.

However, if, like the original poster, you've made several commits after the commit you want to undo the change to, you can still use hard resets to modify it, but doing so also involves using a rebase. Here are the steps that you can use to amend a commit further back in history:

# Create a new branch at the commit you want to amend
git checkout -b temp <commit>

# Amend the commit
git rm <file>
git commit --amend --no-edit

# Rebase your previous branch onto this new commit, starting from the old-commit
git rebase --preserve-merges --onto temp <old-commit> master

# Verify your changes
git diff master@{1}

Solution 3: Non-interactive Rebase

This will work if you just want to remove a commit from history entirely:

# Create a new branch at the parent-commit of the commit that you want to remove
git branch temp <parent-commit>

# Rebase onto the parent-commit, starting from the commit-to-remove
git rebase --preserve-merges --onto temp <commit-to-remove> master

# Or use `-p` insteda of the longer `--preserve-merges`
git rebase -p --onto temp <commit-to-remove> master

# Verify your changes
git diff master@{1}

Solution 4: Interactive Rebases

This solution will allow you to accomplish the same things as solutions #2 and #3, i.e. modify or remove commits further back in history than your immediately previous commit, so which solution you choose to use is sort of up to you. Interactive rebases are not well-suited to rebasing hundreds of commits, for performance reasons, so I would use non-interactive rebases or the filter branch solution (see below) in those sort of situations.

To begin the interactive rebase, use the following:

git rebase --interactive <commit-to-amend-or-remove>~

# Or `-i` instead of the longer `--interactive`
git rebase -i <commit-to-amend-or-remove>~

This will cause git to rewind the commit history back to the parent of the commit that you want to modify or remove. It will then present you a list of the rewound commits in reverse order in whatever editor git is set to use (this is Vim by default):

pick 00ddaac Add symlinks for executables
pick 03fa071 Set `push.default` to `simple`
pick 7668f34 Modify Bash config to use Homebrew recommended PATH
pick 475593a Add global .gitignore file for OS X
pick 1b7f496 Add alias for Dr Java to Bash config (OS X)

The commit that you want to modify or remove will be at the top of this list. To remove it, simply delete its line in the list. Otherwise, replace "pick" with "edit" on the 1st line, like so:

edit 00ddaac Add symlinks for executables
pick 03fa071 Set `push.default` to `simple`

Next, enter git rebase --continue. If you chose to remove the commit entirely, then that it all you need to do (other than verification, see final step for this solution). If, on the other hand, you wanted to modify the commit, then git will reapply the commit and then pause the rebase.

Stopped at 00ddaacab0a85d9989217dd9fe9e1b317ed069ac... Add symlinks
You can amend the commit now, with

        git commit --amend

Once you are satisfied with your changes, run

        git rebase --continue

At this point, you can remove the file and amend the commit, then continue the rebase:

git rm <file>
git commit --amend --no-edit
git rebase --continue

That's it. As a final step, whether you modified the commit or removed it completely, it's always a good idea to verify that no other unexpected changes were made to your branch by diffing it with its state before the rebase:

git diff master@{1}

Solution 5: Filtering Branches

Finally, this solution is best if you want to completely wipe out all traces of a file's existence from history, and none of the other solutions are quite up to the task.

git filter-branch --index-filter \
'git rm --cached --ignore-unmatch <file>'

That will remove <file> from all commits, starting from the root commit. If instead you just want to rewrite the commit range HEAD~5..HEAD, then you can pass that as an additional argument to filter-branch, as pointed out in this answer:

git filter-branch --index-filter \
'git rm --cached --ignore-unmatch <file>' HEAD~5..HEAD

Again, after the filter-branch is complete, it's usually a good idea to verify that there are no other unexpected changes by diffing your branch with its previous state before the filtering operation:

git diff master@{1}

Filter-Branch Alternative: BFG Repo Cleaner

I've heard that the BFG Repo Cleaner tool runs faster than git filter-branch, so you might want to check that out as an option too. It's even mentioned officially in the filter-branch documentation as a viable alternative:

git-filter-branch allows you to make complex shell-scripted rewrites of your Git history, but you probably don’t need this flexibility if you’re simply removing unwanted data like large files or passwords. For those operations you may want to consider The BFG Repo-Cleaner, a JVM-based alternative to git-filter-branch, typically at least 10-50x faster for those use-cases, and with quite different characteristics:

  • Any particular version of a file is cleaned exactly once. The BFG, unlike git-filter-branch, does not give you the opportunity to handle a file differently based on where or when it was committed within your history. This constraint gives the core performance benefit of The BFG, and is well-suited to the task of cleansing bad data - you don’t care where the bad data is, you just want it gone.

  • By default The BFG takes full advantage of multi-core machines, cleansing commit file-trees in parallel. git-filter-branch cleans commits sequentially (ie in a single-threaded manner), though it is possible to write filters that include their own parallellism, in the scripts executed against each commit.

  • The command options are much more restrictive than git-filter branch, and dedicated just to the tasks of removing unwanted data- e.g: --strip-blobs-bigger-than 1M.

Additional Resources

  1. Pro Git § 6.4 Git Tools - Rewriting History.
  2. git-filter-branch(1) Manual Page.
  3. git-commit(1) Manual Page.
  4. git-reset(1) Manual Page.
  5. git-rebase(1) Manual Page.
  6. The BFG Repo Cleaner (see also this answer from the creator himself).

Copy output of a JavaScript variable to the clipboard

I just want to add, if someone wants to copy two different inputs to clipboard. I also used the technique of putting it to a variable then put the text of the variable from the two inputs into a text area.

Note: the code below is from a user asking how to copy multiple user inputs into clipboard. I just fixed it to work correctly. So expect some old style like the use of var instead of let or const. I also recommend to use addEventListener for the button.

_x000D_
_x000D_
    function doCopy() {_x000D_
_x000D_
        try{_x000D_
            var unique = document.querySelectorAll('.unique');_x000D_
            var msg ="";_x000D_
_x000D_
            unique.forEach(function (unique) {_x000D_
                msg+=unique.value;_x000D_
            });_x000D_
_x000D_
            var temp =document.createElement("textarea");_x000D_
            var tempMsg = document.createTextNode(msg);_x000D_
            temp.appendChild(tempMsg);_x000D_
_x000D_
            document.body.appendChild(temp);_x000D_
            temp.select();_x000D_
            document.execCommand("copy");_x000D_
            document.body.removeChild(temp);_x000D_
            console.log("Success!")_x000D_
_x000D_
_x000D_
        }_x000D_
        catch(err) {_x000D_
_x000D_
            console.log("There was an error copying");_x000D_
        }_x000D_
    }
_x000D_
<input type="text" class="unique" size="9" value="SESA / D-ID:" readonly/>_x000D_
<input type="text" class="unique" size="18" value="">_x000D_
<button id="copybtn" onclick="doCopy()"> Copy to clipboard </button>
_x000D_
_x000D_
_x000D_

Deleting an object in C++

Isn't this the normal way to free the memory associated with an object?

This is a common way of managing dynamically allocated memory, but it's not a good way to do so. This sort of code is brittle because it is not exception-safe: if an exception is thrown between when you create the object and when you delete it, you will leak that object.

It is far better to use a smart pointer container, which you can use to get scope-bound resource management (it's more commonly called resource acquisition is initialization, or RAII).

As an example of automatic resource management:

void test()
{
    std::auto_ptr<Object1> obj1(new Object1);

} // The object is automatically deleted when the scope ends.

Depending on your use case, auto_ptr might not provide the semantics you need. In that case, you can consider using shared_ptr.

As for why your program crashes when you delete the object, you have not given sufficient code for anyone to be able to answer that question with any certainty.

Adding a view controller as a subview in another view controller

A couple of observations:

  1. When you instantiate the second view controller, you are calling ViewControllerB(). If that view controller programmatically creates its view (which is unusual) that would be fine. But the presence of the IBOutlet suggests that this second view controller's scene was defined in Interface Builder, but by calling ViewControllerB(), you are not giving the storyboard a chance to instantiate that scene and hook up all the outlets. Thus the implicitly unwrapped UILabel is nil, resulting in your error message.

    Instead, you want to give your destination view controller a "storyboard id" in Interface Builder and then you can use instantiateViewController(withIdentifier:) to instantiate it (and hook up all of the IB outlets). In Swift 3:

    let controller = storyboard!.instantiateViewController(withIdentifier: "scene storyboard id")
    

    You can now access this controller's view.

  2. But if you really want to do addSubview (i.e. you're not transitioning to the next scene), then you are engaging in a practice called "view controller containment". You do not just want to simply addSubview. You want to do some additional container view controller calls, e.g.:

    let controller = storyboard!.instantiateViewController(withIdentifier: "scene storyboard id")
    addChild(controller)
    controller.view.frame = ...  // or, better, turn off `translatesAutoresizingMaskIntoConstraints` and then define constraints for this subview
    view.addSubview(controller.view)
    controller.didMove(toParent: self)
    

    For more information about why this addChild (previously called addChildViewController) and didMove(toParent:) (previously called didMove(toParentViewController:)) are necessary, see WWDC 2011 video #102 - Implementing UIViewController Containment. In short, you need to ensure that your view controller hierarchy stays in sync with your view hierarchy, and these calls to addChild and didMove(toParent:) ensure this is the case.

    Also see Creating Custom Container View Controllers in the View Controller Programming Guide.


By the way, the above illustrates how to do this programmatically. It is actually much easier if you use the "container view" in Interface Builder.

enter image description here

Then you don't have to worry about any of these containment-related calls, and Interface Builder will take care of it for you.

For Swift 2 implementation, see previous revision of this answer.

How to get the selected value from drop down list in jsp?

use jquery

$("#item").change(function({
    var x=$(this).val();
});

Your value will be in x variable, use this variable value in your jsp, like this {x} this statement will give the value

Set padding for UITextField with UITextBorderStyleNone

Here is a Swift code to give padding in UITextfield

 func txtPaddingVw(txt:UITextField) {
     let paddingView = UIView(frame: CGRectMake(0, 0, 10, 10))
     txt.leftViewMode = .Always
     txt.leftView = paddingView
 }

and call using

self.txtPaddingVw(txtPin)

Angular JS update input field after change

I'm guessing that when you enter a value into the totals field that value expression somehow gets overwritten.

However, you can take an alternative approach: Create a field for the total value and when either one or two changes update that field.

<li>Total <input type="text" ng-model="total">{{total}}</li>

And change the javascript:

function TodoCtrl($scope) {
    $scope.$watch('one * two', function (value) {
        $scope.total = value;
    });
}

Example fiddle here.

R dplyr: Drop multiple columns

Check the help on select_vars. That gives you some extra ideas on how to work with this.

In your case:

iris %>% select(-one_of(drop.cols))

How to determine if a list of polygon points are in clockwise order?

This is my solution using the explanations in the other answers:

def segments(poly):
    """A sequence of (x,y) numeric coordinates pairs """
    return zip(poly, poly[1:] + [poly[0]])

def check_clockwise(poly):
    clockwise = False
    if (sum(x0*y1 - x1*y0 for ((x0, y0), (x1, y1)) in segments(poly))) < 0:
        clockwise = not clockwise
    return clockwise

poly = [(2,2),(6,2),(6,6),(2,6)]
check_clockwise(poly)
False

poly = [(2, 6), (6, 6), (6, 2), (2, 2)]
check_clockwise(poly)
True

What's the difference between Perl's backticks, system, and exec?

What's the difference between Perl's backticks (`), system, and exec?

exec -> exec "command"; ,
system -> system("command"); and 
backticks -> print `command`;

exec

exec executes a command and never resumes the Perl script. It's to a script like a return statement is to a function.

If the command is not found, exec returns false. It never returns true, because if the command is found, it never returns at all. There is also no point in returning STDOUT, STDERR or exit status of the command. You can find documentation about it in perlfunc, because it is a function.

E.g.:

#!/usr/bin/perl
print "Need to start exec command";
my $data2 = exec('ls');
print "Now END exec command";
print "Hello $data2\n\n";

In above code, there are three print statements, but due to exec leaving the script, only the first print statement is executed. Also, the exec command output is not being assigned to any variable.

Here, only you're only getting the output of the first print statement and of executing the ls command on standard out.

system

system executes a command and your Perl script is resumed after the command has finished. The return value is the exit status of the command. You can find documentation about it in perlfunc.

E.g.:

#!/usr/bin/perl
print "Need to start system command";
my $data2 = system('ls');
print "Now END system command";
print "Hello $data2\n\n";

In above code, there are three print statements. As the script is resumed after the system command, all three print statements are executed.

Also, the result of running system is assigned to data2, but the assigned value is 0 (the exit code from ls).

Here, you're getting the output of the first print statement, then that of the ls command, followed by the outputs of the final two print statements on standard out.

backticks (`)

Like system, enclosing a command in backticks executes that command and your Perl script is resumed after the command has finished. In contrast to system, the return value is STDOUT of the command. qx// is equivalent to backticks. You can find documentation about it in perlop, because unlike system and exec, it is an operator.

E.g.:

#!/usr/bin/perl
print "Need to start backticks command";
my $data2 = `ls`;
print "Now END system command";
print "Hello $data2\n\n";

In above code, there are three print statements and all three are being executed. The output of ls is not going to standard out directly, but assigned to the variable data2 and then printed by the final print statement.

How to download Javadoc to read offline?

I use javadoc packaged by Allimant since I was in college.

http://www.allimant.org/javadoc/

The javadoc is in the CHM format (standard windows help format), so it's the best viewed when you're using windows.

Android WebView not loading an HTTPS URL

My website is a subdomain which is developed on angular 8 which is also using localstorage and cookies. website showed after setting the below line, along with other solutions mentioned above.

webSettings.setDomStorageEnabled(true);

MySQL string replace

You can simply use replace() function,

with where clause-

update tabelName set columnName=REPLACE(columnName,'from','to') where condition;

without where clause-

update tabelName set columnName=REPLACE(columnName,'from','to');

Note: The above query if for update records directly in table, if you want on select query and the data should not be affected in table then can use the following query-

select REPLACE(columnName,'from','to') as updateRecord;

how to change listen port from default 7001 to something different?

As my experience, you can add another domain which listens different port than 7001, and use this domain in to deploy app.

Here's an example: http://st-curriculum.oracle.com/obe/fmw/wls/10g/r3/installconfig/install_wls/install_wls.htm

HTH.

Object array initialization without default constructor

You can create an array of pointers.

Car** mycars = new Car*[userInput];
for (int i=0; i<userInput; i++){
    mycars[i] = new Car(...);
}

...

for (int i=0; i<userInput; i++){
    delete mycars[i];
}
delete [] mycars;

or

Car() constructor does not need to be public. Add a static method to your class that builds an array:

static Car* makeArray(int length){
    return new Car[length];
}

PHP compare time

Simple way to compare time is :

$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
     // your code
}

How do I increase modal width in Angular UI Bootstrap?

Use max-width on modal-dialog for angular 5

.mod-class .modal-dialog {
    max-width: 1000px;
}

and use windowClass as others recommended, TS eg:

this.modalService.open(content, { windowClass: 'mod-class' }).result.then(
        (result) => {
            // this.closeResult = `Closed with: ${result}`;
         }, (reason) => {
            // this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});

Also, I had to put the css code in global styles > styles.css.

How to create a unique index on a NULL column?

The calculated column trick is widely known as a "nullbuster"; my notes credit Steve Kass:

CREATE TABLE dupNulls (
pk int identity(1,1) primary key,
X  int NULL,
nullbuster as (case when X is null then pk else 0 end),
CONSTRAINT dupNulls_uqX UNIQUE (X,nullbuster)
)

How to fix Terminal not loading ~/.bashrc on OS X Lion

I have the following in my ~/.bash_profile:

if [ -f ~/.bashrc ]; then . ~/.bashrc; fi

If I had .bashrc instead of ~/.bashrc, I'd be seeing the same symptom you're seeing.

How to programmatically determine the current checked out Git branch

Same results as accepted answer in a one-line variable assignment:

branch_name=$((git symbolic-ref HEAD 2>/dev/null || echo "(unnamed branch)")|cut -d/ -f3-)

What Are Some Good .NET Profilers?

I've worked with RedGate's profiler in the past. Did the job for me.

Force "portrait" orientation mode

Set force Portrait or Landscape mode, Add lines respectively.

Import below line:

import android.content.pm.ActivityInfo;

Add Below line just above setContentView(R.layout.activity_main);

For Portrait:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//Set Portrait

For Landscap:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//Set Landscape

This will definitely work.

Changing the text on a label

There are many ways to tackle a problem like this. There are many ways to do this. I'm going to give you the most simple solution to this question I know. When changing the text of a label or any kind of wiget really. I would do it like this.

Name_Of_Label["text"] = "Your New Text"

So when I apply this knowledge to your code. It would look something like this.

from tkinter import*

class MyGUI:
   def __init__(self):
    self.__mainWindow = Tk()
    #self.fram1 = Frame(self.__mainWindow)
    self.labelText = 'Enter amount to deposit'
    self.depositLabel = Label(self.__mainWindow, text = self.labelText)
    self.depositEntry = Entry(self.__mainWindow, width = 10)
    self.depositEntry.bind('<Return>', self.depositCallBack)
    self.depositLabel.pack()
    self.depositEntry.pack()

    mainloop()

  def depositCallBack(self,event):
    self.labelText["text"] = 'change the value'
    print(self.labelText)

myGUI = MyGUI()

If this helps please let me know!

ngModel cannot be used to register form controls with a parent formGroup directive

_x000D_
_x000D_
import { FormControl, FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';_x000D_
_x000D_
_x000D_
    this.userInfoForm = new FormGroup({_x000D_
      userInfoUserName: new FormControl({ value: '' }, Validators.compose([Validators.required])),_x000D_
      userInfoName: new FormControl({ value: '' }, Validators.compose([Validators.required])),_x000D_
      userInfoSurName: new FormControl({ value: '' }, Validators.compose([Validators.required]))_x000D_
    });
_x000D_
<form [formGroup]="userInfoForm" class="form-horizontal">_x000D_
            <div class="form-group">_x000D_
                <label class="control-label"><i>*</i> User Name</label>_x000D_
                    <input type="text" formControlName="userInfoUserName" class="form-control" [(ngModel)]="userInfo.userName">_x000D_
            </div>_x000D_
            <div class="form-group">_x000D_
                <label class="control-label"><i>*</i> Name</label>_x000D_
                    <input type="text" formControlName="userInfoName" class="form-control" [(ngModel)]="userInfo.name">_x000D_
            </div>_x000D_
            <div class="form-group">_x000D_
                <label class="control-label"><i>*</i> Surname</label>_x000D_
                    <input type="text" formControlName="userInfoSurName" class="form-control" [(ngModel)]="userInfo.surName">_x000D_
            </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

In my case I used sudo mkdir projectFolder to create folder. It was owned by root user and I was logged in using non root user.

So I changed the folder permission using command sudo chown mynonrootuser:mynonrootuser projectFolder and then it worked fine.

How to improve a case statement that uses two columns

Just change your syntax ever so slightly:

CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
     ELSE '"DECLINED"'
END

If you don't put the field expression before the CASE statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.

How to convert FormData (HTML5 object) to JSON

If you are using lodash it can be done concisely with fromPairs

import {fromPairs} from 'lodash';

const object = fromPairs(Array.from(formData.entries()));

Java Multiple Inheritance

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.

class A {  
    void msg() {
        System.out.println("From A");
    }  
}

class B {  
    void msg() {
        System.out.println("From B");
    }  
}

class C extends A,B { // suppose if this was possible
    public static void main(String[] args) {  
        C obj = new C();  
        obj.msg(); // which msg() method would be invoked?  
    }
} 

Make a simple fade in animation in Swift?

Swift only solution

Similar to Luca's anwer, I use a UIView extension. Compared to his solution I use DispatchQueue.main.async to make sure animations are done on the main thread, alpha parameter for fading to a specific value and optional duration parameters for cleaner code.

extension UIView {
  func fadeTo(_ alpha: CGFloat, duration: TimeInterval = 0.3) {
    DispatchQueue.main.async {
      UIView.animate(withDuration: duration) {
        self.alpha = alpha
      }
    }
  }

  func fadeIn(_ duration: TimeInterval = 0.3) {
    fadeTo(1.0, duration: duration)
  }

  func fadeOut(_ duration: TimeInterval = 0.3) {
    fadeTo(0.0, duration: duration)
  }
}

How to use it:

// fadeIn() - always animates to alpha = 1.0
yourView.fadeIn()     // uses default duration of 0.3
yourView.fadeIn(1.0)  // uses custom duration (1.0 in this example)

// fadeOut() - always animates to alpha = 0.0
yourView.fadeOut()    // uses default duration of 0.3
yourView.fadeOut(1.0) // uses custom duration (1.0 in this example)

// fadeTo() - used if you want a custom alpha value
yourView.fadeTo(0.5)  // uses default duration of 0.3
yourView.fadeTo(0.5, duration: 1.0)

How do I use namespaces with TypeScript external modules?

Try this namespaces module

namespaceModuleFile.ts

export namespace Bookname{
export class Snows{
    name:any;
    constructor(bookname){
        console.log(bookname);
    }
}
export class Adventure{
    name:any;
    constructor(bookname){
        console.log(bookname);
    }
}
}





export namespace TreeList{
export class MangoTree{
    name:any;
    constructor(treeName){
        console.log(treeName);
    }
}
export class GuvavaTree{
    name:any;
    constructor(treeName){
        console.log(treeName);
    }
}
}

bookTreeCombine.ts

---compilation part---

import {Bookname , TreeList} from './namespaceModule';
import b = require('./namespaceModule');
let BooknameLists = new Bookname.Adventure('Pirate treasure');
BooknameLists = new Bookname.Snows('ways to write a book'); 
const TreeLis = new TreeList.MangoTree('trees present in nature');
const TreeLists = new TreeList.GuvavaTree('trees are the celebraties');

Can we call the function written in one JavaScript in another JS file?

As long as both are referenced by the web page, yes.

You simply call the functions as if they are in the same JS file.

git pull fails "unable to resolve reference" "unable to update local ref"

I had this same issue and solved it by going to the file it was erroring on:

\repo\.git\refs\remotes\origin\master

This file was full of nulls, I replaced it with the latest ref from github.

What is the best way to convert an array to a hash in Ruby

Simply use Hash[*array_variable.flatten]

For example:

a1 = ['apple', 1, 'banana', 2]
h1 = Hash[*a1.flatten(1)]
puts "h1: #{h1.inspect}"

a2 = [['apple', 1], ['banana', 2]]
h2 = Hash[*a2.flatten(1)]
puts "h2: #{h2.inspect}"

Using Array#flatten(1) limits the recursion so Array keys and values work as expected.

JavaScript naming conventions

I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.

Swift Error: Editor placeholder in source file

Sometimes, XCode does not forget the line which had an "Editor Placeholder" even if you have replaced it with a value. Cut the portion of the code where XCode is complaining and paste the code back to the same place to make the error message go away. This worked for me.

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

   SELECT CONVERT(varchar(11),getdate(),101)  -- mm/dd/yyyy

   SELECT CONVERT(varchar(11),getdate(),103)  -- dd/mm/yyyy

Check this . I am assuming D30.SPGD30_TRACKED_ADJUSTMENT_X is of datetime datatype .
That is why i am using CAST() function to make it as an character expression because CHARINDEX() works on character expression.
Also I think there is no need of OR condition.

select case when CHARINDEX('-',cast(D30.SPGD30_TRACKED_ADJUSTMENT_X as varchar )) > 0 

then 'Score Calculation - '+CONVERT(VARCHAR(11), D30.SPGD30_TRACKED_ADJUSTMENT_X, 103)
end

EDIT:

select case when CHARINDEX('-',D30.SPGD30_TRACKED_ADJUSTMENT_X) > 0 
then 'Score Calculation - '+
CONVERT( VARCHAR(11), CAST(D30.SPGD30_TRACKED_ADJUSTMENT_X as DATETIME) , 103)
end

See this link for conversion to other date formats: https://www.w3schools.com/sql/func_sqlserver_convert.asp

How can I store HashMap<String, ArrayList<String>> inside a list?

Always try to use interface reference in Collection, this adds more flexibility.
What is the problem with the below code?

List<Map<String,List<String>>> list = new ArrayList<Map<String,List<String>>>();//This is the final list you need
Map<String, List<String>> map1 = new HashMap<String, List<String>>();//This is one instance of the  map you want to store in the above list.
List<String> arraylist1 = new ArrayList<String>();
arraylist1.add("Text1");//And so on..
map1.put("key1",arraylist1);
//And so on...
list.add(map1);//In this way you can add.

You can easily do it like the above.

Storing Data in MySQL as JSON

json characters are nothing special when it comes down to storage, chars such as

{,},[,],',a-z,0-9.... are really nothing special and can be stored as text.

the first problem your going to have is this

{ profile_id: 22, username: 'Robert', password: 'skhgeeht893htgn34ythg9er' }

that stored in a database is not that simple to update unless you had your own proceedure and developed a jsondecode for mysql

UPDATE users SET JSON(user_data,'username') = 'New User';

So as you cant do that you would Have to first SELECT the json, Decode it, change it, update it, so in theory you might as well spend more time constructing a suitable database structure!

I do use json to store data but only Meta Data, data that dont get updated often, not related to the user specific.. example if a user adds a post, and in that post he adds images ill parse the images and create thumbs and then use the thumb urls in a json format.

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

fig.add_subplot(ROW,COLUMN,POSITION)

  • ROW=number of rows
  • COLUMN=number of columns
  • POSITION= position of the graph you are plotting

Examples

`fig.add_subplot(111)` #There is only one subplot or graph  
`fig.add_subplot(211)`  *and*  `fig.add_subplot(212)` 

There are total 2 rows,1 column therefore 2 subgraphs can be plotted. Its location is 1st. There are total 2 rows,1 column therefore 2 subgraphs can be plotted.Its location is 2nd

Recommendation for compressing JPG files with ImageMagick

If the image has big dimenssions is hard to get good results without resizing, below is a 60 percent resizing which for most of the purposes doesn't destroys too much of the image.

I use this with good result for gray-scale images (I convert from PNG):

ls ./*.png | xargs -L1 -I {} convert {} -strip -interlace JPEG -sampling-factor 4:2:0 -adaptive-resize 60%   -gaussian-blur 0.05 -colorspace Gray -quality 20  {}.jpg

I use this for scanned B&W pages get them to gray-scale images (the extra arguments cleans shadows from previous pages):

ls ./*.png | xargs -L1 -I {} convert {} -strip -interlace JPEG -sampling-factor 4:2:0 -adaptive-resize 60%   -gaussian-blur 0.05 -colorspace Gray -quality 20 -density 300 -fill white -fuzz 40% +opaque "#000000" -density 300 {}.jpg 

I use this for color images:

ls ./*.png | xargs -L1 -I {} convert {} -strip -interlace JPEG -sampling-factor 4:2:0 -adaptive-resize 60%   -gaussian-blur 0.05 -colorspace RGB -quality 20  {}.jpg 

PHP Using RegEx to get substring of a string

<?php
$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string
?>

Using If else in SQL Select statement

Here is some example using CASE WHEN

SELECT 
    CASE WHEN A > 1 THEN
            'Greater than 1'
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 THEN
            A
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 and B > 1 THEN
            'Greater than 1'
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 THEN
            'greater than 1'
         ELSE
            'less than 1'
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 THEN
            'greater than 1'
         ELSE CASE WHEN A >= 0 THEN
                      'greater than or equal 0'
                   ELSE
                      'less than 0'
              END        
    END  
FROM TRIANGLES;

Hope this helps

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

Anti-virus software may interfere with the HAXM installation. After trying to figure out what went wrong for a few hours I found a strange solution - uninstalling my anti-virus software , installing HAXM (which worked) and then re-installing the anti-virus software (Avast in my case but it could happen with other anti-virus programs as well.

The full check I went through to get this running is:

  1. Check the 'Virtualization' and vt-X feature in the BIOS.
  2. Verifying Hyper-V is not installed.
  3. Checking weather vt-X is enabled in windows with the Intel tool and MS tool (mentioned in previous posts in this thread).
  4. Disabling the anti-virus which didn't help.
  5. Uninstalling the anti-virus (which solved the problem for me).

Print PHP Call Stack

Strange that noone posted this way:

debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);

This actually prints backtrace without the garbage - just what method was called and where.

sql query to return differences between two tables

You can use except , for example something like this :

-- DB1..Tb1 have values than DB2..Tb1 not have
Select Col1,Col2,Col3 From DB1..Tb1
except
Select Col1,Col2,Col3 From DB2..Tb1
-- Now we change order
-- DB2..Tb1 have values than DB1..Tb1 not have
Select Col1,Col2,Col3 From DB2..Tb1
except
Select Col1,Col2,Col3 From DB1..Tb1

How to include (source) R script in other scripts

Say util.R produces a function foo(). You can check if this function is available in the global environment and source the script if it isn't:

if(identical(length(ls(pattern = "^foo$")), 0))
    source("util.R")

That will find anything with the name foo. If you want to find a function, then (as mentioned by @Andrie) exists() is helpful but needs to be told exactly what type of object to look for, e.g.

if(exists("foo", mode = "function"))
    source("util.R")

Here is exists() in action:

> exists("foo", mode = "function")
[1] FALSE
> foo <- function(x) x
> exists("foo", mode = "function")
[1] TRUE
> rm(foo)
> foo <- 1:10
> exists("foo", mode = "function")
[1] FALSE

How can I wrap or break long text/word in a fixed width span?

Try this

span {
    display: block;
    width: 150px;
}

Executing a shell script from a PHP script

Without really knowing the complexity of the setup, I like the sudo route. First, you must configure sudo to permit your webserver to sudo run the given command as root. Then, you need to have the script that the webserver shell_exec's(testscript) run the command with sudo.

For A Debian box with Apache and sudo:

  1. Configure sudo:

    • As root, run the following to edit a new/dedicated configuration file for sudo:

      visudo -f /etc/sudoers.d/Webserver
      

      (or whatever you want to call your file in /etc/sudoers.d/)

    • Add the following to the file:

      www-data ALL = (root) NOPASSWD: <executable_file_path>
      

      where <executable_file_path> is the command that you need to be able to run as root with the full path in its name(say /bin/chown for the chown executable). If the executable will be run with the same arguments every time, you can add its arguments right after the executable file's name to further restrict its use.

      For example, say we always want to copy the same file in the /root/ directory, we would write the following:

      www-data ALL = (root) NOPASSWD: /bin/cp /root/test1 /root/test2
      
  2. Modify the script(testscript):

    Edit your script such that sudo appears before the command that requires root privileges(say sudo /bin/chown ... or sudo /bin/cp /root/test1 /root/test2). Make sure that the arguments specified in the sudo configuration file exactly match the arguments used with the executable in this file. So, for our example above, we would have the following in the script:

    sudo /bin/cp /root/test1 /root/test2
    

If you are still getting permission denied, the script file and it's parent directories' permissions may not allow the webserver to execute the script itself. Thus, you need to move the script to a more appropriate directory and/or change the script and parent directory's permissions to allow execution by www-data(user or group), which is beyond the scope of this tutorial.

Keep in mind:

When configuring sudo, the objective is to permit the command in it's most restricted form. For example, instead of permitting the general use of the cp command, you only allow the cp command if the arguments are, say, /root/test1 /root/test2. This means that cp's arguments(and cp's functionality cannot be altered).

how to display excel sheet in html page

Like you, I cannot get MS Office Web Components to work. I would not consider Google Docs since Google seems to think they own anything that passes through their hands. I have tried MS Publish Objects but the quality of the generated html/css is truely awful.

The secret of converting an Excel worksheet to html that will display correctly on a smartphone is to create clean, lean html/css.

The structure of the HTML is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    HEAD
  </head>
  <body>
    BODY
  </body>
</html>

There are useful html elements that can replace "HEAD" but it is not clear to me how you would generate them from an Excel worksheet. They would need to be added separately.

The obvious output for a worksheet or a range is an html table so the following assumes BODY will be replaced by an html table.

The structure of an html table is:

<table TABLE-ATTRIBUTES>
  <tr TABLE-ROW-ATTRIBUTES>
    <td TABLE-CELL-ATTRIBUTES>CELL-VALUE</td>
    More <td>...</td> elements as necessary
  </tr>
  More <tr>...</tr> as necessary
</table>  

Include as few TABLE-ATTRIBUTES, TABLE-ROW-ATTRIBUTES and TABLE-CELL-ATTRIBUTES as possible. Do not set column widths in pixels. Use css attributes rather than html attributes.

A table attribute worth considering is style = "border-collapse: collapse;". The default is separate with a gap around each cell. With collapse the cells touch as they do with Excel.

Three table attribute worth considering are style="background-color:aliceblue;", style="color:#0000FF;" and style="text-align:right;". With the first, you can specify the background colour to be any of the fifty or so named html colours. With the second, you can specify the font colour to be any of 256*256*256 colours. With the third you can right-align numeric values.

The above covers only a fraction of the formatting information that could be converted from Excel to html/css. I am developing an add-in that will convert as much Excel formatting as possible but I hope the above helps anyone with simple requirements.

element not interactable exception in selenium web automation

If it's working in the debug, then wait must be the proper solution.
I will suggest to use the explicit wait, as given below:

WebDriverWait wait = new WebDriverWait(new ChromeDriver(), 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#Passwd")));

Sql query to insert datetime in SQL Server

No need to use convert. Simply list it as a quoted date in ISO 8601 format.
Like so:

select * from table1 where somedate between '2000/01/01' and '2099/12/31'

The separator needs to be a / and it needs to be surrounded by single ' quotes.

OS X Terminal shortcut: Jump to beginning/end of line

fn + leftArraw or fn + rightArrow worked for me!

Convert a SQL query result table to an HTML table for email

This might give you some idea --

CREATE TABLE #Temp 
( 
  [Rank]  [int],
  [Player Name]  [varchar](128),
  [Ranking Points] [int],
  [Country]  [varchar](128)
)


INSERT INTO #Temp
SELECT 1,'Rafael Nadal',12390,'Spain'
UNION ALL
SELECT 2,'Roger Federer',7965,'Switzerland'
UNION ALL
SELECT 3,'Novak Djokovic',7880,'Serbia'


DECLARE @xml NVARCHAR(MAX)
DECLARE @body NVARCHAR(MAX)


SET @xml = CAST(( SELECT [Rank] AS 'td','',[Player Name] AS 'td','',
       [Ranking Points] AS 'td','', Country AS 'td'
FROM  #Temp ORDER BY Rank 
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))


SET @body ='<html><body><H3>Tennis Rankings Info</H3>
<table border = 1> 
<tr>
<th> Rank </th> <th> Player Name </th> <th> Ranking Points </th> <th> Country </th></tr>'    


SET @body = @body + @xml +'</table></body></html>'


EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SQL ALERTING', -- replace with your SQL Database Mail Profile 
@body = @body,
@body_format ='HTML',
@recipients = '[email protected]', -- replace with your email address
@subject = 'E-mail in Tabular Format' ;


DROP TABLE #Temp

How do I serialize an object and save it to a file in Android?

I've tried this 2 options (read/write), with plain objects, array of objects (150 objects), Map:

Option1:

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();

Option2:

SharedPreferences mPrefs=app.getSharedPreferences(app.getApplicationInfo().name, Context.MODE_PRIVATE);
SharedPreferences.Editor ed=mPrefs.edit();
Gson gson = new Gson(); 
ed.putString("myObjectKey", gson.toJson(objectToSave));
ed.commit();

Option 2 is twice quicker than option 1

The option 2 inconvenience is that you have to make specific code for read:

Gson gson = new Gson();
JsonParser parser=new JsonParser();
//object arr example
JsonArray arr=parser.parse(mPrefs.getString("myArrKey", null)).getAsJsonArray();
events=new Event[arr.size()];
int i=0;
for (JsonElement jsonElement : arr)
    events[i++]=gson.fromJson(jsonElement, Event.class);
//Object example
pagination=gson.fromJson(parser.parse(jsonPagination).getAsJsonObject(), Pagination.class);

Resize image in the wiki of GitHub using Markdown

This addresses the different question, how to get images in gist (as opposed to github) markdown in the first place ?


In December 2015, it seems that only links to files on github.com or cloud.githubusercontent.com or the like work. Steps that worked for me in a gist:

  1. Make a gist, say Mygist.md (and optionally more files)
  2. Go to the "Write Comment" box at the end
  3. Click "Attach files ... by selecting them"; select your local image file
  4. GitHub echos a long long string where it put the image, e.g. ![khan-lasso-squared](https://cloud.githubusercontent.com/assets/1280390/12011119/596fdca4-acc2-11e5-84d0-4878164e04bb.png)
  5. Cut-paste that by hand into your Mygist.md.

But: GitHub people may change this behavior tomorrow, without documenting it.

Getting MAC Address

For Linux you can retrieve the MAC address using a SIOCGIFHWADDR ioctl.

struct ifreq    ifr;
uint8_t         macaddr[6];

if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0)
    return -1;

strcpy(ifr.ifr_name, "eth0");

if (ioctl(s, SIOCGIFHWADDR, (void *)&ifr) == 0) {
    if (ifr.ifr_hwaddr.sa_family == ARPHRD_ETHER) {
        memcpy(macaddr, ifr.ifr_hwaddr.sa_data, 6);
        return 0;
... etc ...

You've tagged the question "python". I don't know of an existing Python module to get this information. You could use ctypes to call the ioctl directly.

How to insert a new key value pair in array in php?

To add:

$arr["key"] = "value";

Then simply return $arr

Can't return directly like this way return $arr["key"] = "value";

What is the HTML tabindex attribute?

the values you set determine the order that your keyboard focus will move between elements on the website.

In the following example, the first time you press tab, your cursor will move to #foo, then #awesome, then #bar

<input id="foo" tabindex="1"  />
<input id="bar" tabindex="3"  />
<input id="awesome" tabindex="2"  />

If you have not defined tab indexes anywhere, the keyboard focus will follow the HTML tags of you page in the order in which they are defined in the HTML document.

If you tab more times than you have specified tabindexes for, the focus will move as if there were no tabindexes, i.e. in the order of appearance of the HTML tags

How to reset / remove chrome's input highlighting / focus border?

This will definitely work. Orange outline won't show up anymore.. Common for all tags:

*:focus {
    outline: none;
   }

Specific to some tag, ex: input tag

input:focus{
   outline:none;
  }

How do I create a WPF Rounded Corner container?

You don't need a custom control, just put your container in a border element:

<Border BorderBrush="#FF000000" BorderThickness="1" CornerRadius="8">
   <Grid/>
</Border>

You can replace the <Grid/> with any of the layout containers...

Access to Image from origin 'null' has been blocked by CORS policy

For local development you could serve the files with a simple web server.

With Python installed, go into the folder where your project is served, like cd my-project/. And then use python -m SimpleHTTPServer which would make index.html and it's JavaScript files available at localhost:8000.

How to update primary key

You shouldn't really do this but insert in a new record instead and update it that way.
But, if you really need to, you can do the following:

  • Disable enforcing FK constraints temporarily (e.g. ALTER TABLE foo WITH NOCHECK CONSTRAINT ALL)
  • Then update your PK
  • Then update your FKs to match the PK change
  • Finally enable back enforcing FK constraints

how to convert an RGB image to numpy array?

OpenCV image format supports the numpy array interface. A helper function can be made to support either grayscale or color images. This means the BGR -> RGB conversion can be conveniently done with a numpy slice, not a full copy of image data.

Note: this is a stride trick, so modifying the output array will also change the OpenCV image data. If you want a copy, use .copy() method on the array!

import numpy as np

def img_as_array(im):
    """OpenCV's native format to a numpy array view"""
    w, h, n = im.width, im.height, im.channels
    modes = {1: "L", 3: "RGB", 4: "RGBA"}
    if n not in modes:
        raise Exception('unsupported number of channels: {0}'.format(n))
    out = np.asarray(im)
    if n != 1:
        out = out[:, :, ::-1]  # BGR -> RGB conversion
    return out

querying WHERE condition to character length?

Sorry, I wasn't sure which SQL platform you're talking about:

In MySQL:

$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");

in MSSQL

$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");

The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.

Edit

I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.

So, for MySQL there's the CHAR_LENGTH(). The following example highlights the difference between LENGTH() an CHAR_LENGTH():

CREATE TABLE words (
    word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;

INSERT INTO words(word) VALUES('??'), ('happy'), ('hayir');

SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;

+--------+-----------+----------------+
| word   | num_bytes | num_characters |
+--------+-----------+----------------+
| ??    |         6 |              2 |
| happy  |         5 |              5 |
| hayir  |         6 |              5 |
+--------+-----------+----------------+

Be careful if you're dealing with multi-byte characters.

Setting up Eclipse with JRE Path

I have several version of JDK (not JRE) instaled and I launch Eclipse with:

C:\eclipse\eclipse.exe -vm "%JAVA_HOME%\bin\javaw.exe" -data f:\dev\java\2013

As you can see, I set JAVA_HOME to point to the version of JDK I want to use.

I NEVER add javaw.exe in the PATH.

-data is used to choose a workspace for a particular job/client/context.

PostgreSQL visual interface similar to phpMyAdmin?

phpPgAdmin might work for you, if you're already familiar with phpMyAdmin.

Please note that development of phpPgAdmin has moved to github per this notice but the SourceForge link above is for historical / documentation purposes.

But really there are dozens of tools that can do this.

How do I get the directory from a file's full path?

Use below mentioned code to get the folder path

Path.GetDirectoryName(filename);

This will return "C:\MyDirectory" in your case

TypeError: sequence item 0: expected string, int found

Replace

values = ",".join(value_list)

with

values = ','.join([str(i) for i in value_list])

OR

values = ','.join(str(value_list)[1:-1])

How do I change an HTML selected option using JavaScript?

I believe that the blog post JavaScript Beginners – Select a dropdown option by value might help you.

<a href="javascript:void(0);" onclick="selectItemByValue(document.getElementById('personlist'),11)">change</a>

function selectItemByValue(elmnt, value){

  for(var i=0; i < elmnt.options.length; i++)
  {
    if(elmnt.options[i].value === value) {
      elmnt.selectedIndex = i;
      break;
    }
  }
}

Difference between Apache CXF and Axis

One more thing is the activity of the community. Compare the mailing list traffic for axis and cxf (2013).

So if this is any indicator of usage then axis is by far less used than cxf.

Compare CXF and Axis statistics at ohloh. CXF has very high activity while Axis has low activity overall.

This is the chart for the number of commits over time for CXF (red) and Axis1 (green) Axis2 (blue). enter image description here

How to downgrade or install an older version of Cocoapods

Several notes:

Make sure you first get a list of all installed versions. I actually had the version I wanted to downgrade to already installed, but ended up uninstalling that as well. To see the list of all your versions do:

sudo gem list cocoapods

Then when you want to delete a version, specify that version.

sudo gem uninstall cocoapods -v 1.6.2

You could remove the version specifier -v 1.6.2 and that would delete all versions:

You may try all this and still see that the Cocoapods you expected is still installed. If that's the case then it might be because Cocoaposa is stored in a different directory.

sudo gem uninstall -n /usr/local/bin cocoapods -v 1.6.2

Then you will have to also install it in a different directory, otherwise you may get an error saying You don't have write permissions for the /usr/bin directory

sudo gem install -n /usr/local/bin cocoapods -v 1.6.1

To check which version is your default do:

pod --version

For more on the directory problem see here

Sorting an ArrayList of objects using a custom sorting order

BalusC and bguiz have already given very complete answers on how to use Java's built-in Comparators.

I just want to add that google-collections has an Ordering class which is more "powerful" than the standard Comparators. It might be worth checking out. You can do cool things such as compounding Orderings, reversing them, ordering depending on a function's result for your objects...

Here is a blog post that mentions some of its benefits.

Rolling back local and remote git repository by 1 commit

on local master

git reflog
-- this will list all last commit
  e.g Head@{0} -- wrong push
      Head@{1} -- correct push  
git checkout Head@{1} .
  -- this will reset your last modified files

git status 
git commit -m "reverted to last best"
git push origin/master

No need to worry if other has pulled or not.

Done!

How to retrieve an element from a set without removing it?

Seemingly the most compact (6 symbols) though very slow way to get a set element (made possible by PEP 3132):

e,*_=s

With Python 3.5+ you can also use this 7-symbol expression (thanks to PEP 448):

[*s][0]

Both options are roughly 1000 times slower on my machine than the for-loop method.

How to add scroll bar to the Relative Layout?

You want to enclose it with a scrollView.

Get current directory name (without full path) in a Bash script

Use:

basename "$PWD"

OR

IFS=/ 
var=($PWD)
echo ${var[-1]} 

Turn the Internal Filename Separator (IFS) back to space.

IFS= 

There is one space after the IFS.

How to get only filenames within a directory using c#?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetNameOfFiles
{
    public class Program
    {
        static void Main(string[] args)
        {
           string[] fileArray = Directory.GetFiles(@"YOUR PATH");
           for (int i = 0; i < fileArray.Length; i++)
           {

               Console.WriteLine(fileArray[i]);
           }
            Console.ReadLine();
        }
    }
}

Trying to check if username already exists in MySQL database using PHP

change your query to like.

$username = mysql_real_escape_string($username); // escape string before passing it to query.
$query = mysql_query("SELECT username FROM Users WHERE username='".$username."'");

However, MySQL is deprecated. You should instead use MySQLi or PDO

Primitive type 'short' - casting in Java

Given that the "why int by default" question hasn't been answered ...

First, "default" is not really the right term (although close enough). As noted by VonC, an expression composed of ints and longs will have a long result. And an operation consisting of ints/logs and doubles will have a double result. The compiler promotes the terms of an expression to whatever type provides a greater range and/or precision in the result (floating point types are presumed to have greater range and precision than integral, although you do lose precision converting large longs to double).

One caveat is that this promotion happens only for the terms that need it. So in the following example, the subexpression 5/4 uses only integral values and is performed using integer math, even though the overall expression involves a double. The result isn't what you might expect...

(5/4) * 1000.0

OK, so why are byte and short promoted to int? Without any references to back me up, it's due to practicality: there are a limited number of bytecodes.

"Bytecode," as its name implies, uses a single byte to specify an operation. For example iadd, which adds two ints. Currently, 205 opcodes are defined, and integer math takes 18 for each type (ie, 36 total between integer and long), not counting conversion operators.

If short, and byte each got their own set of opcodes, you'd be at 241, limiting the ability of the JVM to expand. As I said, no references to back me up on this, but I suspect that Gosling et al said "how often do people actually use shorts?" On the other hand, promoting byte to int leads to this not-so-wonderful effect (the expected answer is 96, the actual is -16):

byte x = (byte)0xC0;
System.out.println(x >> 2);

How to start color picker on Mac OS?

Take a look into NSColorWell class reference.

How to fix 'Microsoft Excel cannot open or save any more documents'

After giving necessary permissions in DCOM configurations I also needed to change the identity of my application in the IIS to a custom account

How do I download/extract font from chrome developers tools?

I found the Chrome option to be OK but there are quite a few steps to go through to get to the font files. Once you're there, the downloading is super easy. I usually use the dev tools in Safari as there are fewer steps. Just go to the page you want, click on "Show page source" or "show page resources" in the Developer menu (both work for this) and the page resources are listed in folders on the left hand side. Click the font folder and the fonts are listed. Right click and save file. If you are downloading a lot of font files from one site it may be quicker to work your way through Chrome's pathway as the "open in tab" does download the fonts quicker. If you're taking one or two fonts from a lot of different sites, Safari will be quicker overall.

Tips for debugging .htaccess rewrite rules

Some mistakes I observed happens when writing .htaccess

Using of ^(.*)$ repetitively in multiple rules, using ^(.*)$ causes other rules to be impotent in most cases, because it matches all of the url in single hit.

So, if we are using rule for this url sapmle/url it will also consume this url sapmle/url/string.


[L] flag should be used to ensure our rule has done processing.


Should know about:

Difference in %n and $n

%n is matched during %{RewriteCond} part and $n is matches on %{RewriteRule} part.

Working of RewriteBase

The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path.

This directive is required when you use a relative path in a substitution in per-directory (htaccess) context unless any of the following conditions are true:

The original request, and the substitution, are underneath the DocumentRoot (as opposed to reachable by other means, such as Alias). The filesystem path to the directory containing the RewriteRule, suffixed by the relative substitution is also valid as a URL path on the server (this is rare). In Apache HTTP Server 2.4.16 and later, this directive may be omitted when the request is mapped via Alias or mod_userdir.

How do I suspend painting for a control and its children?

Or just use Control.SuspendLayout() and Control.ResumeLayout().

Datatables warning(table id = 'example'): cannot reinitialise data table

You have to destroy the datatable and empty the table body before binding DataTable by doing this below,

function Create() {
if ($.fn.DataTable.isDataTable('#dataTable')) {
    $('#dataTable').DataTable().destroy();
}
$('#dataTable tbody').empty();
//Here call the Datatable Bind function;} 

How can I mix LaTeX in with Markdown?

What language are you using?

If you can use ruby, then maruku can be configured to process maths using various latex->MathML converters. Instiki uses this. It's also possible to extend PHPMarkdown to use itex2MML as well to convert maths. Basically, you insert extra steps in the Markdown engine at the appropriate points.

So with ruby and PHP, this is done. I guess these solutions could also be adapted to other languages - I've gotten the itex2MML extension to produce perl bindings as well.

How to convert an array to a string in PHP?

PHP's implode function can be used to convert an array into a string --- it is similar to join in other languages.

You can use it like so:

$string_product = implode(',', $array);

With an array like [1, 2, 3], this would result in a string like "1,2,3".

Java ElasticSearch None of the configured nodes are available

Check the ES server logs

sudo tail -f /var/log/elasticsearch/elasticsearch.log

I was using an outdated client

Received message from unsupported version: [5.0.0] minimal compatible version is: [6.8.0]

What online brokers offer APIs?

Looks like E*Trade has an API now.

For access to historical data, I've found EODData to have reasonable prices for their data dumps. For side projects, I can't afford (rather don't want to afford) a huge subscription fee just for some data to tinker with.

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

You can use the .tostring() method with datetime format specifiers to format to whatever you need:

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

(Get-Date).AddDays(-1).ToString('MM-dd-yyyy')
11-01-2013

Automatic HTTPS connection/redirect with node.js/express

The idea is to check if the incoming request is made with https, if so simply don't redirect it again to https but continue as usual. Else, if it is http, redirect it with appending https.

app.use (function (req, res, next) {
  if (req.secure) {
          next();
  } else {
          res.redirect('https://' + req.headers.host + req.url);
  }
});

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

Socket accept - "Too many open files"

Just another information about CentOS. In this case, when using "systemctl" to launch process. You have to modify the system file ==> /usr/lib/systemd/system/processName.service .Had this line in the file :

LimitNOFILE=50000

And just reload your system conf :

systemctl daemon-reload

How to delete an app from iTunesConnect / App Store Connect

Apps can’t be deleted if they are part of a Game Center group, in an app bundle, or currently displayed on a store. You’ll want to remove the app from sale or from the group if you want to delete it.

Source: iTunes Connect Developer Guide - Transferring and Deleting Apps

With CSS, how do I make an image span the full width of the page as a background image?

If you're hoping to use background-image: url(...);, I don't think you can. However, if you want to play with layering, you can do something like this:

<img class="bg" src="..." />

And then some CSS:

.bg
{
  width: 100%;
  z-index: 0;
}

You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%; to apply to the whole page.

Here's a quick demo if you can't rely on background-size: http://jsfiddle.net/bB3Uc/

Sublime Text 2 - View whitespace characters

Here is an Offical tutorial of how to that!
http://sublimetexttips.com/show-whitespace-sublime-text/

just like this!

enter image description here
enter image description here

Hope help for your!

Fastest way to add an Item to an Array

Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
ReDim Preserve arr (3)
arr(3)=newItem

for more info Redim

How to use the PI constant in C++

Rather than writing

#define _USE_MATH_DEFINES

I would recommend using -D_USE_MATH_DEFINES or /D_USE_MATH_DEFINES depending on your compiler.

This way you are assured that even in the event of someone including the header before you do (and without the #define) you will still have the constants instead of an obscure compiler error that you will take ages to track down.

Creating multiple log files of different content with log4j

For the main logfile/appender, set up a .Threshold = INFO to limit what is actually logged in the appender to INFO and above, regardless of whether or not the loggers have DEBUG, TRACE, etc, enabled.

As for catching DEBUG and nothing above that... you'd probably have to write a custom appender.

However I'd recommend not doing this, as it sounds like it would make troubleshooting and analysis pretty hard:

  1. If your goal is to have a single file where you can look to troubleshoot something, then spanning your log data across different files will be annoying - unless you have a very regimented logging policy, you'll likely need content from both DEBUG and INFO to be able to trace execution of the problematic code effectively.
  2. By still logging all of your debug messages, you are losing any performance gains you usually get in a production system by turning the logging (way) down.

bower command not found

Just like in this question (npm global path prefix) all you need is to set proper npm prefix.

UNIX:

$ npm config set prefix /usr/local
$ npm install -g bower

$ which bower
>> /usr/local/bin/bower

Windows ans NVM:

$ npm config set prefix /c/Users/xxxxxxx/AppData/Roaming/nvm/v8.9.2
$ npm install -g bower

Then bower should be located just in your $PATH.

Redirect to Action by parameter mvc

Try this,

return RedirectToAction("ActionEventName", "Controller", new { ID = model.ID, SiteID = model.SiteID });

Here i mention you are pass multiple values or model also. That's why here i mention that.

Failed to run sdkmanager --list with Java 9

Another solution possible to this error is check your Java version, maybe you can solve it downloading this jdk oracle-jdk-8, this was my mistake :P

Convert string with comma to integer

If someone is looking to sub out more than a comma I'm a fan of:

"1,200".chars.grep(/\d/).join.to_i

dunno about performance but, it is more flexible than a gsub, ie:

"1-200".chars.grep(/\d/).join.to_i

Git Cherry-pick vs Merge Workflow

Rebase and Cherry-pick is the only way you can keep clean commit history. Avoid using merge and avoid creating merge conflict. If you are using gerrit set one project to Merge if necessary and one project to cherry-pick mode and try yourself.

How can I zoom an HTML element in Firefox and Opera?

try this code to zoom the whole page in fireFox

-moz-transform: scale(2);

if I am using this code, the whole page scaled with y and x scroll not properly zoom

so Sorry to say fireFox not working well using "-moz-transform: scale(2);"

**

Simply you can't zoom your page using css in fireFox

**

null terminating a string

'\0' is the way to go. It's a character, which is what's wanted in a string and has the null value.

When we say null terminated string in C/C++, it really means 'zero terminated string'. The NULL macro isn't intended for use in terminating strings.

Struct memory layout in C

You can start by reading the data structure alignment wikipedia article to get a better understanding of data alignment.

From the wikipedia article:

Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

From 6.54.8 Structure-Packing Pragmas of the GCC documentation:

For compatibility with Microsoft Windows compilers, GCC supports a set of #pragma directives which change the maximum alignment of members of structures (other than zero-width bitfields), unions, and classes subsequently defined. The n value below always is required to be a small power of two and specifies the new alignment in bytes.

  1. #pragma pack(n) simply sets the new alignment.
  2. #pragma pack() sets the alignment to the one that was in effect when compilation started (see also command line option -fpack-struct[=] see Code Gen Options).
  3. #pragma pack(push[,n]) pushes the current alignment setting on an internal stack and then optionally sets the new alignment.
  4. #pragma pack(pop) restores the alignment setting to the one saved at the top of the internal stack (and removes that stack entry). Note that #pragma pack([n]) does not influence this internal stack; thus it is possible to have #pragma pack(push) followed by multiple #pragma pack(n) instances and finalized by a single #pragma pack(pop).

Some targets, e.g. i386 and powerpc, support the ms_struct #pragma which lays out a structure as the documented __attribute__ ((ms_struct)).

  1. #pragma ms_struct on turns on the layout for structures declared.
  2. #pragma ms_struct off turns off the layout for structures declared.
  3. #pragma ms_struct reset goes back to the default layout.

Select arrow style change

This would work well especially for those using Bootstrap, tested in latest browser versions:

_x000D_
_x000D_
select {_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
  /* Some browsers will not display the caret when using calc, so we put the fallback first */ _x000D_
  background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat 98.5% !important; /* !important used for overriding all other customisations */_x000D_
  background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat calc(100% - 10px) !important; /* Better placement regardless of input width */_x000D_
}_x000D_
/*For IE*/_x000D_
select::-ms-expand { display: none; }
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-6">_x000D_
      <select class="form-control">_x000D_
       <option>Option 1</option>_x000D_
       <option>Option 2</option>_x000D_
       <option>Option 3</option>_x000D_
      </select>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_