Programs & Examples On #Webseal

WebSEAL is a high performance, multi-threaded Web server that applies fine-grained security policy to the Tivoli Access Manager protected Web object space. WebSEAL can provide single sign-on solutions and incorporate back-end Web application server resources into its security policy.

Reverse engineering from an APK file to a project

If you are looking for a professional alternative, have a look at JEB Decompiler from PNF Software.

There is a demo version that will let you decompile most code.

Group a list of objects by an attribute

Map<String, List<Student>> map = new HashMap<String, List<Student>>();

for (Student student : studlist) {
    String key  = student.stud_location;
    if(map.containsKey(key)){
        List<Student> list = map.get(key);
        list.add(student);

    }else{
        List<Student> list = new ArrayList<Student>();
        list.add(student);
        map.put(key, list);
    }

}

how to add values to an array of objects dynamically in javascript?

In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently

data = [...data, {"label": 2, "value": 13}]

Examples

_x000D_
_x000D_
var data = [_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
    ];_x000D_
    _x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

For your case (i know it was in 2011), we can do it with map() & forEach() like below

_x000D_
_x000D_
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
   data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
 ({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
_x000D_
_x000D_

How can I get the current page name in WordPress?

This is what I ended up using, as of 2018:

<section id="top-<?=(is_front_page() ? 'home' : basename(get_permalink()));?>">

PHP Notice: Undefined offset: 1 with array when reading data

my quickest solution was to minus 1 to the length of the array as

  $len = count($data);

    for($i=1; $i<=$len-1;$i++){
      echo $data[$i];
    }

my offset was always the last value if the count was 140 then it will say offset 140 but after using the minus 1 everything was fine

postgresql - sql - count of `true` values

Cast the Boolean to an integer and sum.

SELECT count(*),sum(myCol::int);

You get 6,3.

Disable mouse scroll wheel zoom on embedded Google Maps

In Google Maps v3 you can now disable scroll to zoom, which leads to a much better user experience. Other map functions will still work and you don't need extra divs. I also thought there should be some feedback for the user so they can see when scrolling is enabled, so I added a map border.

// map is the google maps object, '#map' is the jquery selector
preventAccidentalZoom(map, '#map'); 

// Disables and enables scroll to zoom as appropriate. Also
// gives the user a UI cue as to when scrolling is enabled.
function preventAccidentalZoom(map, mapSelector){
  var mapElement = $(mapSelector);

  // Disable the scroll wheel by default
  map.setOptions({ scrollwheel: false })

  // Enable scroll to zoom when there is a mouse down on the map.
  // This allows for a click and drag to also enable the map
  mapElement.on('mousedown', function () {
    map.setOptions({ scrollwheel: true });
    mapElement.css('border', '1px solid blue')
  });

  // Disable scroll to zoom when the mouse leaves the map.
  mapElement.mouseleave(function () {
    map.setOptions({ scrollwheel: false })
    mapElement.css('border', 'none')
  });
};

How do I fix MSB3073 error in my post-build event?

The Post-Build Event (under Build Events, in the properties dialog) of an imported project, had an environment variable which was not defined.
Navigated to Control Panel\All Control Panel Items\System\Advanced system settings to add the appropriate environment variable, and doing no more than restarting VS2017 resolved the error.
Also, following on from @Seans and other answers regarding multiple project races/contentions, create a temp folder in the output folder like so,

like so

and select the project producing the preferred output:

enter image description here

and build (no rebuild/clean) is a speedy solution.

Single Page Application: advantages and disadvantages

One major disadvantage of SPA - SEO. Only recently Google and Bing started indexing Ajax-based pages by executing JavaScript during crawling, and still in many cases pages are being indexed incorrectly.

While developing SPA, you will be forced to handle SEO issues, probably by post-rendering all your site and creating static html snapshots for crawler's use. This will require a solid investment in a proper infrastructures.

Update 19.06.16:

Since writing this answer a while ago, I gain much more experience with Single Page Apps (namely, AngularJS 1.x) - so I have more info to share.

In my opinion, the main disadvantage of SPA applications is SEO, making them limited to kind of "dashboard" apps only. In addition, you are going to have a much harder times with caching, compared to classic solutions. For example, in ASP.NET caching is extreamly easy - just turn on OutputCaching and you are good: the whole HTML page will be cached according to URL (or any other parameters). However, in SPA you will need to handle caching yourself (by using some solutions like second level cache, template caching, etc..).

Why call git branch --unset-upstream to fixup?

This might solve your problem.

after doing changes you can commit it and then

git remote add origin https://(address of your repo) it can be https or ssh
then
git push -u origin master

hope it works for you.

thanks

How to secure the ASP.NET_SessionId cookie?

Found that setting the secure property in Session_Start is sufficient, as recommended in MSDN blog "Securing Session ID: ASP/ASP.NET" with some augmentation.

    protected void Session_Start(Object sender, EventArgs e)
    {
        SessionStateSection sessionState = 
 (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
        string sidCookieName = sessionState.CookieName;

        if (Request.Cookies[sidCookieName] != null)
        {
            HttpCookie sidCookie = Response.Cookies[sidCookieName];
            sidCookie.Value = Session.SessionID;
            sidCookie.HttpOnly = true;
            sidCookie.Secure = true;
            sidCookie.Path = "/";
        }
    }

plot.new has not been called yet

If someone is using print function (for example, with mtext), then firstly depict a null plot:

plot(0,type='n',axes=FALSE,ann=FALSE)

and then print with newpage = F

print(data, newpage = F)

How to iterate through range of Dates in Java?

The following snippet (uses java.time.format of Java 8) maybe used to iterate over a date range :

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    // Any chosen date format maybe taken  
    LocalDate startDate = LocalDate.parse(startDateString,formatter);
    LocalDate endDate = LocalDate.parse(endDateString,formatter);
    if(endDate.isBefore(startDate))
    {
        //error
    }
    LocalDate itr = null;
    for (itr = startDate; itr.isBefore(endDate)||itr.isEqual(itr); itr = itr.plusDays(1))
    {
        //Processing  goes here
    }

The plusMonths()/plusYears() maybe chosen for time unit increment. Increment by a single day is being done in above illustration.

Windows Forms - Enter keypress activates submit button?

If you set your Form's AcceptButton property to one of the Buttons on the Form, you'll get that behaviour by default.

Otherwise, set the KeyPreview property to true on the Form and handle its KeyDown event. You can check for the Enter key and take the necessary action.

Excel formula to reference 'CELL TO THE LEFT'

You could use a VBA script that changes the conditional formatting of a selection (you might have to adjust the condition & formatting accordingly):

For Each i In Selection
i.FormatConditions.Delete
i.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, Formula1:="=" & i.Offset(0, -1).Address
With i.FormatConditions(1).Font
    .Bold = True
End With
Next i

Erasing elements from a vector

Depending on why you are doing this, using a std::set might be a better idea than std::vector.

It allows each element to occur only once. If you add it multiple times, there will only be one instance to erase anyway. This will make the erase operation trivial. The erase operation will also have lower time complexity than on the vector, however, adding elements is slower on the set so it might not be much of an advantage.

This of course won't work if you are interested in how many times an element has been added to your vector or the order the elements were added.

Print page numbers on pages when printing html

I know this is not a coding answer but it is what the OP wanted and what I have spent half the day trying to achieve - print from a web page with page numbers.

Yes, it is two steps instead of one but I haven't been able to find any CSS option despite several hours of searching. Real shame all the browsers removed the functionality that used to allow it.

jquery dialog save cancel button styling

As of jquery ui version 1.8.16 below is how I got it working.

$('#element').dialog({
  buttons: { 
      "Save": {  
          text: 'Save', 
          class: 'btn primary', 
          click: function () {
              // do stuff
          }
      }
});

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

How do I register a DLL file on Windows 7 64-bit?

Open the start menu and type cmd into the search box Hold Ctrl + Shift and press Enter

This runs the Command Prompt in Administrator mode.

Now type: regsvr32 MyComobject.dll

R command for setting working directory to source file location in Rstudio

This answer can help:

script.dir <- dirname(sys.frame(1)$ofile)

Note: script must be sourced in order to return correct path

I found it in: https://support.rstudio.com/hc/communities/public/questions/200895567-can-user-obtain-the-path-of-current-Project-s-directory-

The BumbleBee´s answer (with parent.frame instead sys.frame) didn´t work to me, I always get an error.

Authenticate Jenkins CI for Github private repository

An alternative to the answer from sergey_mo is to create multiple ssh keys on the jenkins server.

(Though as the first commenter to sergey_mo's answer said, this may end up being more painful than managing a single key-pair.)

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

The easy way to fix this is to add this to your form.

{{ csrf_field() }}
<input type="hidden" name="_method" value="PUT">

then the update method will be like this :

public function update(Request $request, $id)
{
    $project = Project::findOrFail($id);
    $project->name = $request->name;
    $project->description = $request->description;

    $post->save();
}

Still Reachable Leak detected by Valgrind

You don't appear to understand what still reachable means.

Anything still reachable is not a leak. You don't need to do anything about it.

Accessing a class' member variables in Python?

You are declaring a local variable, not a class variable. To set an instance variable (attribute), use

class Example(object):
    def the_example(self):
        self.itsProblem = "problem"  # <-- remember the 'self.'

theExample = Example()
theExample.the_example()
print(theExample.itsProblem)

To set a class variable (a.k.a. static member), use

class Example(object):
    def the_example(self):
        Example.itsProblem = "problem"
        # or, type(self).itsProblem = "problem"
        # depending what you want to do when the class is derived.

JavaScript: IIF like statement

var x = '<option value="' + col + '"'
if (col == 'screwdriver') x += ' selected';
x += '>Very roomy</option>';

Android open pdf file

Kotlin version below (Updated version of @paul-burke response:

fun openPDFDocument(context: Context, filename: String) {
    //Create PDF Intent
    val pdfFile = File(Environment.getExternalStorageDirectory().absolutePath + "/" + filename)
    val pdfIntent = Intent(Intent.ACTION_VIEW)
    pdfIntent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf")
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)

    //Create Viewer Intent
    val viewerIntent = Intent.createChooser(pdfIntent, "Open PDF")
    context.startActivity(viewerIntent)
}

Update values from one column in same table to another in SQL Server

Your select statement was before the update statement see Updated fiddle

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

Read specific columns from a csv file with csv module?

import csv
from collections import defaultdict

columns = defaultdict(list) # each value in each column is appended to a list

with open('file.txt') as f:
    reader = csv.DictReader(f) # read rows into a dictionary format
    for row in reader: # read a row as {column1: value1, column2: value2,...}
        for (k,v) in row.items(): # go over each column name and value 
            columns[k].append(v) # append the value into the appropriate list
                                 # based on column name k

print(columns['name'])
print(columns['phone'])
print(columns['street'])

With a file like

name,phone,street
Bob,0893,32 Silly
James,000,400 McHilly
Smithers,4442,23 Looped St.

Will output

>>> 
['Bob', 'James', 'Smithers']
['0893', '000', '4442']
['32 Silly', '400 McHilly', '23 Looped St.']

Or alternatively if you want numerical indexing for the columns:

with open('file.txt') as f:
    reader = csv.reader(f)
    reader.next()
    for row in reader:
        for (i,v) in enumerate(row):
            columns[i].append(v)
print(columns[0])

>>> 
['Bob', 'James', 'Smithers']

To change the deliminator add delimiter=" " to the appropriate instantiation, i.e reader = csv.reader(f,delimiter=" ")

Getting multiple selected checkbox values in a string in javascript and PHP

In some cases it might make more sense to process each selected item one at a time.

In other words, make a separate server call for each selected item passing the value of the selected item. In some cases the list will need to be processed as a whole, but in some not.

I needed to process a list of selected people and then have the results of the query show up on an existing page beneath the existing data for that person. I initially though of passing the whole list to the server, parsing the list, then passing back the data for all of the patients. I would have then needed to parse the returning data and insert it into the page in each of the appropriate places. Sending the request for the data one person at a time turned out to be much easier. Javascript for getting the selected items is described here: check if checkbox is checked javascript and jQuery for the same is described here: How to check whether a checkbox is checked in jQuery?.

How to undo a SQL Server UPDATE query?

If you can catch this in time and you don't have the ability to ROLLBACK or use the transaction log, you can take a backup immediately and use a tool like Redgate's SQL Data Compare to generate a script to "restore" the affected data. This worked like a charm for me. :)

How to download and save an image in Android

public class testCrop extends AppCompatActivity {
    ImageView iv;
    String imagePath = "https://style.pk/wp-content/uploads/2015/07/omer-Shahzad-performed-umrah-600x548.jpg";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testcrpop);
        iv = (ImageView) findViewById(R.id.testCrop);
        imageDownload image = new imageDownload(testCrop.this, iv);
        image.execute(imagePath);
    }
    class imageDownload extends AsyncTask<String, Integer, Bitmap> {
        Context context;
        ImageView imageView;
        Bitmap bitmap;
        InputStream in = null;
        int responseCode = -1;
//constructor.
        public imageDownload(Context context, ImageView imageView) {
            this.context = context;
            this.imageView = imageView;
        }
        @Override
        protected void onPreExecute() {
        }
        @Override
        protected Bitmap doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setDoOutput(true);
                httpURLConnection.connect();
                responseCode = httpURLConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    in = httpURLConnection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(in);
                    in.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }
        @Override
        protected void onPostExecute(Bitmap data) {
            imageView.setImageBitmap(data);
            saveImage(data);
        }

        private void saveImage(Bitmap data) {
            File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test");
            createFolder.mkdir();
            File saveImage = new File(createFolder,"downloadimage.jpg");
            try {
                OutputStream outputStream = new FileOutputStream(saveImage);
                data.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
                outputStream.flush();
                outputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

OUTPUTenter image description here

Make sure you added permission to write data in memory

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

Order by multiple columns with Doctrine

The orderBy method requires either two strings or an Expr\OrderBy object. If you want to add multiple order declarations, the correct thing is to use addOrderBy method, or instantiate an OrderBy object and populate it accordingly:

   # Inside a Repository method:
   $myResults = $this->createQueryBuilder('a')
       ->addOrderBy('a.column1', 'ASC')
       ->addOrderBy('a.column2', 'ASC')
       ->addOrderBy('a.column3', 'DESC')
   ;

   # Or, using a OrderBy object:
   $orderBy = new OrderBy('a.column1', 'ASC');
   $orderBy->add('a.column2', 'ASC');
   $orderBy->add('a.column3', 'DESC');

   $myResults = $this->createQueryBuilder('a')
       ->orderBy($orderBy)
   ;

Downgrade npm to an older version

npm install -g npm@4

This will install the latest version on the major release 4, no no need to specify version number. Replace 4 with whatever major release you want.

Automatically run %matplotlib inline in IPython Notebook

In your ipython_config.py file, search for the following lines

# c.InteractiveShellApp.matplotlib = None

and

# c.InteractiveShellApp.pylab = None

and uncomment them. Then, change None to the backend that you're using (I use 'qt4') and save the file. Restart IPython, and matplotlib and pylab should be loaded - you can use the dir() command to verify which modules are in the global namespace.

How to check whether a select box is empty using JQuery/Javascript

Another correct way to get selected value would be using this selector:

$("option[value="0"]:selected")

Best for you!

Create random list of integers in Python

All the random methods end up calling random.random() so the best way is to call it directly:

[int(1000*random.random()) for i in xrange(10000)]

For example,

  • random.randint calls random.randrange.
  • random.randrange has a bunch of overhead to check the range before returning istart + istep*int(self.random() * n).

NumPy is much faster still of course.

Compare a string using sh shell

You should use the = operator for string comparison:

Sourcesystem="ABC"

if [ "$Sourcesystem" = "XYZ" ]; then 
    echo "Sourcesystem Matched" 
else
    echo "Sourcesystem is NOT Matched $Sourcesystem"  
fi;

man test says that you use -z to match for empty strings.

How can I view live MySQL queries?

Gibbs MySQL Spyglass

AgilData launched recently the Gibbs MySQL Scalability Advisor (a free self-service tool) which allows users to capture a live stream of queries to be uploaded to Gibbs. Spyglass (which is Open Source) will watch interactions between your MySQL Servers and client applications. No reconfiguration or restart of the MySQL database server is needed (either client or app).

GitHub: AgilData/gibbs-mysql-spyglass

Learn more: Packet Capturing MySQL with Rust

Install command:

curl -s https://raw.githubusercontent.com/AgilData/gibbs-mysql-spyglass/master/install.sh | bash

php & mysql query not echoing in html with tags?

<td class="first"> <?php echo $proxy ?> </td> is inside a literal string that you are echoing. End the string, or concatenate it correctly:

<td class="first">' . $proxy . '</td>

How to check if a given directory exists in Ruby

File.exist?("directory")

Dir[] returns an array, so it will never be nil. If you want to do it your way, you could do

Dir["directory"].empty?

which will return true if it wasn't found.

log4j configuration via JVM argument(s)?

If you are using gradle. You can apply 'aplication' plugin and use the following command

  applicationDefaultJvmArgs = [
             "-Dlog4j.configurationFile=your.xml",
                              ]

Appending a line break to an output file in a shell script

Try

echo -en "`date` User `whoami` started the script.\n" >> output.log

Try issuing this multiple times. I hope you are looking for the same output.

can't start MySql in Mac OS 10.6 Snow Leopard

YOU MUST REINSTALL mySQL after upgrading to Snow Leopard and remove any previous versions as well as previous startup from the preference panel. install 86_64 10.5...I find the others did not work for me.

  1. Download MySQL version Mac OS X 10.5 (x86_64) located at http://dev.mysql.com/downloads/mysql/5.4.html#macosx-dmg
  2. Install startup Item (follow instructions)
  3. Then install the beta version (follow instructions)
  4. If you want the start up in the Preference Panel...install mySQL.prefpane I find that SQL does not run from the terminal unless you start mySQL in the preference panel.

Distribution certificate / private key not installed

  1. go to this link https://developer.apple.com/account/resources/certificates/list

  2. find certificate name in your alert upload then

  3. Revoke certificate that

  4. if you have certificate you download again
  5. upload testflight again

Hadoop/Hive : Loading data from .csv on a local machine

Let me work you through the following simple steps:

Steps:

First, create a table on hive using the field names in your csv file. Lets say for example, your csv file contains three fields (id, name, salary) and you want to create a table in hive called "staff". Use the below code to create the table in hive.

hive> CREATE TABLE Staff (id int, name string, salary double) row format delimited fields terminated by ',';

Second, now that your table is created in hive, let us load the data in your csv file to the "staff" table on hive.

hive>  LOAD DATA LOCAL INPATH '/home/yourcsvfile.csv' OVERWRITE INTO TABLE Staff;

Lastly, display the contents of your "Staff" table on hive to check if the data were successfully loaded

hive> SELECT * FROM Staff;

Thanks.

Get the last insert id with doctrine 2?

I had to use this after the flush to get the last insert id:

$em->persist($user);
$em->flush();
$user->getId();

On duplicate key ignore?

Mysql has this handy UPDATE INTO command ;)

edit Looks like they renamed it to REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

Change width of select tag in Twitter Bootstrap

In bootstrap 3, it is recommended that you size inputs by wrapping them in col-**-# div tags. It seems that most things have 100% width, especially .form-control elements.

https://getbootstrap.com/docs/3.3/css/#forms-control-sizes

How to load local html file into UIWebView

if let htmlFile = NSBundle.mainBundle().pathForResource("aa", ofType: "html"){
    do{
        let htmlString = try NSString(contentsOfFile: htmlFile, encoding:NSUTF8StringEncoding )
        webView.loadHTMLString(htmlString as String, baseURL: nil)
    }
    catch _ {
    }
}

How do I add a library project to Android Studio?

Android Studio 3.0

Just add the library name to the dependencies block of your app's build.gradle file.

dependencies {
    // ...
    implementation 'com.example:some-library:1.0.0'
}

Note that you should use implementation rather than compile now. This is new with Android Studio 3.0. See this Q&A for an explanation of the difference.

How do I analyze a .hprof file?

You can also use HeapWalker from the Netbeans Profiler or the Visual VM stand-alone tool. Visual VM is a good alternative to JHAT as it is stand alone, but is much easier to use than JHAT.

You need Java 6+ to fully use Visual VM.

Why do we need boxing and unboxing in C#?

Boxing isn't really something that you use - it is something the runtime uses so that you can handle reference and value types in the same way when necessary. For example, if you used an ArrayList to hold a list of integers, the integers got boxed to fit in the object-type slots in the ArrayList.

Using generic collections now, this pretty much goes away. If you create a List<int>, there is no boxing done - the List<int> can hold the integers directly.

ldap query for group members

The query should be:

(&(objectCategory=user)(memberOf=CN=Distribution Groups,OU=Mybusiness,DC=mydomain.local,DC=com))

You missed & and ()

PHP cURL, extract an XML response

$sXML = download_page('http://alanstorm.com/atom');
// Comment This    
// $oXML = new SimpleXMLElement($sXML);
// foreach($oXML->entry as $oEntry){
//  echo $oEntry->title . "\n";
// }
// Use json encode
$xml = simplexml_load_string($sXML);
$json = json_encode($xml);
$arr = json_decode($json,true);
print_r($arr);

Inner join with count() on three tables

i tried putting distinct on both, count(distinct ord.ord_id) as num_order, count(distinct items.item_id) as num items

its working :)

    SELECT
         people.pe_name,
         COUNT(distinct orders.ord_id) AS num_orders,
         COUNT(distinct items.item_id) AS num_items
    FROM
         people
         INNER JOIN orders ON (orders.pe_id = people.pe_id)
         INNER JOIN items ON items.pe_id = people.pe_id
    GROUP BY
         people.pe_id;

Thanks for the Thread it helps :)

Google drive limit number of download

It looks like that this limitation can be avoided if you use the following URL pattern:

https://googledrive.com/host/file-id

For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg

Please keep in mind that this method works only if file is shared with "Public on the web" option.

Phone: numeric keyboard for text input

 <input type="text" inputmode="decimal">

it will give u text input using numeric key-pad

Round up to Second Decimal Place in Python

Here is a more general one-liner that works for any digits:

import math
def ceil(number, digits) -> float: return math.ceil((10.0 ** digits) * number) / (10.0 ** digits)

Example usage:

>>> ceil(1.111111, 2)
1.12

Caveat: as stated by nimeshkiranverma:

>>> ceil(1.11, 2) 
1.12  #Because: 1.11 * 100.0 has value 111.00000000000001

How to find out the server IP address (using JavaScript) that the browser is connected to?

Can do this thru a plug-in like Java applet or Flash, then have the Javascript call a function in the applet or vice versa (OR have the JS call a function in Flash or other plugin ) and return the IP. This might not be the IP used by the browser for getting the page contents. Also if there are images, css, js -> browser could have made multiple connections. I think most browsers only use the first IP they get from the DNS call (that connected successfully, not sure what happens if one node goes down after few resources are got and still to get others - timers/ ajax that add html that refer to other resources).

If java applet would have to be signed, make a connection to the window.location (got from javascript, in case applet is generic and can be used on any page on any server) else just back to home server and use java.net.Address to get IP.

Error while installing json gem 'mkmf.rb can't find header files for ruby'

Most voted solution didn't work on my machine (linux mint 18.04). After a careful look, i found that g++ was missing. Solved with

sudo apt-get install g++

HTML5 Local storage vs. Session storage

sessionStorage is the same as localStorage, except that it stores the data for only one session, and it will be removed when the user closes the browser window that created it.

Why does an onclick property set with setAttribute fail to work in IE?

Did you try:

    execBtn.setAttribute("onclick", function() { runCommand() });

Submit HTML form on self page

You can do it using the same page on the action attribute: action='<yourpage>'

Importing CSV with line breaks in Excel 2007

This worked on Mac, using csv and opening the file in Excel.

Using python to write the csv file.

data= '"first line of cell a1\r 2nd line in cell a1\r 3rd line in cell a1","cell b1","1st line in cell c1\r 2nd line in cell c1"\n"first line in cell a2"\n'

file.write(data)

Best way to handle list.index(might-not-exist) in python?

I'd suggest:

if thing in thing_list:
  list_index = -1
else:
  list_index = thing_list.index(thing)

Downloading jQuery UI CSS from Google's CDN

You could use this one if you mean the jQuery UI css:

<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

Close Bootstrap Modal

Try This

$('#modal_id').modal('hide');

Difference between Inheritance and Composition

In Simple Word Aggregation means Has A Relationship ..

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

Why Use Aggregation

Code Reusability

When Use Aggregation

Code reuse is also best achieved by aggregation when there is no is a Relation ship

Inheritance

Inheritance is a Parent Child Relationship Inheritance Means Is A RelationShip

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Using inheritance in Java 1 Code Reusability. 2 Add Extra Feature in Child Class as well as Method Overriding (so runtime polymorphism can be achieved).

<img>: Unsafe value used in a resource URL context

Pipe

// Angular
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

/**
 * Sanitize HTML
 */
@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {
  /**
   * Pipe Constructor
   *
   * @param _sanitizer: DomSanitezer
   */
  // tslint:disable-next-line
  constructor(protected _sanitizer: DomSanitizer) {
  }

  /**
   * Transform
   *
   * @param value: string
   * @param type: string
   */
  transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
      case 'html':
        return this._sanitizer.bypassSecurityTrustHtml(value);
      case 'style':
        return this._sanitizer.bypassSecurityTrustStyle(value);
      case 'script':
        return this._sanitizer.bypassSecurityTrustScript(value);
      case 'url':
        return this._sanitizer.bypassSecurityTrustUrl(value);
      case 'resourceUrl':
        return this._sanitizer.bypassSecurityTrustResourceUrl(value);
      default:
        return this._sanitizer.bypassSecurityTrustHtml(value);
    }
  }
}

Template

{{ data.url | safe:'url' }}

That's it!

Note: You shouldn't need it but here is the component use of the pipe
  // Public properties
  itsSafe: SafeHtml;

  // Private properties
  private safePipe: SafePipe = new SafePipe(this.domSanitizer);

  /**
   * Component constructor
   *
   * @param safePipe: SafeHtml
   * @param domSanitizer: DomSanitizer
   */
  constructor(private safePipe: SafePipe, private domSanitizer: DomSanitizer) {
  }

  /**
   * On init
   */
  ngOnInit(): void {
    this.itsSafe = this.safePipe.transform('<h1>Hi</h1>', 'html');
  }

How do I drop a MongoDB database from the command line?

Like this:

mongo <dbname> --eval "db.dropDatabase()"

More info on scripting the shell from the command line here: https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/#scripting

Android studio doesn't list my phone under "Choose Device"

I had the same issue and couldn't get my Nexus 6P to show up as an available device until I changed the connection type from "Charging" to "Photo Transfer(PTP)" and installed the Google USB driver while in PTP mode. Installing the driver prior to that while in Charging mode yielded no results.

How to generate a range of numbers between two numbers?

declare @start int = 1000
declare @end    int =1050

;with numcte  
AS  
(  
  SELECT @start [SEQUENCE]  
  UNION all  
  SELECT [SEQUENCE] + 1 FROM numcte WHERE [SEQUENCE] < @end 
)      
SELECT * FROM numcte

Linq order by, group by and order by each group?

I think you want an additional projection that maps each group to a sorted-version of the group:

.Select(group => group.OrderByDescending(student => student.Grade))

It also appears like you might want another flattening operation after that which will give you a sequence of students instead of a sequence of groups:

.SelectMany(group => group)

You can always collapse both into a single SelectMany call that does the projection and flattening together.


EDIT: As Jon Skeet points out, there are certain inefficiencies in the overall query; the information gained from sorting each group is not being used in the ordering of the groups themselves. By moving the sorting of each group to come before the ordering of the groups themselves, the Max query can be dodged into a simpler First query.

How can I wait for set of asynchronous callback functions?

You can use jQuery's Deferred object along with the when method.

deferredArray = [];
forloop {
    deferred = new $.Deferred();
    ajaxCall(function() {
      deferred.resolve();
    }
    deferredArray.push(deferred);
}

$.when(deferredArray, function() {
  //this code is called after all the ajax calls are done
});

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

Make first letter of a string upper case (with maximum performance)

send a string to this function. it will first check string is empty or null, if not string will be all lower chars. then return first char of string upper rest of them lower.

string FirstUpper(string s)
    {
        // Check for empty string.
        if (string.IsNullOrEmpty(s))
        {
            return string.Empty;
        }
        s = s.ToLower();
        // Return char and concat substring.
        return char.ToUpper(s[0]) + s.Substring(1);
    }

Replace words in a string - Ruby

You can try using this way :

sentence ["Robert"] = "Roger"

Then the sentence will become :

sentence = "My name is Roger" # Robert is replaced with Roger

How to compare two tags with git?

If source code is on Github, you can use their comparing tool: https://help.github.com/articles/comparing-commits-across-time/

How can I store JavaScript variable output into a PHP variable?

JavaScript variable = PHP variable try follow:-

<script>
var a="Hello";
<?php
$variable='a';
?>
</script>

Note:-It run only when you do php code under script tag.I have a successfully initialise php variable.

Reading a file line by line in Go

Another method is to use the io/ioutil and strings libraries to read the entire file's bytes, convert them into a string and split them using a "\n" (newline) character as the delimiter, for example:

import (
    "io/ioutil"
    "strings"
)

func main() {
    bytesRead, _ := ioutil.ReadFile("something.txt")
    file_content := string(bytesRead)
    lines := strings.Split(file_content, "\n")
}

Technically you're not reading the file line-by-line, however you are able to parse each line using this technique. This method is applicable to smaller files. If you're attempting to parse a massive file use one of the techniques that reads line-by-line.

how to stop a loop arduino

just use this line to exit function:

return;

How to integrate SAP Crystal Reports in Visual Studio 2017

I had exactly the same problem with my VS 2013 solutions when I install VS 2017 and Crystal Reports SP21. In fact it's because VS does not necessarily convert the solution in the first launch.

Once you have installed Crystal Report SP 21, make sure that VS 2017 upgrade your solution : a window must appear "SAP Crystal Reports, version for Visual" with a radio button "Convert the solution".

Screenshot in french :

enter image description here

When I used the menu "File / Open / Project/Solution", the conversion was not done.

I have to do that :

  1. Add VS 2017 on the tasks bar
  2. Run VS 2017 and Open the solution with File menu
  3. Try to build the project, errors appear with Crystal Reports
  4. Close VS 2017
  5. Right click on VS 2017 shortcur in then tasks bar and open the solution directly
  6. The conversion run this time, you can open .rpt and the solution build without error.

CodeIgniter removing index.php from url

I think your all setting is good but you doing to misplace your htaccess file go and add your htaccess to your project file

project_folder->htaccess

and add this code to your htaccess

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Find if a String is present in an array

String[] a= {"tube", "are", "fun"};
Arrays.asList(a).contains("any");

Switch statement equivalent in Windows batch file

I searched switch / case in batch files today and stumbled upon this. I used this solution and extended it with a goto exit.

IF "%1"=="red" echo "one selected" & goto exit
IF "%1"=="two" echo "two selected" & goto exit
...

echo "Options: [one | two | ...]

:exit 

Which brings in the default state (echo line) and no extra if's when the choice is found.

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

Before i was running this command

npm install typescript -g

after changing the command it worked perfectly.

npm install -g typescript

Make an image width 100% of parent div, but not bigger than its own width

You should set the max width and if you want you can also set some padding on one of the sides. In my case the max-width: 100% was good but the image was right next to the end of the screen.

  max-width: 100%;
  padding-right: 30px;
  /*add more paddings if needed*/

Can Android Studio be used to run standard Java projects?

Tested in Android Studio 0.8.14:
I was able to get a standard project running with minimal steps in this way:

  • In an open Android Studio project, click File > New Module.
  • Click More Modules > Java Library > Next, then fill in whatever you prefer for the names.
  • A new module will appear as a folder on the same level as your "app" folder in the Project Structure. Open it and open the new Java class file.

    You can then add your code, and choose Build > Run 'YourClassName'. Presto, your code is running with no Android device!

  • Disable elastic scrolling in Safari

    You can achieve this more universally by applying the following CSS:

    html,
    body {
      height: 100%;
      width: 100%;
      overflow: auto;
    }
    

    This allows your content, whatever it is, to become scrollable within body, but be aware that the scrolling context where scroll event is fired is now document.body, not window.

    How to pass values between Fragments

    I think a good way to solve this problem is to use a custom interface.

    Lets say you have two fragments (A and B) which are inside of the same activity and you want to send data from A to B.

    Interface :

    public interface OnDataSentListener{
        void onDataSent(Object data);
    }
    

    Activity:

        public class MyActivity extends AppCompatActivity{
    
                private OnDataSentListener onDataSentListener;
    
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_activity);
    
                    FragmentTransaction trans = getFragmentManager().beginTransaction();
    
                    FragmentA fa = new FragmentA();
                    FragmentB fb = new FragmentB();
    
                   fa.setOnDataSentListener(new Listeners.OnDataSentListener() {
                        @Override
                        public void onDataSent(Object data) {
                             if(onDataSentListener != null)  onDataSentListener.onDataSent(data);
                        }
                   });
    
                    transaction.add(R.id.frame_a, fa);
                    transaction.add(R.id.frame_b, fb);
    
                    transaction.commit();
                }
    
                public void setOnDataSentListener(OnDataSentListener listener){
                    this.onDataSentListener = listener;
                }
            }
    

    Fragment A:

    public class FragmentA extends Fragment{
    
        private OnDataSentListener onDataSentListener;
    
        private void sendDataToFragmentB(Object data){
            if(onDataSentListener != null) onDataSentListener.onDataSent(data);
        }
    
        public void setOnDataSentListener(OnDataSentListener listener){
            this.onDataSentListener = listener;
        }
    }
    

    Fragment B:

    public class FragmentB extends Fragment{
    
        private void initReceiver(){
            ((MyActivity) getActivity()).setOnDataSentListener(new OnDataSentListener() {
                @Override
                public void onDataSent(Object data) {
                    //Here you receive the data from fragment A
                }
            });
        }
    }
    

    Android Respond To URL in Intent

    You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/ vs https/, www. vs no www., etc).

    For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms)

    Note that path prefix is optional.

            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
    
                <data android:scheme="http" />
                <data android:scheme="https" />
    
                <data android:host="www.docs.google.com" />
                <data android:host="docs.google.com" />
    
                <data android:pathPrefix="/forms" />
            </intent-filter>
    

    How do you uninstall MySQL from Mac OS X?

    OS version: 10.14.6 MYSQL version: 8.0.14

    Goto System preferences -> MYSQLenter image description here

    Stop MySQL server

    enter image description here

    One option will be shown here to uninstall MYSQL 8 after stopping Mysql server

    String.contains in Java

    Thinking of a string as a set of characters, in mathematics the empty set is always a subset of any set.

    Where is NuGet.Config file located in Visual Studio project?

    There are multiple nuget packages read in the following order:

    1. First the NuGetDefaults.Config file. You will find this in %ProgramFiles(x86)%\NuGet\Config.
    2. The computer-level file.
    3. The user-level file. You will find this in %APPDATA%\NuGet\nuget.config.
    4. Any file named nuget.config beginning from the root of your drive up to the directory where nuget.exe is called.
    5. The config file you specify in the -configfile option when calling nuget.exe

    You can find more information here.

    Function overloading in Python: Missing

    You can pass a mutable container datatype into a function, and it can contain anything you want.

    If you need a different functionality, name the functions differently, or if you need the same interface, just write an interface function (or method) that calls the functions appropriately based on the data received.

    It took a while to me to get adjusted to this coming from Java, but it really isn't a "big handicap".

    Check if a string contains an element from a list (of strings)

    As I needed to check if there are items from a list in a (long) string, I ended up with this one:

    listOfStrings.Any(x => myString.ToUpper().Contains(x.ToUpper()));
    

    Or in vb.net:

    listOfStrings.Any(Function(x) myString.ToUpper().Contains(x.ToUpper()))
    

    Trees in Twitter Bootstrap

    If someone wants expandable/collapsible version of the treeview from Vitaliy Bychik's answer, you can save some time :)

    http://jsfiddle.net/mehmetatas/fXzHS/2/

    $(function () {
        $('.tree li').hide();
        $('.tree li:first').show();
        $('.tree li').on('click', function (e) {
            var children = $(this).find('> ul > li');
            if (children.is(":visible")) children.hide('fast');
            else children.show('fast');
            e.stopPropagation();
        });
    });
    

    slideToggle JQuery right to left

    $("#mydiv").toggle(500,"swing");
    
    more https://api.jquery.com/toggle/
    

    PHP foreach loop through multidimensional array

    If you mean the first and last entry of the array when talking about a.first and a.last, it goes like this:

    foreach ($arr_nav as $inner_array) {
        echo reset($inner_array); //apple, orange, pear
        echo end($inner_array); //My Apple, View All Oranges, A Pear
    }
    

    arrays in PHP have an internal pointer which you can manipulate with reset, next, end. Retrieving keys/values works with key and current, but using each might be better in many cases..

    UL or DIV vertical scrollbar

    You need to define height of ul or your div and set overflow equals to auto as below:

    <ul style="width: 300px; height: 200px; overflow: auto">
      <li>text</li>
      <li>text</li>
    

    Using only CSS, show div on hover over <a>

    _x000D_
    _x000D_
    .showme {_x000D_
      display: none;_x000D_
    }_x000D_
    _x000D_
    .showhim:hover .showme {_x000D_
      display: block;_x000D_
    }
    _x000D_
    <div class="showhim">HOVER ME_x000D_
      <div class="showme">hai</div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    jsfiddle

    Since this answer is popular I think a small explanation is needed. Using this method when you hover on the internal element, it wont disappear. Because the .showme is inside .showhim it will not disappear when you move your mouse between the two lines of text (or whatever it is).

    These are example of quirqs you need to take care of when implementing such behavior.

    It all depends what you need this for. This method is better for a menu style scenario, while Yi Jiang's is better for tooltips.

    How to get IntPtr from byte[] in C#

    In some cases you can use an Int32 type (or Int64) in case of the IntPtr. If you can, another useful class is BitConverter. For what you want you could use BitConverter.ToInt32 for example.

    How do I split a string with multiple separators in JavaScript?

    You can pass a regex into Javascript's split operator. For example:

    "1,2 3".split(/,| /) 
    ["1", "2", "3"]
    

    Or, if you want to allow multiple separators together to act as one only:

    "1, 2, , 3".split(/(?:,| )+/) 
    ["1", "2", "3"]
    

    (You have to use the non-capturing (?:) parens because otherwise it gets spliced back into the result. Or you can be smart like Aaron and use a character class.)

    (Examples tested in Safari + FF)

    variable or field declared void

    Did you put void while calling your function?

    For example:

    void something(int x){
        logic..
    }
    
    int main() {
    
        **void** something();
    
        return 0;
    
    }
    

    If so, you should delete the last void.

    jQuery class within class selector

    For this html:

    <div class="outer">
         <div class="inner"></div>
    </div>
    

    This selector should work:

    $('.outer > .inner')
    

    Child with max-height: 100% overflows parent

    _x000D_
    _x000D_
    .container {_x000D_
      background: blue;_x000D_
      padding: 10px;_x000D_
      max-height: 200px;_x000D_
      max-width: 200px;_x000D_
      float: left;_x000D_
      margin-right: 20px;_x000D_
    }_x000D_
    _x000D_
    .img1 {_x000D_
      display: block;_x000D_
      max-height: 100%;_x000D_
      max-width: 100%;_x000D_
    }_x000D_
    _x000D_
    .img2 {_x000D_
      display: block;_x000D_
      max-height: inherit;_x000D_
      max-width: inherit;_x000D_
    }
    _x000D_
    <!-- example 1  -->_x000D_
    <div class="container">_x000D_
      <img class='img1' src="http://via.placeholder.com/350x450" />_x000D_
    </div>_x000D_
    _x000D_
    <!-- example 2  -->_x000D_
    _x000D_
    <div class="container">_x000D_
      <img class='img2' src="http://via.placeholder.com/350x450" />_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    I played around a little. On a larger image in firefox, I got a good result with using the inherit property value. Will this help you?

    .container {
        background: blue;
        padding: 10px;
        max-height: 100px;
        max-width: 100px;
        text-align:center;
    }
    
    img {
        max-height: inherit;
        max-width: inherit;
    }
    

    what is the difference between const_iterator and iterator?

    Performance wise there is no difference. The only purpose of having const_iterator over iterator is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:

    std::vector<int> integers{ 3, 4, 56, 6, 778 };
    

    If we were to read & write the members of a container we will use iterator:

    for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
           {*it = 4;  std::cout << *it << std::endl; }
    

    If we were to only read the members of the container integers you might wanna use const_iterator which doesn't allow to write or modify members of container.

    for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
           { cout << *it << endl; }
    

    NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.

    Streaming Audio from A URL in Android using MediaPlayer?

    Looking my projects:

    1. https://github.com/master255/ImmortalPlayer http/FTP support, One thread to read, send and save to cache data. Most simplest way and most fastest work. Complex logic - best way!
    2. https://github.com/master255/VideoViewCache Simple Videoview with cache. Two threads for play and save data. Bad logic, but if you need then use this.

    How to Get the HTTP Post data in C#?

    You can simply use Request["recipient"] to "read the HTTP values sent by a client during a Web request"

    To access data from the QueryString, Form, Cookies, or ServerVariables collections, you can write Request["key"]

    Source: MSDN

    Update: Summarizing conversation

    In order to view the values that MailGun is posting to your site you will need to read them from the web request that MailGun is making, record them somewhere and then display them on your page.

    You should have one endpoint where MailGun will send the POST values to and another page that you use to view the recorded values.

    It appears that right now you have one page. So when you view this page, and you read the Request values, you are reading the values from YOUR request, not MailGun.

    Selenium WebDriver How to Resolve Stale Element Reference Exception?

    Use the Expected Conditions provided by Selenium to wait for the WebElement.

    While you debug, the client is not as fast as if you just run a unit test or a maven build. This means in debug mode the client has more time to prepare the element, but if the build is running the same code he is much faster and the WebElement your looking for is might not visible in the DOM of the Page.

    Trust me with this, I had the same problem.

    for example:

    inClient.waitUntil(ExpectedConditions.visibilityOf(YourElement,2000))
    

    This easy method calls wait after his call for 2 seconds on the visibility of your WebElement on DOM.

    React Native absolute positioning horizontal centre

    <View style={{...StyleSheet.absoluteFillObject, justifyContent: 'center', alignItems: 'center'}}>
      <Text>CENTERD TEXT</Text>
    </View>
    

    And add this

    import {StyleSheet} from 'react-native';
    

    JQuery $.ajax() post - data in a java servlet

    For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:

      &A2168=1&A1837=5&A8472=1&A1987=2
    

    On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:

    Enumeration keys = request.getParameterNames(); 
    HashMap map = new HashMap(); 
    String key = null; 
    while(keys.hasMoreElements()){ 
          key = keys.nextElement().toString(); 
          map.put(key, request.getParameter(key)); 
    }
    

    spring autowiring with unique beans: Spring expected single matching bean but found 2

    If you have 2 beans of the same class autowired to one class you shoud use @Qualifier (Spring Autowiring @Qualifier example).

    But it seems like your problem comes from incorrect Java Syntax.

    Your object should start with lower case letter

    SuggestionService suggestion;
    

    Your setter should start with lower case as well and object name should be with Upper case

    public void setSuggestion(final Suggestion suggestion) {
        this.suggestion = suggestion;
    }
    

    How to split (chunk) a Ruby array into parts of X elements?

    If you're using rails you can also use in_groups_of:

    foo.in_groups_of(3)
    

    Java image resize, maintain aspect ratio

    public class ImageTransformation {
    
    public static final String PNG = "png";
    
    public static byte[] resize(FileItem fileItem, int width, int height) {
    
        try {
            ResampleOp resampleOp = new ResampleOp(width, height);
            BufferedImage scaledImage = resampleOp.filter(ImageIO.read(fileItem.getInputStream()), null);
    
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(scaledImage, PNG, baos);
    
            return baos.toByteArray();
        } catch (Exception ex) {
            throw new MapsException("An error occured during image resizing.", ex);
        }
    
    }
    
    public static byte[] resizeAdjustMax(FileItem fileItem, int maxWidth, int maxHeight) {
    
        try {
            BufferedInputStream bis = new BufferedInputStream(fileItem.getInputStream());  
            BufferedImage bufimg = ImageIO.read(bis);   
    
            //check size of image 
            int img_width = bufimg.getWidth();
            int img_height = bufimg.getHeight();
            if(img_width > maxWidth || img_height > maxHeight) {
                float factx = (float) img_width / maxWidth;
                float facty = (float) img_height / maxHeight;
                float fact = (factx>facty) ? factx : facty;
                img_width = (int) ((int) img_width / fact);
                img_height = (int) ((int) img_height / fact);
            }
    
            return resize(fileItem,img_width, img_height);
    
        } catch (Exception ex) {
            throw new MapsException("An error occured during image resizing.", ex);
        }
    
    }
    

    }

    Remove last character from C++ string

    That's all you need:

    #include <string>  //string::pop_back & string::empty
    
    if (!st.empty())
        st.pop_back();
    

    Wrapping long text without white space inside of a div

    I have found something strange here about word-wrap only works with width property of CSS properly.

    _x000D_
    _x000D_
    #ONLYwidth {_x000D_
      width: 200px;_x000D_
    }_x000D_
    _x000D_
    #wordwrapWITHOUTWidth {_x000D_
      word-wrap: break-word;_x000D_
    }_x000D_
    _x000D_
    #wordwrapWITHWidth {_x000D_
      width: 200px;_x000D_
      word-wrap: break-word;_x000D_
    }
    _x000D_
    <b>This is the example of word-wrap only using width property</b>_x000D_
    <p id="ONLYwidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>_x000D_
    <br/>_x000D_
    <b>This is the example of word-wrap without width property</b>_x000D_
    <p id="wordwrapWITHOUTWidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>_x000D_
    <br/>_x000D_
    <b>This is the example of word-wrap with width property</b>_x000D_
    <p id="wordwrapWITHWidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>
    _x000D_
    _x000D_
    _x000D_

    Here is a working demo that I have prepared about it. http://jsfiddle.net/Hss5g/2/

    How to print spaces in Python?

    rjust() and ljust()

    test_string = "HelloWorld"
    
    test_string.rjust(20)
    '          HelloWorld'
    
    test_string.ljust(20)
    'HelloWorld          '
    

    List of all index & index columns in SQL Server DB

    sELECT 
         TableName = t.name,
         IndexName = ind.name,
         --IndexId = ind.index_id,
         ColumnId = ic.index_column_id,
         ColumnName = col.name,
         key_ordinal,
         ind.type_desc
         --ind.*,
         --ic.*,
         --col.* 
    FROM 
         sys.indexes ind 
    INNER JOIN 
         sys.index_columns ic ON  ind.object_id = ic.object_id and ind.index_id = ic.index_id 
    INNER JOIN 
         sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id 
    INNER JOIN 
         sys.tables t ON ind.object_id = t.object_id 
    WHERE 
         ind.is_primary_key = 0 
         AND ind.is_unique = 0 
         AND ind.is_unique_constraint = 0 
         AND t.is_ms_shipped = 0 
         and t.name='CompanyReconciliation' --table name
         and key_ordinal>0
    ORDER BY 
         t.name, ind.name, ind.index_id, ic.index_column_id 
    

    What is a good Hash Function?

    This is an example of a good one and also an example of why you would never want to write one. It is a Fowler / Noll / Vo (FNV) Hash which is equal parts computer science genius and pure voodoo:

    unsigned fnv_hash_1a_32 ( void *key, int len ) {
        unsigned char *p = key;
        unsigned h = 0x811c9dc5;
        int i;
    
        for ( i = 0; i < len; i++ )
          h = ( h ^ p[i] ) * 0x01000193;
    
       return h;
    }
    
    unsigned long long fnv_hash_1a_64 ( void *key, int len ) {
        unsigned char *p = key;
        unsigned long long h = 0xcbf29ce484222325ULL;
        int i;
    
        for ( i = 0; i < len; i++ )
          h = ( h ^ p[i] ) * 0x100000001b3ULL;
    
       return h;
    }
    

    Edit:

    • Landon Curt Noll recommends on his site the FVN-1A algorithm over the original FVN-1 algorithm: The improved algorithm better disperses the last byte in the hash. I adjusted the algorithm accordingly.

    Disable button in angular with two conditions?

    In addition to the other answer, I would like to point out that this reasoning is also known as the De Morgan's law. It's actually more about mathematics than programming, but it is so fundamental that every programmer should know about it.

    Your problem started like this:

    enabled  = A and B
    disabled = not ( A and B )
    

    So far so good, but you went one step further and tried to remove the braces. And that's a little tricky, because you have to replace the and/&& with an or/||.

    not ( A and B ) = not(A) OR not(B)
    

    Or in a more mathematical notation:

    enter image description here

    I always keep this law in mind whenever I simplify conditions or work with probabilities.

    Embedding DLLs in a compiled executable

    Another product that can handle this elegantly is SmartAssembly, at SmartAssembly.com. This product will, in addition to merging all dependencies into a single DLL, (optionally) obfuscate your code, remove extra meta-data to reduce the resulting file size, and can also actually optimize the IL to increase runtime performance.

    There is also some kind of global exception handling/reporting feature it adds to your software (if desired) that could be useful. I believe it also has a command-line API so you can make it part of your build process.

    Create a git patch from the uncommitted changes in the current working directory

    If you want to do binary, give a --binary option when you run git diff.

    Turning multi-line string into single comma-separated

    You can use grep:

    grep -o "+\S\+" in.txt | tr '\n' ','
    

    which finds the string starting with +, followed by any string \S\+, then convert new line characters into commas. This should be pretty quick for large files.

    Code-first vs Model/Database-first

    I think one of the Advantages of code first is that you can back up all the changes you've made to a version control system like Git. Because all your tables and relationships are stored in what are essentially just classes, you can go back in time and see what the structure of your database was before.

    How to maintain aspect ratio using HTML IMG tag

    The poster is showing a dimension constrained by height in most cases he posted >>> (256x256, 1024x768, 500x400, 205x246, etc.) but fitting a 64px max height pixel dimension, typical of most landscape "photos". So my guess is he wants an image that is always 64 pixels in height. To achieve that, do the following:

    <img id="photo1" style="height:64px;width:auto;" src="photo.jpg" height="64" />
    

    This solution guarantees the images are all 64 pixels max in height and allows width to extend or shrink based on each image's aspect ratio. Setting height to 64 in the img height attribute reserves a space in the browser's Rendertree layout as images download, so the content doesn't shift waiting for images to download. Also, the new HTML5 standard does not always honor width and height attributes. They are dimensional "hints" only, not final dimensions of the image. If in your style sheet you reset or change the image height and width, the actual values in the images attributes get reset to either your CSS value or the images native default dimensions. Setting the CSS height to "64px" and the width to "auto" forces width to start with the native image width (not image attribute width) and then calculate a new aspect-ratio using the CSS style for height. That gets you a new width. So the height and width "img" attributes are really not needed here and just force the browser to do extra calculations.

    ValueError: Wrong number of items passed - Meaning and suggestions?

    Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.

    C#: Printing all properties of an object

    Following snippet will do the desired function:

    Type t = obj.GetType(); // Where obj is object whose properties you need.
    PropertyInfo [] pi = t.GetProperties();
    foreach (PropertyInfo p in pi)
    {
        System.Console.WriteLine(p.Name + " : " + p.GetValue(obj));
    }
    

    I think if you write this as extension method you could use it on all type of objects.

    C# how to convert File.ReadLines into string array?

    File.ReadLines() returns an object of type System.Collections.Generic.IEnumerable<String>
    File.ReadAllLines() returns an array of strings.

    If you want to use an array of strings you need to call the correct function.

    You could use Jim solution, just use ReadAllLines() or you could change your return type.

    This would also work:

    System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("c:\\file.txt");
    

    You can use any generic collection which implements IEnumerable. IList for an example.

    How to delete all files and folders in a directory?

    Here is the tool I ended with after reading all posts. It does

    • Deletes all that can be deleted
    • Returns false if some files remain in folder

    It deals with

    • Readonly files
    • Deletion delay
    • Locked files

    It doesn't use Directory.Delete because the process is aborted on exception.

        /// <summary>
        /// Attempt to empty the folder. Return false if it fails (locked files...).
        /// </summary>
        /// <param name="pathName"></param>
        /// <returns>true on success</returns>
        public static bool EmptyFolder(string pathName)
        {
            bool errors = false;
            DirectoryInfo dir = new DirectoryInfo(pathName);
    
            foreach (FileInfo fi in dir.EnumerateFiles())
            {
                try
                {
                    fi.IsReadOnly = false;
                    fi.Delete();
    
                    //Wait for the item to disapear (avoid 'dir not empty' error).
                    while (fi.Exists)
                    {
                        System.Threading.Thread.Sleep(10);
                        fi.Refresh();
                    }
                }
                catch (IOException e)
                {
                    Debug.WriteLine(e.Message);
                    errors = true;
                }
            }
    
            foreach (DirectoryInfo di in dir.EnumerateDirectories())
            {
                try
                {
                    EmptyFolder(di.FullName);
                    di.Delete();
    
                    //Wait for the item to disapear (avoid 'dir not empty' error).
                    while (di.Exists)
                    {
                        System.Threading.Thread.Sleep(10);
                        di.Refresh();
                    }
                }
                catch (IOException e)
                {
                    Debug.WriteLine(e.Message);
                    errors = true;
                }
            }
    
            return !errors;
        }
    

    Convert list of ints to one number?

    This seems pretty clean, to me.

    def magic( aList, base=10 ):
        n= 0
        for d in aList:
            n = base*n + d
        return n
    

    Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

    The following works perfectly:-

    if(isset($_POST['signup'])){
    $username=mysqli_real_escape_string($connect,$_POST['username']);
    $email=mysqli_real_escape_string($connect,$_POST['email']);
    $pass1=mysqli_real_escape_string($connect,$_POST['pass1']);
    $pass2=mysqli_real_escape_string($connect,$_POST['pass2']);
    

    Now, the $connect is my variable containing my connection to the database. You only left out the connection variable. Include it and it shall work perfectly.

    Setting Android Theme background color

    Open res -> values -> styles.xml and to your <style> add this line replacing with your image path <item name="android:windowBackground">@drawable/background</item>. Example:

    <resources>
    
        <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
            <!-- Customize your theme here. -->
            <item name="colorPrimary">@color/colorPrimary</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="colorAccent">@color/colorAccent</item>
            <item name="android:windowBackground">@drawable/background</item>
        </style>
    
    </resources>
    

    There is a <item name ="android:colorBackground">@color/black</item> also, that will affect not only your main window background but all the component in your app. Read about customize theme here.

    If you want version specific styles:

    If a new version of Android adds theme attributes that you want to use, you can add them to your theme while still being compatible with old versions. All you need is another styles.xml file saved in a values directory that includes the resource version qualifier. For example:

    res/values/styles.xml        # themes for all versions
    res/values-v21/styles.xml    # themes for API level 21+ only
    

    Because the styles in the values/styles.xml file are available for all versions, your themes in values-v21/styles.xml can inherit them. As such, you can avoid duplicating styles by beginning with a "base" theme and then extending it in your version-specific styles.

    Read more here(doc in theme).

    How to use sudo inside a docker container?

    If you have a container running as root that runs a script (which you can't change) that needs access to the sudo command, you can simply create a new sudo script in your $PATH that calls the passed command.

    e.g. In your Dockerfile:

    RUN if type sudo 2>/dev/null; then \ 
         echo "The sudo command already exists... Skipping."; \
        else \
         echo -e "#!/bin/sh\n\${@}" > /usr/sbin/sudo; \
         chmod +x /usr/sbin/sudo; \
        fi
    

    Why is vertical-align:text-top; not working in CSS

    The vertical-align attribute is for inline elements only. It will have no effect on block level elements, like a div. Also text-top only moves the text to the top of the current font size. If you would like to vertically align an inline element to the top just use this.

    vertical-align: top;
    

    The paragraph tag is not outdated. Also, the vertical-align attribute applied to a span element may not display as intended in some mozilla browsers.

    iOS download and save image inside app

    You cannot save anything inside the app's bundle, but you can use +[NSData dataWithContentsOfURL:] to store the image in your app's documents directory, e.g.:

    NSData *imageData = [NSData dataWithContentsOfURL:myImageURL];
    NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];
    [imageData writeToFile:imagePath atomically:YES];
    

    Not exactly permanent, but it stays there at least until the user deletes the app.

    Inserting string at position x of another string

    Quick fix! If you don't want to manually add a space, you can do this:

    _x000D_
    _x000D_
    var a = "I want apple";_x000D_
    var b = "an";_x000D_
    var position = 6;_x000D_
    var output = [a.slice(0, position + 1), b, a.slice(position)].join('');_x000D_
    console.log(output);
    _x000D_
    _x000D_
    _x000D_

    (edit: i see that this is actually answered above, sorry!)

    MySQL Error #1133 - Can't find any matching row in the user table

    I encountered this error using MySQL in a different context (not within phpMyAdmin). GRANT and SET PASSWORD commands failed on a particular existing user, who was listed in the mysql.user table. In my case, it was fixed by running

    FLUSH PRIVILEGES;
    

    The documentation for this command says

    Reloads the privileges from the grant tables in the mysql database.

    The server caches information in memory as a result of GRANT and CREATE USER statements. This memory is not released by the corresponding REVOKE and DROP USER statements, so for a server that executes many instances of the statements that cause caching, there will be an increase in memory use. This cached memory can be freed with FLUSH PRIVILEGES.

    Apparently the user table cache had reached an inconsistent state, causing this weird error message. More information is available here.

    How to convert Varchar to Double in sql?

    use DECIMAL() or NUMERIC() as they are fixed precision and scale numbers.

    SELECT fullName, 
           CAST(totalBal as DECIMAL(9,2)) _totalBal
    FROM client_info 
    ORDER BY _totalBal DESC
    

    Regular Expression with wildcards to match any character

    Without knowing the exact regex implementation you're making use of, I can only give general advice. (The syntax I will be perl as that's what I know, some languages will require tweaking)

    Looking at ABC: (z) jan 02 1999 \n

    • The first thing to match is ABC: So using our regex is /ABC:/

    • You say ABC is always at the start of the string so /^ABC/ will ensure that ABC is at the start of the string.

    • You can match spaces with the \s (note the case) directive. With all directives you can match one or more with + (or 0 or more with *)

    • You need to escape the usage of ( and ) as it's a reserved character. so \(\)

    • You can match any non space or newline character with .

    • You can match anything at all with .* but you need to be careful you're not too greedy and capture everything.

    So in order to capture what you've asked. I would use /^ABC:\s*\(.+?\)\s*(.+)$/

    Which I read as:

    Begins with ABC:

    May have some spaces

    has (

    has some characters

    has )

    may have some spaces

    then capture everything until the end of the line (which is $).

    I highly recommend keeping a copy of the following laying about http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

    Convert serial.read() into a useable string using Arduino?

    Unlimited string readed:

    String content = "";
    char character;
        
    while(Serial.available()) {
         character = Serial.read();
         content.concat(character);
    }
          
    if (content != "") {
         Serial.println(content);
    }
    

    Java Pass Method as Parameter

    In Java 8, you can now pass a method more easily using Lambda Expressions and Method References. First, some background: a functional interface is an interface that has one and only one abstract method, although it can contain any number of default methods (new in Java 8) and static methods. A lambda expression can quickly implement the abstract method, without all the unnecessary syntax needed if you don't use a lambda expression.

    Without lambda expressions:

    obj.aMethod(new AFunctionalInterface() {
        @Override
        public boolean anotherMethod(int i)
        {
            return i == 982
        }
    });
    

    With lambda expressions:

    obj.aMethod(i -> i == 982);
    

    Here is an excerpt from the Java tutorial on Lambda Expressions:

    Syntax of Lambda Expressions

    A lambda expression consists of the following:

    • A comma-separated list of formal parameters enclosed in parentheses. The CheckPerson.test method contains one parameter, p, which represents an instance of the Person class.

      Note: You can omit the data type of the parameters in a lambda expression. In addition, you can omit the parentheses if there is only one parameter. For example, the following lambda expression is also valid:

      p -> p.getGender() == Person.Sex.MALE 
          && p.getAge() >= 18
          && p.getAge() <= 25
      
    • The arrow token, ->

    • A body, which consists of a single expression or a statement block. This example uses the following expression:

      p.getGender() == Person.Sex.MALE 
          && p.getAge() >= 18
          && p.getAge() <= 25
      

      If you specify a single expression, then the Java runtime evaluates the expression and then returns its value. Alternatively, you can use a return statement:

      p -> {
          return p.getGender() == Person.Sex.MALE
              && p.getAge() >= 18
              && p.getAge() <= 25;
      }
      

      A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). However, you do not have to enclose a void method invocation in braces. For example, the following is a valid lambda expression:

      email -> System.out.println(email)
      

    Note that a lambda expression looks a lot like a method declaration; you can consider lambda expressions as anonymous methods—methods without a name.


    Here is how you can "pass a method" using a lambda expression:

    interface I {
        public void myMethod(Component component);
    }
    
    class A {
        public void changeColor(Component component) {
            // code here
        }
    
        public void changeSize(Component component) {
            // code here
        }
    }
    
    class B {
        public void setAllComponents(Component[] myComponentArray, I myMethodsInterface) {
            for(Component leaf : myComponentArray) {
                if(leaf instanceof Container) { // recursive call if Container
                    Container node = (Container)leaf;
                    setAllComponents(node.getComponents(), myMethodInterface);
                } // end if node
                myMethodsInterface.myMethod(leaf);
            } // end looping through components
        }
    }
    
    class C {
        A a = new A();
        B b = new B();
    
        public C() {
            b.setAllComponents(this.getComponents(), component -> a.changeColor(component));
            b.setAllComponents(this.getComponents(), component -> a.changeSize(component));
        }
    }
    

    Class C can be shortened even a bit further by the use of method references like so:

    class C {
        A a = new A();
        B b = new B();
    
        public C() {
            b.setAllComponents(this.getComponents(), a::changeColor);
            b.setAllComponents(this.getComponents(), a::changeSize);
        }
    }
    

    SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

    Many time this error is caused when you update a product in your custom module's observer as shown below.

    class [NAMESPACE]_[MODULE NAME]_Model_Observer
    {
        /**
         * Flag to stop observer executing more than once
         *
         * @var static bool
         */
        static protected $_singletonFlag = false;
    
        public function saveProductData(Varien_Event_Observer $observer)
        {
            if (!self::$_singletonFlag) {
                self::$_singletonFlag = true;
    
                $product = $observer->getEvent()->getProduct();
                 //do stuff to the $product object
                // $product->save();  // commenting out this line prevents the error
                $product->getResource()->save($product);
        }
    } 
    

    Hence whenever you save your product after updating some properties in your module's observer use $product->getResource()->save($product) instead of $product->save()

    Conversion failed when converting date and/or time from character string while inserting datetime

    Simple answer - 5 is Italian "yy" and 105 is Italian "yyyy". Therefore:

    SELECT convert(datetime,'21-02-12 6:10:00 PM',5)
    

    will work correctly, but

    SELECT convert(datetime,'21-02-12 6:10:00 PM',105)
    

    will give error.

    Likewise,

    SELECT convert(datetime,'21-02-2012 6:10:00 PM',5)
    

    will give error, where as

    SELECT convert(datetime,'21-02-2012 6:10:00 PM',105)
    

    will work.

    How to get package name from anywhere?

    For those who are using Gradle, as @Billda mentioned, you can get the package name via:

    BuildConfig.APPLICATION_ID
    

    This gives you the package name declared in your app gradle:

    android {
        defaultConfig {
            applicationId "com.domain.www"
        }
    }
    

    If you are interested to get the package name used by your java classes (which sometimes is different than applicationId), you can use

    BuildConfig.class.getPackage().toString()
    

    If you are confused which one to use, read here:

    Note: The application ID used to be directly tied to your code's package name; so some Android APIs use the term "package name" in their method names and parameter names, but this is actually your application ID. For example, the Context.getPackageName() method returns your application ID. There's no need to ever share your code's true package name outside your app code.

    Simplest way to form a union of two lists

    If it is two IEnumerable lists you can't use AddRange, but you can use Concat.

    IEnumerable<int> first = new List<int>{1,1,2,3,5};
    IEnumerable<int> second = new List<int>{8,13,21,34,55};
    
    var allItems = first.Concat(second);
    // 1,1,2,3,5,8,13,21,34,55
    

    Could not load file or assembly 'System.Data.SQLite'

    System.Data.SQLite has a dependency on System.Data.SQLite.interop make sure both packages are the same version and are both x86.

    This is an old question, but I tried all the above. I was working on a strictly x86 project, so there was not two folders /x86, /x64. But for some reason, the System.Data.SQLite was a different version to System.Data.SQLite.interop, once I pulled down matching dlls the problem was fixed.

    Understanding PIVOT function in T-SQL

    To set Compatibility error

    use this before using pivot function

    ALTER DATABASE [dbname] SET COMPATIBILITY_LEVEL = 100  
    

    VBA - how to conditionally skip a for loop iteration

    Hi I am also facing this issue and I solve this using below example code

    For j = 1 To MyTemplte.Sheets.Count
    
           If MyTemplte.Sheets(j).Visible = 0 Then
               GoTo DoNothing        
           End If 
    
    
    'process for this for loop
    DoNothing:
    
    Next j 
    

    Convert date to UTC using moment.js

    This will be the answer:

    moment.utc(moment(localdate)).format()
    
    localdate = '2020-01-01 12:00:00'
    
    moment(localdate)
    //Moment<2020-01-01T12:00:00+08:00>
    
    moment.utc(moment(localdate)).format()
    //2020-01-01T04:00:00Z
    

    Running Command Line in Java

    what about

    public class CmdExec {
    
    public static Scanner s = null;
    
    
    public static void main(String[] args) throws InterruptedException, IOException {
        s = new Scanner(System.in);
        System.out.print("$ ");
        String cmd = s.nextLine();
        final Process p = Runtime.getRuntime().exec(cmd);
    
        new Thread(new Runnable() {
            public void run() {
                BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = null; 
    
                try {
                    while ((line = input.readLine()) != null) {
                        System.out.println(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    
        p.waitFor();
         }
    
     }
    

    reStructuredText tool support

    Salvaging (and extending) the list from an old version of the Wikipedia page:

    Documentation

    Implementations

    Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.

    Python - Docutils

    The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:

    • rst2html - from reStructuredText to HTML
    • rst2xml - from reStructuredText to XML
    • rst2latex - from reStructuredText to LaTeX
    • rst2odt - from reStructuredText to ODF Text (word processor) document.
    • rst2s5 - from reStructuredText to S5, a Simple Standards-based Slide Show System
    • rst2man - from reStructuredText to Man page

    Haskell - Pandoc

    Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.

    There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),

    • POT truncates input rather more shortly. The POT user must render input in chunks that could be rendered whole by the ROR.
    • POT output lacks the helpful error messages displayed by the ROR (and generated by docutils)

    Java - JRst

    JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.

    Scala - Laika

    Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.

    Perl

    PHP

    C#/.NET

    Nim/C

    The Nim compiler features the commands rst2htmland rst2tex which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:

    • rst - implements a reStructuredText parser
    • rstast - implements an AST for the reStructuredText parser
    • rstgen - implements a generator of HTML/Latex from reStructuredText

    Other 3rd party converters

    Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.

    From reStructuredText

    • restview - This pip-installable python package requires docutils, which does the actual rendering. restview's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
      1. starts a small web server
      2. calls docutils to render your document(s) to HTML
      3. calls your device's browser to display the output HTML.
    • rst2pdf - from reStructuredText to PDF
    • rst2odp - from reStructuredText to ODF Presentation
    • rst2beamer - from reStructuredText to LaTeX beamer Presentation class
    • Wikir - from reStructuredText to a Google (and possibly other) Wiki formats
    • rst2qhc - Convert a collection of reStructuredText files into a Qt (toolkit) Help file and (optional) a Qt Help Project file

    To reStructuredText

    • xml2rst is an XSLT script to convert Docutils internal XML representation (back) to reStructuredText
    • Pandoc (see above) can also convert from Markdown, HTML and LaTeX to reStructuredText
    • db2rst is a simple and limited DocBook to reStructuredText translator
    • pod2rst - convert .pod files to reStructuredText files

    Extensions

    Some projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.

    Sphinx

    The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.

    rest2web

    rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.

    Pygments

    Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.

    Free Editors

    While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.

    Emacs

    The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el

    Vim

    The vim-common package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:

    Jed

    There is a rst mode for the Jed programmers editor.

    gedit

    gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.

    Geany

    Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).

    Leo

    Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).

    It also provides a way to preview the resulting HTML, in a "viewrendered" pane.

    FTE

    The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.

    PyK

    PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.

    Eclipse

    The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.

    NoTex

    NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.

    Notepad++

    Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.

    Visual Studio Code

    Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.

    Dedicated reStructuredText Editors

    Proprietary editors

    Sublime Text

    Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.

    BBEdit / TextWrangler

    BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.

    TextMate

    TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.

    Intype

    Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.

    E Text Editor

    E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.

    PyCharm

    PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).instant preview)

    Wiki

    here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:

    MediaWiki

    MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst> and </rst>.

    MoinMoin

    MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.

    There is a reStructuredText Parser for MoinMoin.

    Trac

    Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.

    This Wiki

    This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.

    rstiki

    rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.

    ikiwiki

    Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.

    Web Services

    Sandbox

    An Online reStructuredText editor can be used to play with the markup and see the results immediately.

    Blogging frameworks

    WordPress

    WordPreSt reStructuredText plugin for WordPress. (PHP)

    Zine

    reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)

    pelican

    Pelican is a static blog generator that supports writing articles in ReST. (Python)

    hyde

    Hyde is a static website generator that supports ReST. (Python)

    Acrylamid

    Acrylamid is a static blog generator that supports writing articles in ReST. (Python)

    Nikola

    Nikola is a Static Site and Blog Generator that supports ReST. (Python)

    ipsum genera

    Ipsum genera is a static blog generator written in Nim.

    Yozuch

    Yozuch is a static blog generator written in Python.

    More

    Sending Windows key using SendKeys

    SetForegroundWindow( /* window to gain focus */ );
    SendKeys.SendWait("^{ESC}"); // ^{ESC} is code for ctrl + esc which mimics the windows key.
    

    Use of min and max functions in C++

    fmin and fmax are only for floating point and double variables.

    min and max are template functions that allow comparison of any types, given a binary predicate. They can also be used with other algorithms to provide complex functionality.

    getting the reason why websockets closed with close code 1006

    In my and possibly @BIOHAZARD case it was nginx proxy timeout. In default it's 60 sec without activity in socket

    I changed it to 24h in nginx and it resolved problem

    proxy_read_timeout 86400s;
    proxy_send_timeout 86400s;
    

    Resolving instances with ASP.NET Core DI from within ConfigureServices

    Manually resolving instances involves using the IServiceProvider interface:

    Resolving Dependency in Startup.ConfigureServices

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<IMyService, MyService>();
    
        var serviceProvider = services.BuildServiceProvider();
        var service = serviceProvider.GetService<IMyService>();
    }
    

    Resolving Dependencies in Startup.Configure

    public void Configure(
        IApplicationBuilder application,
        IServiceProvider serviceProvider)
    {
        // By type.
        var service1 = (MyService)serviceProvider.GetService(typeof(MyService));
    
        // Using extension method.
        var service2 = serviceProvider.GetService<MyService>();
    
        // ...
    }
    

    Resolving Dependencies in Startup.Configure in ASP.NET Core 3

    public void Configure(
        IApplicationBuilder application,
        IWebHostEnvironment webHostEnvironment)
    {
        application.ApplicationServices.GetService<MyService>();
    }
    

    Using Runtime Injected Services

    Some types can be injected as method parameters:

    public class Startup
    {
        public Startup(
            IHostingEnvironment hostingEnvironment,
            ILoggerFactory loggerFactory)
        {
        }
    
        public void ConfigureServices(
            IServiceCollection services)
        {
        }
    
        public void Configure(
            IApplicationBuilder application,
            IHostingEnvironment hostingEnvironment,
            IServiceProvider serviceProvider,
            ILoggerFactory loggerfactory,
            IApplicationLifetime applicationLifetime)
        {
        }
    }
    

    Resolving Dependencies in Controller Actions

    [HttpGet("/some-action")]
    public string SomeAction([FromServices] IMyService myService) => "Hello";
    

    TypeError: ObjectId('') is not JSON serializable

    in my case I needed something like this:

    class JsonEncoder():
        def encode(self, o):
            if '_id' in o:
                o['_id'] = str(o['_id'])
            return o
    

    Is it possible to pull just one file in Git?

    git checkout master -- myplugin.js
    

    master = branch name

    myplugin.js = file name

    JavaScript, get date of the next day

    You can use:

    var tomorrow = new Date();
    tomorrow.setDate(new Date().getDate()+1);
    

    For example, since there are 30 days in April, the following code will output May 1:

    var day = new Date('Apr 30, 2000');
    console.log(day); // Apr 30 2000
    
    var nextDay = new Date(day);
    nextDay.setDate(day.getDate() + 1);
    console.log(nextDay); // May 01 2000    
    

    See fiddle.

    How can I present a file for download from an MVC controller?

    Use .ashx file type and use the same code

    Passing multiple values to a single PowerShell script parameter

    Parameters take input before arguments. What you should do instead is add a parameter that accepts an array, and make it the first position parameter. ex:

    param(
        [Parameter(Position = 0)]
        [string[]]$Hosts,
        [string]$VLAN
        )
    
    foreach ($i in $Hosts)  
    { 
        Do-Stuff $i
    }
    

    Then call it like:

    .\script.ps1 host1, host2, host3 -VLAN 2
    

    Notice the comma between the values. This collects them in an array

    How permission can be checked at runtime without throwing SecurityException?

    Enable GPS location Android Studio

    1. Add permission entry in AndroidManifest.Xml

    1. MapsActivity.java

      public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
      
      private GoogleMap mMap;
      private Context context;
      private static final int PERMISSION_REQUEST_CODE = 1;
      Activity activity;
      /**
       * ATTENTION: This was auto-generated to implement the App Indexing API.
       * See https://g.co/AppIndexing/AndroidStudio for more information.
       */
      private GoogleApiClient client;
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          context = getApplicationContext();
          activity = this;
          super.onCreate(savedInstanceState);
          requestPermission();
          checkPermission();
          setContentView(R.layout.activity_maps);
          // Obtain the SupportMapFragment and get notified when the map is ready to be used.
          SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                  .findFragmentById(R.id.map);
          mapFragment.getMapAsync(this);
      
      }
      
      @Override
      public void onMapReady(GoogleMap googleMap) {
          mMap = googleMap;
          LatLng location = new LatLng(0, 0);
          mMap.addMarker(new MarkerOptions().position(location).title("Marker in Bangalore"));
          mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
          mMap.setMyLocationEnabled(true);
      }
      
      private void requestPermission() {
          if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
              Toast.makeText(context, "GPS permission allows us to access location data. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
          } else {
              ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
          }
      }
      
      private boolean checkPermission() {
          int result = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
          if (result == PackageManager.PERMISSION_GRANTED) {
              return true;
          } else {
              return false;
          }
      }
      

    ERROR: Cannot open source file " "

    1. Copy the contents of the file,
    2. Create an .h file, give it the name of the original .h file
    3. Copy the contents of the original file to the newly created one
    4. Build it
    5. VOILA!!

    How to check if an integer is within a range?

    Tested your 3 ways with a 1000000-times-loop.

    t1_test1: ($val >= $min && $val <= $max): 0.3823 ms

    t2_test2: (in_array($val, range($min, $max)): 9.3301 ms

    t3_test3: (max(min($var, $max), $min) == $val): 0.7272 ms

    T1 was fastest, it was basicly this:

    function t1($val, $min, $max) {
      return ($val >= $min && $val <= $max);
    }
    

    Open a link in browser with java button?

    public static void openWebPage(String url) {
        try {
            Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
            if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
                desktop.browse(new URI(url));
            }
            throw new NullPointerException();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, url, "", JOptionPane.PLAIN_MESSAGE);
        }
    }
    

    Object of custom type as dictionary key

    An alternative in Python 2.6 or above is to use collections.namedtuple() -- it saves you writing any special methods:

    from collections import namedtuple
    MyThingBase = namedtuple("MyThingBase", ["name", "location"])
    class MyThing(MyThingBase):
        def __new__(cls, name, location, length):
            obj = MyThingBase.__new__(cls, name, location)
            obj.length = length
            return obj
    
    a = MyThing("a", "here", 10)
    b = MyThing("a", "here", 20)
    c = MyThing("c", "there", 10)
    a == b
    # True
    hash(a) == hash(b)
    # True
    a == c
    # False
    

    How to run a command as a specific user in an init script?

    On RHEL systems, the /etc/rc.d/init.d/functions script is intended to provide similar to what you want. If you source that at the top of your init script, all of it's functions become available.

    The specific function provided to help with this is daemon. If you are intending to use it to start a daemon-like program, a simple usage would be:

    daemon --user=username command
    

    If that is too heavy-handed for what you need, there is runuser (see man runuser for full info; some versions may need -u prior to the username):

    /sbin/runuser username -s /bin/bash -c "command(s) to run as user username"
    

    Wipe data/Factory reset through ADB

    After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

     * The arguments which may be supplied in the recovery.command file:
     *   --send_intent=anystring - write the text out to recovery.intent
     *   --update_package=path - verify install an OTA package file
     *   --wipe_data - erase user data (and cache), then reboot
     *   --wipe_cache - wipe cache (but not user data), then reboot
     *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
    

    Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

    adb shell
    recovery --wipe_data
    

    Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

    EDIT:

    For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

    For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c

    Eloquent Collection: Counting and Detect Empty

    I think better to used

    $result->isEmpty();
    

    The isEmpty method returns true if the collection is empty; otherwise, false is returned.

    How to vertically center a container in Bootstrap?

    If you're using Bootstrap 4, you just have to add 2 divs:

    _x000D_
    _x000D_
    .jumbotron{_x000D_
      height:100%;_x000D_
      width:100%;_x000D_
    }
    _x000D_
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>    _x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>_x000D_
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
    _x000D_
    <body>_x000D_
      <div class="jumbotron">_x000D_
        <div class="d-table w-100 h-100">_x000D_
          <div class="d-table-cell w-100 h-100 align-middle">_x000D_
            <h5>_x000D_
              your stuff..._x000D_
            </h5>_x000D_
            <div class="container">_x000D_
              <div class="row">_x000D_
                <div class="col-12">_x000D_
                  <p>_x000D_
                    More stuff..._x000D_
                  </p>_x000D_
                </div>_x000D_
              </div>_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </body>
    _x000D_
    _x000D_
    _x000D_

    The classes: d-table, d-table-cell, w-100, h-100 and align-middle will do the job

    Bootstrap control with multiple "data-toggle"

    When you opening modal on a tag and want show tooltip and if you implement tooltip inside tag it will show tooltip nearby tag. like this

    enter image description here

    I will suggest that use div outside a tag and use "display: inline-block;"

    <div data-toggle="tooltip" title="" data-original-title="Add" style=" display inline-block;">
        <a class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="setSelectedRoleId(6)">
         <span class="fa fa-plus"></span>
        </a>
    </div>
    

    enter image description here

    Cannot GET / Nodejs Error

    I think you're missing your routes, you need to define at least one route for example '/' to index.

    e.g.

    app.get('/', function (req, res) {
      res.render('index', {});
    });
    

    How to set the background image of a html 5 canvas to .png image

    You can give the background image in css :

    #canvas { background:url(example.jpg) }
    

    it will show you canvas back ground image

    How to get string objects instead of Unicode from JSON?

    A solution with object_hook

    import json
    
    def json_load_byteified(file_handle):
        return _byteify(
            json.load(file_handle, object_hook=_byteify),
            ignore_dicts=True
        )
    
    def json_loads_byteified(json_text):
        return _byteify(
            json.loads(json_text, object_hook=_byteify),
            ignore_dicts=True
        )
    
    def _byteify(data, ignore_dicts = False):
        # if this is a unicode string, return its string representation
        if isinstance(data, unicode):
            return data.encode('utf-8')
        # if this is a list of values, return list of byteified values
        if isinstance(data, list):
            return [ _byteify(item, ignore_dicts=True) for item in data ]
        # if this is a dictionary, return dictionary of byteified keys and values
        # but only if we haven't already byteified it
        if isinstance(data, dict) and not ignore_dicts:
            return {
                _byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True)
                for key, value in data.iteritems()
            }
        # if it's anything else, return it in its original form
        return data
    

    Example usage:

    >>> json_loads_byteified('{"Hello": "World"}')
    {'Hello': 'World'}
    >>> json_loads_byteified('"I am a top-level string"')
    'I am a top-level string'
    >>> json_loads_byteified('7')
    7
    >>> json_loads_byteified('["I am inside a list"]')
    ['I am inside a list']
    >>> json_loads_byteified('[[[[[[[["I am inside a big nest of lists"]]]]]]]]')
    [[[[[[[['I am inside a big nest of lists']]]]]]]]
    >>> json_loads_byteified('{"foo": "bar", "things": [7, {"qux": "baz", "moo": {"cow": ["milk"]}}]}')
    {'things': [7, {'qux': 'baz', 'moo': {'cow': ['milk']}}], 'foo': 'bar'}
    >>> json_load_byteified(open('somefile.json'))
    {'more json': 'from a file'}

    How does this work and why would I use it?

    Mark Amery's function is shorter and clearer than these ones, so what's the point of them? Why would you want to use them?

    Purely for performance. Mark's answer decodes the JSON text fully first with unicode strings, then recurses through the entire decoded value to convert all strings to byte strings. This has a couple of undesirable effects:

    • A copy of the entire decoded structure gets created in memory
    • If your JSON object is really deeply nested (500 levels or more) then you'll hit Python's maximum recursion depth

    This answer mitigates both of those performance issues by using the object_hook parameter of json.load and json.loads. From the docs:

    object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders

    Since dictionaries nested many levels deep in other dictionaries get passed to object_hook as they're decoded, we can byteify any strings or lists inside them at that point and avoid the need for deep recursion later.

    Mark's answer isn't suitable for use as an object_hook as it stands, because it recurses into nested dictionaries. We prevent that recursion in this answer with the ignore_dicts parameter to _byteify, which gets passed to it at all times except when object_hook passes it a new dict to byteify. The ignore_dicts flag tells _byteify to ignore dicts since they already been byteified.

    Finally, our implementations of json_load_byteified and json_loads_byteified call _byteify (with ignore_dicts=True) on the result returned from json.load or json.loads to handle the case where the JSON text being decoded doesn't have a dict at the top level.

    Java: Instanceof and Generics

    Old post, but a simple way to do generic instanceOf checking.

    public static <T> boolean isInstanceOf(Class<T> clazz, Class<T> targetClass) {
        return clazz.isInstance(targetClass);
    }
    

    How do I find the install time and date of Windows?

    Press WindowsKey + R and enter cmd

    In the command window type:

    systeminfo | find /i "Original"
    

    (for older versions of windows, type "ORIGINAL" in all capital letters).

    How to change ViewPager's page?

    for switch to another page, try with this code:

    viewPager.postDelayed(new Runnable()
    {
        @Override
        public void run()
        {
            viewPager.setCurrentItem(num, true);
        }
    }, 100);
    

    How to make clang compile to llvm IR

    Given some C/C++ file foo.c:

    > clang -S -emit-llvm foo.c
    

    Produces foo.ll which is an LLVM IR file.

    The -emit-llvm option can also be passed to the compiler front-end directly, and not the driver by means of -cc1:

    > clang -cc1 foo.c -emit-llvm
    

    Produces foo.ll with the IR. -cc1 adds some cool options like -ast-print. Check out -cc1 --help for more details.


    To compile LLVM IR further to assembly, use the llc tool:

    > llc foo.ll
    

    Produces foo.s with assembly (defaulting to the machine architecture you run it on). llc is one of the LLVM tools - here is its documentation.

    Split comma separated column data into additional columns

    If the number of fields in the CSV is constant then you could do something like this:

    select a[1], a[2], a[3], a[4]
    from (
        select regexp_split_to_array('a,b,c,d', ',')
    ) as dt(a)
    

    For example:

    => select a[1], a[2], a[3], a[4] from (select regexp_split_to_array('a,b,c,d', ',')) as dt(a);
     a | a | a | a 
    ---+---+---+---
     a | b | c | d
    (1 row)
    

    If the number of fields in the CSV is not constant then you could get the maximum number of fields with something like this:

    select max(array_length(regexp_split_to_array(csv, ','), 1))
    from your_table
    

    and then build the appropriate a[1], a[2], ..., a[M] column list for your query. So if the above gave you a max of 6, you'd use this:

    select a[1], a[2], a[3], a[4], a[5], a[6]
    from (
        select regexp_split_to_array(csv, ',')
        from your_table
    ) as dt(a)
    

    You could combine those two queries into a function if you wanted.

    For example, give this data (that's a NULL in the last row):

    => select * from csvs;
         csv     
    -------------
     1,2,3
     1,2,3,4
     1,2,3,4,5,6
    
    (4 rows)
    
    => select max(array_length(regexp_split_to_array(csv, ','), 1)) from csvs;
     max 
    -----
       6
    (1 row)
    
    => select a[1], a[2], a[3], a[4], a[5], a[6] from (select regexp_split_to_array(csv, ',') from csvs) as dt(a);
     a | a | a | a | a | a 
    ---+---+---+---+---+---
     1 | 2 | 3 |   |   | 
     1 | 2 | 3 | 4 |   | 
     1 | 2 | 3 | 4 | 5 | 6
       |   |   |   |   | 
    (4 rows)
    

    Since your delimiter is a simple fixed string, you could also use string_to_array instead of regexp_split_to_array:

    select ...
    from (
        select string_to_array(csv, ',')
        from csvs
    ) as dt(a);
    

    Thanks to Michael for the reminder about this function.

    You really should redesign your database schema to avoid the CSV column if at all possible. You should be using an array column or a separate table instead.

    How to turn on front flash light programmatically in Android?

    Try this.

    CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        String cameraId = null; // Usually front camera is at 0 position.
        try {
            cameraId = camManager.getCameraIdList()[0];
            camManager.setTorchMode(cameraId, true);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    

    Set a:hover based on class

    try this

    .div
    {
    text-decoration:none;
    font-size:16;
    display:block;
    padding:14px;
    }
    
    .div a:hover
    {
    background-color:#080808;
    color:white;
    }
    

    lets say we have a anchor tag used in our code and class"div" is called in the main program. the a:hover will do the thing, it will give a vampire black color to the background and white color to the text when the mouse is moved over it that's what hover means.

    Passing an integer by reference in Python

    A numpy single-element array is mutable and yet for most purposes, it can be evaluated as if it was a numerical python variable. Therefore, it's a more convenient by-reference number container than a single-element list.

        import numpy as np
        def triple_var_by_ref(x):
            x[0]=x[0]*3
        a=np.array([2])
        triple_var_by_ref(a)
        print(a+1)
    

    output:

    3
    

    How to add a boolean datatype column to an existing table in sql?

    In SQL SERVER it is BIT, though it allows NULL to be stored

    ALTER TABLE person add  [AdminApproved] BIT default 'FALSE';
    

    Also there are other mistakes in your query

    1. When you alter a table to add column no need to mention column keyword in alter statement

    2. For adding default constraint no need to use SET keyword

    3. Default value for a BIT column can be ('TRUE' or '1') / ('FALSE' or 0). TRUE or FALSE needs to mentioned as string not as Identifier

    How can I include a YAML file inside another?

    Probably it was not supported when question was asked but you can import other YAML file into one:

    imports: [/your_location_to_yaml_file/Util.area.yaml]
    

    Though I don't have any online reference but this works for me.

    Laravel 5 – Clear Cache in Shared Hosting Server

    While I strongly disagree with the idea of running a laravel app on shared hosting (a bad idea all around), this package would likely solve your problem. It is a package that allows you to run some artisan commands from the web. It's far from perfect, but can work for some usecases.

    https://github.com/recca0120/laravel-terminal

    Proper way to initialize C++ structs

    You need to initialize whatever members you have in your struct, e.g.:

    struct MyStruct {
      private:
        int someInt_;
        float someFloat_;
    
      public:
        MyStruct(): someInt_(0), someFloat_(1.0) {} // Initializer list will set appropriate values
    
    };
    

    Python: can't assign to literal

    1 is a literal. name = value is an assignment. 1 = value is an assignment to a literal, which makes no sense. Why would you want 1 to mean something other than 1?

    How to create a shared library with cmake?

    Always specify the minimum required version of cmake

    cmake_minimum_required(VERSION 3.9)
    

    You should declare a project. cmake says it is mandatory and it will define convenient variables PROJECT_NAME, PROJECT_VERSION and PROJECT_DESCRIPTION (this latter variable necessitate cmake 3.9):

    project(mylib VERSION 1.0.1 DESCRIPTION "mylib description")
    

    Declare a new library target. Please avoid the use of file(GLOB ...). This feature does not provide attended mastery of the compilation process. If you are lazy, copy-paste output of ls -1 sources/*.cpp :

    add_library(mylib SHARED
        sources/animation.cpp
        sources/buffers.cpp
        [...]
    )
    

    Set VERSION property (optional but it is a good practice):

    set_target_properties(mylib PROPERTIES VERSION ${PROJECT_VERSION})
    

    You can also set SOVERSION to a major number of VERSION. So libmylib.so.1 will be a symlink to libmylib.so.1.0.0.

    set_target_properties(mylib PROPERTIES SOVERSION 1)
    

    Declare public API of your library. This API will be installed for the third-party application. It is a good practice to isolate it in your project tree (like placing it include/ directory). Notice that, private headers should not be installed and I strongly suggest to place them with the source files.

    set_target_properties(mylib PROPERTIES PUBLIC_HEADER include/mylib.h)
    

    If you work with subdirectories, it is not very convenient to include relative paths like "../include/mylib.h". So, pass a top directory in included directories:

    target_include_directories(mylib PRIVATE .)
    

    or

    target_include_directories(mylib PRIVATE include)
    target_include_directories(mylib PRIVATE src)
    

    Create an install rule for your library. I suggest to use variables CMAKE_INSTALL_*DIR defined in GNUInstallDirs:

    include(GNUInstallDirs)
    

    And declare files to install:

    install(TARGETS mylib
        LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
        PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
    

    You may also export a pkg-config file. This file allows a third-party application to easily import your library:

    Create a template file named mylib.pc.in (see pc(5) manpage for more information):

    prefix=@CMAKE_INSTALL_PREFIX@
    exec_prefix=@CMAKE_INSTALL_PREFIX@
    libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@
    includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
    
    Name: @PROJECT_NAME@
    Description: @PROJECT_DESCRIPTION@
    Version: @PROJECT_VERSION@
    
    Requires:
    Libs: -L${libdir} -lmylib
    Cflags: -I${includedir}
    

    In your CMakeLists.txt, add a rule to expand @ macros (@ONLY ask to cmake to not expand variables of the form ${VAR}):

    configure_file(mylib.pc.in mylib.pc @ONLY)
    

    And finally, install generated file:

    install(FILES ${CMAKE_BINARY_DIR}/mylib.pc DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)
    

    You may also use cmake EXPORT feature. However, this feature is only compatible with cmake and I find it difficult to use.

    Finally the entire CMakeLists.txt should looks like:

    cmake_minimum_required(VERSION 3.9)
    project(mylib VERSION 1.0.1 DESCRIPTION "mylib description")
    include(GNUInstallDirs)
    add_library(mylib SHARED src/mylib.c)
    set_target_properties(mylib PROPERTIES
        VERSION ${PROJECT_VERSION}
        SOVERSION 1
        PUBLIC_HEADER api/mylib.h)
    configure_file(mylib.pc.in mylib.pc @ONLY)
    target_include_directories(mylib PRIVATE .)
    install(TARGETS mylib
        LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
        PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
    install(FILES ${CMAKE_BINARY_DIR}/mylib.pc
        DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)
    

    Add space between HTML elements only using CSS

    You can take advantage of the fact that span is an inline element

    span{
         word-spacing:10px;
    }
    

    However, this solution will break if you have more than one word of text in your span

    Launch Bootstrap Modal on page load

    In addition to user2545728 and Reft answers, without javascript but with the modal-backdrop in

    3 things to add

    1. a div with the classes modal-backdrop in before the .modal class
    2. style="display:block;" to the .modal class
    3. fade in together with the .modal class

    Example

    <div class="modal-backdrop in"></div>
    
    <div class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="channelModal" style="display:block;">
    
        <div class="modal-dialog modal-lg" role="document">
    
            <div class="modal-content">
    
                <div class="modal-header">
    
                    <h4 class="modal-title" id="channelModal">Welcome!</h4>
    
                </div>
    
                <div class="modal-body" style="height:350px;">
    
                    How did you find us?
    
                </div>
    
            </div>
    
        </div>
    
    </div>