Programs & Examples On #Sigprocmask

How to post JSON to PHP with curl

You need to set a few extra flags so that curl sends the data as JSON.

command

$ curl -H "Content-Type: application/json" \
       -X POST \
       -d '{"JSON": "HERE"}' \
       http://localhost:3000/api/url

flags

  • -H: custom header, next argument is expected to be header
  • -X: custom HTTP verb, next argument is expected to be verb
  • -d: sends the next argument as data in an HTTP POST request

resources

Should switch statements always contain a default clause?

I disagree with the most voted answer of Vanwaril above.

Any code adds complexity. Also tests and documentation must be done for it. So it is always good if you can program using less code. My opinion is that I use a default clause for non-exhaustive switch statements while I use no default clause for exhaustive switch statements. To be sure that I did that right I use a static code analysis tool. So let's go into the details:

  1. Nonexhaustive switch statements: Those should always have a default value. As the name suggests those are statements which do not cover all possible values. This also might not be possible, e.g. a switch statement on an integer value or on a String. Here I would like to use the example of Vanwaril (It should be mentioned that I think he used this example to make a wrong suggestion. I use it here to state the opposite --> Use a default statement):

    switch(keystroke)
    {
      case 'w':
        // move up
      case 'a':
        // move left
      case 's':
        // move down
      case 'd':
        // move right
      default:          
        // cover all other values of the non-exhaustive switch statement
    }
    

    The player could press any other key. Then we could not do anything (this can be shown in the code just by adding a comment to the default case) or it should for example print something on the screen. This case is relevant as it may happen.

  2. Exhaustive switch statements: Those switch statements cover all possible values, e.g. a switch statement on an enumeration of grade system types. When developing code the first time it is easy to cover all values. However, as we are humans there is a small chance to forget some. Additionally if you add an enum value later such that all switch statements have to be adapted to make them exhaustive again opens the path to error hell. The simple solution is a static code analysis tool. The tool should check all switch statements and check if they are exhaustive or if they have a default value. Here an example for an exhaustive switch statement. First we need an enum:

    public enum GradeSystemType {System1To6, SystemAToD, System0To100}
    

    Then we need a variable of this enum like GradeSystemType type = .... An exhaustive switch statement would then look like this:

    switch(type)
    {
      case GradeSystemType.System1To6:
        // do something
      case GradeSystemType.SystemAToD:
        // do something
      case GradeSystemType.System0To100:
        // do something
    }
    

    So if we extend the GradeSystemType by for example System1To3 the static code analysis tool should detect that there is no default clause and the switch statement is not exhaustive so we are save.

Just one additional thing. If we always use a default clause it might happen that the static code analysis tool is not capable of detecting exhaustive or non-exhaustive switch statements as it always detects the default clause. This is super bad as we will not be informed if we extend the enum by another value and forget to add it to one switch statement.

How to get the text of the selected value of a dropdown list?

You can use option:selected to get the chosen option of the select element, then the text() method:

$("select option:selected").text();

Here's an example:

_x000D_
_x000D_
console.log($("select option:selected").text());
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<select>_x000D_
    <option value="1">Volvo</option>_x000D_
    <option value="2" selected="selected">Saab</option>_x000D_
    <option value="3">Mercedes</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Objective-C for Windows

Expanding on the two previous answers, if you just want Objective-C but not any of the Cocoa frameworks, then gcc will work on any platform. You can use it through Cygwin or get MinGW. However, if you want the Cocoa frameworks, or at least a reasonable subset of them, then GNUStep and Cocotron are your best bets.

Cocotron implements a lot of stuff that GNUStep does not, such as CoreGraphics and CoreData, though I can't vouch for how complete their implementation is on a specific framework. Their aim is to keep Cocotron up to date with the latest version of OS X so that any viable OS X program can run on Windows. Because GNUStep typically uses the latest version of gcc, they also add in support for Objective-C++ and a lot of the Objective-C 2.0 features.

I haven't tested those features with GNUStep, but if you use a sufficiently new version of gcc, you might be able to use them. I was not able to use Objective-C++ with GNUStep a few years ago. However, GNUStep does compile from just about any platform. Cocotron is a very mac-centric project. Although it is probably possible to compile it on other platforms, it comes XCode project files, not makefiles, so you can only compile its frameworks out of the box on OS X. It also comes with instructions on compiling Windows apps on XCode, but not any other platform. Basically, it's probably possible to set up a Windows development environment for Cocotron, but it's not as easy as setting one up for GNUStep, and you'll be on your own, so GNUStep is definitely the way to go if you're developing on Windows as opposed to just for Windows.

For what it's worth, Cocotron is licensed under the MIT license, and GNUStep is licensed under the LGPL.

Difference between a Structure and a Union

A union is useful in a couple scenarios. union can be a tool for very low level manipulation like writing device drivers for a kernel.

An example of that is dissecting a float number by using union of a struct with bitfields and a float. I save a number in the float, and later I can access particular parts of the float through that struct. The example shows how union is used to have different angles to look at data.

#include <stdio.h>                                                                                                                                       

union foo {
    struct float_guts {
        unsigned int fraction : 23;
        unsigned int exponent : 8;
        unsigned int sign     : 1;
    } fg;
    float f;
};

void print_float(float f) {
    union foo ff;
    ff.f = f;
    printf("%f: %d 0x%X 0x%X\n", f, ff.fg.sign, ff.fg.exponent, ff.fg.fraction);

}

int main(){
    print_float(0.15625);
    return 0;
}

Take a look at single precision description on wikipedia. I used the example and the magic number 0.15625 from there.


union can also be used to implement an algebraic data type that has multiple alternatives. I found an example of that in the "Real World Haskell" book by O'Sullivan, Stewart, and Goerzen. Check it out in the The discriminated union section.

Cheers!

How to target only IE (any version) within a stylesheet?

Another working solution for IE specific styling is

<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">

And then your selector

html[data-useragent*='MSIE 10.0'] body .my-class{
        margin-left: -0.4em;
    }

Finding repeated words on a string and counting the repetitions

Using java8

private static void findWords(String s, List<String> output, List<Integer> count){
    String[] words = s.split(", ");
    Map<String, Integer> map = new LinkedHashMap<>();
    Arrays.stream(words).forEach(e->map.put(e, map.getOrDefault(e, 0) + 1));
    map.forEach((k,v)->{
        output.add(k);
        count.add(v);
    });
}

Also, use a LinkedHashMap if you want to preserve the order of insertion

private static void findWords(){
    String s = "House, House, House, Dog, Dog, Dog, Dog";
    List<String> output = new ArrayList<>();
    List<Integer> count = new ArrayList<>();
    findWords(s, output, count);
    System.out.println(output);
    System.out.println(count);
}

Output

[House, Dog]
[3, 4]

psql - save results of command to a file

Use o parameter of pgsql command.

-o, --output=FILENAME send query results to file (or |pipe)

psql -d DatabaseName -U UserName -c "SELECT * FROM TABLE" -o /root/Desktop/file.txt

Function to get yesterday's date in Javascript in format DD/MM/YYYY

Try this:

function getYesterdaysDate() {
    var date = new Date();
    date.setDate(date.getDate()-1);
    return date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();
}

Reading all files in a directory, store them in objects, and send the object

For the code to work smoothy in different enviroments, path.resolve can be used in places where path is manipulated. Here is code which works better.

Reading part:

var fs = require('fs');

function readFiles(dirname, onFileContent, onError) {
  fs.readdir(dirname, function(err, filenames) {
    if (err) {
      onError(err);
      return;
    }
    filenames.forEach(function(filename) {
      fs.readFile(path.resolve(dirname, filename), 'utf-8', function(err, content) {
        if (err) {
          onError(err);
          return;
        }
        onFileContent(filename, content);
      });
    });
  });
}

Storing part:

var data = {};
readFiles(path.resolve(__dirname, 'dirname/'), function(filename, content) {
  data[filename] = content;
}, function(error) {
  throw err;
});

How to import local packages in go?

Well, I figured out the problem. Basically Go starting path for import is $HOME/go/src

So I just needed to add myapp in front of the package names, that is, the import should be:

import (
    "log"
    "net/http"
    "myapp/common"
    "myapp/routers"
)

PHP: if !empty & empty

if(!empty($youtube) && empty($link)) {

}
else if(empty($youtube) && !empty($link)) {

}
else if(empty($youtube) && empty($link)) {
}

sendmail: how to configure sendmail on ubuntu?

Combine two answers above, I finally make it work. Just be careful that the first single quote for each string is a backtick (`) in file sendmail.mc.

#Change to your mail config directory:
cd /etc/mail

#Make a auth subdirectory
mkdir auth
chmod 700 auth  #maybe not, because I cannot apply cmd "cd auth" if I do so.

#Create a file with your auth information to the smtp server
cd auth
touch client-info

#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"

#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..

#Add the following lines to sendmail.mc. Make sure you update your smtp server
#The first single quote for each string should be changed to a backtick (`) like this:
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl

#run 
sudo sendmailconfig

git diff between cloned and original remote repository

1) Add any remote repositories you want to compare:

git remote add foobar git://github.com/user/foobar.git

2) Update your local copy of a remote:

git fetch foobar

Fetch won't change your working copy.

3) Compare any branch from your local repository to any remote you've added:

git diff master foobar/master

How to convert Seconds to HH:MM:SS using T-SQL

Using SQL Server 05 I can get this to work by using:

declare @OrigValue int;
set @OrigValue = 121.25;
select replace(str(@OrigValue/3600,len(ltrim(@OrigValue/3600))+abs(sign(@OrigValue/359999)-1)) + ':' + str((@OrigValue/60)%60,2) + ':' + str(@OrigValue%60,2),' ','0')

Automatically size JPanel inside JFrame

You need to set a layout manager for the JFrame to use - This deals with how components are positioned. A useful one is the BorderLayout manager.

Simply adding the following line of code should fix your problems:

mainFrame.setLayout(new BorderLayout());

(Do this before adding components to the JFrame)

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

For the people like myself, who started recently: The loaders keyword is replaced with rules; even though it still represents the concept of loaders. So my webpack.config.js, for a React app, is as follows:

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');

var config = {
  entry: APP_DIR + '/index.jsx',
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js'
  },
  module : {
    rules : [
      {
        test : /\.jsx?/,
        include : APP_DIR,
        loader : 'babel-loader'
      }
    ]
  }
};

module.exports = config;

How to get current date in 'YYYY-MM-DD' format in ASP.NET?

Might be worthwhile using the CultureInfo to apply DateTime formatting throughout the website. Insteado f running around formatting whever you have to.

CultureInfo.CurrentUICulture.DateTimeFormat.SetAllDateTimePatterns( ...

or

CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd"; 

Code should go somewhere in your Global.asax file

protected void Application_Start(){ ...

Semaphore vs. Monitors - what's the difference?

When a semaphore is used to guard a critical region, there is no direct relationship between the semaphore and the data being protected. This is part of the reason why semaphores may be dispersed around the code, and why it is easy to forget to call wait or notify, in which case the result will be, respectively, to violate mutual exclusion or to lock the resource permanently.

In contrast, niehter of these bad things can happen with a monitor. A monitor is tired directly to the data (it encapsulates the data) and, because the monitor operations are atomic actions, it is impossible to write code that can access the data without calling the entry protocol. The exit protocol is called automatically when the monitor operation is completed.

A monitor has a built-in mechanism for condition synchronisation in the form of condition variable before proceeding. If the condition is not satisfied, the process has to wait until it is notified of a change in the condition. When a process is waiting for condition synchronisation, the monitor implementation takes care of the mutual exclusion issue, and allows another process to gain access to the monitor.

Taken from The Open University M362 Unit 3 "Interacting process" course material.

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

There is one more chance to get this exception even we used class name i.e., if we have two classes with same name in different packages. we'll get this problem.

I think hibernate may get ambiguity and throws this exception, so the solution is to use complete qualified name(like com.test.Customerv)

I added this answer that will help in scenario as I mentioned. I got the same scenario got stuck for some time.

Change the row color in DataGridView based on the quantity of a cell value

Just remove the : in your Quantity. Make sure that your attribute is the same with the parameter you include in the code, like this:

Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
        If Me.DataGridView1.Rows(i).Cells("Quantity").Value < 5 Then
            Me.DataGridView1.Rows(i).Cells("Quantity").Style.ForeColor = Color.Red
        End If
    Next
End Sub

SQL Server 2008 can't login with newly created user

SQL Server was not configured to allow mixed authentication.

Here are steps to fix:

  1. Right-click on SQL Server instance at root of Object Explorer, click on Properties
  2. Select Security from the left pane.
  3. Select the SQL Server and Windows Authentication mode radio button, and click OK.

    enter image description here

  4. Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).

This is also incredibly helpful for IBM Connections users, my wizards were not able to connect until I fxed this setting.

How do I combine the first character of a cell with another cell in Excel?

Not sure why no one is using semicolons. This is how it works for me:

=CONCATENATE(LEFT(A1;1); B1)

Solutions with comma produce an error in Excel.

How to change the port number for Asp.Net core app?

In visual studio 2017 we can change the port number from LaunchSetting.json

In Properties-> LaunchSettings.json.

Open LaunchSettings.json and change the Port Number.

Launch

Change the port Number in json file

enter image description here

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

    String str1,str2;
    Scanner S=new Scanner(System.in);
    str1=S.nextLine();
    System.out.println(str1);
    str2=S.nextLine();
    str1=str1.concat(str2);
    System.out.println(str1.toLowerCase()); 

Is it possible to return empty in react render function?

for those developers who came to this question about checking where they can return null from component instead of checking in ternary mode to render or not render the component, the answer is YES, You Can!

i mean instead of this junk ternary condition inside your jsx in render part of your component:

// some component body
return(
  <section>
   {/* some ui */}
   
   { someCondition && <MyComponent /> }
   or
   { someCondition ? <MyComponent /> : null }

   {/* more ui */}
  </section>
)

you can check than condition inside your component like:

const MyComponent:React.FC = () => {
  
  // get someCondition from context at here before any thing


  if(someCondition) return null; // i mean this part , checking inside component! 
  
  return (
    <section>   
     // some ui...
    </section>
  )
}

Just Consider that in my case i provide the someCondition variable from a context in upper level component ( for example, just consider in your mind ) and i don't need to prop drill the someCondition inside MyComponent.

Just look how clean view your code gets after that, i mean you don't need to user ternary operator inside your JSX, and your parent component would like below:

// some component body
return(
  <section>
   {/* some ui */}
   
   <MyComponent />

   {/* more ui */}
  </section>
)

and MyComponent would handle the rest for you!

VBA Excel - Insert row below with same format including borders and frames

well, using the Macro record, and doing it manually, I ended up with this code .. which seems to work .. (although it's not a one liner like yours ;)

lrow = Selection.Row()
Rows(lrow).Select
Selection.Copy
Rows(lrow + 1).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False
Selection.ClearContents

(I put the ClearContents in there because you indicated you wanted format, and I'm assuming you didn't want the data ;) )

Javascript checkbox onChange

I know this seems like noob answer but I'm putting it here so that it can help others in the future.

Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.

<!-- Begin Loop-->
<tr>
 <td><?=$criteria?></td>
 <td><?=$indicator?></td>
 <td><?=$target?></td>
 <td>
   <div class="form-check">
    <input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>> 
<!-- mark as 'checked' if checkbox was selected on a previous save -->
   </div>
 </td>
</tr>
<!-- End of Loop -->

You place a button below the table with a hidden input:

<form method="post" action="/goalobj-review" id="goalobj">

 <!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->

 <input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
 <button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>

You can write your script like so:

<script type="text/javascript">
    var checkboxes = document.getElementsByClassName('form-check-input');
    var i;
    var tid = setInterval(function () {
        if (document.readyState !== "complete") {
            return;
        }
        clearInterval(tid);
    for(i=0;i<checkboxes.length;i++){
        checkboxes[i].addEventListener('click',checkBoxValue);
    }
    },100);

    function checkBoxValue(event) {
        var selected = document.querySelector("input[id=selected]");
        var result = 0;
        if(this.checked) {

            if(selected.value.length > 0) {
                result = selected.value + "," + this.value;
                document.querySelector("input[id=selected]").value = result;
            } else {
                result = this.value;
                document.querySelector("input[id=selected]").value = result;
            }
        }
        if(! this.checked) { 

// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.

            var compact = selected.value.split(","); // split string into array
            var index = compact.indexOf(this.value); // return index of our selected checkbox
            compact.splice(index,1); // removes 1 item at specified index
            var newValue = compact.join(",") // returns a new string
            document.querySelector("input[id=selected]").value = newValue;
        }

    }
</script>

The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.

How do we update URL or query strings using javascript/jQuery without reloading the page?

Yes

document.location is the normal way.

However document.location is effectively the same as window.location, except for window.location is a bit more supported in older browsers so may be the prefferable choice.

Check out this thread on SO for more info:

What's the difference between window.location and document.location in JavaScript?

Compare every item to every other item in ArrayList

What's the problem with using for loop inside, just like outside?

for (int j = i + 1; j < list.size(); ++j) {
    ...
}

In general, since Java 5, I used iterators only once or twice.

How to create a sticky navigation bar that becomes fixed to the top after scrolling

In answer to Shubham Patwa: This way, the page is "jumpy" soon as the class "navbar-fixed-top" applies. That's because the #mainnav is throwen in and out of the document's DOM flow. This can result in an ugly UX if the page has a "critical height", jumping between fixed and un-fixed #mainnav position.

I altered the code this way, which seems to work fine (not pixel-perfect, but fine):

$(document).ready(function() {
  var navpos = $('#mainnav').offset();
  var navheight = $('#mainnav').outerHeight();

$(window).bind('scroll', function() {
  if ($(window).scrollTop() > navpos.top) {
   $('#mainnav').addClass('navbar-fixed-top');
   $('body').css('marginTop',navheight);
   }
   else {
     $('#mainnav').removeClass('navbar-fixed-top');
     $('body').css('marginTop','0');
   }
});

Unable to cast object of type 'System.DBNull' to type 'System.String`

ExecuteScalar will return

  • null if there is no result set
  • otherwise the first column of the first row of the resultset, which may be DBNull.

If you know that the first column of the resultset is a string, then to cover all bases you need to check for both null and DBNull. Something like:

object accountNumber = ...ExecuteScalar(...);
return (accountNumber == null) ? String.Empty : accountNumber.ToString();

The above code relies on the fact that DBNull.ToString returns an empty string.

If accountNumber was another type (say integer), then you'd need to be more explicit:

object accountNumber = ...ExecuteScalar(...);
return (accountNumber == null || Convert.IsDBNull(accountNumber) ?     
         (int) accountNumber : 0;

If you know for sure that your resultset will always have at least one row (e.g. SELECT COUNT(*)...), then you can skip the check for null.

In your case the error message "Unable to cast object of type ‘System.DBNull’ to type ‘System.String`" indicates that the first column of your result set is a DBNUll value. This is from the cast to string on the first line:

string accountNumber = (string) ... ExecuteScalar(...);

Marc_s's comment that you don't need to check for DBNull.Value is wrong.

Append a Lists Contents to another List C#

if you want to get "terse" :)

List<string>GlobalStrings = new List<string>(); 

for(int x=1; x<10; x++) GlobalStrings.AddRange(new List<string> { "some value", "another value"});

How to debug ORA-01775: looping chain of synonyms?

Today I got this error, and after debugging I figured out that the actual tables were misssing, which I was referring using synonyms. So I suggest - first check that whether the tables exists!! :-))

How to access global js variable in AngularJS directive

I created a working CodePen example demonstrating how to do this the correct way in AngularJS. The Angular $window service should be used to access any global objects since directly accessing window makes testing more difficult.

HTML:

<section ng-app="myapp" ng-controller="MainCtrl">
  Value of global variable read by AngularJS: {{variable1}}
</section>

JavaScript:

// global variable outside angular
var variable1 = true;

var app = angular.module('myapp', []);

app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.variable1 = $window.variable1;
}]);

PHP: Show yes/no confirmation dialog

<input type="submit" name="submit" value="submit" onclick="return confirm('Are you sure?');"/> you can perform this action on Button too!

How to change value of ArrayList element in java

Change it to for(int i=0;i<=9;i++)

indexOf and lastIndexOf in PHP?

<?php
// sample array
$fruits3 = [
    "iron",
    1,
    "ascorbic",
    "potassium",
    "ascorbic",
    2,
    "2",
    "1",
];

// Let's say we are looking for the item "ascorbic", in the above array

//a PHP function matching indexOf() from JS
echo(array_search("ascorbic", $fruits3, true)); //returns "2"

// a PHP function matching lastIndexOf() from JS world
function lastIndexOf($needle, $arr)
{
    return array_search($needle, array_reverse($arr, true), true);
}

echo(lastIndexOf("ascorbic", $fruits3)); //returns "4"

// so these (above) are the two ways to run a function similar to indexOf and lastIndexOf()

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

$sql="SELECT tot_visit FROM visitors WHERE date = DATE(NOW()) - 1 into @s                
$conn->query($sql);
$sql = "INSERT INTO visitors (nbvisit_day,date,tot_visit) VALUES (1,CURRENT_DATE,@s+1)";
$conn->query($sql);

Blur or dim background when Android PopupWindow active

ok, so i follow uhmdown's answer for dimming background activity when pop window is open. But it creates problem for me. it was dimming activity and include popup window (means dimmed-black layered on both activity and popup also, it can not be separate them).

so i tried this way,

create an dimming_black.xml file for dimming effect,

 <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#33000000" />
</shape>

And add as background in FrameLayout as root xml tag, also put my other controls in LinearLayout like this layout.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/ff_drawable_black">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="bottom"
        android:background="@color/white">

        // other codes...
    </LinearLayout>

</FrameLayout>

at last i show popup on my MainActivity with some extra parameter set as below.

           //instantiate popup window
            popupWindow = new PopupWindow(viewPopup, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);

            //display the popup window
            popupWindow.showAtLocation(layout_ff, Gravity.BOTTOM, 0, 0);

Result: enter image description here

it works for me, also solved problem as commented by BaDo. With this Actionbar also can be dimmed.

P.s i am not saying uhmdown's is wrong. i learnt form his answer and try to evolve for my problem. I also confused whether this is a good way or not.

Any suggestions is also appreciated also sorry for my bad English.

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

In may case, I nedded to copy the gacutil.exe, gacutil.exe.config AND ALSO the gacutlrc.dll (from the 1033 directory)

Doing HTTP requests FROM Laravel to an external API

Basic Solution for Laravel 8 is

use Illuminate\Support\Facades\Http;

$response = Http::get('http://example.com');

I had conflict between "GuzzleHTTP sending requests" and "Illuminate\Http\Request;" don't ask me why... [it's here to be searchable]

So looking for 1sec i found in Laravel 8 Doc...

**Guzzle is inside the Laravel 8 Http Request !**

https://laravel.com/docs/8.x/http-client#making-requests

as you can see

https://laravel.com/docs/8.x/http-client#introduction

Laravel provides an expressive, minimal API around the Guzzle HTTP client, allowing you to quickly make outgoing HTTP requests to communicate with other web applications. Laravel's wrapper around Guzzle is focused on its most common use cases and a wonderful developer experience.

It worked for me very well, have fun and if helpful point up!

How to know user has clicked "X" or the "Close" button?

The CloseReason enumeration you found on MSDN is just for the purpose of checking whether the user closed the app, or it was due to a shutdown, or closed by the task manager, etc...

You can do different actions, according to the reason, like:

void Form_FormClosing(object sender, FormClosingEventArgs e)
{
    if(e.CloseReason == CloseReason.UserClosing)
        // Prompt user to save his data

    if(e.CloseReason == CloseReason.WindowsShutDown)
        // Autosave and clear up ressources
}

But like you guessed, there is no difference between clicking the x button, or rightclicking the taskbar and clicking 'close', or pressing Alt F4, etc. It all ends up in a CloseReason.UserClosing reason.

Solving "adb server version doesn't match this client" error

  1. adb kill-server
  2. close any pc side application you are using for manage the android phone, e.g. 360mobile(360????). you might need to end them in task manager in necessary.
  3. adb start-server and it should be solved

How to capture Curl output to a file?

use --trace-asci output.txt can output the curl details to the output.txt

Loop timer in JavaScript

It should be:

function moveItem() {
  jQuery(".stripTransmitter ul li a").trigger('click');
}
setInterval(moveItem,2000);

setInterval(f, t) calls the the argument function, f, once every t milliseconds.

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

Tainted canvases may not be exported

I also solved this error by adding useCORS : true, in my code like -

html2canvas($("#chart-section")[0], {
        useCORS : true,
        allowTaint : true,
        scale : 0.98,
        dpi : 500,
        width: 1400, height: 900
    }).then();

index.php not loading by default

After reading all this and trying to fix it, I got a simple solution on ubuntu forum (https://help.ubuntu.com/community/ApacheMySQLPHP). The problem lies with libapache2-mod-php5 module. Thats why the browser downloads the index.php file rather than showing the web page. Do the following. If sudo a2enmod php5 returns module does not exist then the problem is with libapache2-mod-php5. Purge remove the module with command sudo apt-get --purge remove libapache2-mod-php5 Then install it again sudo apt-get install libapache2-mod-php5

Cannot create Maven Project in eclipse

It's actually easy and straight forward.

just navigate to your .m2 folder.

.m2/repository/org/apache/maven

inside this maven folder, you will see a folder called Archetypes... delete this folder and the problem is solved.

but if you don't feel like deleting the whole folder, you can navigate into the archetype folder and delete all the archetype you want there. The reason why it keeps failing is because, the archetype you are trying to create is trying to tell you that she already exists in that folder, hence move away...

summarily, deleting the archetype folder in the .m2 folder is the easiest solution.

How to copy files between two nodes using ansible

You can use deletgate with scp too:

- name: Copy file to another server
  become: true
  shell: "scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null admin@{{ inventory_hostname }}:/tmp/file.yml /tmp/file.yml"
  delegate_to: other.example.com

Because of delegate the command is run on the other server and it scp's the file to itself.

How to export data from Spark SQL to CSV

You can use below statement to write the contents of dataframe in CSV format df.write.csv("/data/home/csv")

If you need to write the whole dataframe into a single CSV file, then use df.coalesce(1).write.csv("/data/home/sample.csv")

For spark 1.x, you can use spark-csv to write the results into CSV files

Below scala snippet would help

import org.apache.spark.sql.hive.HiveContext
// sc - existing spark context
val sqlContext = new HiveContext(sc)
val df = sqlContext.sql("SELECT * FROM testtable")
df.write.format("com.databricks.spark.csv").save("/data/home/csv")

To write the contents into a single file

import org.apache.spark.sql.hive.HiveContext
// sc - existing spark context
val sqlContext = new HiveContext(sc)
val df = sqlContext.sql("SELECT * FROM testtable")
df.coalesce(1).write.format("com.databricks.spark.csv").save("/data/home/sample.csv")

how to use XPath with XDocument?

you can use the example from Microsoft - for you without namespace:

using System.Xml.Linq;
using System.Xml.XPath;
var e = xdoc.XPathSelectElement("./Report/ReportInfo/Name");     

should do it

How/When does Execute Shell mark a build as failure in Jenkins?

So by adding the #!/bin/sh will allow you to execute with no option.

It also helped me in fixing an issue where I was executing bash script from Jenkins master on my Linux slave. By just adding #!/bin/bash above my actual script in "Execute Shell" block it fixed my issue as otherwise it was executing windows git provided version of bash shell that was giving an error.

Getting user input

Use the following simple way to interactively get user data by a prompt as Arguments on what you want.

Version : Python 3.X

name = input('Enter Your Name: ')
print('Hello ', name)

How to include external Python code to use in other files?

You will need to import the other file as a module like this:

import Math

If you don't want to prefix your Calculate function with the module name then do this:

from Math import Calculate

If you want to import all members of a module then do this:

from Math import *

Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.

Print: Entry, ":CFBundleIdentifier", Does Not Exist

I also came across this issue as well and I found a way to fix it

Here is what i did:

1) Make sure there is no white spaces in the file directory.

2) cd project directory

3) run command react-native upgrade

4) Go to native ios folder and open xcode project.

5) Go to File > Project Settings > Advanced...

6) select custom > Relative to workspace

7) products path should be 'build/Build/Products'

8) intermediates path should be 'build/Build/Intermediates'

9) now try running command in your terminal react-native run-ios

I hope that this solutions will help some of us facing this issue.

T-SQL Cast versus Convert

CAST uses ANSI standard. In case of portability, this will work on other platforms. CONVERT is specific to sql server. But is very strong function. You can specify different styles for dates

How to install mechanize for Python 2.7?

using pip:

pip install mechanize

or download the mechanize distribution archive, open it, and run:

python setup.py install

What's "this" in JavaScript onclick?

keyword this in addEventListener event

_x000D_
_x000D_
function getValue(o) {_x000D_
  alert(o.innerHTML);_x000D_
}_x000D_
_x000D_
function hide(current) {_x000D_
  current.setAttribute("style", "display: none");_x000D_
}_x000D_
_x000D_
var bullet = document.querySelectorAll(".bullet");_x000D_
_x000D_
for (var x in bullet) { _x000D_
  bullet[x].onclick = function() {_x000D_
    hide(this);_x000D_
  };_x000D_
};_x000D_
 _x000D_
/* Using dynamic DOM Event */_x000D_
document.querySelector("#li").addEventListener("click", function() {_x000D_
  getValue(this); /* this = document.querySelector("#li") Object */_x000D_
});
_x000D_
li {_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<ul>_x000D_
  <li onclick="getValue(this);">A</li>_x000D_
  <li id="li" >B</li>_x000D_
  <hr />_x000D_
  <li class="bullet" >1</li>_x000D_
  <li class="bullet" >2</li>_x000D_
  <li class="bullet" >3</li>_x000D_
  <li class="bullet" >4</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

jwt check if token expired

This is for react-native, but login will work for all types.

isTokenExpired = async () => {
    try {
        const LoginTokenValue = await AsyncStorage.getItem('LoginTokenValue');
        if (JSON.parse(LoginTokenValue).RememberMe) {
            const { exp } = JwtDecode(LoginTokenValue);
            if (exp < (new Date().getTime() + 1) / 1000) {
                this.handleSetTimeout();
                return false;
            } else {
                //Navigate inside the application
                return true;
            }
        } else {
            //Navigate to the login page
        }
    } catch (err) {
        console.log('Spalsh -> isTokenExpired -> err', err);
        //Navigate to the login page
        return false;
    }
}

How to set tbody height with overflow scroll

Making scrolling tables is always a challenge. This is a solution where the table is scrolled both horizontally and vertically with fixed height on tbody making theader and tbody "stick" (without display: sticky). I've added a "big" table just to show. I got inspiration from G-Cyrillus to make the tbody display:block; But when it comes to width of a cell (both in header and body), it's depending on the inside content. Therefore I added content with specific width inside each cell, both in thead and minimum first row in tbody (the other rows adapt accordingly)

_x000D_
_x000D_
.go-wrapper {_x000D_
    overflow-x: auto;_x000D_
    width: 100%;_x000D_
}_x000D_
.go-wrapper table {_x000D_
    width: auto;_x000D_
}_x000D_
.go-wrapper table tbody {_x000D_
    display: block;_x000D_
    height: 220px;_x000D_
    overflow: auto;_x000D_
}_x000D_
.go-wrapper table thead {_x000D_
    display: table;_x000D_
}_x000D_
.go-wrapper table tfoot {_x000D_
    display: table;_x000D_
}_x000D_
.go-wrapper table thead tr, _x000D_
.go-wrapper table tbody tr,_x000D_
.go-wrapper table tfoot tr {_x000D_
    display: table-row;_x000D_
}_x000D_
_x000D_
.go-wrapper table th,_x000D_
.go-wrapper table td { _x000D_
    white-space: nowrap; _x000D_
}_x000D_
_x000D_
.go-wrapper .aw-50  { min-height: 1px; width: 50px; }_x000D_
.go-wrapper .aw-100 { min-height: 1px; width: 100px; }_x000D_
.go-wrapper .aw-200 { min-height: 1px; width: 200px; }_x000D_
.go-wrapper .aw-400 { min-height: 1px; width: 400px; }_x000D_
_x000D_
/***** Colors *****/_x000D_
.go-wrapper table {_x000D_
    border: 2px solid red_x000D_
}_x000D_
.go-wrapper table thead, _x000D_
.go-wrapper table tbody, _x000D_
.go-wrapper table tfoot {_x000D_
    outline: 1px solid green_x000D_
}_x000D_
.go-wrapper td {_x000D_
    outline: 1px solid blue_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">_x000D_
    <title>Template</title>_x000D_
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
    <link rel="stylesheet" href="css/main.css">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <div class="container">_x000D_
        <div class="row mt-5 justify-content-md-center">_x000D_
            <div class="col-8">_x000D_
                <div class="go-wrapper">_x000D_
                    <table class="table">_x000D_
                        <thead>_x000D_
                            <tr>_x000D_
                                <th><div class="aw-50" ><div class="checker"><span><input type="checkbox" class="styled"></span></div></div></th>_x000D_
                                <th><div class="aw-200">Name</div></th>_x000D_
                                <th><div class="aw-50" >Week</div></th>_x000D_
                                <th><div class="aw-100">Date</div></th>_x000D_
                                <th><div class="aw-100">Time</div></th>_x000D_
                                <th><div class="aw-200">Project</div></th>_x000D_
                                <th><div class="aw-400">Text</div></th>_x000D_
                                <th><div class="aw-200">Activity</div></th>_x000D_
                                <th><div class="aw-50" >Hours</th>_x000D_
                                <th><div class="aw-50" >Pause</div></th>_x000D_
                                <th><div class="aw-100">Status</div></th>_x000D_
                            </tr>_x000D_
                        </thead>_x000D_
                        <tbody>_x000D_
                            <tr>_x000D_
                                <td><div class="aw-50"><div class="checker"><span><input type="checkbox" class="styled"></span></div></div></td>_x000D_
                                <td><div class="aw-200">AAAAA</div></td>_x000D_
                                <td><div class="aw-50" >15</div></td>_x000D_
                                <td><div class="aw-100">07.04.2020</div></td>_x000D_
                                <td><div class="aw-100">10:00</div></td>_x000D_
                                <td><div class="aw-200">Project 1</div></td>_x000D_
                                <td><div class="aw-400">Blah blah blah</div></td>_x000D_
                                <td><div class="aw-200">Activity</div></td>_x000D_
                                <td><div class="aw-50" >2t</div></td>_x000D_
                                <td><div class="aw-50" >30min</div></td>_x000D_
                                <td><div class="aw-100">Waiting</div></td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>BBBBB</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>CCCCC</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah Blah blah blah</td>_x000D_
                                <td>Activity Activity Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>DDDDD</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>EEEEE</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>FFFFF</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity Activity Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>GGGGG</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>HHHHH</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>IIIII</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>JJJJJ</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>KKKKK</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>LLLLL</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>MMMMM</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>NNNNN</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>OOOOO</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>PPPPP</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>QQQQQ</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>RRRRR</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>SSSSS</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>TTTTT</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>UUUUU</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>VVVVV</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>XXXXX</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>YYYYY</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>ZZZZZ</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>ÆÆÆÆÆ</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>ØØØØØ</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td><div class="checker"><span><input type="checkbox" class="styled"></span></div></td>_x000D_
                                <td>ÅÅÅÅÅ</td>_x000D_
                                <td>15</td>_x000D_
                                <td>07.04.2020</td>_x000D_
                                <td>10:00</td>_x000D_
                                <td>Project 1</td>_x000D_
                                <td>Blah blah blah</td>_x000D_
                                <td>Activity</td>_x000D_
                                <td>2t</td>_x000D_
                                <td>30min</td>_x000D_
                                <td>Waiting</td>_x000D_
                            </tr>_x000D_
                        </tbody>_x000D_
                        <tfoot>_x000D_
                            <tr>_x000D_
                                <th><div class="aw-50" ><div class="checker"><span><input type="checkbox" class="styled"></span></div></div></th>_x000D_
                                <th><div class="aw-200">Name</div></th>_x000D_
                                <th><div class="aw-50" >Week</div></th>_x000D_
                                <th><div class="aw-100">Date</div></th>_x000D_
                                <th><div class="aw-100">Time</div></th>_x000D_
                                <th><div class="aw-200">Project</div></th>_x000D_
                                <th><div class="aw-400">Text</div></th>_x000D_
                                <th><div class="aw-200">Activity</div></th>_x000D_
                                <th><div class="aw-50" >Hours</th>_x000D_
                                <th><div class="aw-50" >Pause</div></th>_x000D_
                                <th><div class="aw-100">Status</div></th>_x000D_
                            </tr>_x000D_
                        </tfoot>_x000D_
                    </table>_x000D_
                </div>_x000D_
            </div>_
                  

How can I go back/route-back on vue-router?

You can use Programmatic Navigation.In order to go back, you use this:

router.go(n) 

Where n can be positive or negative (to go back). This is the same as history.back().So you can have your element like this:

<a @click="$router.go(-1)">back</a>

HTML text input allow only numeric input

Here is a very short solution that doesn't use the deprecated keyCode or which, doesn't block any non input keys, and uses pure javascript. (Tested in Chromium 70.0.3533, Firefox 62.0, and Edge 42.17134.1.0)

HTML:

<input type="text" onkeypress="validate(event)">

JS:

function validate(ev) {
    if (!ev) {
        ev = window.event;
    }

    if (!ev.ctrlKey && ev.key.length === 1 && (isNaN(+ev.key) || ev.key === " ")) {
        return ev.preventDefault();
    }
}

How to Specify "Vary: Accept-Encoding" header in .htaccess

I'm afraid Aularon didn't provide enough steps to complete the process. With a little trial and error, I was able to successfully enable Gzipping on my dedicated WHM server.

Below are the steps:

  • Run EasyApache within WHM, select Deflate within the Exhaustive Options list, and rebuild the server.

  • Once done, goto Services Configuration >> Apache Configuration >> Include Editor >> Post VirtualHost Include, select All Versions, and then paste the mod_headers.c and mod_headers.c code (listed above in Aularon's post) on top of on another within the input field.

  • Once saved, I was seeing a 75.36% data savings on average! You can run a before and after test by using this HTTP Compression tool to see your own results: http://www.whatsmyip.org/http_compression/

Hope this works for you all!

  • Matt

C++ deprecated conversion from string constant to 'char*'

I also got the same problem. And what I simple did is just adding const char* instead of char*. And the problem solved. As others have mentioned above it is a compatible error. C treats strings as char arrays while C++ treat them as const char arrays.

Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");

*----------------Sorry I oversight, for static function already answered the question by adrift*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Update

I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

How to jump back to NERDTree from file in tab?

ctrl-ww Could be useful when you have limited tabs open. But could get annoying when you have too many tabs open.

I type in :NERDTree again to get the focus back on NERDTree tab instantly wherever my cursor's focus is. Hope that helps

What is the largest Safe UDP Packet Size on the Internet

576 is the minimum maximum reassembly buffer size, i.e. each implementation must be able to reassemble packets of at least that size. See IETF RFC 1122 for details.

How to get address location from latitude and longitude in Google Map.?

You have to make one ajax call to get the required result, in this case you can use Google API to get the same

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false

Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level

How can I get the length of text entered in a textbox using jQuery?

You need to only grab the element with an appropriate jQuery selector and then the .val() method to get the string contained in the input textbox and then call the .length on that string.

$('input:text').val().length

However, be warned that if the selector matches multiple inputs, .val() will only return the value of the first textbox. You can also change the selector to get a more specific element but keep the :text to ensure it's an input textbox.

On another note, to get the length of a string contained in another, non-input element, you can use the .text() function to get the string and then use .length on that string to find its length.

C# : Out of Memory exception

3 years old topic, but I found another working solution. If you're sure you have enough free memory, running 64 bit OS and still getting exceptions, go to Project properties -> Build tab and be sure to set x64 as a Platform target.

enter image description here

How to find the mime type of a file in python?

I 've tried a lot of examples but with Django mutagen plays nicely.

Example checking if files is mp3

from mutagen.mp3 import MP3, HeaderNotFoundError  

try:
    audio = MP3(file)
except HeaderNotFoundError:
    raise ValidationError('This file should be mp3')

The downside is that your ability to check file types is limited, but it's a great way if you want not only check for file type but also to access additional information.

Node Express sending image files as API response

There is an api in Express.

res.sendFile

app.get('/report/:chart_id/:user_id', function (req, res) {
    // res.sendFile(filepath);
});

http://expressjs.com/en/api.html#res.sendFile

How to locate the Path of the current project directory in Java (IDE)?

This is the new way to do it:

Path root = FileSystems.getDefault().getPath("").toAbsolutePath();
Path filePath = Paths.get(root.toString(),"src", "main", "resources", fileName);

Or even better:

Path root = Paths.get(".").normalize().toAbsolutePath();

But I would take it one step further:

public String getUsersProjectRootDirectory() {
    String envRootDir = System.getProperty("user.dir");
    Path rootDIr = Paths.get(".").normalize().toAbsolutePath();
    if ( rootDir.startsWith(envRootDir) ) {
        return rootDir;
    } else {
        throw new RuntimeException("Root dir not found in user directory.");
    }
}

How do I find the index of a character within a string in C?

Just subtract the string address from what strchr returns:

char *string = "qwerty";
char *e;
int index;

e = strchr(string, 'e');
index = (int)(e - string);

Note that the result is zero based, so in above example it will be 2.

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

How to distinguish mouse "click" and "drag"

Pure JS with DeltaX and DeltaY

This DeltaX and DeltaY as suggested by a comment in the accepted answer to avoid the frustrating experience when trying to click and get a drag operation instead due to a one tick mousemove.

    deltaX = deltaY = 2;//px
    var element = document.getElementById('divID');
    element.addEventListener("mousedown", function(e){
        if (typeof InitPageX == 'undefined' && typeof InitPageY == 'undefined') {
            InitPageX = e.pageX;
            InitPageY = e.pageY;
        }

    }, false);
    element.addEventListener("mousemove", function(e){
        if (typeof InitPageX !== 'undefined' && typeof InitPageY !== 'undefined') {
            diffX = e.pageX - InitPageX;
            diffY = e.pageY - InitPageY;
            if (    (diffX > deltaX) || (diffX < -deltaX)
                    || 
                    (diffY > deltaY) || (diffY < -deltaY)   
                    ) {
                console.log("dragging");//dragging event or function goes here.
            }
            else {
                console.log("click");//click event or moving back in delta goes here.
            }
        }
    }, false);
    element.addEventListener("mouseup", function(){
        delete InitPageX;
        delete InitPageY;
    }, false);

   element.addEventListener("click", function(){
        console.log("click");
    }, false);

Defining custom attrs

The answer above covers everything in great detail, apart from a couple of things.

First, if there are no styles, then the (Context context, AttributeSet attrs) method signature will be used to instantiate the preference. In this case just use context.obtainStyledAttributes(attrs, R.styleable.MyCustomView) to get the TypedArray.

Secondly it does not cover how to deal with plaurals resources (quantity strings). These cannot be dealt with using TypedArray. Here is a code snippet from my SeekBarPreference that sets the summary of the preference formatting its value according to the value of the preference. If the xml for the preference sets android:summary to a text string or a string resouce the value of the preference is formatted into the string (it should have %d in it, to pick up the value). If android:summary is set to a plaurals resource, then that is used to format the result.

// Use your own name space if not using an android resource.
final static private String ANDROID_NS = 
    "http://schemas.android.com/apk/res/android";
private int pluralResource;
private Resources resources;
private String summary;

public SeekBarPreference(Context context, AttributeSet attrs) {
    // ...
    TypedArray attributes = context.obtainStyledAttributes(
        attrs, R.styleable.SeekBarPreference);
    pluralResource =  attrs.getAttributeResourceValue(ANDROID_NS, "summary", 0);
    if (pluralResource !=  0) {
        if (! resources.getResourceTypeName(pluralResource).equals("plurals")) {
            pluralResource = 0;
        }
    }
    if (pluralResource ==  0) {
        summary = attributes.getString(
            R.styleable.SeekBarPreference_android_summary);
    }
    attributes.recycle();
}

@Override
public CharSequence getSummary() {
    int value = getPersistedInt(defaultValue);
    if (pluralResource != 0) {
        return resources.getQuantityString(pluralResource, value, value);
    }
    return (summary == null) ? null : String.format(summary, value);
}

  • This is just given as an example, however, if you want are tempted to set the summary on the preference screen, then you need to call notifyChanged() in the preference's onDialogClosed method.

Why would $_FILES be empty when uploading files to PHP?

Here's a check-list for file uploading in PHP:

  1. Check php.ini for:
    file_uploads = On
    post_max_size = 100M
    upload_max_filesize = 100M

    • You might need to use .htaccess or .user.ini if you are on shared hosting and don't have access to php.ini.
    • Make sure you’re editing the correct ini file – use the phpinfo() function to verify your settings are actually being applied.
    • Also make sure you don’t misspell the sizes - it should be 100M not 100MB.
  2. Make sure your <form> tag has the enctype="multipart/form-data" attribute. No other tag will work, it has to be your FORM tag. Double check that it is spelled correctly. Double check that multipart/form-data is surrounded by STRAIGHT QUOTES, not smart quotes pasted in from Word OR from a website blog (WordPress converts straight quotes to angle quotes!). If you have multiple forms on the page, make sure they both have this attribute. Type them in manually, or try straight single quotes typed in manually.

  3. Make sure you do not have two input file fields with the same name attribute. If you need to support multiple, put square brackets at the end of the name:

    <input type="file" name="files[]">
    <input type="file" name="files[]">
    
  4. Make sure your tmp and upload directories have the correct read+write permissions set. The temporary upload folder is specified in PHP settings as upload_tmp_dir.

  5. Make sure your file destination and tmp/upload directories do not have spaces in them.

  6. Make sure all <form>'s on your page have </form> close tags.

  7. Make sure your FORM tag has method="POST". GET requests do not support multipart/form-data uploads.

  8. Make sure your file input tag has a NAME attribute. An ID attribute is NOT sufficient! ID attributes are for use in the DOM, not for POST payloads.

  9. Make sure you are not using Javascript to disable your <input type="file"> field on submission

  10. Make sure you're not nesting forms like <form><form></form></form>

  11. Check your HTML structure for invalid/overlapping tags like <div><form></div></form>

  12. Also make sure that the file you are uploading does not have any non-alphanumeric characters in it.

  13. Once, I just spent hours trying to figure out why this was happening to me all of a sudden. It turned out that I had modified some of the PHP settings in .htaccess, and one of them (not sure which yet) was causing the upload to fail and $_FILES to be empty.

  14. You could potentially try avoiding underscores (_) in the name="" attribute of the <input> tag

  15. Try uploading very small files to narrow down whether it's a file-size issue.

  16. Check your available disk space. Although very rare, it is mentioned in this PHP Manual page comment:

    If the $_FILES array suddenly goes mysteriously empty, even though your form seems correct, you should check the disk space available for your temporary folder partition. In my installation, all file uploads failed without warning. After much gnashing of teeth, I tried freeing up additional space, after which file uploads suddenly worked again.

  17. Be sure that you're not submitting the form through an AJAX POST request instead of a normal POST request that causes a page to reload. I went through each and every point in the list above, and finally found out that the reason due to which my $_FILES variable was empty was that I was submitting the form using an AJAX POST request. I know that there are methods to upload files using ajax too, but this could be a valid reason why your $_FILES array is empty.

Source for some of these points:
http://getluky.net/2004/10/04/apachephp-_files-array-mysteriously-empty/

Eclipse "Invalid Project Description" when creating new project from existing source

Go to the .project file of your project make sure it display the same name as displayed in project folder. if not change the name. it will work.

jQuery select change show/hide div event

Try this:

 $(function () {
     $('#row_dim').hide(); // this line you can avoid by adding #row_dim{display:none;} in your CSS
     $('#type').change(function () {
         $('#row_dim').hide();
         if (this.options[this.selectedIndex].value == 'parcel') {
             $('#row_dim').show();
         }
     });
 });

Demo here

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

As mentioned previously, this is a problem with multidex: you should add implementation to your build.gradle and MainApplication.java. But what you add really depends on whether you support AndroidX or not. Here is what you need to solve this problem:

  1. If you support AndroidX

Put these lines of code into your build.gradle (android/app/build.gradle):

defaultConfig {
  applicationId "com.your.application"
  versionCode 1
  versionName "1.0"
  ...
  multiDexEnabled true // <-- THIS LINE
}
...
...
dependencies {
  ...
  implementation "androidx.multidex:multidex:2.0.1" // <-- THIS LINE
  ...
}

Put these lines into your MainApplication.java (android/app/src/main/java/.../MainApplication.java):

package com.your.package;

import androidx.multidex.MultiDexApplication; // <-- THIS LINE
...
...
public class MainApplication extends MultiDexApplication { ... } // <-- THIS LINE
  1. If you don't support AndroidX

Put these lines of code into your build.gradle (android/app/build.gradle):

defaultConfig {
  applicationId "com.your.application"
  versionCode 1
  versionName "1.0"
  ...
  multiDexEnabled true // <-- THIS LINE
}
...
...
dependencies {
  ...
  implementation "com.android.support:multidex:1.0.3" // <-- THIS LINE
  ...
}

Put these lines into your MainApplication.java (android/app/src/main/java/.../MainApplication.java):

package com.your.package;

import android.support.multidex.MultiDex;; // <-- THIS LINE
...
...
public class MainApplication extends MultiDexApplication { ... } // <-- THIS LINE

Convert timestamp to date in MySQL query

If you are getting the query in your output you need to show us the code that actually echos the result. Can you post the code that calls requeteSQL?

For example, if you have used single quotes in php, it will print the variable name, not the value

echo 'foo is $foo'; // foo is $foo

This sounds exactly like your problem and I am positive this is the cause.

Also, try removing the @ symbol to see if that helps by giving you more infromation.

so that

$SQL_result = @mysql_query($SQL_requete); // run the query

becomes

  $SQL_result = mysql_query($SQL_requete); // run the query

This will stop any error suppression if the query is throwing an error.

CSS Printing: Avoiding cut-in-half DIVs between pages?

I got this problem while using Bootstrap and I had multiple columns in each rows.

I was trying to give page-break-inside: avoid; or break-inside: avoid; to the col-md-6 div elements. That was not working.

I took a hint from the answers given above by DOK that floating elements do not work well with page-break-inside: avoid;.

Instead, I had to give page-break-inside: avoid; or break-inside: avoid; to the <div class="row"> element. And I had multiple rows in my print page.

That is, each row only had 2 columns in it. And they always fit horizontally and do not wrap on a new line.

In another example case, if you want 4 columns in each row, then use col-md-3.

What does PermGen actually stand for?

Permanent Generation. Details are of course implementation specific.

Briefly, it contains the Java objects associated with classes and interned strings. In Sun's client implementation with sharing on, classes.jsa is memory mapped to form the initial data, with about half read-only and half copy-on-write.

Java objects that are merely old are kept in the Tenured Generation.

Custom Card Shape Flutter SDK

You can use it this way

enter image description here

Card(
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(15.0),
  ),
  child: Text(
    'Card with circular border',
    textScaleFactor: 1.2,
  ),
),
Card(
  shape: BeveledRectangleBorder(
    borderRadius: BorderRadius.circular(10.0),
  ),
  child: Text(
    'Card with Beveled border',
    textScaleFactor: 1.2,
  ),
),
Card(
  shape: StadiumBorder(
  side: BorderSide(
    color: Colors.black,
    width: 2.0,
  ),
),
  child: Text(
    'Card with Beveled border',
    textScaleFactor: 1.2,
  ),
),

How to make sure docker's time syncs with that of the host?

Although this is not a general solution for every host, someone may find it useful. If you know where you are based (UK for me) then look at tianon's answer here.

FROM alpine:3.6
RUN apk add --no-cache tzdata
ENV TZ Europe/London

This is what I added to my Dockerfile ^ and the timezone problem was fixed.

Check if a time is between two times (time DataType)

select *
from MyTable
where CAST(Created as time) not between '07:00' and '22:59:59 997'

Flutter- wrapping text

The Flexible does the trick

new Container(
       child: Row(
         children: <Widget>[
            Flexible(
               child: new Text("A looooooooooooooooooong text"))
                ],
        ));

This is the official doc https://flutter.dev/docs/development/ui/layout#lay-out-multiple-widgets-vertically-and-horizontally on how to arrange widgets.

Remember that Flexible and also Expanded, should only be used within a Column, Row or Flex, because of the Incorrect use of ParentDataWidget.

The solution is not the mere Flexible

How can I read numeric strings in Excel cells as string (not numbers)?

The below code worked for me for any type of cell.

InputStream inp =getClass().getResourceAsStream("filename.xls"));
Workbook wb = WorkbookFactory.create(inp);
DataFormatter objDefaultFormat = new DataFormatter();
FormulaEvaluator objFormulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) wb);

Sheet sheet= wb.getSheetAt(0);
Iterator<Row> objIterator = sheet.rowIterator();

while(objIterator.hasNext()){

    Row row = objIterator.next();
    Cell cellValue = row.getCell(0);
    objFormulaEvaluator.evaluate(cellValue); // This will evaluate the cell, And any type of cell will return string value
    String cellValueStr = objDefaultFormat.formatCellValue(cellValue,objFormulaEvaluator);

}

SELECT CONVERT(VARCHAR(10), GETDATE(), 110) what is the meaning of 110 here?

When you convert expressions from one type to another, in many cases there will be a need within a stored procedure or other routine to convert data from a datetime type to a varchar type. The Convert function is used for such things. The CONVERT() function can be used to display date/time data in various formats.

Syntax

CONVERT(data_type(length), expression, style)

Style - style values for datetime or smalldatetime conversion to character data. Add 100 to a style value to get a four-place year that includes the century (yyyy).

Example 1

take a style value 108 which defines the following format:

hh:mm:ss

Now use the above style in the following query:

select convert(varchar(20),GETDATE(),108) 

Example 2

we use the style value 107 which defines the following format:

Mon dd, yy

Now use that style in the following query:

select convert(varchar(20),GETDATE(),107) 

Similarly

style-106 for Day,Month,Year (26 Sep 2013)
style-6 for Day, Month, Year (26 Sep 13)
style-113 for Day,Month,Year, Timestamp (26 Sep 2013 14:11:53:300)

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Time part of a DateTime Field in SQL

you can use CONVERT(TIME,GETDATE()) in this case:

INSERT INTO infoTbl
(itDate, itTime)
VALUES (GETDATE(),CONVERT(TIME,GETDATE()))

or if you want print it or return that time use like this:

DECLARE @dt TIME
SET @dt = CONVERT(TIME,GETDATE())
PRINT @dt

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }
}

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

Small addition to the help above: I got the mismatch error after adding a static libto an older VST solution using VST 2017 . VST now generates "stdfax.h" for precompiled headers containing these 2 lines:

// Turn off iterator debugging as it makes the compiler very slow on large methods in debug builds
#define _HAS_ITERATOR_DEBUGGING 0

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

You can just put this all on one line:

LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/path/to/library" ./sync_test

Should make things a little easier, even if it doesn't change anything fundamental

Get custom product attributes in Woocommerce

Try this to get an array of attribute name => attribute value(s):

global $product;

$formatted_attributes = array();

$attributes = $product->get_attributes();

foreach($attributes as $attr=>$attr_deets){

    $attribute_label = wc_attribute_label($attr);

    if ( isset( $attributes[ $attr ] ) || isset( $attributes[ 'pa_' . $attr ] ) ) {

        $attribute = isset( $attributes[ $attr ] ) ? $attributes[ $attr ] : $attributes[ 'pa_' . $attr ];

        if ( $attribute['is_taxonomy'] ) {

            $formatted_attributes[$attribute_label] = implode( ', ', wc_get_product_terms( $product->id, $attribute['name'], array( 'fields' => 'names' ) ) );

        } else {

            $formatted_attributes[$attribute_label] = $attribute['value'];
        }

    }
}

//print_r($formatted_attributes);

return $formatted_attributes;

It's little inefficient but does the trick.

How do I position one image on top of another in HTML?

You can absolutely position pseudo elements relative to their parent element.

This gives you two extra layers to play with for every element - so positioning one image on top of another becomes easy - with minimal and semantic markup (no empty divs etc).

markup:

<div class="overlap"></div>

css:

.overlap
{
    width: 100px;
    height: 100px;
    position: relative;
    background-color: blue;
}
.overlap:after
{
    content: '';
    position: absolute;
    width: 20px;
    height: 20px;
    top: 5px;
    left: 5px;
    background-color: red;
}

Here's a LIVE DEMO

Python slice first and last element in list

first, last = some_list[0], some_list[-1]

Is there an equivalent of lsusb for OS X

I got tired of forgetting the system_profiler SPUSBDataType syntax, so I made an lsusb alternative. You can find it here , or install it with homebrew:

brew install lsusb

How to get the current TimeStamp?

I think you are looking for this function:

http://doc.qt.io/qt-5/qdatetime.html#toTime_t

uint QDateTime::toTime_t () const

Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, > Coordinated Universal Time (Qt::UTC).

On systems that do not support time zones, this function will behave as if local time were Qt::UTC.

See also setTime_t().

Python Hexadecimal

Another solution is:

>>> "".join(list(hex(255))[2:])
'ff'

Probably an archaic answer, but functional.

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

I found the solution below on https://developercommunity.visualstudio.com/content/problem/260196/add-a-reference-raise-error-error-hresult-e-fail-h.html address.

It worked for me in VS 2019:

1 Open "Developer Command Prompt for VS 2017" as Admin

2 CD into "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\PublicAssemblies"

3 Run "gacutil -i Microsoft.VisualStudio.Shell.Interop.11.0.dll"

After a restart, it all worked well.

'Property does not exist on type 'never'

This seems to be similar to this issue: False "Property does not exist on type 'never'" when changing value inside callback with strictNullChecks, which is closed as a duplicate of this issue (discussion): Trade-offs in Control Flow Analysis.

That discussion is pretty long, if you can't find a good solution there you can try this:

if (instance == null) {
    console.log('Instance is null or undefined');
} else {
    console.log(instance!.name); // ok now
}

Why do we use volatile keyword?

In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia

http://en.wikipedia.org/wiki/Volatile_variable

Checking to see if one array's elements are in another array in PHP

You could also use in_array as follows:

<?php
$found = null;
$people = array(3,20,2);
$criminals = array( 2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
foreach($people as $num) {
    if (in_array($num,$criminals)) {
        $found[$num] = true;
    } 
}
var_dump($found);
// array(2) { [20]=> bool(true)   [2]=> bool(true) }

While array_intersect is certainly more convenient to use, it turns out that its not really superior in terms of performance. I created this script too:

<?php
$found = null;
$people = array(3,20,2);
$criminals = array( 2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
$fastfind = array_intersect($people,$criminals);
var_dump($fastfind);
// array(2) { [1]=> int(20)   [2]=> int(2) }

Then, I ran both snippets respectively at: http://3v4l.org/WGhO7/perf#tabs and http://3v4l.org/g1Hnu/perf#tabs and checked the performance of each. The interesting thing is that the total CPU time, i.e. user time + system time is the same for PHP5.6 and the memory also is the same. The total CPU time under PHP5.4 is less for in_array than array_intersect, albeit marginally so.

What's is the difference between include and extend in use case diagram?

The include relationship allows one use case to include the steps of another use case.

For example, suppose you have an Amazon Account and you want to check on an order, well it is impossible to check on the order without first logging into your account. So the flow of events would like so...

enter image description here

The extend relationship is used to add an extra step to the flow of a use case, that is usually an optional step...

enter image description here

Imagine that we are still talking about your amazon account. Lets assume the base case is Order and the extension use case is Amazon Prime. The user can choose to just order the item regularly, or, the user has the option to select Amazon Prime which ensure his order will arrive faster at higher cost.

However, note that the user does not have to select Amazon Prime, this is just an option, they can choose to ignore this use case.

Do you know the Maven profile for mvnrepository.com?

Place this in the ~/.m2/settings.xml or custom file to be run with $ mvn -s custom-settings.xml install

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>${user.home}/.m2/repository</localRepository>
<interactiveMode/>
<offline/>
<pluginGroups/>
<profiles>
    <profile>
        <repositories>
            <repository>
                <id>mvnrepository</id>
                <name>mvnrepository</name>
                <url>http://www.mvnrepository.com</url>
            </repository>
        </repositories>
    </profile>
</profiles>
<activeProfiles>
    <activeProfile>mvnrepository</activeProfile>
</activeProfiles>
</settings>

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Vertical align middle with Bootstrap responsive grid

Add !important rule to display: table of your .v-center class.

.v-center {
    display:table !important;
    border:2px solid gray;
    height:300px;
}

Your display property is being overridden by bootstrap to display: block.

Example

Scroll to the top of the page using JavaScript?

$(document).scrollTop(0); also works.

Convert string to decimal, keeping fractions

The value is the same even though the printed representation is not what you expect:

decimal d = (decimal )1200.00;
Console.WriteLine(Decimal.Parse("1200") == d); //True

Position: absolute and parent height?

If I understand what you're trying to do correctly, then I don't think this is possible with CSS while keeping the children absolutely positioned.

Absolutely positioned elements are completely removed from the document flow, and thus their dimensions cannot alter the dimensions of their parents.

If you really had to achieve this affect while keeping the children as position: absolute, you could do so with JavaScript by finding the height of the absolutely positioned children after they have rendered, and using that to set the height of the parent.

Alternatively, just use float: left/float:right and margins to get the same positioning effect while keeping the children in the document flow, you can then use overflow: hidden on the parent (or any other clearfix technique) to cause its height to expand to that of its children.

article {
    position: relative;
    overflow: hidden;
}

.one {
    position: relative;
    float: left;
    margin-top: 10px;
    margin-left: 10px;
    background: red;
    width: 30px;
    height: 30px;
}

.two {
    position: relative;
    float: right;
    margin-top: 10px;
    margin-right: 10px;
    background: blue;
    width: 30px;
    height: 30px;
}

How do I escape a reserved word in Oracle?

Oracle does use double-quotes, but you most likely need to place the object name in upper case, e.g. "TABLE". By default, if you create an object without double quotes, e.g.

CREATE TABLE table AS ...

Oracle would create the object as upper case. However, the referencing is not case sensitive unless you use double-quotes!

How can I set the background color of <option> in a <select> element?

I assume you mean the <select> input element?

Support for that is pretty new, but FF 3.6, Chrome and IE 8 render this all right:

_x000D_
_x000D_
<select name="select">
  <option value="1" style="background-color: blue">Test</option>
  <option value="2" style="background-color: green">Test</option>
</select>
_x000D_
_x000D_
_x000D_

How do I modify a MySQL column to allow NULL?

Use: ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);

ReactJS - Add custom event listener to component

I recommend using React.createRef() and ref=this.elementRef to get the DOM element reference instead of ReactDOM.findDOMNode(this). This way you can get the reference to the DOM element as an instance variable.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);

    this.elementRef = React.createRef();
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }
    
  componentDidMount() {
    this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
  }

  componentWillUnmount() {
    this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
  }

  render() {
    return (
      <element ref={this.elementRef} />
    )
  }

}

export default MenuItem;

Rails ActiveRecord date between

I would personally created a scope to make it more readable and re-usable:

In you Comment.rb, you can define a scope:

scope :created_between, lambda {|start_date, end_date| where("created_at >= ? AND created_at <= ?", start_date, end_date )}

Then to query created between:

@comment.created_between(1.year.ago, Time.now)

Hope it helps.

Include an SVG (hosted on GitHub) in MarkDown

Just like this worked for me on Github.

![Imgae Caption](ImageAddressOnGitHub.svg)

or

<img src="ImageAddressOnGitHub.svg">

Create local maven repository

Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.

To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source

Add a file to your repository like this:

mvn install:install-file \
  -Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID 
  -DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
  -Dpackaging=jar \
  -DlocalRepositoryPath=/var/www/html/mavenRepository

If your domain is example.com and the root directory of the web server is located at /var/www/html/, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>.

Is there a way to avoid null check before the for-each loop iteration starts?

I guess the right answer is that: there is no way to make it shorter. There are some techniques such as the ones in the comments, but I don't see myself using them. I think it's better to write a "if" block than to use those techniques. and yes.. before anybody mentions it yet again :) "ideally" the code should be desgined such that list should never be a null

How to pass arguments to a Dockerfile?

You are looking for --build-arg and the ARG instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg to the Dockerfile and then build with docker build --build-arg arg=2.3 ..

Multiple contexts with the same path error running web service in Eclipse using Tomcat

Go to server.xml and Search for "Context" tag with a property name "docBase".

Remove the duplicate lines here. Then try to restart the server.

How do you find what version of libstdc++ library is installed on your linux machine?

What exactly do you want to know?

The shared library soname? That's part of the filename, libstdc++.so.6, or shown by readelf -d /usr/lib64/libstdc++.so.6 | grep soname.

The minor revision number? You should be able to get that by simply checking what the symlink points to:

$ ls -l  /usr/lib/libstdc++.so.6
lrwxrwxrwx. 1 root root 19 Mar 23 09:43 /usr/lib/libstdc++.so.6 -> libstdc++.so.6.0.16

That tells you it's 6.0.16, which is the 16th revision of the libstdc++.so.6 version, which corresponds to the GLIBCXX_3.4.16 symbol versions.

Or do you mean the release it comes from? It's part of GCC so it's the same version as GCC, so unless you've screwed up your system by installing unmatched versions of g++ and libstdc++.so you can get that from:

$ g++ -dumpversion
4.6.3

Or, on most distros, you can just ask the package manager. On my Fedora host that's

$ rpm -q libstdc++
libstdc++-4.6.3-2.fc16.x86_64
libstdc++-4.6.3-2.fc16.i686

As other answers have said, you can map releases to library versions by checking the ABI docs

firefox proxy settings via command line

I don't think there is a direct way to set the proxy (on Windows).

You could however install an add-on like FoxyProxy, create several configurations for different proxies and prior to starting FireFox move the appropriate configuration to the correct folder in your FireFox profile (using a batch file).

How can I specify the schema to run an sql file against in the Postgresql command line

Main Example

The example below will run myfile.sql on database mydatabase using schema myschema.

psql "dbname=mydatabase options=--search_path=myschema" -a -f myfile.sql

The way this works is the first argument to the psql command is the dbname argument. The docs mention a connection string can be provided.

If this parameter contains an = sign or starts with a valid URI prefix (postgresql:// or postgres://), it is treated as a conninfo string

The dbname keyword specifies the database to connect to and the options keyword lets you specify command-line options to send to the server at connection startup. Those options are detailed in the server configuration chapter. The option we are using to select the schema is search_path.

Another Example

The example below will connect to host myhost on database mydatabase using schema myschema. The = special character must be url escaped with the escape sequence %3D.

psql postgres://myuser@myhost?options=--search_path%3Dmyschema

Disabled UIButton not faded or grey

Set title color for different states:

@IBOutlet weak var loginButton: UIButton! {
        didSet {
            loginButton.setTitleColor(UIColor.init(white: 1, alpha: 0.3), for: .disabled)
            loginButton.setTitleColor(UIColor.init(white: 1, alpha: 1), for: .normal)
        }
    }

Usage: (text color will get change automatically)

loginButton.isEnabled = false

enter image description here

PHP removing a character in a string

I think that it's better to use simply str_replace, like the manual says:

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().

<?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);

Python reshape list to ndim array

Step by step:

# import numpy library
import numpy as np
# create list
my_list = [0,0,1,1,2,2,3,3]
# convert list to numpy array
np_array=np.asarray(my_list)
# reshape array into 4 rows x 2 columns, and transpose the result
reshaped_array = np_array.reshape(4, 2).T 

#check the result
reshaped_array
array([[0, 1, 2, 3],
       [0, 1, 2, 3]])

How to return JSON data from spring Controller using @ResponseBody

When I was facing this issue, I simply put just getter setter methods and my issues were resolved.

I am using Spring boot version 2.0.

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

Update Item to Revision vs Revert to Revision

Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent. This is used to test a specific rev purpose, if your test has done, you can use this command to test another rev or use SVN Update to get HEAD

If you want to undo an earlier change permanently, use Revert to this revision instead.

-- from TSVN help doc

If you Update your working copy to an earlier rev, this is only affect your own working copy, after you do some change, and want to commit, you will fail,TSVN will alert you to update your WC to latest revision first If you Revert to a rev, you can commit to repository.everyone will back to the rev after they do an update.

jQuery fade out then fade in

This might help: http://jsfiddle.net/danielredwood/gBw9j/
Basically $(this).fadeOut().next().fadeIn(); is what you require

Make file echo displaying "$PATH" string

The make uses the $ for its own variable expansions. E.g. single character variable $A or variable with a long name - ${VAR} and $(VAR).

To put the $ into a command, use the $$, for example:

all:
  @echo "Please execute next commands:"
  @echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'

Also note that to make the "" and '' (double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @ sign to see what make sends to shell.) To prevent the shell from expanding $PATH, second line uses the ''.

How do I purge a linux mail box with huge number of emails?

Just use:

mail
d 1-15
quit

Which will delete all messages between number 1 and 15. to delete all, use the d *.

I just used this myself on ubuntu 12.04.4, and it worked like a charm.

For example:

eric@dev ~ $ mail
Heirloom Mail version 12.4 7/29/08.  Type ? for help.
"/var/spool/mail/eric": 2 messages 2 new
>N  1 Cron Daemon           Tue Jul 29 17:43  23/1016  "Cron <eric@ip-10-0-1-51> /usr/bin/php /var/www/sandbox/eric/c"
 N  2 Cron Daemon           Tue Jul 29 17:44  23/1016  "Cron <eric@ip-10-0-1-51> /usr/bin/php /var/www/sandbox/eric/c"
& d *
& quit

Then check your mail again:

eric@dev ~ $ mail
No mail for eric
eric@dev ~ $

What is tripping you up is you are using x or exit to quit which rolls back the changes during that session.

Adding custom radio buttons in android

Use the same XML file format from Evan's answer, but one drawable file is all you need for formatting.

<RadioButton
    android:id="@+id/radio0"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/custom_button_background"
    android:button="@android:color/transparent"
    android:checked="true"
    android:text="RadioButton1" />

And your separate drawable file:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:state_pressed="true" >
         <shape android:shape="rectangle" >
             <corners android:radius="3dip" />
             <stroke android:width="1dip" android:color="#333333" />
             <solid android:color="#cccccc" />            
         </shape>
    </item>

    <item android:state_checked="true">
         <shape android:shape="rectangle" >
             <corners android:radius="3dip" />
             <stroke android:width="1dip" android:color="#333333" />
             <solid android:color="#cccccc" /> 
         </shape>
    </item>  

    <item>
         <shape android:shape="rectangle"  >
             <corners android:radius="3dip" />
             <stroke android:width="1dip" android:color="#cccccc" />
             <solid android:color="#ffffff" />            
         </shape>
    </item>
</selector>

BeautifulSoup: extract text from anchor tag

This will help:

from bs4 import BeautifulSoup

data = '''<div class="image">
        <a href="http://www.example.com/eg1">Content1<img  
        src="http://image.example.com/img1.jpg" /></a>
        </div>
        <div class="image">
        <a href="http://www.example.com/eg2">Content2<img  
        src="http://image.example.com/img2.jpg" /> </a>
        </div>'''

soup = BeautifulSoup(data)

for div in soup.findAll('div', attrs={'class':'image'}):
    print(div.find('a')['href'])
    print(div.find('a').contents[0])
    print(div.find('img')['src'])

If you are looking into Amazon products then you should be using the official API. There is at least one Python package that will ease your scraping issues and keep your activity within the terms of use.

How to use cURL in Java?

Curl is a non-java program and must be provided outside your Java program.

You can easily get much of the functionality using Jakarta Commons Net, unless there is some specific functionality like "resume transfer" you need (which is tedious to code on your own)

Microsoft.ACE.OLEDB.12.0 provider is not registered

Basically, if you're on a 64-bit machine, IIS 7 is not (by default) serving 32-bit apps, which the database engine operates on. So here is exactly what you do:

1) ensure that the 2007 database engine is installed, this can be downloaded at: http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en

2) open IIS7 manager, and open the Application Pools area. On the right sidebar, you will see an option that says "Set application pool defaults". Click it, and a window will pop up with the options.

3) the second field down, which says 'Enable 32-bit applications' is probably set to FALSE by default. Simply click where it says 'false' to change it to 'true'.

4) Restart your app pool (you can do this by hitting RECYCLE instead of STOP then START, which will also work).

5) done, and your error message will go away.

How to change file encoding in NetBeans?

Go to etc folder in Netbeans home --> open netbeans.conf file and add on netbeans_default_options following line:

-J-Dfile.encoding=UTF-8

Restart Netbeans and it should be in UTF-8

To check go to help --> about and check System: Windows Vista version 6.0 running on x86; UTF-8; nl_NL (nb)

How to change TextField's height and width?

If you want to increase the height of TextFormField dynamically while typing the text in it. Set maxLines to null. Like

TextFormField(
          onSaved: (newText) {
            enteredTextEmail = newText;
          },

          obscureText: false,
          keyboardType: TextInputType.emailAddress,
          validator: validateName,
          maxLines: null,
          // style: style,
          decoration: InputDecoration(
              contentPadding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
              hintText: "Enter Question",
              labelText: "Enter Question",
              border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10.0))),
        ),

Folder structure for a Node.js project

It's important to note that there's no consensus on what's the best approach and related frameworks in general do not enforce nor reward certain structures.

I find this to be a frustrating and huge overhead but equally important. It is sort of a downplayed version (but IMO more important) of the style guide issue. I like to point this out because the answer is the same: it doesn't matter what structure you use as long as it's well defined and coherent.

So I'd propose to look for a comprehensive guide that you like and make it clear that the project is based on this.

It's not easy, especially if you're new to this! Expect to spend hours researching. You'll find most guides recommending an MVC-like structure. While several years ago that might have been a solid choice, nowadays that's not necessarily the case. For example here's another approach.

Find all elements on a page whose element ID contains a certain text using jQuery

$('*[id*=mytext]:visible').each(function() {
    $(this).doStuff();
});

Note the asterisk '*' at the beginning of the selector matches all elements.

See the Attribute Contains Selectors, as well as the :visible and :hidden selectors.

Change MySQL root password in phpMyAdmin

You can change the mysql root password by logging in to the database directly (mysql -h your_host -u root) then run

SET PASSWORD FOR root@localhost = PASSWORD('yourpassword');

Loop backwards using indices in Python?

I tried this in one of the codeacademy exercises (reversing chars in a string without using reversed nor :: -1)

def reverse(text):
    chars= []
    l = len(text)
    last = l-1
    for i in range (l):
        chars.append(text[last])
        last-=1

    result= ""   
    for c in chars:
        result += c
    return result
print reverse('hola')

disable horizontal scroll on mobile web

Simply add this CSS:

html, body {
  overflow-x: hidden;
}
body {
  position: relative
}

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Import MySQL database into a MS SQL Server

Also you can use 'ODBC' + 'SQL Server Import and Export Wizard'. Below link describes it: https://www.mssqltips.com/sqlservertutorial/2205/mysql-to-sql-server-data-migration/

enter image description here

How to stop and restart memcached server?

If you want to be allowed to shutdown the memcached server you can give it that option before start it :

memcached -A &

With this option when you connect to memcached server for example:

telnet localhost 11211

then you can use shutdown command to shutdown the server. You can also shutdown the memcached server when it is run as a process, first find the process PID using:

pidof memcached

then use:

kill PID command

How to parse a String containing XML in Java and retrieve the value of the root node?

One of the above answer states to convert XML String to bytes which is not needed. Instead you can can use InputSource and supply it with StringReader.

String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());

How to set selectedIndex of select element using display text?

You can set the index by this code :

sel.selectedIndex = 0;

but remember a caution in this practice, You would not be able to call the server side onclick method if you select the previous value selected in the drop down..

Callback when CSS3 transition finishes

The accepted answer currently fires twice for animations in Chrome. Presumably this is because it recognizes webkitAnimationEnd as well as animationEnd. The following will definitely only fires once:

/* From Modernizr */
function whichTransitionEvent(){

    var el = document.createElement('fakeelement');
    var transitions = {
        'animation':'animationend',
        'OAnimation':'oAnimationEnd',
        'MSAnimation':'MSAnimationEnd',
        'WebkitAnimation':'webkitAnimationEnd'
    };

    for(var t in transitions){
        if( transitions.hasOwnProperty(t) && el.style[t] !== undefined ){
            return transitions[t];
        }
    }
}

$("#elementToListenTo")
    .on(whichTransitionEvent(),
        function(e){
            console.log('Transition complete!  This is the callback!');
            $(this).off(e);
        });

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

It also gives the same error if you just stop your PostgreSQL app. You just need to start it again. (PostgreSQL 11)

How can I check if a single character appears in a string?

You can use string.indexOf('a').

If the char a is present in string :

it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.

Resize iframe height according to content height in it

Try using scrolling=no attribute on the iframe tag. Mozilla also has an overflow-x and overflow-y CSS property you may look into.

In terms of the height, you could also try height=100% on the iframe tag.

How to read attribute value from XmlNode in C#?

If you use chldNode as XmlElement instead of XmlNode, you can use

var attributeValue = chldNode.GetAttribute("Name");

The return value will just be an empty string, in case the attribute name does not exist.

So your loop could look like this:

XmlDocument document = new XmlDocument();
var nodes = document.SelectNodes("//Node/N0de/node");

foreach (XmlElement node in nodes)
{
    var attributeValue = node.GetAttribute("Name");
}

This will select all nodes <node> surrounded by <Node><N0de></N0de><Node> tags and subsequently loop through them and read the attribute "Name".

How to create a popup windows in javafx

Have you looked into ControlsFx Popover control.


import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;

private PopOver item;

final Scene scene = addItemButton.getScene();

final Point2D windowCoord = new Point2D(scene.getWindow()
        .getX(), scene.getWindow().getY());

final Point2D sceneCoord = new Point2D(scene.getX(), scene.
                getY());

final Point2D nodeCoord = addItemButton.localToScene(0.0,
                        0.0);
final double clickX = Math.round(windowCoord.getX()
    + sceneCoord.getY() + nodeCoord.getX());

final double clickY = Math.round(windowCoord.getY()
        + sceneCoord.getY() + nodeCoord.getY());
item.setContentNode(addItemScreen);
item.setArrowLocation(ArrowLocation.BOTTOM_LEFT);
item.setCornerRadius(4);                            
item.setDetachedTitle("Add New Item");
item.show(addItemButton.getParent(), clickX, clickY);

This is only an example but a PopOver sounds like it could accomplish what you want. Check out the documentation for more info.

Important note: ControlsFX will only work on JavaFX 8.0 b118 or later.

How can I implement rate limiting with Apache? (requests per second)

Depends on why you want to rate limit.

If it's to protect against overloading the server, it actually makes sense to put NGINX in front of it, and configure rate limiting there. It makes sense because NGINX uses much less resources, something like a few MB per ten thousand connections. So, if the server is flooded, NGINX will do the rate limiting(using an insignificant amount of resources) and only pass the allowed traffic to Apache.

If all you're after is simplicity, then use something like mod_evasive.

As usual, if it's to protect against DDoS or DoS attacks, use a service like Cloudflare which also has rate limiting.

Mapping a JDBC ResultSet to an object

I would like to hint on q2o. It is a JPA based Java object mapper which helps with many of the tedious SQL and JDBC ResultSet related tasks, but without all the complexity an ORM framework comes with. With its help mapping a ResultSet to an object is as easy as this:

while(rs.next()) {
    users.add(Q2Obj.fromResultSet(rs, User.class));
}

More about q2o can be found here.

Eclipse Error: "Failed to connect to remote VM"

I had and solved this problem by disconnecting from all remote Java applications in the debug window/perspective and restarting Eclipse. I could connect again after doing so.

Execute multiple command lines with the same process using .NET

ProcessStartInfo pStartInfo = new ProcessStartInfo();
pStartInfo.FileName = "CMD";
pStartInfo.Arguments = @"/C mysql --user=root --password=sa casemanager && \. " + Environment.CurrentDirectory + @"\MySQL\CaseManager.sql"
pStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(pStartInfo);

The && is the way to tell the command shell that there is another command to execute.

How to insert an object in an ArrayList at a specific position

You must handle ArrayIndexOutOfBounds by yourself when adding to a certain position.

For convenience, you may use this extension function in Kotlin

/**
 * Adds an [element] to index [index] or to the end of the List in case [index] is out of bounds
 */
fun <T> MutableList<T>.insert(index: Int, element: T) {
    if (index <= size) {
        add(index, element)
    } else {
        add(element)
    }
}

Is it acceptable and safe to run pip install under sudo?

Is it acceptable & safe to run pip install under sudo?

It's not safe and it's being frowned upon – see What are the risks of running 'sudo pip'? To install Python package in your home directory you don't need root privileges. See description of --user option to pip.

JSON formatter in C#?

You could also use the Newtonsoft.Json library for this and call SerializeObject with the Formatting.Indented enum -

var x = JsonConvert.SerializeObject(jsonString, Formatting.Indented);

Documentation: Serialize an Object


Update -

Just tried it again. Pretty sure this used to work - perhaps it changed in a subsequent version or perhaps i'm just imagining things. Anyway, as per the comments below, it doesn't quite work as expected. These do, however (just tested in linqpad). The first one is from the comments, the 2nd one is an example i found elsewhere in SO -

void Main()
{
    //Example 1
    var t = "{\"x\":57,\"y\":57.0,\"z\":\"Yes\"}";
    var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(t); 
    var f = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
    Console.WriteLine(f);

    //Example 2
    JToken jt = JToken.Parse(t);
    string formatted = jt.ToString(Newtonsoft.Json.Formatting.Indented);
    Console.WriteLine(formatted);

    //Example 2 in one line -
    Console.WriteLine(JToken.Parse(t).ToString(Newtonsoft.Json.Formatting.Indented));
}

'tuple' object does not support item assignment

The second line should have been pixels[0], with an S. You probably have a tuple named pixel, and tuples are immutable. Construct new pixels instead:

image = Image.open('balloon.jpg')

pixels = [(pix[0] + 20,) + pix[1:] for pix in image.getdata()]

image.putdate(pixels)

DateTime.Compare how to check if a date is less than 30 days old?

No it's not correct, try this :

DateTime expiryDate = DateTime.Now.AddDays(-31);
if (DateTime.Compare(expiryDate, DateTime.Now.AddDays(-30)) < 1)
{
    matchFound = true;
}

Calculating the area under a curve given a set of coordinates, without knowing the function

If you have sklearn isntalled, a simple alternative is to use sklearn.metrics.auc

This computes the area under the curve using the trapezoidal rule given arbitrary x, and y array

import numpy as np
from sklearn.metrics import auc

dx = 5
xx = np.arange(1,100,dx)
yy = np.arange(1,100,dx)

print('computed AUC using sklearn.metrics.auc: {}'.format(auc(xx,yy)))
print('computed AUC using np.trapz: {}'.format(np.trapz(yy, dx = dx)))

both output the same area: 4607.5

the advantage of sklearn.metrics.auc is that it can accept arbitrarily-spaced 'x' array, just make sure it is ascending otherwise the results will be incorrect

Domain Account keeping locking out with correct password every few minutes

Finally i found my problem. SQL Reporting Service was causing my account lockout. Stop and try, after confirm no more passwords bad attempts i should reconfigure reporting services service account ---Not at Service Properties, it is in Reporting Service own config--.

How does internationalization work in JavaScript?

You can also try another library - https://github.com/wikimedia/jquery.i18n .

In addition to parameter replacement and multiple plural forms, it has support for gender a rather unique feature of custom grammar rules that some languages need.

Switch statement: must default be the last case?

The C99 standard is not explicit about this, but taking all facts together, it is perfectly valid.

A case and default label are equivalent to a goto label. See 6.8.1 Labeled statements. Especially interesting is 6.8.1.4, which enables the already mentioned Duff's Device:

Any statement may be preceded by a prefix that declares an identifier as a label name. Labels in themselves do not alter the flow of control, which continues unimpeded across them.

Edit: The code within a switch is nothing special; it is a normal block of code as in an if-statement, with additional jump labels. This explains the fall-through behaviour and why break is necessary.

6.8.4.2.7 even gives an example:

switch (expr) 
{ 
    int i = 4; 
    f(i); 
case 0: 
    i=17; 
    /*falls through into default code */ 
default: 
    printf("%d\n", i); 
} 

In the artificial program fragment the object whose identifier is i exists with automatic storage duration (within the block) but is never initialized, and thus if the controlling expression has a nonzero value, the call to the printf function will access an indeterminate value. Similarly, the call to the function f cannot be reached.

The case constants must be unique within a switch statement:

6.8.4.2.3 The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion. There may be at most one default label in a switch statement.

All cases are evaluated, then it jumps to the default label, if given:

6.8.4.2.5 The integer promotions are performed on the controlling expression. The constant expression in each case label is converted to the promoted type of the controlling expression. If a converted value matches that of the promoted controlling expression, control jumps to the statement following the matched case label. Otherwise, if there is a default label, control jumps to the labeled statement. If no converted case constant expression matches and there is no default label, no part of the switch body is executed.

How to convert image into byte array and byte array to base64 String in android?

here is another solution...

System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];

System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
    m.Write (buffer, 0, buffer.Length);
}  
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();

hope it helps!

Inserting the same value multiple times when formatting a string

incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}

You may like to have a read of this to get an understanding: String Formatting Operations.

How to do something to each file in a directory with a batch script

Alternatively, use:

forfiles /s /m *.png /c "cmd /c echo @path"

The forfiles command is available in Windows Vista and up.

Make Axios send cookies in its requests automatically

You are getting the two thinks mixed.

You have "react-cookie" and "axios"

react-cookie => is for handling the cookie on the client side

axios => is for sending ajax requests to the server

With that info, if you want the cookies from the client side to be communicated in the backend side as well, you will need to connect them together.

Note from "react-cookie" Readme:

Isomorphic cookies!

To be able to access user cookies while doing server-rendering, you can use plugToRequest or setRawCookie.

link to readme

If this is what you need, great.

If not, please comment so I could elaborate more.

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

So we are all doing the same home work?

Strange how the most up-voted answer is wrong. Remember, draw/fillOval take height and width as parameters, not the radius. So to correctly draw and center a circle with user-provided x, y, and radius values you would do something like this:

public static void drawCircle(Graphics g, int x, int y, int radius) {

  int diameter = radius * 2;

  //shift x and y by the radius of the circle in order to correctly center it
  g.fillOval(x - radius, y - radius, diameter, diameter); 

}

How to parse XML in Bash?

While there are quite a few ready-made console utilities that might do what you want, it will probably take less time to write a couple of lines of code in a general-purpose programming language such as Python which you can easily extend and adapt to your needs.

Here is a python script which uses lxml for parsing — it takes the name of a file or a URL as the first parameter, an XPath expression as the second parameter, and prints the strings/nodes matching the given expression.

Example 1

#!/usr/bin/env python
import sys
from lxml import etree

tree = etree.parse(sys.argv[1])
xpath_expression = sys.argv[2]

#  a hack allowing to access the
#  default namespace (if defined) via the 'p:' prefix    
#  E.g. given a default namespaces such as 'xmlns="http://maven.apache.org/POM/4.0.0"'
#  an XPath of '//p:module' will return all the 'module' nodes
ns = tree.getroot().nsmap
if ns.keys() and None in ns:
    ns['p'] = ns.pop(None)
#   end of hack    

for e in tree.xpath(xpath_expression, namespaces=ns):
    if isinstance(e, str):
        print(e)
    else:
        print(e.text and e.text.strip() or etree.tostring(e, pretty_print=True))

lxml can be installed with pip install lxml. On ubuntu you can use sudo apt install python-lxml.

Usage

python xpath.py myfile.xml "//mynode"

lxml also accepts a URL as input:

python xpath.py http://www.feedforall.com/sample.xml "//link"

Note: If your XML has a default namespace with no prefix (e.g. xmlns=http://abc...) then you have to use the p prefix (provided by the 'hack') in your expressions, e.g. //p:module to get the modules from a pom.xml file. In case the p prefix is already mapped in your XML, then you'll need to modify the script to use another prefix.


Example 2

A one-off script which serves the narrow purpose of extracting module names from an apache maven file. Note how the node name (module) is prefixed with the default namespace {http://maven.apache.org/POM/4.0.0}:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modules>
        <module>cherries</module>
        <module>bananas</module>
        <module>pears</module>
    </modules>
</project>

module_extractor.py:

from lxml import etree
for _, e in etree.iterparse(open("pom.xml"), tag="{http://maven.apache.org/POM/4.0.0}module"):
    print(e.text)

How to write LDAP query to test if user is member of a group?

You must set your query base to the DN of the user in question, then set your filter to the DN of the group you're wondering if they're a member of. To see if jdoe is a member of the office group then your query will look something like this:

ldapsearch -x -D "ldap_user" -w "user_passwd" -b "cn=jdoe,dc=example,dc=local" -h ldap_host '(memberof=cn=officegroup,dc=example,dc=local)'

If you want to see ALL the groups he's a member of, just request only the 'memberof' attribute in your search, like this:

ldapsearch -x -D "ldap_user" -w "user_passwd" -b "cn=jdoe,dc=example,dc=local" -h ldap_host **memberof**

What is a NullPointerException, and how do I fix it?

NullPointerExceptions are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException. These are the most common, but other ways are listed on the NullPointerException javadoc page.

Probably the quickest example code I could come up with to illustrate a NullPointerException would be:

public class Example {

    public static void main(String[] args) {
        Object obj = null;
        obj.hashCode();
    }

}

On the first line inside main, I'm explicitly setting the Object reference obj equal to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException because there is no code to execute in the location that the reference is pointing.

(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)

Paste in insert mode?

Yes. In Windows Ctrl+V and in Linux pressing both mouse buttons nearly simultaneously.

In Windows I think this line in my _vimrc probably does it:

source $VIMRUNTIME/mswin.vim

In Linux I don't remember how I did it. It looks like I probably deleted some line from the default .vimrc file.

Trigger event when user scroll to specific element - with jQuery

You could use this for all devices,

$(document).on('scroll', function() {
    if( $(this).scrollTop() >= $('#target_element').position().top ){
        do_something();
    }
});

Calling Javascript function from server side

You can call the function from code behind like this :

MyForm.aspx.cs

protected void MyButton_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true);
}

MyForm.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function Test() {
        alert("hi");
        $("#ButtonRow").show();
    }
    function AnotherFunction()
    {
        alert("This is another function");
    }
</script>
</head>
<body>
<form id="form2" runat="server">
<table>
    <tr><td>
            <asp:RadioButtonList ID="SearchCategory" runat="server" onchange="Test()"  RepeatDirection="Horizontal"  BorderStyle="Solid">
               <asp:ListItem>Merchant</asp:ListItem>
               <asp:ListItem>Store</asp:ListItem>
               <asp:ListItem>Terminal</asp:ListItem>
            </asp:RadioButtonList>
        </td>
    </tr>
    <tr id="ButtonRow"style="display:none">
         <td>
            <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
        </td>
    </tr>
    </table> 
</form>

What does "static" mean in C?

A static variable is a special variable that you can use in a function, and it saves the data between calls, and it does not delete it between calls. For example:

void func(void) {
    static int count; // If you don't declare its value, it is initialized with zero
    printf("%d, ", count);
    ++count;
}

int main(void) {
    while(true) {
        func();
    }
    return 0;
}

The output:

0, 1, 2, 3, 4, 5, ...

How to develop Android app completely using python?

You could try BeeWare - as described on their website:

Write your apps in Python and release them on iOS, Android, Windows, MacOS, Linux, Web, and tvOS using rich, native user interfaces. One codebase. Multiple apps.

Gives you want you want now to write Android Apps in Python, plus has the advantage that you won't need to learn yet another framework in future if you end up also wanting to do something on one of the other listed platforms.

Here's the Tutorial for Android Apps.

Counting no of rows returned by a select query

SQL Server requires subqueries that you SELECT FROM or JOIN to have an alias.

Add an alias to your subquery (in this case x):

select COUNT(*) from
(
select m.Company_id
from Monitor as m
    inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
    group by m.Company_id
    having COUNT(m.Monitor_id)>=5)  x

Remove Safari/Chrome textinput/textarea glow

<select class="custom-select">
        <option>option1</option>
        <option>option2</option>
        <option>option3</option>
        <option>option4</option>
</select>

<style>
.custom-select {
        display: inline-block;
        border: 2px solid #bbb;
        padding: 4px 3px 3px 5px;
        margin: 0;
        font: inherit;
        outline:none; /* remove focus ring from Webkit */
        line-height: 1.2;
        background: #f8f8f8;

        -webkit-appearance:none; /* remove the strong OSX influence from Webkit */

        -webkit-border-radius: 6px;
        -moz-border-radius: 6px;
        border-radius: 6px;
    }
    /* for Webkit's CSS-only solution */
    @media screen and (-webkit-min-device-pixel-ratio:0) { 
        .custom-select {
            padding-right:30px;    
        }
    }

    /* Since we removed the default focus styles, we have to add our own */
    .custom-select:focus {
        -webkit-box-shadow: 0 0 3px 1px #c00;
        -moz-box-shadow: 0 0 3px 1px #c00;
        box-shadow: 0 0 3px 1px #c00;
    }

    /* Select arrow styling */
    .custom-select:after {
        content: "?";
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        font-size: 60%;
        line-height: 30px;
        padding: 0 7px;
        background: #bbb;
        color: white;

        pointer-events:none;

        -webkit-border-radius: 0 6px 6px 0;
        -moz-border-radius: 0 6px 6px 0;
        border-radius: 0 6px 6px 0;
    }
</style>

How does tuple comparison work in Python?

I had some confusion before regarding integer comparsion, so I will explain it to be more beginner friendly with an example

a = ('A','B','C') # see it as the string "ABC" b = ('A','B','D')

A is converted to its corresponding ASCII ord('A') #65 same for other elements

So, >> a>b # True you can think of it as comparing between string (It is exactly, actually)

the same thing goes for integers too.

x = (1,2,2) # see it the string "123" y = (1,2,3) x > y # False

because (1 is not greater than 1, move to the next, 2 is not greater than 2, move to the next 2 is less than three -lexicographically -)

The key point is mentioned in the answer above

think of it as an element is before another alphabetically not element is greater than an element and in this case consider all the tuple elements as one string.

Decimal values in SQL for dividing results

SELECT CAST (col1 as float) / col2 FROM tbl1

One cast should work. ("Less is more.")

From Books Online:

Returns the data type of the argument with the higher precedence. For more information about data type precedence, see Data Type Precedence (Transact-SQL).

If an integer dividend is divided by an integer divisor, the result is an integer that has any fractional part of the result truncated

What to put in a python module docstring?

To quote the specifications:

The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.

The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's __init__.py module) should also list the modules and subpackages exported by the package.

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

The docstring of a function or method is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I know this is an old post, but a good time to use PrimaryKeyColumn would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.

In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn.

Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.

Remove columns from DataTable in C#

The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable.

So for that, here is what I did, when I came across the same problem.

string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };

foreach (string ColName in ColumnsToBeDeleted)
{
    if (dt.Columns.Contains(ColName))
        dt.Columns.Remove(ColName);
}

In Python How can I declare a Dynamic Array

In Python, a list is a dynamic array. You can create one like this:

lst = [] # Declares an empty list named lst

Or you can fill it with items:

lst = [1,2,3]

You can add items using "append":

lst.append('a')

You can iterate over elements of the list using the for loop:

for item in lst:
    # Do something with item

Or, if you'd like to keep track of the current index:

for idx, item in enumerate(lst):
    # idx is the current idx, while item is lst[idx]

To remove elements, you can use the del command or the remove function as in:

del lst[0] # Deletes the first item
lst.remove(x) # Removes the first occurence of x in the list

Note, though, that one cannot iterate over the list and modify it at the same time; to do that, you should instead iterate over a slice of the list (which is basically a copy of the list). As in:

 for item in lst[:]: # Notice the [:] which makes a slice
       # Now we can modify lst, since we are iterating over a copy of it

how to convert java string to Date object

"mm" means the "minutes" fragment of a date. For the "months" part, use "MM".

So, try to change the code to:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
Date startDate = df.parse(startDateString);

Edit: A DateFormat object contains a date formatting definition, not a Date object, which contains only the date without concerning about formatting. When talking about formatting, we are talking about create a String representation of a Date in a specific format. See this example:

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class DateTest {

        public static void main(String[] args) throws Exception {
            String startDateString = "06/27/2007";

            // This object can interpret strings representing dates in the format MM/dd/yyyy
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 

            // Convert from String to Date
            Date startDate = df.parse(startDateString);

            // Print the date, with the default formatting. 
            // Here, the important thing to note is that the parts of the date 
            // were correctly interpreted, such as day, month, year etc.
            System.out.println("Date, with the default formatting: " + startDate);

            // Once converted to a Date object, you can convert 
            // back to a String using any desired format.
            String startDateString1 = df.format(startDate);
            System.out.println("Date in format MM/dd/yyyy: " + startDateString1);

            // Converting to String again, using an alternative format
            DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy"); 
            String startDateString2 = df2.format(startDate);
            System.out.println("Date in format dd/MM/yyyy: " + startDateString2);
        }
    }

Output:

Date, with the default formatting: Wed Jun 27 00:00:00 BRT 2007
Date in format MM/dd/yyyy: 06/27/2007
Date in format dd/MM/yyyy: 27/06/2007

How to highlight cell if value duplicate in same column for google spreadsheet?

I tried all the options and none worked.

Only google app scripts helped me.

source : https://ctrlq.org/code/19649-find-duplicate-rows-in-google-sheets

At the top of your document

1.- go to tools > script editor

2.- set the name of your script

3.- paste this code :

function findDuplicates() {
  // List the columns you want to check by number (A = 1)
  var CHECK_COLUMNS = [1];

  // Get the active sheet and info about it
  var sourceSheet = SpreadsheetApp.getActiveSheet();
  var numRows = sourceSheet.getLastRow();
  var numCols = sourceSheet.getLastColumn();

  // Create the temporary working sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var newSheet = ss.insertSheet("FindDupes");

  // Copy the desired rows to the FindDupes sheet
  for (var i = 0; i < CHECK_COLUMNS.length; i++) {
    var sourceRange = sourceSheet.getRange(1,CHECK_COLUMNS[i],numRows);
    var nextCol = newSheet.getLastColumn() + 1;
    sourceRange.copyTo(newSheet.getRange(1,nextCol,numRows));
  }

  // Find duplicates in the FindDupes sheet and color them in the main sheet
  var dupes = false;
  var data = newSheet.getDataRange().getValues();
  for (i = 1; i < data.length - 1; i++) {
    for (j = i+1; j < data.length; j++) {
      if  (data[i].join() == data[j].join()) {
        dupes = true;
        sourceSheet.getRange(i+1,1,1,numCols).setBackground("red");
        sourceSheet.getRange(j+1,1,1,numCols).setBackground("red");
      }
    }
  }

  // Remove the FindDupes temporary sheet
  ss.deleteSheet(newSheet);

  // Alert the user with the results
  if (dupes) {
    Browser.msgBox("Possible duplicate(s) found and colored red.");
  } else {
    Browser.msgBox("No duplicates found.");
  }
};

4.- save and run

In less than 3 seconds, my duplicate row was colored. Just copy-past the script.

If you don't know about google apps scripts , this links could be help you:

https://zapier.com/learn/google-sheets/google-apps-script-tutorial/

https://developers.google.com/apps-script/overview

I hope this helps.

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

Python: Assign Value if None Exists

One-liner solution here:

var1 = locals().get("var1", "default value")

Instead of having NameError, this solution will set var1 to default value if var1 hasn't been defined yet.

Here's how it looks like in Python interactive shell:

>>> var1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'var1' is not defined
>>> var1 = locals().get("var1", "default value 1")
>>> var1
'default value 1'
>>> var1 = locals().get("var1", "default value 2")
>>> var1
'default value 1'
>>>