Programs & Examples On #Time bomb

Install apps silently, with granted INSTALL_PACKAGES permission

Your first bet is to look into Android's native PackageInstaller. I would recommend modifying that app the way you like, or just extract required functionality.


Specifically, if you look into PackageInstallerActivity and its method onClickListener:

 public void onClick(View v) {
    if(v == mOk) {
        // Start subactivity to actually install the application
        Intent newIntent = new Intent();
        ...
        newIntent.setClass(this, InstallAppProgress.class);
        ...
        startActivity(newIntent);
        finish();
    } else if(v == mCancel) {
        // Cancel and finish
        finish();
    }
}

Then you'll notice that actual installer is located in InstallAppProgress class. Inspecting that class you'll find that initView is the core installer function, and the final thing it does is call to PackageManager's installPackage function:

public void initView() {
...
pm.installPackage(mPackageURI, observer, installFlags, installerPackageName);
}

Next step is to inspect PackageManager, which is abstract class. You'll find installPackage(...) function there. The bad news is that it's marked with @hide. This means it's not directly available (you won't be able to compile with call to this method).

 /**
  * @hide
  * ....
  */
  public abstract void installPackage(Uri packageURI,
             IPackageInstallObserver observer, 
             int flags,String installerPackageName); 

But you will be able to access this methods via reflection.

If you are interested in how PackageManager's installPackage function is implemented, take a look at PackageManagerService.

Summary

You'll need to get package manager object via Context's getPackageManager(). Then you will call installPackage function via reflection.

How to enable file sharing for my app?

In Xcode 8.3.3 add new row in .plist with true value

Application supports iTunes file sharing

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Hi I tested below code that worked fine :

    long timeInMillis = System.currentTimeMillis();
    Calendar cal1 = Calendar.getInstance();
    cal1.setTimeInMillis(timeInMillis);
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
    dateFormat.format(cal1.getTime());

Remove NaN from pandas series

A small usage of np.nan ! = np.nan

s[s==s]
Out[953]: 
0    1.0
1    2.0
2    3.0
3    4.0
5    5.0
dtype: float64

More Info

np.nan == np.nan
Out[954]: False

Returning data from Axios API

IMO extremely important rule of thumb for your client side js code is to keep separated the data handling and ui building logic into different funcs, which is also valid for axios data fetching ... in this way your control flow and error handlings will be much more simple and easier to manage, as it could be seen from this ok fetch

and this NOK fetch

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>

       function getUrlParams (){
          var url_params = new URLSearchParams();
          if( window.location.toString().indexOf("?") != -1) {
             var href_part = window.location.search.split('?')[1]
             href_part.replace(/([^=&]+)=([^&]*)/g,
                function(m, key, value) {
                   var attr = decodeURIComponent(key)
                   var val = decodeURIComponent(value)
                   url_params.append(attr,val);
             });
          }
          // for(var pair of url_params.entries()) { consolas.log(pair[0]+ '->'+ pair[1]); }
          return url_params ;
       }


      function getServerData (url, urlParams ){
          if ( typeof url_params == "undefined" ) { urlParams = getUrlParams()  }
          return axios.get(url , { params: urlParams } )
          .then(response => {
             return response ;
          })
          .catch(function(error) {
             console.error ( error )
             return error.response;
          })
       }

    // Action !!!
    getServerData(url , url_params)
        .then( response => {
           if ( response.status === 204 ) {
              var warningMsg = response.statusText
              console.warn ( warningMsg )
              return
           } else if ( response.status === 404 || response.status === 400) {
              var errorMsg = response.statusText // + ": "  + response.data.msg // this is my api
              console.error( errorMsg )
              return ;
           } else {
              var data = response.data
              var dataType = (typeof data)
              if ( dataType === 'undefined' ) {
                 var msg = 'unexpected error occurred while fetching data !!!'
                 // pass here to the ui change method the msg aka
                 // showMyMsg ( msg , "error")
              } else {
                 var items = data.dat // obs this is my api aka "dat" attribute - that is whatever happens to be your json key to get the data from
                 // call here the ui building method
                 // BuildList ( items )
              }
              return
           }

        })




    </script>

Proper usage of Java -D command-line parameters

I suspect the problem is that you've put the "-D" after the -jar. Try this:

java -Dtest="true" -jar myApplication.jar

From the command line help:

java [-options] -jar jarfile [args...]

In other words, the way you've got it at the moment will treat -Dtest="true" as one of the arguments to pass to main instead of as a JVM argument.

(You should probably also drop the quotes, but it may well work anyway - it probably depends on your shell.)

Base64 Encoding Image

Check the following example:

// First get your image
$imgPath = 'path-to-your-picture/image.jpg';
$img = base64_encode(file_get_contents($imgPath));
echo '<img width="100" height="100" src="data:image/jpg;base64,'. $img .'" />'

How can I use goto in Javascript?

const
    start = 0,
    more = 1,
    pass = 2,
    loop = 3,
    skip = 4,
    done = 5;

var label = start;


while (true){
    var goTo = null;
    switch (label){
        case start:
            console.log('start');
        case more:
            console.log('more');
        case pass:
            console.log('pass');
        case loop:
            console.log('loop');
            goTo = pass; break;
        case skip:
            console.log('skip');
        case done:
            console.log('done');

    }
    if (goTo == null) break;
    label = goTo;
}

The Import android.support.v7 cannot be resolved

I tried the answer described here but it doesn´t worked for me. I have the last Android SDK tools ver. 23.0.2 and Android SDK Platform-tools ver. 20

The support library android-support-v4.jar is causing this conflict, just delete the library under /libs folder of your project, don´t be scared, the library is already contained in the library appcompat_v7, clean and build your project, and your project will work like a charm!

enter image description here

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

Try this:

var sql = @"Update [User] SET FirstName = @FirstName WHERE Id = @Id";

ctx.Database.ExecuteSqlCommand(
    sql,
    new SqlParameter("@FirstName", firstname),
    new SqlParameter("@Id", id));

How to get the current time in Google spreadsheet using script editor?

The Date object is used to work with dates and times.

Date objects are created with new Date().

var date= new Date();

 function myFunction() {
        var currentTime = new Date();
        Logger.log(currentTime);
    }

How to convert a table to a data frame

This is deprecated:

as.data.frame(my_table)

Instead use this package:

library("quanteda")
convert(my_table, to="data.frame") 

Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android

Try this way,hope this will help you to solve your problem.

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

MyActivity.java

public class MyActivity extends Activity {

    private WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        webView = (WebView) findViewById(R.id.webView);
        webView.loadData("<a href=\"tel:+1800229933\">Call us free!</a>", "text/html", "utf-8");
    }

}

Please add this permission in AndroidManifest.xml

<uses-permission android:name="android.permission.CALL_PHONE"/>

Prevent Sequelize from outputting SQL to the console on execution of query?

As in other answers, you can just set logging:false, but I think better than completely disabling logging, you can just embrace log levels in your app. Sometimes you may want to take a look at the executed queries so it may be better to configure Sequelize to log at level verbose or debug. for example (I'm using winston here as a logging framework but you can use any other framework) :

var sequelize = new Sequelize('database', 'username', 'password', {
  logging: winston.debug
});

This will output SQL statements only if winston log level is set to debug or lower debugging levels. If log level is warn or info for example SQL will not be logged

What does "javascript:void(0)" mean?

You should always have an href on your a tags. Calling a JavaScript function that returns 'undefined' will do just fine. So will linking to '#'.

Anchor tags in Internet Explorer 6 without an href do not get the a:hover style applied.

Yes, it is terrible and a minor crime against humanity, but then again so is Internet Explorer 6 in general.

I hope this helps.

Internet Explorer 6 is actually a major crime against humanity.

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Better and quicker approach without any software to download.

  • Open command prompt and follow steps mentioned below
  • cd path/from/where/file/istobe/copied
  • ftp (serverip or name)
  • It will ask for Server(AIX) User: (username)
  • It will ask for password : (password)
  • cd path/where/file/istobe/copied
  • pwd (to check current path)
  • mput (directory name which is to be copied)

This should work.

Removing "NUL" characters

Try Find and Replace. type \x00 in Find text box, check the Regular expression option. Leave Replace textbox blank and click on replace all. short cut key for find and replace is ctrl+H.

Create a string of variable length, filled with a repeated character

ES2015 the easiest way is to do something like

'X'.repeat(data.length)

X being any string, data.length being the desired length.

see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

Apache Spark: map vs mapPartitions?

Map:

Map transformation.

The map works on a single Row at a time.

Map returns after each input Row.

The map doesn’t hold the output result in Memory.

Map no way to figure out then to end the service.

// map example

val dfList = (1 to 100) toList

val df = dfList.toDF()

val dfInt = df.map(x => x.getInt(0)+2)

display(dfInt)

MapPartition:

MapPartition transformation.

MapPartition works on a partition at a time.

MapPartition returns after processing all the rows in the partition.

MapPartition output is retained in memory, as it can return after processing all the rows in a particular partition.

MapPartition service can be shut down before returning.

// MapPartition example

Val dfList = (1 to 100) toList

Val df = dfList.toDF()

Val df1 = df.repartition(4).rdd.mapPartition((int) => Iterator(itr.length))

Df1.collec()

//display(df1.collect())

For more details, please refer to the Spark map vs mapPartitions transformation article.

Hope this is helpful!

MS Access VBA: Sending an email through Outlook

Here is email code I used in one of my databases. I just made variables for the person I wanted to send it to, CC, subject, and the body. Then you just use the DoCmd.SendObject command. I also set it to "True" after the body so you can edit the message before it automatically sends.

Public Function SendEmail2()

Dim varName As Variant          
Dim varCC As Variant            
Dim varSubject As Variant      
Dim varBody As Variant          

varName = "[email protected]"
varCC = "[email protected], [email protected]"
'separate each email by a ','

varSubject = "Hello"
'Email subject

varBody = "Let's get ice cream this week"

'Body of the email
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
'Send email command. The True after "varBody" allows user to edit email before sending.
'The False at the end will not send it as a Template File

End Function

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

you just run adb uninstall {{package_name}}. That's it. Now you try the build.

Errors: Data path ".builders['app-shell']" should have required property 'class'

Try update the package.json file from

  "@angular-devkit/build-angular": "^0.800.1" 

to

  "@angular-devkit/build-angular": "^0.12.4"

Then run npm install in the command line.

How do I make a semi transparent background?

Although dated, not one answer on this thread can be used universally. Using rgba to create transparent color masks - that doesn't exactly explain how to do so with background images.

My solution works for background images or color backgrounds.

_x000D_
_x000D_
#parent {_x000D_
    font-family: 'Open Sans Condensed', sans-serif;_x000D_
    font-size: 19px;_x000D_
    text-transform: uppercase;_x000D_
    border-radius: 50%;_x000D_
    margin: 20px auto;_x000D_
    width: 125px;_x000D_
    height: 125px;_x000D_
    background-color: #476172;_x000D_
    background-image: url('https://unsplash.it/200/300/?random');_x000D_
    line-height: 29px;_x000D_
    text-align:center;_x000D_
}_x000D_
_x000D_
#content {_x000D_
    color: white;_x000D_
    height: 125px !important;_x000D_
    width: 125px !important;_x000D_
    display: table-cell;_x000D_
    border-radius: 50%;_x000D_
    vertical-align: middle;_x000D_
    background: rgba(0,0,0, .3);_x000D_
}
_x000D_
<h1 id="parent"><a href="" id="content" title="content" rel="home">Example</a></h1>
_x000D_
_x000D_
_x000D_

What is a magic number, and why is it bad?

@eed3si9n: I'd even suggest that '1' is a magic number. :-)

A principle that's related to magic numbers is that every fact your code deals with should be declared exactly once. If you use magic numbers in your code (such as the password length example that @marcio gave, you can easily end up duplicating that fact, and when your understand of that fact changes you've got a maintenance problem.

Send XML data to webservice using php curl

Check this one. It will work.

function fetch($i1,$i2,$i3,$i4)
{
$input_data = '<I> 
                <i1>'.$i1.'</i1> 
                <i2>'.$i2.'</i2> 
                <i3>'.$i2.'</i3> 
                <i4>'.$i3.'</i4> 
              </I>';
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_PORT => "8080",
  CURLOPT_URL => "http://192.168.1.100:8080/avaliablity",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $input_data,
  CURLOPT_HTTPHEADER => array(
    "Cache-Control: no-cache",
    "Content-Type: application/xml"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
}

fetch('i1','i2','i3','i4');

How to get a unique device ID in Swift?

You can use devicecheck (in Swift 4) Apple documentation

func sendEphemeralToken() {
        //check if DCDevice is available (iOS 11)

        //get the **ephemeral** token
        DCDevice.current.generateToken {
        (data, error) in
        guard let data = data else {
            return
        }

        //send **ephemeral** token to server to 
        let token = data.base64EncodedString()
        //Alamofire.request("https://myServer/deviceToken" ...
    }
}

Typical usage:

Typically, you use the DeviceCheck APIs to ensure that a new user has not already redeemed an offer under a different user name on the same device.

Server action needs:

See WWDC 2017 — Session 702 (24:06)

more from Santosh Botre article - Unique Identifier for the iOS Devices

Your associated server combines this token with an authentication key that you receive from Apple and uses the result to request access to the per-device bits.

Windows CMD command for accessing usb?

You can access the USB drive by its drive letter. To know the drive letter you can run this command:

C:\>wmic logicaldisk where drivetype=2 get deviceid, volumename, description

From here you will get the drive letter (Device ID) of your USB drive.

For example if its F: then run the following command in command prompt to see its contents:

C:\> F:

F:\> dir

What is the use of the square brackets [] in sql statements?

During the dark ages of SQL in the 1990s it was a good practice as the SQL designers were trying to add each word in the dictionary as keyword for endless avalanche of new features and they called it the SQL3 draft.

So it keeps forward compatibility.

And i found that it has another nice side effect, it helps a lot when you use grep in code reviews and refactoring.

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

.table-hover tbody tr:hover td {
    background: #ffffff;
}

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

+1 for SQL Prompt.

Something real simple that I guess I had never seen - which will work with just about ANY SQL environment (and other languages even):

After 12 years of SQL coding, I've recently become a convert to the comma-prefix style after seeing it in some SSMS generated code, I have found it very efficient. I was very surprised that I had never seen this style before, especially since it has boosted my productivity immensely.

SELECT
t.a
,t.b
,t.c
,t.d
FROM t

It makes it really easy to edit select lists, parameter lists, order by lists, group by lists, etc. I'm finding that I'm spending a lot less time fooling with adding and removing commas from the end of lists after cut-and-paste operations - I guess it works out easier because you almost always add things at the end, and with postfix commas, that requires you to move the cursor more.

Try it, you'll be surprised - I know I was.

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

To avoid disabling ssl verification entirely or duplicating / hacking the bundled CA certificate file used by git, you can export the host's certificate chain into a file, and make git use it:

git config --global http.https://the.host.com/.sslCAInfo c:/users/me/the.host.com.cer

If that does not work, you can disable ssl verification only for the host:

git config --global http.https://the.host.com/.sslVerify false

Note : Subjected to possible man in the middle attacks when ssl verification is turned off.

Append an int to a std::string

You are casting ClientID to char* causing the function to assume its a null terinated char array, which it is not.

from cplusplus.com :

string& append ( const char * s ); Appends a copy of the string formed by the null-terminated character sequence (C string) pointed by s. The length of this character sequence is determined by the first ocurrence of a null character (as determined by traits.length(s)).

Throughput and bandwidth difference?

The bandwidth of a link is the theoretical maximum amount of data that could be sent over that channel without regard to practical considerations. For example, you could pump 10^9 bits per second down a Gigabit Ethernet link over a Cat-6e or fiber optic cable. Unfortunately this would be a completely unformatted stream of bits.

To make it actually useful there's a start of frame sequence which precedes any actual data bits, a frame check sequence at the end for error detection and an idle period between transmitted frames. All of those occupy what is referred to as "bit times" meaning the amount of time it takes to transmit one bit over the line. This is all necessary overhead, but is subtracted from the total bandwidth of the link.

And this is only for the lowest level protocol which is stuffing raw data out onto the wire. Once you start adding in the MAC addresses, an IP header and a TCP or UDP header, then you've added even more overhead.

Check out http://en.wikipedia.org/wiki/Ethernet_frame. Similar problems exist for other transmission media.

How to trigger event in JavaScript?

What you want is something like this:

document.getElementByClassName("example").click();

Using jQuery, it would be something like this:

$(".example").trigger("click");

How to detect if a string contains special characters?

SELECT * FROM tableName WHERE columnName LIKE "%#%" OR columnName LIKE "%$%" OR (etc.)

What is the Java equivalent of PHP var_dump?

I like to use GSON because it's often already a dependency of the type of projects I'm working on:

public static String getDump(Object o) {
    return new GsonBuilder().setPrettyPrinting().create().toJson(o);
}

Or substitute GSON for any other JSON library you use.

Android Split string

.split method will work, but it uses regular expressions. In this example it would be (to steal from Cristian):

String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

Also, this came from: Android split not working correctly

How to use Python's "easy_install" on Windows ... it's not so easy

If you are using Anaconda's Python distribution,

you can install it through pip

pip install setuptools

and then execute it as a module

python -m easy_install

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

A lot of the above work. Just to add. If your textboxes are not directly on the form but are on other container objects like a GroupBox, you will have to get the GroupBox object and then iterate through the GroupBox to access the textboxes contained therein.

foreach(Control t in this.Controls.OfType<GroupBox>())
{
   foreach (Control tt in t.Controls.OfType<TextBox>())
   {
        // do stuff
   }
}

Select from one table where not in another

Expanding on Sjoerd's anti-join, you can also use the easy to understand SELECT WHERE X NOT IN (SELECT) pattern.

SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN (SELECT pd.part_num FROM wpsapi4.product_details pd)

Note that you only need to use ` backticks on reserved words, names with spaces and such, not with normal column names.

On MySQL 5+ this kind of query runs pretty fast.
On MySQL 3/4 it's slow.

Make sure you have indexes on the fields in question
You need to have an index on pm.id, pd.part_num.

Center div on the middle of screen

2018: CSS3

div{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%);
}

This is even shorter. For more information see this: CSS: Centering Things

org.json.simple cannot be resolved

try this

<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

How to read a single char from the console in Java (as the user types it)?

You need to knock your console into raw mode. There is no built-in platform-independent way of getting there. jCurses might be interesting, though.

On a Unix system, this might work:

String[] cmd = {"/bin/sh", "-c", "stty raw </dev/tty"};
Runtime.getRuntime().exec(cmd).waitFor();

For example, if you want to take into account the time between keystrokes, here's sample code to get there.

Which is better, return value or out parameter?

There is no real difference. Out parameters are in C# to allow method return more then one value, that's all.

However There are some slight differences , but non of them are really important:

Using out parameter will enforce you to use two lines like:

int n;
GetValue(n);

while using return value will let you do it in one line:

int n = GetValue();

Another difference (correct only for value types and only if C# doesn't inline the function) is that using return value will necessarily make a copy of the value when the function return, while using OUT parameter will not necessarily do so.

How to insert a timestamp in Oracle?

I prefer ANSI timestamp literals:

insert into the_table 
  (the_timestamp_column)
values 
  (timestamp '2017-10-12 21:22:23');

More details in the manual: https://docs.oracle.com/database/121/SQLRF/sql_elements003.htm#SQLRF51062

PHP upload image

I would recommend you to save the image in the server, and then save the URL in MYSQL database.

First of all, you should do more validation on your image, before non-validated files can lead to huge security risks.

  1. Check the image

    if (empty($_FILES['image']))
      throw new Exception('Image file is missing');
    
  2. Save the image in a variable

    $image = $_FILES['image'];
    
  3. Check the upload time errors

    if ($image['error'] !== 0) {
       if ($image['error'] === 1) 
          throw new Exception('Max upload size exceeded');
    
       throw new Exception('Image uploading error: INI Error');
    }
    
  4. Check whether the uploaded file exists in the server

    if (!file_exists($image['tmp_name']))
        throw new Exception('Image file is missing in the server');
    
  5. Validate the file size (Change it according to your needs)

     $maxFileSize = 2 * 10e6; // = 2 000 000 bytes = 2MB
        if ($image['size'] > $maxFileSize)
            throw new Exception('Max size limit exceeded'); 
    
  6. Validate the image (Check whether the file is an image)

     $imageData = getimagesize($image['tmp_name']);
         if (!$imageData) 
         throw new Exception('Invalid image');
    
  7. Validate the image mime type (Do this according to your needs)

     $mimeType = $imageData['mime'];
     $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
     if (!in_array($mimeType, $allowedMimeTypes)) 
        throw new Exception('Only JPEG, PNG and GIFs are allowed');
    

This might help you to create a secure image uploading script with PHP.

Code source: https://developer.hyvor.com/php/image-upload-ajax-php-mysql

Additionally, I suggest you use MYSQLI prepared statements for queries to improve security.

Thank you.

java.math.BigInteger cannot be cast to java.lang.Integer

java.lang.Integer is not a super class of BigInteger. Both BigInteger and Integer do inherit from java.lang.Number, so you could cast to a java.lang.Number.

See the java docs http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Number.html

java: use StringBuilder to insert at the beginning

This thread is quite old, but you could also think about a recursive solution passing the StringBuilder to fill. This allows to prevent any reverse processing etc. Just need to design your iteration with a recursion and carefully decide for an exit condition.

public class Test {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        doRecursive(sb, 100, 0);
        System.out.println(sb.toString());
    }

    public static void doRecursive(StringBuilder sb, int limit, int index) {
        if (index < limit) {
            doRecursive(sb, limit, index + 1);
            sb.append(Integer.toString(index));
        }
    }
}

Twitter Bootstrap - how to center elements horizontally or vertically

for horizontaly centering you can have something like this:

.centering{
float:none;
margin:0 auto
}

 <div class="span8 centering"></div>

How to set a border for an HTML div tag

I guess this is where you are pointing at ..

<div id="divActivites" name="divActivites" style="border:thin">
    <textarea id="inActivities" name="inActivities" style="border:solid">
    </textarea> 
</div> 

Well. it must be written as border-width:thin

Here you go with the link (click here) check out the different types of Border-styles

you can also set the border width by writing the width in terms of pixels.. (like border-width:1px), minimum width is 1px.

How to get the IP address of the docker host from inside a docker container

For those running Docker in AWS, the instance meta-data for the host is still available from inside the container.

curl http://169.254.169.254/latest/meta-data/local-ipv4

For example:

$ docker run alpine /bin/sh -c "apk update ; apk add curl ; curl -s http://169.254.169.254/latest/meta-data/local-ipv4 ; echo"
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/community/x86_64/APKINDEX.tar.gz
v3.3.1-119-gb247c0a [http://dl-cdn.alpinelinux.org/alpine/v3.3/main]
v3.3.1-59-g48b0368 [http://dl-cdn.alpinelinux.org/alpine/v3.3/community]
OK: 5855 distinct packages available
(1/4) Installing openssl (1.0.2g-r0)
(2/4) Installing ca-certificates (20160104-r2)
(3/4) Installing libssh2 (1.6.0-r1)
(4/4) Installing curl (7.47.0-r0)
Executing busybox-1.24.1-r7.trigger
Executing ca-certificates-20160104-r2.trigger
OK: 7 MiB in 15 packages
172.31.27.238

$ ifconfig eth0 | grep -oP 'inet addr:\K\S+'
172.31.27.238

List directory tree structure in python?

A solution without your indentation:

for path, dirs, files in os.walk(given_path):
  print path
  for f in files:
    print f

os.walk already does the top-down, depth-first walk you are looking for.

Ignoring the dirs list prevents the overlapping you mention.

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

The reason is that php cannot find the correct path of mysql.sock.

Please make sure that your mysql is running first.

Then, please confirm that which path is the mysql.sock located, for example /tmp/mysql.sock

then add this path string to php.ini:

  • mysql.default_socket = /tmp/mysql.sock
  • mysqli.default_socket = /tmp/mysql.sock
  • pdo_mysql.default_socket = /tmp/mysql.sock

Finally, restart Apache.

Set System.Drawing.Color values

using System;
using System.Drawing;
public struct MyColor
    {
        private byte a, r, g, b;        
        public byte A
        {
            get
            {
                return this.a;
            }
        }
        public byte R
        {
            get
            {
                return this.r;
            }
        }
        public byte G
        {
            get
            {
                return this.g;
            }
        }
        public byte B
        {
            get
            {
                return this.b;
            }
        }       
        public MyColor SetAlpha(byte value)
        {
            this.a = value;
            return this;
        }
        public MyColor SetRed(byte value)
        {
            this.r = value;
            return this;
        }
        public MyColor SetGreen(byte value)
        {
            this.g = value;
            return this;
        }
        public MyColor SetBlue(byte value)
        {
            this.b = value;
            return this;
        }
        public int ToArgb()
        {
            return (int)(A << 24) || (int)(R << 16) || (int)(G << 8) || (int)(B);
        }
        public override string ToString ()
        {
            return string.Format ("[MyColor: A={0}, R={1}, G={2}, B={3}]", A, R, G, B);
        }

        public static MyColor FromArgb(byte alpha, byte red, byte green, byte blue)
        {
            return new MyColor().SetAlpha(alpha).SetRed(red).SetGreen(green).SetBlue(blue);
        }
        public static MyColor FromArgb(byte red, byte green, byte blue)
        {
            return MyColor.FromArgb(255, red, green, blue);
        }
        public static MyColor FromArgb(byte alpha, MyColor baseColor)
        {
            return MyColor.FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B);
        }
        public static MyColor FromArgb(int argb)
        {
            return MyColor.FromArgb(argb & 255, (argb >> 8) & 255, (argb >> 16) & 255, (argb >> 24) & 255);
        }   
        public static implicit operator Color(MyColor myColor)
        {           
            return Color.FromArgb(myColor.ToArgb());
        }
        public static implicit operator MyColor(Color color)
        {
            return MyColor.FromArgb(color.ToArgb());
        }
    }

Spring boot Security Disable security

I added below settings in application.yml and worked fine.

security:
    route-patterns-to-be-skipped:
      - /**/*

this can be converted as security.route-paterns-to-be-skipped=/**/* for application.properties

Run PHP Task Asynchronously

If it just a question of providing expensive tasks, in case of php-fpm is supported, why not to use fastcgi_finish_request() function?

This function flushes all response data to the client and finishes the request. This allows for time consuming tasks to be performed without leaving the connection to the client open.

You don't really use asynchronicity in this way:

  1. Make all your main code first.
  2. Execute fastcgi_finish_request().
  3. Make all heavy stuff.

Once again php-fpm is needed.

Is there a macro to conditionally copy rows to another worksheet?

If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?

Using grep and sed to find and replace a string

I have taken Vlad's idea and changed it a little bit. Instead of

grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' /dev/null

Which yields

sed: couldn't edit /dev/null: not a regular file

I'm doing in 3 different connections to the remote server

touch deleteme
grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' ./deleteme
rm deleteme

Although this is less elegant and requires 2 more connections to the server (maybe there's a way to do it all in one line) it does the job efficiently as well

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

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

import numpy as np

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

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

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

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

How to display request headers with command line curl

curl's -v or --verbose option shows the HTTP request headers, among other things. Here is some sample output:

$ curl -v http://google.com/
* About to connect() to google.com port 80 (#0)
*   Trying 66.102.7.104... connected
* Connected to google.com (66.102.7.104) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.16.4 (i386-apple-darwin9.0) libcurl/7.16.4 OpenSSL/0.9.7l zlib/1.2.3
> Host: google.com
> Accept: */*
> 
< HTTP/1.1 301 Moved Permanently
< Location: http://www.google.com/
< Content-Type: text/html; charset=UTF-8
< Date: Thu, 15 Jul 2010 06:06:52 GMT
< Expires: Sat, 14 Aug 2010 06:06:52 GMT
< Cache-Control: public, max-age=2592000
< Server: gws
< Content-Length: 219
< X-XSS-Protection: 1; mode=block
< 
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
* Connection #0 to host google.com left intact
* Closing connection #0

Permission denied on accessing host directory in Docker

Typically, permissions issues with a host volume mount are because the uid/gid inside the container does not have access to the file according to the uid/gid permissions of the file on the host. However, this specific case is different.

The dot at the end of the permission string, drwxr-xr-x., indicates SELinux is configured. When using a host mount with SELinux, you need to pass an extra option to the end of the volume definition:

  • The z option indicates that the bind mount content is shared among multiple containers.
  • The Z option indicates that the bind mount content is private and unshared.

Your volume mount command would then look like:

sudo docker run -i -v /data1/Downloads:/Downloads:z ubuntu bash

See more about host mounts with SELinux at: https://docs.docker.com/storage/bind-mounts/#configure-the-selinux-label


For others that see this issue with containers running as a different user, you need to ensure the uid/gid of the user inside the container has permissions to the file on the host. On production servers, this is often done by controlling the uid/gid in the image build process to match a uid/gid on the host that has access to the files (or even better, do not use host mounts in production).

A named volume is often preferred to host mounts because it will initialize the volume directory from the image directory, including any file ownership and permissions. This happens when the volume is empty and the container is created with the named volume.

MacOS users now have OSXFS which handles uid/gid's automatically between the Mac host and containers. One place it doesn't help with are files from inside the embedded VM that get mounted into the container, like /var/lib/docker.sock.

For development environments where the host uid/gid may change per developer, my preferred solution is to start the container with an entrypoint running as root, fix the uid/gid of the user inside the container to match the host volume uid/gid, and then use gosu to drop from root to the container user to run the application inside the container. The important script for this is fix-perms in my base image scripts, which can be found at: https://github.com/sudo-bmitch/docker-base

The important bit from the fix-perms script is:

# update the uid
if [ -n "$opt_u" ]; then
  OLD_UID=$(getent passwd "${opt_u}" | cut -f3 -d:)
  NEW_UID=$(stat -c "%u" "$1")
  if [ "$OLD_UID" != "$NEW_UID" ]; then
    echo "Changing UID of $opt_u from $OLD_UID to $NEW_UID"
    usermod -u "$NEW_UID" -o "$opt_u"
    if [ -n "$opt_r" ]; then
      find / -xdev -user "$OLD_UID" -exec chown -h "$opt_u" {} \;
    fi
  fi
fi

That gets the uid of the user inside the container, and the uid of the file, and if they do not match, calls usermod to adjust the uid. Lastly it does a recursive find to fix any files which have not changed uid's. I like this better than running a container with a -u $(id -u):$(id -g) flag because the above entrypoint code doesn't require each developer to run a script to start the container, and any files outside of the volume that are owned by the user will have their permissions corrected.


You can also have docker initialize a host directory from an image by using a named volume that performs a bind mount. This directory must exist in advance, and you need to provide an absolute path to the host directory, unlike host volumes in a compose file which can be relative paths. The directory must also be empty for docker to initialize it. Three different options for defining a named volume to a bind mount look like:

  # create the volume in advance
  $ docker volume create --driver local \
      --opt type=none \
      --opt device=/home/user/test \
      --opt o=bind \
      test_vol

  # create on the fly with --mount
  $ docker run -it --rm \
    --mount type=volume,dst=/container/path,volume-driver=local,volume-opt=type=none,volume-opt=o=bind,volume-opt=device=/home/user/test \
    foo

  # inside a docker-compose file
  ...
  volumes:
    bind-test:
      driver: local
      driver_opts:
        type: none
        o: bind
        device: /home/user/test
  ...

Lastly, if you try using user namespaces, you'll find that host volumes have permission issues because uid/gid's of the containers are shifted. In that scenario, it's probably easiest to avoid host volumes and only use named volumes.

What is the Windows equivalent of the diff command?

Run this in the CMD shell or batch file:

FC file1 file2

FC can also be used to compare binary files:

FC /B file1 file2

How to remove tab indent from several lines in IDLE?

For IDLE, select the lines, then open the "Format" menu. (Between "Edit" and "Run" if you're having trouble finding it.) This will also give you the keyboard shortcut, for me it turned out that dedent shortcut was "Ctrl+["

Why powershell does not run Angular commands?

script1.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170

This error happens due to a security measure which won't let scripts be executed on your system without you having approved of it. You can do so by opening up a powershell with administrative rights (search for powershell in the main menu and select Run as administrator from the context menu) and entering:

set-executionpolicy remotesigned

How do I set default value of select box in angularjs

You can simple use ng-init like this

<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options"></select>

OAuth 2.0 Authorization Header

You can still use the Authorization header with OAuth 2.0. There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.

It's documented in this spec: https://tools.ietf.org/html/rfc6750#section-2.1

E.g.:

   GET /resource HTTP/1.1
   Host: server.example.com
   Authorization: Bearer mF_9.B5f-4.1JqM

Where mF_9.B5f-4.1JqM is your OAuth access token.

How to know function return type and argument types?

Yes it is.

In Python a function doesn't always have to return a variable of the same type (although your code will be more readable if your functions do always return the same type). That means that you can't specify a single return type for the function.

In the same way, the parameters don't always have to be the same type too.

Android error: Failed to install *.apk on device *: timeout

I have encountered the same problem and tried to change the ADB connection timeout. That did not work. I switched between my PC's USB ports (front -> back) and it fixed the problem!!!

Where can I find the assembly System.Web.Extensions dll?

Your project is mostly likely targetting .NET Framework 4 Client Profile. Check the application tab in your project properties.

This question has a good answer on the different versions: Target framework, what does ".NET Framework ... Client Profile" mean?

How can I implement prepend and append with regular JavaScript?

Here's an example of using prepend to add a paragraph to the document.

var element = document.createElement("p");
var text = document.createTextNode("Example text");
element.appendChild(text);
document.body.prepend(element);

result:

<p>Example text</p>

Unstaged changes left after git reset --hard

RESOLVED!!!

I have resolved this problem using following steps

1) Remove every file from Git's index.

git rm --cached -r .

2) Rewrite the Git index to pick up all the new line endings.

git reset --hard

Solution was part of steps described on git site https://help.github.com/articles/dealing-with-line-endings/

Get width/height of SVG element

A save method to determine the width and height unit of any element (no padding, no margin) is the following:

let div   = document.querySelector("div");
let style = getComputedStyle(div);

let width  = parseFloat(style.width.replace("px", ""));
let height = parseFloat(style.height.replace("px", ""));

Pure css close button

Hi you can used this code in pure css

as like this

css

.arrow {
cursor: pointer;
color: white;
border: 1px solid #AEAEAE;
border-radius: 30px;
background: #605F61;
font-size: 31px;
font-weight: bold;
display: inline-block;
line-height: 0px;
padding: 11px 3px;
}
.arrow:before{
 content: "×";
}

HTML

<a href="#" class="arrow"> 
</a>

? Live demo http://jsfiddle.net/rohitazad/VzZhU/

Android translate animation - permanently move View to new position using AnimationListener

I usually prefer to work with deltas in translate animation, since it avoids a lot of confusion.

Try this out, see if it works for you:

TranslateAnimation anim = new TranslateAnimation(0, amountToMoveRight, 0, amountToMoveDown);
anim.setDuration(1000);

anim.setAnimationListener(new TranslateAnimation.AnimationListener() {

    @Override
    public void onAnimationStart(Animation animation) { }

    @Override
    public void onAnimationRepeat(Animation animation) { }

    @Override
    public void onAnimationEnd(Animation animation) 
    {
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
        params.topMargin += amountToMoveDown;
        params.leftMargin += amountToMoveRight;
        view.setLayoutParams(params);
    }
});

view.startAnimation(anim);

Make sure to make amountToMoveRight / amountToMoveDown final

Hope this helps :)

Converting std::__cxx11::string to std::string

If you can recompile all incompatible libs you use, do it with compiler option

-D_GLIBCXX_USE_CXX11_ABI=1

and then rebuild your project. If you can't do so, add to your project's makefile compiler option

-D_GLIBCXX_USE_CXX11_ABI=0

The define

#define _GLIBCXX_USE_CXX11_ABI 0/1

is also good but you probably need to add it to all your files while compiler option do it for all files at once.

How can I add a line to a file in a shell script?

As far as I understand, you want to prepend column1, column2, column3 to your existing one, two, three.

I would use ed in place of sed, since sed write on the standard output and not in the file.

The command:

printf '0a\ncolumn1, column2, column3\n.\nw\n' | ed testfile.csv

should do the work.

perl -i is worth taking a look as well.

symbol(s) not found for architecture i386

Does your project depend on another project, and is that a target in that project set up to be a direct dependency of your main target? If this is the case and the dependency isn't set up, the dependent target may not be getting built for all configurations (i.e. the simulator)

Just a wild guess.

Setting up FTP on Amazon Cloud Server

Thanks @clone45 for the nice solution. But I had just one important problem with Appendix b of his solution. Immediately after I changed the home directory to var/www/html then I couldn't connect to server through ssh and sftp because it always shows following errors

permission denied (public key)

or in FileZilla I received this error:

No supported authentication methods available (server: public key)

But I could access the server through normal FTP connection.

If you encountered to the same error then just undo the appendix b of @clone45 solution by set the default home directory for the user:

sudo usermod -d /home/username/ username

But when you set user's default home directory then the user have access to many other folders outside /var/www/http. So to secure your server then follow these steps:

1- Make sftponly group Make a group for all users you want to restrict their access to only ftp and sftp access to var/www/html. to make the group:

sudo groupadd sftponly

2- Jail the chroot To restrict access of this group to the server via sftp you must jail the chroot to not to let group's users to access any folder except html folder inside its home directory. to do this open /etc/ssh/sshd.config in the vim with sudo. At the end of the file please comment this line:

Subsystem sftp /usr/libexec/openssh/sftp-server

And then add this line below that:

Subsystem sftp internal-sftp

So we replaced subsystem with internal-sftp. Then add following lines below it:

 Match Group sftponly
        ChrootDirectory /var/www
        ForceCommand internal-sftp
        AllowTcpForwarding no

After adding this line I saved my changes and then restart ssh service by:

sudo service sshd restart

3- Add the user to sftponly group Any user you want to restrict their access must be a member of sftponly group. Therefore we join it to sftponly by: sudo usermod -G sftponly username

4- Restrict user access to just var/www/html To restrict user access to just var/www/html folder we need to make a directory in the home directory (with name of 'html') of that user and then mount /var/www to /home/username/html as follow:

sudo mkdir /home/username/html
sudo mount --bind /var/www /home/username/html

5- Set write access If the user needs write access to /var/www/html, then you must jail the user at /var/www which must have root:root ownership and permissions of 755. You then need to give /var/www/html ownership of root:sftponly and permissions of 775 by adding following lines:

sudo chmod 755 /var/www
sudo chown root:root /var/www
sudo chmod 775 /var/www/html
sudo chown root:www /var/www/html

6- Block shell access If you want restrict access to not access to shell to make it more secure then just change the default shell to bin/false as follow:

sudo usermod -s /bin/false username

How to prevent a double-click using jQuery?

I have the similar issue. You can use setTimeout() to avoid the double-click.

//some codes here above after the click then disable it

// also check here if there's an attribute disabled

// if there's an attribute disabled in the btn tag then // return. Convert that into js.

$('#btn1').prop("disabled", true);

setTimeout(function(){
    $('#btn1').prop("disabled", false);
}, 300);

How should you diagnose the error SEHException - External component has thrown an exception

if you are having a problem as describe in this post:

asp.net mvc debugger throwing SEHException

then the solution is:

if you have any application from Trusteer (like rapport or anything ) just uninstall and reboot your system, it'll work fine ... found this solution here:

http://forums.asp.net/t/1704958.aspx/8/10?Re+SEHException+thrown+when+I+run+the+application

How do I vertically center text with CSS?

Newer browsers now support the CSS calc function. If you are targeting these browsers you may want to look into doing something like this:

_x000D_
_x000D_
<div style="position: relative; width: 400px; height: 400px; background-color: red">_x000D_
  <span style="position: absolute; line-height: 40px; height: 80px; text-align: center; width: 300px; overflow: hidden; top: calc(50% - 40px); left: calc(50% - 150px);">_x000D_
    Here are two lines that will be centered even if the parent div changes size._x000D_
  </span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The key is to use style = "top: calc(50% - [innerFixedHeightInPX/2]px); height: [innerFixedHeightInPX]px;" inside an absolute or relatively positioned parent div.

Difference between == and === in JavaScript

Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html

The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.

0 == false   // true
0 === false  // false, because they are of a different type
1 == "1"     // true, automatic type conversion for value only
1 === "1"    // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false

How to validate array in Laravel?

I have this array as my request data from a HTML+Vue.js data grid/table:

[0] => Array
    (
        [item_id] => 1
        [item_no] => 3123
        [size] => 3e
    )
[1] => Array
    (
        [item_id] => 2
        [item_no] => 7688
        [size] => 5b
    )

And use this to validate which works properly:

$this->validate($request, [
    '*.item_id' => 'required|integer',
    '*.item_no' => 'required|integer',
    '*.size'    => 'required|max:191',
]);

What's the main difference between Java SE and Java EE?

http://www.dreamincode.net/forums/topic/99678-j2se-vs-j2ee-what-are-main-differences/

As far as the language goes it is not as though java changes. Java EE has access to all of the SE libraries. However EE adds a set of libraries for dealing with enterprise applications.

Java EE is more like a "platform" or an general area of development.

In Java SE you write applications that run as standalone java programs or as Applets. In JavaEE you can still do this, but you can also write applications that run inside of a Java EE container. The container can do a great amount of management for you such as scaling an application across threads, providing resource pools, and management features.

Java EE has a web framework based upon Servlets. It has JSP (Java Server Pages) which is a templating language that compiles from JSP to a Java servlet where it can be run by the container.

So Java EE is more or less Java SE + Enterprise platform technologies.

Java EE is far more than just a couple of extra libraries (that is what I thought when I first looked at it) since there are a ton of frameworks and technologies built upon the Java EE specifications.

But it all boils down to just plain old java.

Import CSV into SQL Server (including automatic table creation)

SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.

You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...

From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.

If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/

visual c++: #include files from other projects in the same solution

#include has nothing to do with projects - it just tells the preprocessor "put the contents of the header file here". If you give it a path that points to the correct location (can be a relative path, like ../your_file.h) it will be included correctly.

You will, however, have to learn about libraries (static/dynamic libraries) in order to make such projects link properly - but that's another question.

Share data between AngularJS controllers

There are multiple ways to do this.

  1. Events - already explained well.

  2. ui router - explained above.

  3. Service - with update method displayed above
  4. BAD - Watching for changes.
  5. Another parent child approach rather than emit and brodcast -

*

<superhero flight speed strength> Superman is here! </superhero>
<superhero speed> Flash is here! </superhero>

*

app.directive('superhero', function(){
    return {
        restrict: 'E',
        scope:{}, // IMPORTANT - to make the scope isolated else we will pollute it in case of a multiple components.
        controller: function($scope){
            $scope.abilities = [];
            this.addStrength = function(){
                $scope.abilities.push("strength");
            }
            this.addSpeed = function(){
                $scope.abilities.push("speed");
            }
            this.addFlight = function(){
                $scope.abilities.push("flight");
            }
        },
        link: function(scope, element, attrs){
            element.addClass('button');
            element.on('mouseenter', function(){
               console.log(scope.abilities);
            })
        }
    }
});
app.directive('strength', function(){
    return{
        require:'superhero',
        link: function(scope, element, attrs, superHeroCtrl){
            superHeroCtrl.addStrength();
        }
    }
});
app.directive('speed', function(){
    return{
        require:'superhero',
        link: function(scope, element, attrs, superHeroCtrl){
            superHeroCtrl.addSpeed();
        }
    }
});
app.directive('flight', function(){
    return{
        require:'superhero',
        link: function(scope, element, attrs, superHeroCtrl){
            superHeroCtrl.addFlight();
        }
    }
});

How to read request body in an asp.net core webapi controller?

Writing an extension method is the most efficient way in my opinion

 public static string PeekBody(this HttpRequest request)
        {
            try
            {
                request.EnableBuffering();
                var buffer = new byte[Convert.ToInt32(request.ContentLength)];
                request.Body.Read(buffer, 0, buffer.Length);
                return Encoding.UTF8.GetString(buffer);
            }
            finally
            {
                request.Body.Position = 0;
            }
        }

You can use Request.Body.Peeker Nuget Package as well (source code)

//Return string
var request = HttpContext.Request.PeekBody();

//Return in expected type
LoginRequest request = HttpContext.Request.PeekBody<LoginRequest>();

//Return in expected type asynchronously
LoginRequest request = await HttpContext.Request.PeekBodyAsync<LoginRequest>();

Swift alert view with OK and Cancel: which button tapped?

You may want to consider using SCLAlertView, alternative for UIAlertView or UIAlertController.

UIAlertController only works on iOS 8.x or above, SCLAlertView is a good option to support older version.

github to see the details

example:

let alertView = SCLAlertView()
alertView.addButton("First Button", target:self, selector:Selector("firstButton"))
alertView.addButton("Second Button") {
    print("Second button tapped")
}
alertView.showSuccess("Button View", subTitle: "This alert view has buttons")

Remove duplicates from a dataframe in PySpark

if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):

count before dedupe:

df.count()

do the de-dupe (convert the column you are de-duping to string type):

from pyspark.sql.functions import col
df = df.withColumn('colName',col('colName').cast('string'))

df.drop_duplicates(subset=['colName']).count()

can use a sorted groupby to check to see that duplicates have been removed:

df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)

How to reference Microsoft.Office.Interop.Excel dll?

If you have VS 2013 Express and you cant find Microsoft.Office namespace, try this ('Microsoft Excel 12.0 Object Library' if you want to use Office 2007)

enter image description here

What command shows all of the topics and offsets of partitions in Kafka?

Kafka ships with some tools you can use to accomplish this.

List topics:

# ./bin/kafka-topics.sh --list --zookeeper localhost:2181
test_topic_1
test_topic_2
...

List partitions and offsets:

# ./bin/kafka-run-class.sh kafka.tools.ConsumerOffsetChecker --broker-info --group test_group --topic test_topic --zookeeper localhost:2181
Group           Topic                  Pid Offset          logSize         Lag             Owner
test_group      test_topic             0   698020          698021          1              test_group-0
test_group      test_topic             1   235699          235699          0               test_group-1
test_group      test_topic             2   117189          117189          0               test_group-2

Update for 0.9 (and higher) consumer APIs

If you're using the new apis, there's a new tool you can use: kafka-consumer-groups.sh.

./bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group count_errors --describe
GROUP                          TOPIC                          PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             OWNER
count_errors                   logs                           2          2908278         2908278         0               consumer-1_/10.8.0.55
count_errors                   logs                           3          2907501         2907501         0               consumer-1_/10.8.0.43
count_errors                   logs                           4          2907541         2907541         0               consumer-1_/10.8.0.177
count_errors                   logs                           1          2907499         2907499         0               consumer-1_/10.8.0.115
count_errors                   logs                           0          2907469         2907469         0               consumer-1_/10.8.0.126

javascript filter array multiple conditions

Dynamic filters with AND condition

Filter out people with gender = 'm'

_x000D_
_x000D_
var people = [
    {
        name: 'john',
        age: 10,
        gender: 'm'
    },
    {
        name: 'joseph',
        age: 12,
        gender: 'm'
    },
    {
        name: 'annie',
        age: 8,
        gender: 'f'
    }
]
var filters = {
    gender: 'm'
}

var out = people.filter(person => {
    return Object.keys(filters).every(filter => {
        return filters[filter] === person[filter]
    });
})


console.log(out)
_x000D_
_x000D_
_x000D_

Filter out people with gender = 'm' and name = 'joseph'

_x000D_
_x000D_
var people = [
    {
        name: 'john',
        age: 10,
        gender: 'm'
    },
    {
        name: 'joseph',
        age: 12,
        gender: 'm'
    },
    {
        name: 'annie',
        age: 8,
        gender: 'f'
    }
]
var filters = {
    gender: 'm',
    name: 'joseph'
}

var out = people.filter(person => {
    return Object.keys(filters).every(filter => {
        return filters[filter] === person[filter]
    });
})


console.log(out)
_x000D_
_x000D_
_x000D_

You can give as many filters as you want.

How to test whether a service is running from the command line

Thinking a little bit outside the box here I'm going to propose that powershell may be an answer on up-to-date XP/2003 machines and certainly on Vista/2008 and newer (instead of .bat/.cmd). Anyone who has some Perl in their background should feel at-home pretty quickly.


$serviceName = "ServiceName";
$serviceStatus = (get-service "$serviceName").Status;

if ($serviceStatus -eq "Running") {
    echo "Service is Running";
}
else {
    #Could be Stopped, Stopping, Paused, or even Starting...
    echo "Service is $serviceStatus";
}

Another way, if you have significant investment in batch is to run the PS script as a one-liner, returning an exit code.


@ECHO off
SET PS=powershell -nologo -command
%PS% "& {if((get-service SvcName).Status -eq 'Running'){exit 1}}"

ECHO.%ERRORLEVEL%

Running as a one-liner also gets around the default PS code signing policy at the expense of messiness. To put the PS commands in a .ps1 file and run like powershell myCode.ps1 you may find signing your powershell scripts is neccessary to run them in an automated way (depends on your environment). See http://www.hanselman.com/blog/SigningPowerShellScripts.aspx for details

How to search by key=>value in a multidimensional array in PHP

http://snipplr.com/view/51108/nested-array-search-by-value-or-key/

<?php

//PHP 5.3

function searchNestedArray(array $array, $search, $mode = 'value') {

    foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key => $value) {
        if ($search === ${${"mode"}})
            return true;
    }
    return false;
}

$data = array(
    array('abc', 'ddd'),
    'ccc',
    'bbb',
    array('aaa', array('yyy', 'mp' => 555))
);

var_dump(searchNestedArray($data, 555));

How to select all textareas and textboxes using jQuery?

Password boxes are also textboxes, so if you need them too:

$("input[type='text'], textarea, input[type='password']").css({width: "90%"});

and while file-input is a bit different, you may want to include them too (eg. for visual consistency):

$("input[type='text'], textarea, input[type='password'], input[type='file']").css({width: "90%"});

Lotus Notes email as an attachment to another email

Talking about IBM Notes v. 9 is pretty easy.

To choose the e-mail to be attached and drag until the new e-mail.

Get query from java.sql.PreparedStatement

You can add log4jdbc to your project. This adds logging of sql commands as they execute + a lot of other information.

http://code.google.com/p/log4jdbc/wiki/FAQ

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

Here's a simple script that generally does the trick for me:

SELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time
  FROM sys.dm_exec_requests
  WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE') 

Return positions of a regex match() in Javascript?

function trimRegex(str, regex){
    return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}

let test = '||ab||cd||';
trimRegex(test, /[^|]/);
console.log(test); //output: ab||cd

or

function trimChar(str, trim, req){
    let regex = new RegExp('[^'+trim+']');
    return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}

let test = '||ab||cd||';
trimChar(test, '|');
console.log(test); //output: ab||cd

How to select the last record of a table in SQL?

select ADU.itemid, ADU.startdate, internalcostprice 
from ADUITEMINTERNALCOSTPRICE ADU

right join

   (select max(STARTDATE) as Max_date, itemid 
   from ADUITEMINTERNALCOSTPRICE
   group by itemid) as A

on A.ITEMID = ADU.ITEMID
and startdate= Max_date

How to convert a 3D point into 2D perspective projection?

I see this question is a bit old, but I decided to give an answer anyway for those who find this question by searching.
The standard way to represent 2D/3D transformations nowadays is by using homogeneous coordinates. [x,y,w] for 2D, and [x,y,z,w] for 3D. Since you have three axes in 3D as well as translation, that information fits perfectly in a 4x4 transformation matrix. I will use column-major matrix notation in this explanation. All matrices are 4x4 unless noted otherwise.
The stages from 3D points and to a rasterized point, line or polygon looks like this:

  1. Transform your 3D points with the inverse camera matrix, followed with whatever transformations they need. If you have surface normals, transform them as well but with w set to zero, as you don't want to translate normals. The matrix you transform normals with must be isotropic; scaling and shearing makes the normals malformed.
  2. Transform the point with a clip space matrix. This matrix scales x and y with the field-of-view and aspect ratio, scales z by the near and far clipping planes, and plugs the 'old' z into w. After the transformation, you should divide x, y and z by w. This is called the perspective divide.
  3. Now your vertices are in clip space, and you want to perform clipping so you don't render any pixels outside the viewport bounds. Sutherland-Hodgeman clipping is the most widespread clipping algorithm in use.
  4. Transform x and y with respect to w and the half-width and half-height. Your x and y coordinates are now in viewport coordinates. w is discarded, but 1/w and z is usually saved because 1/w is required to do perspective-correct interpolation across the polygon surface, and z is stored in the z-buffer and used for depth testing.

This stage is the actual projection, because z isn't used as a component in the position any more.

The algorithms:

Calculation of field-of-view

This calculates the field-of view. Whether tan takes radians or degrees is irrelevant, but angle must match. Notice that the result reaches infinity as angle nears 180 degrees. This is a singularity, as it is impossible to have a focal point that wide. If you want numerical stability, keep angle less or equal to 179 degrees.

fov = 1.0 / tan(angle/2.0)

Also notice that 1.0 / tan(45) = 1. Someone else here suggested to just divide by z. The result here is clear. You would get a 90 degree FOV and an aspect ratio of 1:1. Using homogeneous coordinates like this has several other advantages as well; we can for example perform clipping against the near and far planes without treating it as a special case.

Calculation of the clip matrix

This is the layout of the clip matrix. aspectRatio is Width/Height. So the FOV for the x component is scaled based on FOV for y. Far and near are coefficients which are the distances for the near and far clipping planes.

[fov * aspectRatio][        0        ][        0              ][        0       ]
[        0        ][       fov       ][        0              ][        0       ]
[        0        ][        0        ][(far+near)/(far-near)  ][        1       ]
[        0        ][        0        ][(2*near*far)/(near-far)][        0       ]

Screen Projection

After clipping, this is the final transformation to get our screen coordinates.

new_x = (x * Width ) / (2.0 * w) + halfWidth;
new_y = (y * Height) / (2.0 * w) + halfHeight;

Trivial example implementation in C++

#include <vector>
#include <cmath>
#include <stdexcept>
#include <algorithm>

struct Vector
{
    Vector() : x(0),y(0),z(0),w(1){}
    Vector(float a, float b, float c) : x(a),y(b),z(c),w(1){}

    /* Assume proper operator overloads here, with vectors and scalars */
    float Length() const
    {
        return std::sqrt(x*x + y*y + z*z);
    }
    
    Vector Unit() const
    {
        const float epsilon = 1e-6;
        float mag = Length();
        if(mag < epsilon){
            std::out_of_range e("");
            throw e;
        }
        return *this / mag;
    }
};

inline float Dot(const Vector& v1, const Vector& v2)
{
    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}

class Matrix
{
    public:
    Matrix() : data(16)
    {
        Identity();
    }
    void Identity()
    {
        std::fill(data.begin(), data.end(), float(0));
        data[0] = data[5] = data[10] = data[15] = 1.0f;
    }
    float& operator[](size_t index)
    {
        if(index >= 16){
            std::out_of_range e("");
            throw e;
        }
        return data[index];
    }
    Matrix operator*(const Matrix& m) const
    {
        Matrix dst;
        int col;
        for(int y=0; y<4; ++y){
            col = y*4;
            for(int x=0; x<4; ++x){
                for(int i=0; i<4; ++i){
                    dst[x+col] += m[i+col]*data[x+i*4];
                }
            }
        }
        return dst;
    }
    Matrix& operator*=(const Matrix& m)
    {
        *this = (*this) * m;
        return *this;
    }

    /* The interesting stuff */
    void SetupClipMatrix(float fov, float aspectRatio, float near, float far)
    {
        Identity();
        float f = 1.0f / std::tan(fov * 0.5f);
        data[0] = f*aspectRatio;
        data[5] = f;
        data[10] = (far+near) / (far-near);
        data[11] = 1.0f; /* this 'plugs' the old z into w */
        data[14] = (2.0f*near*far) / (near-far);
        data[15] = 0.0f;
    }

    std::vector<float> data;
};

inline Vector operator*(const Vector& v, const Matrix& m)
{
    Vector dst;
    dst.x = v.x*m[0] + v.y*m[4] + v.z*m[8 ] + v.w*m[12];
    dst.y = v.x*m[1] + v.y*m[5] + v.z*m[9 ] + v.w*m[13];
    dst.z = v.x*m[2] + v.y*m[6] + v.z*m[10] + v.w*m[14];
    dst.w = v.x*m[3] + v.y*m[7] + v.z*m[11] + v.w*m[15];
    return dst;
}

typedef std::vector<Vector> VecArr;
VecArr ProjectAndClip(int width, int height, float near, float far, const VecArr& vertex)
{
    float halfWidth = (float)width * 0.5f;
    float halfHeight = (float)height * 0.5f;
    float aspect = (float)width / (float)height;
    Vector v;
    Matrix clipMatrix;
    VecArr dst;
    clipMatrix.SetupClipMatrix(60.0f * (M_PI / 180.0f), aspect, near, far);
    /*  Here, after the perspective divide, you perform Sutherland-Hodgeman clipping 
        by checking if the x, y and z components are inside the range of [-w, w].
        One checks each vector component seperately against each plane. Per-vertex
        data like colours, normals and texture coordinates need to be linearly
        interpolated for clipped edges to reflect the change. If the edge (v0,v1)
        is tested against the positive x plane, and v1 is outside, the interpolant
        becomes: (v1.x - w) / (v1.x - v0.x)
        I skip this stage all together to be brief.
    */
    for(VecArr::iterator i=vertex.begin(); i!=vertex.end(); ++i){
        v = (*i) * clipMatrix;
        v /= v.w; /* Don't get confused here. I assume the divide leaves v.w alone.*/
        dst.push_back(v);
    }

    /* TODO: Clipping here */

    for(VecArr::iterator i=dst.begin(); i!=dst.end(); ++i){
        i->x = (i->x * (float)width) / (2.0f * i->w) + halfWidth;
        i->y = (i->y * (float)height) / (2.0f * i->w) + halfHeight;
    }
    return dst;
}

If you still ponder about this, the OpenGL specification is a really nice reference for the maths involved. The DevMaster forums at http://www.devmaster.net/ have a lot of nice articles related to software rasterizers as well.

Best dynamic JavaScript/JQuery Grid

My suggestion for dynamic JQuery Grid are below.

http://reconstrukt.com/ingrid/

https://github.com/mleibman/SlickGrid

http://www.datatables.net/index

Best one is :

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.

Variable length pagination

On-the-fly filtering

Multi-column sorting with data type detection

Smart handling of column widths

Display data from almost any data source

DOM, Javascript array, Ajax file and server-side processing (PHP, C#, Perl, Ruby, AIR, Gears etc)

Scrolling options for table viewport

Fully internationalisable

jQuery UI ThemeRoller support

Rock solid - backed by a suite of 2600+ unit tests

Wide variety of plug-ins inc. TableTools, FixedColumns, KeyTable and more

Dynamic creation of tables

Ajax auto loading of data

Custom DOM positioning

Single column filtering

Alternative pagination types

Non-destructive DOM interaction

Sorting column(s) highlighting

Advanced data source options

Extensive plug-in support

Sorting, type detection, API functions, pagination and filtering

Fully themeable by CSS

Solid documentation

110+ pre-built examples

Full support for Adobe AIR

Is there a <meta> tag to turn off caching in all browsers?

This is a link to a great Case Study on the industry wide misunderstanding of controlling caches.

http://securityevaluators.com/knowledge/case_studies/caching/

In summary, according to this article, only Cache-Control: no-store is recognized by Chrome, Firefox, and IE. IE recognizes other controls, but Chrome and Firefox do not.

Convert a string to datetime in PowerShell

ParseExact is told the format of the date it is expected to parse, not the format you wish to get out.

$invoice = '01-Jul-16'
[datetime]::parseexact($invoice, 'dd-MMM-yy', $null)

If you then wish to output a date string:

[datetime]::parseexact($invoice, 'dd-MMM-yy', $null).ToString('yyyy-MM-dd')

Chris

How do I find the last column with data?

I think we can modify the UsedRange code from @Readify's answer above to get the last used column even if the starting columns are blank or not.

So this lColumn = ws.UsedRange.Columns.Count modified to

this lColumn = ws.UsedRange.Column + ws.UsedRange.Columns.Count - 1 will give reliable results always

enter image description here

?Sheet1.UsedRange.Column + Sheet1.UsedRange.Columns.Count - 1

Above line Yields 9 in the immediate window.

How to get base64 encoded data from html image

You can try following sample http://jsfiddle.net/xKJB8/3/

<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

In my case it was an old dependency that was using compile for the transitive dependencies : com.jakewharton.hugo

After removing it from my gradle it compiled.

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

I used Laravel 8, This is my solution

Goto: storage/framework/cache/data
set permission directory data is 777

It's worked for me

setting an environment variable in virtualenv

If you're already using Heroku, consider running your server via Foreman. It supports a .env file which is simply a list of lines with KEY=VAL that will be exported to your app before it runs.

PHPExcel - set cell type before writing a value in it

For Numbers with leading zeroes and comma separated:

You can put 'A' to affect the entire column'.

$objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);

Then you can write to the cell as you normally would.

How to change progress bar's progress color in Android

Here is the code for changing the color of ProgressBar by programatically.

ProgressBar progressBar = (ProgressBar) findViewById(R.id.pb_listProgressBar);
int colorCodeDark = Color.parseColor("#F44336");
progressBar.setIndeterminateTintList(ColorStateList.valueOf(colorCodeDark));

How to change node.js's console font color?

There are multiple packages available for formatting console text in Node.js. The most popular are:

Usage:

CHALK:

const chalk = require('chalk');
console.log(chalk.red('Text in red'));

COLORS:

const colors = require('colors');
console.log('Text in red'.red);

CLI-COLOR:

const clc = require('cli-color');
console.log(clc.red('Text in red'));

Many people have noted their disapproval of colors altering the String prototype. If you prefer your prototypes to be left alone, use the following code instead:

const colors = require('colors/safe');
console.log(colors.red('Text in red'));

postgresql COUNT(DISTINCT ...) very slow

I was also searching same answer, because at some point of time I needed total_count with distinct values along with limit/offset.

Because it's little tricky to do- To get total count with distinct values along with limit/offset. Usually it's hard to get total count with limit/offset. Finally I got the way to do -

SELECT DISTINCT COUNT(*) OVER() as total_count, * FROM table_name limit 2 offset 0;

Query performance is also high.

Deleting an object in C++

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

Yes, it is.

I realized that it automatically invokes the destructor... is this normal?

Yes

Make sure that you did not double delete your object.

window.location.reload with clear cache

reload() is supposed to accept an argument which tells it to do a hard reload, ie, ignoring the cache:

location.reload(true);

I can't vouch for its reliability, you may want to investigate this further.

How to read PDF files using Java?

PDFBox is the best library I've found for this purpose, it's comprehensive and really quite easy to use if you're just doing basic text extraction. Examples can be found here.

It explains it on the page, but one thing to watch out for is that the start and end indexes when using setStartPage() and setEndPage() are both inclusive. I skipped over that explanation first time round and then it took me a while to realise why I was getting more than one page back with each call!

Itext is another alternative that also works with C#, though I've personally never used it. It's more low level than PDFBox, so less suited to the job if all you need is basic text extraction.

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Select Help->About

for 64 bit.. it would say version as 64 bit Edition.

I see this in IE 9.. may be true with lesser versions too..

Python:Efficient way to check if dictionary is empty or not

I would say that way is more pythonic and fits on line:

If you need to check value only with the use of your function:

if filter( your_function, dictionary.values() ): ...

When you need to know if your dict contains any keys:

if dictionary: ...

Anyway, using loops here is not Python-way.

How to access a dictionary element in a Django template?

You need to find (or define) a 'get' template tag, for example, here.

The tag definition:

@register.filter
def hash(h, key):
    return h[key]

And it’s used like:

{% for o in objects %}
  <li>{{ dictionary|hash:o.id }}</li>
{% endfor %}

Change Input to Upper Case

Can also do it this way but other ways seem better, this comes in handy if you only need it the once.

onkeyup="this.value = this.value.toUpperCase();"

how to get current month and year

label1.Text = DateTime.Now.Month.ToString();

and

label2.Text = DateTime.Now.Year.ToString();

Online PHP syntax checker / validator

http://phpcodechecker.com/ performs syntax check and a custom check for common errors.

I'm a novice, but it helped me.

How can I create a simple index.html file which lists all files/directories?

Did you try to allow it for this directory via .htaccess?

Options +Indexes

I use this for some of my directories where directory listing is disabled by my provider

How to disable button in React.js

In HTML,

<button disabled/>
<buttton disabled="true">
<buttton disabled="false">
<buttton disabled="21">

All of them boils down to disabled="true" that is because it returns true for a non-empty string. Hence, in order to return false, pass a empty string in a conditional statement like this.input.value?"true":"".

render() {
    return (
        <div className="add-item">
            <input type="text" className="add-item__input" ref={(input) => this.input = input} placeholder={this.props.placeholder} />
            <button disabled={this.input.value?"true":""} className="add-item__button" onClick={this.add.bind(this)}>Add</button>
        </div>
    );
}

Correct way to detach from a container without stopping it

You can use the --detach-keys option when you run docker attach to override the default CTRL+P, CTRL + Q sequence (that doesn't always work).

For example, when you run docker attach --detach-keys="ctrl-a" test and you press CTRL+A you will exit the container, without killing it.

Other examples:

  • docker attach --detach-keys="ctrl-a,x" test - press CTRL+A and then X to exit
  • docker attach --detach-keys="a,b,c" test - press A, then B, then C to exit

Extract from the official documentation:

If you want, you can configure an override the Docker key sequence for detach. This is useful if the Docker default sequence conflicts with key sequence you use for other applications. There are two ways to define your own detach key sequence, as a per-container override or as a configuration property on your entire configuration.

To override the sequence for an individual container, use the --detach-keys="<sequence>" flag with the docker attach command. The format of the <sequence> is either a letter [a-Z], or the ctrl- combined with any of the following:

  • a-z (a single lowercase alpha character )
  • @ (at sign)
  • [ (left bracket)
  • \ (two backward slashes)
  • _ (underscore)
  • ^ (caret)

These a, ctrl-a, X, or ctrl-\\ values are all examples of valid key sequences. To configure a different configuration default key sequence for all containers, see Configuration file section.

Note: This works since docker version 1.10+ (at the time of this answer, the current version is 18.03)

How may I sort a list alphabetically using jQuery?

I was looking to do this myself, and I wasnt satisfied with any of the answers provided simply because, I believe, they are quadratic time, and I need to do this on lists hundreds of items long.

I ended up extending jquery, and my solution uses jquery, but could easily be modified to use straight javascript.

I only access each item twice, and perform one linearithmic sort, so this should, I think, work out to be a lot faster on large datasets, though I freely confess I could be mistaken there:

sortList: function() {
   if (!this.is("ul") || !this.length)
      return
   else {
      var getData = function(ul) {
         var lis     = ul.find('li'),
             liData  = {
               liTexts : []
            }; 

         for(var i = 0; i<lis.length; i++){
             var key              = $(lis[i]).text().trim().toLowerCase().replace(/\s/g, ""),
             attrs                = lis[i].attributes;
             liData[key]          = {},
             liData[key]['attrs'] = {},
             liData[key]['html']  = $(lis[i]).html();

             liData.liTexts.push(key);

             for (var j = 0; j < attrs.length; j++) {
                liData[key]['attrs'][attrs[j].nodeName] = attrs[j].nodeValue;
             }
          }

          return liData;
       },

       processData = function (obj){
          var sortedTexts = obj.liTexts.sort(),
              htmlStr     = '';

          for(var i = 0; i < sortedTexts.length; i++){
             var attrsStr   = '',
                 attributes = obj[sortedTexts[i]].attrs;

             for(attr in attributes){
                var str = attr + "=\'" + attributes[attr] + "\' ";
                attrsStr += str;
             }

             htmlStr += "<li "+ attrsStr + ">" + obj[sortedTexts[i]].html+"</li>";
          }

          return htmlStr;

       };

       this.html(processData(getData(this)));
    }
}

Using Bootstrap Modal window as PartialView

I have achieved this by using one nice example i have found here. I have replaced the jquery dialog used in that example with the Twitter Bootstrap Modal windows.

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

Integration Testing POSTing an entire object to Spring MVC controller

I ran into the same issue a while ago and did solve it by using reflection with some help from Jackson.

First populate a map with all the fields on an Object. Then add those map entries as parameters to the MockHttpServletRequestBuilder.

In this way you can use any Object and you are passing it as request parameters. I'm sure there are other solutions out there but this one worked for us:

    @Test
    public void testFormEdit() throws Exception {
        getMockMvc()
                .perform(
                        addFormParameters(post(servletPath + tableRootUrl + "/" + POST_FORM_EDIT_URL).servletPath(servletPath)
                                .param("entityID", entityId), validEntity)).andDo(print()).andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(equalTo(entityId)));
    }

    private MockHttpServletRequestBuilder addFormParameters(MockHttpServletRequestBuilder builder, Object object)
            throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

        SimpleDateFormat dateFormat = new SimpleDateFormat(applicationSettings.getApplicationDateFormat());

        Map<String, ?> propertyValues = getPropertyValues(object, dateFormat);

        for (Entry<String, ?> entry : propertyValues.entrySet()) {
            builder.param(entry.getKey(),
                    Util.prepareDisplayValue(entry.getValue(), applicationSettings.getApplicationDateFormat()));
        }

        return builder;
    }

    private Map<String, ?> getPropertyValues(Object object, DateFormat dateFormat) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(dateFormat);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.registerModule(new JodaModule());

        TypeReference<HashMap<String, ?>> typeRef = new TypeReference<HashMap<String, ?>>() {};

        Map<String, ?> returnValues = mapper.convertValue(object, typeRef);

        return returnValues;

    }

how to print a string to console in c++

All you have to do is add:

#include <string>
using namespace std;

at the top. (BTW I know this was posted in 2013 but I just wanted to answer)

fileReader.readAsBinaryString to upload files

(Following is a late but complete answer)

FileReader methods support


FileReader.readAsBinaryString() is deprecated. Don't use it! It's no longer in the W3C File API working draft:

void abort();
void readAsArrayBuffer(Blob blob);
void readAsText(Blob blob, optional DOMString encoding);
void readAsDataURL(Blob blob);

NB: Note that File is a kind of extended Blob structure.

Mozilla still implements readAsBinaryString() and describes it in MDN FileApi documentation:

void abort();
void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0
void readAsBinaryString(in Blob blob);
void readAsDataURL(in Blob file);
void readAsText(in Blob blob, [optional] in DOMString encoding);

The reason behind readAsBinaryString() deprecation is in my opinion the following: the standard for JavaScript strings are DOMString which only accept UTF-8 characters, NOT random binary data. So don't use readAsBinaryString(), that's not safe and ECMAScript-compliant at all.

We know that JavaScript strings are not supposed to store binary data but Mozilla in some sort can. That's dangerous in my opinion. Blob and typed arrays (ArrayBuffer and the not-yet-implemented but not necessary StringView) were invented for one purpose: allow the use of pure binary data, without UTF-8 strings restrictions.

XMLHttpRequest upload support


XMLHttpRequest.send() has the following invocations options:

void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);

XMLHttpRequest.sendAsBinary() has the following invocations options:

void sendAsBinary(   in DOMString body );

sendAsBinary() is NOT a standard and may not be supported in Chrome.

Solutions


So you have several options:

  1. send() the FileReader.result of FileReader.readAsArrayBuffer ( fileObject ). It is more complicated to manipulate (you'll have to make a separate send() for it) but it's the RECOMMENDED APPROACH.
  2. send() the FileReader.result of FileReader.readAsDataURL( fileObject ). It generates useless overhead and compression latency, requires a decompression step on the server-side BUT it's easy to manipulate as a string in Javascript.
  3. Being non-standard and sendAsBinary() the FileReader.result of FileReader.readAsBinaryString( fileObject )

MDN states that:

The best way to send binary content (like in files upload) is using ArrayBuffers or Blobs in conjuncton with the send() method. However, if you want to send a stringifiable raw data, use the sendAsBinary() method instead, or the StringView (Non native) typed arrays superclass.

how to pass value from one php page to another using session

Solution using just POST - no $_SESSION

page1.php

<form action="page2.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>

page2.php

<?php
    // this page outputs the contents of the textarea if posted
    $textarea1 = ""; // set var to avoid errors
    if(isset($_POST['textarea1'])){
        $textarea1 = $_POST['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

Solution using $_SESSION and POST

page1.php

<?php

    session_start(); // needs to be before anything else on page to use $_SESSION
    $textarea1 = "";
    if(isset($_POST['textarea1'])){
        $_SESSION['textarea1'] = $_POST['textarea1'];
    }

?>


<form action="page1.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>

page2.php

<?php
    session_start(); // needs to be before anything else on page to use $_SESSION
    // this page outputs the textarea1 from the session IF it exists
    $textarea1 = ""; // set var to avoid errors
    if(isset($_SESSION['textarea1'])){
        $textarea1 = $_SESSION['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

WARNING!!! - This contains no validation!!!

Java method: Finding object in array list given a known attribute value

If you have to get an attribute that is not the ID. I would use CollectionUtils.

Dog someDog = new Dog();
Dog dog = CollectionUtils(dogList, new Predicate() {

@Override
public boolean evaluate(Object o)
{
    Dog d = (Dog)o;
    return someDog.getName().equals(d.getName());
}
});

Java 8 Stream API to find Unique Object matching a property value

findAny & orElse

By using findAny() and orElse():

Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);

Stops looking after finding an occurrence.

findAny

Optional<T> findAny()

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)

how to inherit Constructor from super class to sub class

Superclass constructor CAN'T be inherited in extended class. Although it can be invoked in extended class constructor's with super() as the first statement.

Windows 7: unable to register DLL - Error Code:0X80004005

Use following command should work on windows 7. don't forget to enclose the dll name with full path in double quotations.

C:\Windows\SysWOW64>regsvr32 "c:\dll.name" 

How do I get the IP address into a batch-file variable?

try something like this

echo "yours ip addresses are:"
ifconfig | grep "inet addr" | cut -d':' -f2 | cut -d' ' -f1

linux like systems

Make a simple fade in animation in Swift?

The problem is that you're trying start the animation too early in the view controller's lifecycle. In viewDidLoad, the view has just been created, and hasn't yet been added to the view hierarchy, so attempting to animate one of its subviews at this point produces bad results.

What you really should be doing is continuing to set the alpha of the view in viewDidLoad (or where you create your views), and then waiting for the viewDidAppear: method to be called. At this point, you can start your animations without any issue.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 1.5) {
        self.myFirstLabel.alpha = 1.0
        self.myFirstButton.alpha = 1.0
        self.mySecondButton.alpha = 1.0
    }
}

Git: "Corrupt loose object"

I was getting a corrupt loose object error as well.

./objects/x/x

I successfully fixed it by going into the directory of the corrupt object. I saw that the users assigned to that object was not my git user's. I don't know how it happened, but I ran a chown git:git on that file and then it worked again.

This may be a potential fix for some peoples' issues but not necessary all of them.

Print list without brackets in a single row

print(', '.join(names))

This, like it sounds, just takes all the elements of the list and joins them with ', '.

How to change color in circular progress bar?

To add to Dato's answer, i find SRC_ATOP to be a preferable filter to multiply as it better supports the alpha channel.

ProgressBar v = (ProgressBar) findViewById(R.id.progress);
v.getIndeterminateDrawable().setColorFilter(0xFFcc0000, android.graphics.PorterDuff.Mode.SRC_ATOP);

Read a plain text file with php

$file="./doc.txt";
$doc=file_get_contents($file);

$line=explode("\n",$doc);
foreach($line as $newline){
    echo '<h3 style="color:#453288">'.$newline.'</h3><br>';

}

How do I find all of the symlinks in a directory tree?

One command, no pipes

find . -type l -ls

Explanation: find from the current directory . onwards all references of -type link and list -ls those in detail. Plain and simple...

Expanding upon this answer, here are a couple more symbolic link related find commands:

Find symbolic links to a specific target

find . -lname link_target

Note that link_target is a pattern that may contain wildcard characters.

Find broken symbolic links

find -L . -type l -ls

The -L option instructs find to follow symbolic links, unless when broken.

Find & replace broken symbolic links

find -L . -type l -delete -exec ln -s new_target {} \;

More find examples

More find examples can be found here: https://hamwaves.com/find/

ADB Android Device Unauthorized

The solution is to copy your file ~/.android/adbkey.pub (on GNU/Linux, or %USERPROFILE%\.android\adbkey.pub on Windows) to Android, and place it as /data/misc/adb/adb_keys. You need root privileges to do that.

You can transfer the file any way you like (or are able to), be it USB, e-mail or a temporary file upload service. In my case, as it was a new Android-x86 installation in a Virtual Machine, no usable web browser, and with network/TCP adb not working, I had to actually type in the 715 characters.

At least it worked.

MySQL Query to select data from last week?

I often do a quick "last week" check as well and the following tends to work well for me and includes today.

DECLARE @StartDate DATETIME 
DECLARE @EndDate DATETIME 

SET @StartDate = Getdate() - 7 /* Seven Days Earlier */
SET @EndDate = Getdate() /* Now */

SELECT id 
FROM   mytable 
WHERE  date BETWEEN @StartDate AND @Enddate 

If you want this to NOT include today just subtract an extra day from the @EndDate. If I select these two variables today get

@StartDate 2015-11-16 16:34:05.347 /* Last Monday */

@EndDate 2015-11-23 16:34:05.347 /* This Monday */

If I wanted Sunday to Sunday I would have the following.

SET @StartDate = Getdate() - 8 /* Eight Days Earlier */
SET @EndDate = Getdate() - 1  /* Yesterday */

@StartDate 2015-11-15 16:34:05.347 /* Previous Sunday */

@EndDate 2015-11-22 16:34:05.347 /* Last Sunday */

Execute bash script from URL

Using wget, which is usually part of default system installation:

bash <(wget -qO- http://mywebsite.com/myscript.txt)

Null check in an enhanced for loop

Another way to effectively guard against a null in a for loop is to wrap your collection with Google Guava's Optional<T> as this, one hopes, makes the possibility of an effectively empty collection clear since the client would be expected to check if the collection is present with Optional.isPresent().

How to create folder with PHP code?

Purely basic folder creation

<?php mkdir("testing"); ?> <= this, actually creates a folder called "testing".



Basic file creation

<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>

Use the a or a+ switch to add/append to file.



EDIT:

This version will create a file and folder at the same time and show it on screen after.

<?php

// change the name below for the folder you want
$dir = "new_folder_name";

$file_to_write = 'test.txt';
$content_to_write = "The content";

if( is_dir($dir) === false )
{
    mkdir($dir);
}

$file = fopen($dir . '/' . $file_to_write,"w");

// a different way to write content into
// fwrite($file,"Hello World.");

fwrite($file, $content_to_write);

// closes the file
fclose($file);

// this will show the created file from the created folder on screen
include $dir . '/' . $file_to_write;

?>

How to concatenate columns in a Postgres SELECT?

For example if there is employee table which consists of columns as:

employee_number,f_name,l_name,email_id,phone_number 

if we want to concatenate f_name + l_name as name.

SELECT employee_number,f_name ::TEXT ||','|| l_name::TEXT  AS "NAME",email_id,phone_number,designation FROM EMPLOYEE;

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

If you have no FIRST/FIRST conflicts and no FIRST/FOLLOW conflicts, your grammar is LL(1).

An example of a FIRST/FIRST conflict:

S -> Xb | Yc
X -> a 
Y -> a 

By seeing only the first input symbol a, you cannot know whether to apply the production S -> Xb or S -> Yc, because a is in the FIRST set of both X and Y.

An example of a FIRST/FOLLOW conflict:

S -> AB 
A -> fe | epsilon 
B -> fg 

By seeing only the first input symbol f, you cannot decide whether to apply the production A -> fe or A -> epsilon, because f is in both the FIRST set of A and the FOLLOW set of A (A can be parsed as epsilon and B as f).

Notice that if you have no epsilon-productions you cannot have a FIRST/FOLLOW conflict.

Carriage return and Line feed... Are both required in C#?

I know this is a little old, but for anyone stumbling across this page should know there is a difference between \n and \r\n.

The \r\n gives a CRLF end of line and the \n gives an LF end of line character. There is very little difference to the eye in general.

Create a .txt from the string and then try and open in notepad (normal not notepad++) and you will notice the difference

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIOD
Q44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901
Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

The above is using 'CRLF' and the below is what 'LF only' would look like (There is a character that cant be seen where the LF shows).

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIODQ44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

If the Line Ends need to be corrected and the file is small enough in size, you can change the line endings in NotePad++ (or paste into word then back into Notepad - although this will make CRLF only).

This may cause some functions that read these files to potenitially no longer function (The example lines given are from GP Prescribing data - England. The file has changed from a CRLF Line end to an LF line end). This stopped an SSIS job from running and failed as couldn't read the LF line endings.

Source of Line Ending Information: https://en.wikipedia.org/wiki/Newline#Representations_in_different_character_encoding_specifications

Hope this helps someone in future :) CRLF = Windows based, LF or CF are from Unix based systems (Linux, MacOS etc.)

filter items in a python dictionary where keys contain a specific string

input = {"A":"a", "B":"b", "C":"c"}
output = {k:v for (k,v) in input.items() if key_satifies_condition(k)}

Laravel 5.4 Specific Table Migration

if you use tab for autocomplete

php artisan migrate --path='./database/migrations/2019_12_31_115457_create_coworking_personal_memberships_table.php'

How to remove part of a string?

string = "test_1234";
alert(string.substring(string.indexOf('_')+1));

It even works if the string has no underscore. Try it at http://jsbin.com/

Freeing up a TCP/IP port?

To check all ports:

netstat -lnp

To close an open port:

fuser -k port_no/tcp

Example:

fuser -k 8080/tcp

In both cases you can use the sudo command if needed.

minimize app to system tray

I found this to accomplish the entire solution. The answer above fails to remove the window from the task bar.

private void ImportStatusForm_Resize(object sender, EventArgs e)
{
    if (this.WindowState == FormWindowState.Minimized)
    {
        notifyIcon.Visible = true;
        notifyIcon.ShowBalloonTip(3000);
        this.ShowInTaskbar = false;
    }
}

private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
    this.WindowState = FormWindowState.Normal;
    this.ShowInTaskbar = true;
    notifyIcon.Visible = false;
}

Also it is good to set the following properties of the notify icon control using the forms designer.

this.notifyIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info; //Shows the info icon so the user doesn't think there is an error.
this.notifyIcon.BalloonTipText = "[Balloon Text when Minimized]";
this.notifyIcon.BalloonTipTitle = "[Balloon Title when Minimized]";
this.notifyIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon.Icon"))); //The tray icon to use
this.notifyIcon.Text = "[Message shown when hovering over tray icon]";

Getting a better understanding of callback functions in JavaScript

the proper implementation would be:

if( callback ) callback();

this makes the callback parameter optional..

Binding value to style

  • In your app.component.html use:

      [ngStyle]="{'background-color':backcolor}"
    
  • In app.ts declare variable of string type backcolor:string.

  • Set the variable this.backcolor="red".

ASP.NET Core Identity - get current user

If you are using Bearing Token Auth, the above samples do not return an Application User.

Instead, use this:

ClaimsPrincipal currentUser = this.User;
var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
ApplicationUser user = await _userManager.FindByNameAsync(currentUserName);

This works in apsnetcore 2.0. Have not tried in earlier versions.

How do I fetch only one branch of a remote Git repository?

I know there are a lot of answers already, but these are the steps that worked for me:

  1. git fetch <remote_name> <branch_name>
  2. git branch <branch_name> FETCH_HEAD
  3. git checkout <branch_name>

These are based on the answer by @Abdulsattar Mohammed, the comment by @Christoph on that answer, and these other stack overflow questions and their answers:

How to remove a directory from git repository?

You can try this: git rm -rf <directory_name>

It will force delete the directory.

Get all validation errors from Angular 2 FormGroup

export class GenericValidator {
    constructor(private validationMessages: { [key: string]: { [key: string]: string } }) {
    }

processMessages(container: FormGroup): { [key: string]: string } {
    const messages = {};
    for (const controlKey in container.controls) {
        if (container.controls.hasOwnProperty(controlKey)) {
            const c = container.controls[controlKey];
            if (c instanceof FormGroup) {
                const childMessages = this.processMessages(c);
                // handling formGroup errors messages
                const formGroupErrors = {};
                if (this.validationMessages[controlKey]) {
                    formGroupErrors[controlKey] = '';
                    if (c.errors) {
                        Object.keys(c.errors).map((messageKey) => {
                            if (this.validationMessages[controlKey][messageKey]) {
                                formGroupErrors[controlKey] += this.validationMessages[controlKey][messageKey] + ' ';
                            }
                        })
                    }
                }
                Object.assign(messages, childMessages, formGroupErrors);
            } else {
                // handling control fields errors messages
                if (this.validationMessages[controlKey]) {
                    messages[controlKey] = '';
                    if ((c.dirty || c.touched) && c.errors) {
                        Object.keys(c.errors).map((messageKey) => {
                            if (this.validationMessages[controlKey][messageKey]) {
                                messages[controlKey] += this.validationMessages[controlKey][messageKey] + ' ';
                            }
                        })
                    }
                }
            }
        }
    }
    return messages;
}
}

I took it from Deborahk and modified it a little bit.

printf with std::string?

printf accepts a variable number of arguments. Those can only have Plain Old Data (POD) types. Code that passes anything other than POD to printf only compiles because the compiler assumes you got your format right. %s means that the respective argument is supposed to be a pointer to a char. In your case it is an std::string not const char*. printf does not know it because the argument type goes lost and is supposed to be restored from the format parameter. When turning that std::string argument into const char* the resulting pointer will point to some irrelevant region of memory instead of your desired C string. For that reason your code prints out gibberish.

While printf is an excellent choice for printing out formatted text, (especially if you intend to have padding), it can be dangerous if you haven't enabled compiler warnings. Always enable warnings because then mistakes like this are easily avoidable. There is no reason to use the clumsy std::cout mechanism if the printf family can do the same task in a much faster and prettier way. Just make sure you have enabled all warnings (-Wall -Wextra) and you will be good. In case you use your own custom printf implementation you should declare it with the __attribute__ mechanism that enables the compiler to check the format string against the parameters provided.

Nested attributes unpermitted parameters

If you use a JSONB field, you must convert it to JSON with .to_json (ROR)

Can anyone explain what JSONP is, in layman terms?

Say you had some URL that gave you JSON data like:

{'field': 'value'}

...and you had a similar URL except it used JSONP, to which you passed the callback function name 'myCallback' (usually done by giving it a query parameter called 'callback', e.g. http://example.com/dataSource?callback=myCallback). Then it would return:

myCallback({'field':'value'})

...which is not just an object, but is actually code that can be executed. So if you define a function elsewhere in your page called myFunction and execute this script, it will be called with the data from the URL.

The cool thing about this is: you can create a script tag and use your URL (complete with callback parameter) as the src attribute, and the browser will run it. That means you can get around the 'same-origin' security policy (because browsers allow you to run script tags from sources other than the domain of the page).

This is what jQuery does when you make an ajax request (using .ajax with 'jsonp' as the value for the dataType property). E.g.

$.ajax({
  url: 'http://example.com/datasource',
  dataType: 'jsonp',
  success: function(data) {
    // your code to handle data here
  }
});

Here, jQuery takes care of the callback function name and query parameter - making the API identical to other ajax calls. But unlike other types of ajax requests, as mentioned, you're not restricted to getting data from the same origin as your page.

Counter exit code 139 when running, but gdb make it through

exit code 139 (people say this means memory fragmentation)

No, it means that your program died with signal 11 (SIGSEGV on Linux and most other UNIXes), also known as segmentation fault.

Could anybody tell me why the run fails but debug doesn't?

Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).

Your first step should be running this program under Valgrind, and fixing all errors it reports.

If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out) and then analyze that core dump with GDB: gdb ./a.out core; then use where command.

Inserting HTML elements with JavaScript

As others said the convenient jQuery prepend functionality can be emulated:

var html = '<div>Hello prepended</div>';
document.body.innerHTML = html + document.body.innerHTML;

While some say it is better not to "mess" with innerHTML, it is reliable in many use cases, if you know this:

If a <div>, <span>, or <noembed> node has a child text node that includes the characters (&), (<), or (>), innerHTML returns these characters as &amp, &lt and &gt respectively. Use Node.textContent to get a correct copy of these text nodes' contents.

https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

Or:

var html = '<div>Hello prepended</div>';
document.body.insertAdjacentHTML('afterbegin', html)

insertAdjacentHTML is probably a good alternative: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

How to change value of process.env.PORT in node.js?

EDIT: Per @sshow's comment, if you're trying to run your node app on port 80, the below is not the best way to do it. Here's a better answer: How do I run Node.js on port 80?

Original Answer:

If you want to do this to run on port 80 (or want to set the env variable more permanently),

  1. Open up your bash profile vim ~/.bash_profile
  2. Add the environment variable to the file export PORT=80
  3. Open up the sudoers config file sudo visudo
  4. Add the following line to the file exactly as so Defaults env_keep +="PORT"

Now when you run sudo node app.js it should work as desired.

PHP, pass array through POST

There are two things to consider: users can modify forms, and you need to secure against Cross Site Scripting (XSS).

XSS

XSS is when a user enters HTML into their input. For example, what if a user submitted this value?:

" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value="

This would be written into your form like so:

<input type="hidden" name="prova[]" value="" /><script type="text/javascript" src="http://example.com/malice.js"></script><input value=""/>

The best way to protect against this is to use htmlspecialchars() to secure your input. This encodes characters such as < into &lt;. For example:

<input type="hidden" name="prova[]" value="<?php echo htmlspecialchars($array); ?>"/>

You can read more about XSS here: https://www.owasp.org/index.php/XSS

Form Modification

If I were on your site, I could use Chrome's developer tools or Firebug to modify the HTML of your page. Depending on what your form does, this could be used maliciously.

I could, for example, add extra values to your array, or values that don't belong in the array. If this were a file system manager, then I could add files that don't exist or files that contain sensitive information (e.g.: replace myfile.jpg with ../index.php or ../db-connect.php).

In short, you always need to check your inputs later to make sure that they make sense, and only use safe inputs in forms. A File ID (a number) is safe, because you can check to see if the number exists, then extract the filename from a database (this assumes that your database contains validated input). A File Name isn't safe, for the reasons described above. You must either re-validate the filename or else I could change it to anything.

How do you read scanf until EOF in C?

For C users, this will also work

while ( gets(str) != NULL )

jquery - How to determine if a div changes its height or any css attribute?

Another simple example.

For this sample we can use 100x100 DIV-box:

<div id="box" style="width: 100px; height: 100px; border: solid 1px red;">
 // Red box contents here...
</div>

And small jQuery trick:

<script type="text/javascript">
  jQuery("#box").bind("resize", function() {
    alert("Box was resized from 100x100 to 200x200");
  });
  jQuery("#box").width(200).height(200).trigger("resize");
</script>

Steps:

  1. We created DIV block element for resizing operatios
  2. Add simple JavaScript code with:
    • jQuery bind
    • jQuery resizer with trigger action "resize" - trigger is most important thing in my example
  3. After resize you can check the browser alert information

That's all. ;-)

Convert an NSURL to an NSString

Try this in Swift :

var urlString = myUrl.absoluteString

Objective-C:

NSString *urlString = [myURL absoluteString];

What is the difference between sscanf or atoi to convert a string to an integer?

When there is no concern about invalid string input or range issues, use the simplest: atoi()

Otherwise, the method with best error/range detection is neither atoi(), nor sscanf(). This good answer all ready details the lack of error checking with atoi() and some error checking with sscanf().

strtol() is the most stringent function in converting a string to int. Yet it is only a start. Below are detailed examples to show proper usage and so the reason for this answer after the accepted one.

// Over-simplified use
int strtoi(const char *nptr) {
  int i = (int) strtol(nptr, (char **)NULL, 10);
  return i; 
}

This is the like atoi() and neglects to use the error detection features of strtol().

To fully use strtol(), there are various features to consider:

  1. Detection of no conversion: Examples: "xyz", or "" or "--0"? In these cases, endptr will match nptr.

    char *endptr;
    int i = (int)strtol(nptr, &endptr, 10);
    if (nptr == endptr) return FAIL_NO_CONVERT;
    
  2. Should the whole string convert or just the leading portion: Is "123xyz" OK?

    char *endptr;
    int i = (int)strtol(nptr, &endptr, 10);
    if (*endptr != '\0') return FAIL_EXTRA_JUNK;
    
  3. Detect if value was so big, the the result is not representable as a long like "999999999999999999999999999999".

    errno = 0;
    long L = strtol(nptr, &endptr, 10);
    if (errno == ERANGE) return FAIL_OVERFLOW;
    
  4. Detect if the value was outside the range of than int, but not long. If int and long have the same range, this test is not needed.

    long L = strtol(nptr, &endptr, 10);
    if (L < INT_MIN || L > INT_MAX) return FAIL_INT_OVERFLOW;
    
  5. Some implementations go beyond the C standard and set errno for additional reasons such as errno to EINVAL in case no conversion was performed or EINVAL The value of the Base parameter is not valid.. The best time to test for these errno values is implementation dependent.

Putting this all together: (Adjust to your needs)

#include <errno.h>
#include <stdlib.h>

int strtoi(const char *nptr, int *error_code) {
  char *endptr;
  errno = 0;
  long i = strtol(nptr, &endptr, 10);

  #if LONG_MIN < INT_MIN || LONG_MAX > INT_MAX
  if (errno == ERANGE || i > INT_MAX || i < INT_MIN) {
    errno = ERANGE;
    i = i > 0 : INT_MAX : INT_MIN;
    *error_code = FAIL_INT_OVERFLOW;
  }
  #else
  if (errno == ERANGE) {
    *error_code = FAIL_OVERFLOW;
  }
  #endif

  else if (endptr == nptr) {
    *error_code = FAIL_NO_CONVERT;
  } else if (*endptr != '\0') {
    *error_code = FAIL_EXTRA_JUNK;
  } else if (errno) {
    *error_code = FAIL_IMPLEMENTATION_REASON;
  }
  return (int) i;
}

Note: All functions mentioned allow leading spaces, an optional leading sign character and are affected by locale change. Additional code is required for a more restrictive conversion.


Note: Non-OP title change skewed emphasis. This answer applies better to original title "convert string to integer sscanf or atoi"

When should null values of Boolean be used?

ANSWER TO OWN QUESTION: I thought it would be useful to answer my own question as I have learnt a lot from the answers. This answer is intended to help those - like me - who do not have a complete understanding of the issues. If I use incorrect language please correct me.

  • The null "value" is not a value and is fundamentally different from true and false. It is the absence of a pointer to objects. Therefore to think that Boolean is 3-valued is fundamentally wrong
  • The syntax for Boolean is abbreviated and conceals the fact that the reference points to Objects:

    Boolean a = true;

conceals the fact that true is an object. Other equivalent assignments might be:

Boolean a = Boolean.TRUE;

or

Boolean a = new Boolean(true);
  • The abbreviated syntax

    if (a) ...

is different from most other assignments and conceals the fact that a might be an object reference or a primitive. If an object it is necessary to test for null to avoid NPE. For me it is psychologically easier to remember this if there is an equality test:

if (a == true) ...

where we might be prompted to test for null. So the shortened form is only safe when a is a primitive.

For myself I now have the recommendations:

  • Never use null for a 3-valued logic. Only use true and false.
  • NEVER return Boolean from a method as it could be null. Only return boolean.
  • Only use Boolean for wrapping elements in containers, or arguments to methods where objects are required

What is float in Java?

In Java, when you type a decimal number as 3.6, its interpreted as a double. double is a 64-bit precision IEEE 754 floating point, while floatis a 32-bit precision IEEE 754 floating point. As a float is less precise than a double, the conversion cannot be performed implicitly.

If you want to create a float, you should end your number with f (i.e.: 3.6f).

For more explanation, see the primitive data types definition of the Java tutorial.

What are 'get' and 'set' in Swift?

You should look at Computed Properties

In your code sample, perimeter is a property not backed up by a class variable, instead its value is computed using the get method and stored via the set method - usually referred to as getter and setter.

When you use that property like this:

var cp = myClass.perimeter

you are invoking the code contained in the get code block, and when you use it like this:

myClass.perimeter = 5.0

you are invoking the code contained in the set code block, where newValue is automatically filled with the value provided at the right of the assignment operator.

Computed properties can be readwrite if both a getter and a setter are specified, or readonly if the getter only is specified.

How to detect when an Android app goes to the background and come back to the foreground

The onPause() and onResume() methods are called when the application is brought to the background and into the foreground again. However, they are also called when the application is started for the first time and before it is killed. You can read more in Activity.

There isn't any direct approach to get the application status while in the background or foreground, but even I have faced this issue and found the solution with onWindowFocusChanged and onStop.

For more details check here Android: Solution to detect when an Android app goes to the background and come back to the foreground without getRunningTasks or getRunningAppProcesses.

Converting a view to Bitmap without displaying it in Android?

Layout or view to bitmap:

 private Bitmap createBitmapFromLayout(View tv) {      
    int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    tv.measure(spec, spec);
    tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());
    Bitmap b = Bitmap.createBitmap(tv.getMeasuredWidth(), tv.getMeasuredWidth(),
            Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    c.translate((-tv.getScrollX()), (-tv.getScrollY()));
    tv.draw(c);
    return b;
}

Calling Method:

Bitmap src = createBitmapFromLayout(View.inflate(this, R.layout.sample, null)/* or pass your view object*/);

The Android emulator is not starting, showing "invalid command-line parameter"

I started Task Manager, made sure adb.exe is closed (it locks some files)

Create the folder C:\Android Moved folder + all files from C:\Program Files\android-sdk to C:\Android

Edited C:\Documents and Settings\All Users\Start Menu\Programs\Android SDK Tools shortcuts.

I considered uninstalling the SDK and re-installing, but for the life of me, where does it store the temp files?? I don't want to re-download the platforms, samples and doco that I have added to the SDK.

Where to place JavaScript in an HTML file?

Using cuzillion you can test the affect on page load of different placement of script tags using different methods: inline, external, "HTML tags", "document.write", "JS DOM element", "iframe", and "XHR eval". See the help for an explanation of the differences. It can also test stylesheets, images and iframes.

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

new_vector.assign(old_vector.begin(),old_vector.end()); // Method 1
new_vector = old_vector; // Method 2

How to save username and password with Mercurial?

If you are using TortoiseHg you have to perform these three steps shown in the attached screen shot, this would add your credentials for the specific repository you are working with.

enter image description here

To add global settings you can access the file C:\users\user.name\mercurial.ini and add the section

[auth]
bb.prefix=https://bitbucket.org/zambezia/packagemanager
bb.username = $username
bb.password = $password

Hope this helps.

How to change link color (Bootstrap)

I'm fully aware that the code in the original quesiton displays a situation of being navbar related. But as you also dive into other compontents, it maybe helpful to know that the class options for text styling may not work.

But you can still create your own helper classes to keep the "Bootstrap flow" going in your HTML. Here is one idea to help style links that are in panel-title regions.

The following code by itself will not style a warning color on your anchor link...

<div class="panel panel-default my-panel-styles"> 
...    
  <h4 class="panel-title">
    <a class="accordion-toggle btn-block text-warning" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
      My Panel title that is also a link
    </a>
  </h4>
 ...
 </div>

But you could extend the Bootstrap styling package by adding your own class with appropriate colors like this...

.my-panel-styles .text-muted {color:#777;}
.my-panel-styles .text-primary {color:#337ab7;}
.my-panel-styles .text-success {color:#d44950;}
.my-panel-styles .text-info {color:#31708f;}
.my-panel-styles .text-warning {color:#8a6d3b;}
.my-panel-styles .text-danger {color:#a94442;}

...Now you can continue building out your panel anchor links with the Bootstrap colors you want.

Filtering DataSet

No mention of Merge?

DataSet newdataset = new DataSet();

newdataset.Merge( olddataset.Tables[0].Select( filterstring, sortstring ));

What is the best way to create and populate a numbers table?

I know this thread is old and answered, but there is a way to squeeze a little extra performance out of Method 7:

Instead of this (essentially method 7 but with some ease of use polish):

DECLARE @BIT AS BIT = 0
IF OBJECT_ID('tempdb..#TALLY') IS NOT NULL
  DROP TABLE #TALLY
DECLARE @RunDate datetime
SET @RunDate=GETDATE()
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO #TALLY
    FROM sys.objects s1       --use sys.columns if you don't get enough rows returned to generate all the numbers you need
    CROSS JOIN sys.objects s2 --use sys.co
ALTER TABLE #TALLY ADD PRIMARY KEY(Number)
PRINT CONVERT(varchar(20),datediff(ms,@RunDate,GETDATE()))+' milliseconds'

Try this:

DECLARE @BIT AS BIT = 0
IF OBJECT_ID('tempdb..#TALLY') IS NOT NULL
  DROP TABLE #TALLY
DECLARE @RunDate datetime
SET @RunDate=GETDATE()
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO #TALLY
    FROM        (SELECT @BIT [X] UNION ALL SELECT @BIT) [T2]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T4]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T8]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T16]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T32]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T64]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T128]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T256]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T512]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T1024]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T2048]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T4096]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T8192]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T16384]
ALTER TABLE #TALLY ADD PRIMARY KEY(Number)
PRINT CONVERT(varchar(20),datediff(ms,@RunDate,GETDATE()))+' milliseconds'

On my server this takes ~10 ms as opposed to the ~16-20 ms when selecting from sys.objects. It also has the added benefit of not being dependent on how many objects are in sys.objects. While it's pretty safe, it's technically a dependency and the other one goes faster anyway. I think the speed boost is down to using BITs if you change:

DECLARE @BIT AS BIT = 0

to:

DECLARE @BIT AS BIGINT = 0

It adds ~8-10 ms to the total time on my server. That said, when you scale up to 1,000,000 records BIT vs BIGINT doesn't appreciably affect my query anymore, but it still runs around ~680ms vs ~730ms from sys.objects.

Fast check for NaN in NumPy

Ray's solution is good. However, on my machine it is about 2.5x faster to use numpy.sum in place of numpy.min:

In [13]: %timeit np.isnan(np.min(x))
1000 loops, best of 3: 244 us per loop

In [14]: %timeit np.isnan(np.sum(x))
10000 loops, best of 3: 97.3 us per loop

Unlike min, sum doesn't require branching, which on modern hardware tends to be pretty expensive. This is probably the reason why sum is faster.

edit The above test was performed with a single NaN right in the middle of the array.

It is interesting to note that min is slower in the presence of NaNs than in their absence. It also seems to get slower as NaNs get closer to the start of the array. On the other hand, sum's throughput seems constant regardless of whether there are NaNs and where they're located:

In [40]: x = np.random.rand(100000)

In [41]: %timeit np.isnan(np.min(x))
10000 loops, best of 3: 153 us per loop

In [42]: %timeit np.isnan(np.sum(x))
10000 loops, best of 3: 95.9 us per loop

In [43]: x[50000] = np.nan

In [44]: %timeit np.isnan(np.min(x))
1000 loops, best of 3: 239 us per loop

In [45]: %timeit np.isnan(np.sum(x))
10000 loops, best of 3: 95.8 us per loop

In [46]: x[0] = np.nan

In [47]: %timeit np.isnan(np.min(x))
1000 loops, best of 3: 326 us per loop

In [48]: %timeit np.isnan(np.sum(x))
10000 loops, best of 3: 95.9 us per loop

connecting to MySQL from the command line

Best practice would be to mysql -u root -p. Then MySQL will prompt for password after you hit enter.

Python check if website exists

def isok(mypath):
    try:
        thepage = urllib.request.urlopen(mypath)
    except HTTPError as e:
        return 0
    except URLError as e:
        return 0
    else:
        return 1

What's the best way to do a backwards loop in C/C#/C++?

In C#, using Visual Studio 2005 or later, type 'forr' and hit [TAB] [TAB]. This will expand to a for loop that goes backwards through a collection.

It's so easy to get wrong (at least for me), that I thought putting this snippet in would be a good idea.

That said, I like Array.Reverse() / Enumerable.Reverse() and then iterate forwards better - they more clearly state intent.

Unsupported major.minor version 52.0 when rendering in Android Studio

Im my case I had to change the dependencies of the build.gradle file to:

dependencies { 
    classpath 'com.android.tools.build:gradle:2.1.0'
}

(originally was 2.2.2) I guess this was generated by get several people working in the same project with different versions of gradle. So check your gradle version and edit this file properly.

Good vibes!

Collision Detection between two images in Java

Here's a useful of an open source game that uses a lot of collisions: http://robocode.sourceforge.net/

You may take a look at the code and complement with the answers written here.

How to change the colors of a PNG image easily?

Ok guys it can be done easy in photoshop.

Open png photo and then check image -> mode value(i had indexed color). Go image -> mode and check rgb color. Now change your color EASY.

Return row of Data Frame based on value in a column - R

Use which.min:

df <- data.frame(Name=c('A','B','C','D'), Amount=c(150,120,175,160))
df[which.min(df$Amount),]

> df[which.min(df$Amount),]
  Name Amount
2    B    120

From the help docs:

Determines the location, i.e., index of the (first) minimum or maximum of a numeric (or logical) vector.

How do I remove the blue styling of telephone numbers on iPhone/iOS?

In case people find this question on Google, all you need to do is treat the telephone number as a link as Apple will automatically set it as one.

your HTML

<p id="phone-text">Call us on <strong>+44 (0)20 7194 8000</strong></p>

your css

#phone-text a{color:#fff; text-decoration:none;}

Add CSS or JavaScript files to layout head from views or partial views

Try the out-of-the-box solution (ASP.NET MVC 4 or later):

@{
    var bundle = BundleTable.Bundles.GetRegisteredBundles().First(b => b.Path == "~/js");

    bundle.Include("~/Scripts/myFile.js");
}

How do you get a list of the names of all files present in a directory in Node.js?

Get files in all subdirs

const fs=require('fs');

function getFiles (dir, files_){
    files_ = files_ || [];
    var files = fs.readdirSync(dir);
    for (var i in files){
        var name = dir + '/' + files[i];
        if (fs.statSync(name).isDirectory()){
            getFiles(name, files_);
        } else {
            files_.push(name);
        }
    }
    return files_;
}

console.log(getFiles('path/to/dir'))

Undefined reference to `pow' and `floor'

For the benefit of anyone reading this later, you need to link against it as Fred said:

gcc fib.c -lm -o fibo

One good way to find out what library you need to link is by checking the man page if one exists. For example, man pow and man floor will both tell you:

Link with -lm.

An explanation for linking math library in C programming - Linking in C