Programs & Examples On #Ex

ex is a line editor which serves as the foundation of vi. ex commands work on the current line or on a range of lines in a file. ex is invoked using the colon syntax within vi, and can be invoked on its own from the shell.

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

conflicting types for 'outchar'

In C, the order that you define things often matters. Either move the definition of outchar to the top, or provide a prototype at the top, like this:

#include <stdio.h> #include <stdlib.h>  void outchar(char ch);  int main() {     outchar('A');     outchar('B');     outchar('C');     return 0; }  void outchar(char ch) {     printf("%c", ch); } 

Also, you should be specifying the return type of every function. I added that for you.

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

How to implement a simple scenario the OO way

The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

Method Call Chaining; returning a pointer vs a reference?

The difference between pointers and references is quite simple: a pointer can be null, a reference can not.

Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).

Here it looks like references are more appropriate.

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

Two constructors

Let's, just as example:

public class Test {     public Test() {         System.out.println("NO ARGS");     }      public Test(String s) {         this();         System.out.println("1 ARG");     }      public static void main(String args[])     {         Test t = new Test("s");     } } 

It will print

>>> NO ARGS >>> 1 ARG 

The correct way to call the constructor is by:

this(); 

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

Ruby - ignore "exit" in code

loop {   begin     Bar.new   rescue SystemExit     p $!  #: #<SystemExit: exit>   end } 

This will print #<SystemExit: exit> in an infinite loop, without ever exiting.

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

python variable NameError

Your if statements are checking for int values. raw_input returns a string. Change the following line:

tSizeAns = raw_input() 

to

tSizeAns = int(raw_input()) 

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

Why my regexp for hyphenated words doesn't work?

You can use this:

r'[a-z]+(?:-[a-z]+)*' 

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

C# - insert values from file into two arrays

var Text = File.ReadAllLines("Path"); foreach (var i in Text) {    var SplitText = i.Split().Where(x=> x.Lenght>1).ToList();    //@Array1 add SplitText[0]    //@Array2 add SpliteText[1]   }  

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

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

I think you missed a equal sign at:

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

Change to:

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

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

Instantiating a generic type

No, and the fact that you want to seems like a bad idea. Do you really need a default constructor like this?

When to create variables (memory management)

So notice variables are on the stack, the values they refer to are on the heap. So having variables is not too bad but yes they do create references to other entities. However in the simple case you describe it's not really any consequence. If it is never read again and within a contained scope, the compiler will probably strip it out before runtime. Even if it didn't the garbage collector will be able to safely remove it after the stack squashes. If you are running into issues where you have too many stack variables, it's usually because you have really deep stacks. The amount of stack space needed per thread is a better place to adjust than to make your code unreadable. The setting to null is also no longer needed

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

SQL permissions for roles

Unless the role was made dbo, db_owner or db_datawriter, it won't have permission to edit any data. If you want to grant full edit permissions to a single table, do this:

GRANT ALL ON table1 TO doctor 

Users in that role will have no permissions whatsoever to other tables (not even read).

Difference between opening a file in binary vs text

The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n on input, and conversely on output.


From the C99 standard (the N869 draft document), §7.19.2/2,

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

And in §7.19.3/2

Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.

About use of fseek, in §7.19.9.2/4:

For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

About use of ftell, in §17.19.9.4:

The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

I think that’s the most important, but there are some more details.

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

Generating a list of pages (not posts) without the index file

I can offer you a jquery solution

add this in your <head></head> tag

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

add this after </ul>

 <script> $('ul li:first').remove(); </script> 

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

Removing "http://" from a string

$new_website = substr($str, ($pos = strrpos($str, '//')) !== false ? $pos + 2 : 0); 

This would remove everything before the '//'.

EDIT

This one is tested. Using strrpos() instead or strpos().

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

How do I hide the PHP explode delimiter from submitted form results?

You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.

$fh = fopen("employees.txt", "r"); if ($fh) {     while (($line = fgets($fh)) !== false) {         $line = trim($line);         echo "<option value='".$line."'>".$line."</option>";     } } else {     // error opening the file, do something } 

Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?

And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.

Got a NumberFormatException while trying to parse a text file for objects

The problem might be your split() call. Try just split(" ") without the square brackets.

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Are these methods thread safe?

The only problem with threads is accessing the same object from different threads without synchronization.

If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

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>

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

xlrd.biffh.XLRDError: Excel xlsx file; not supported

As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:

xlrd has explicitly removed support for anything other than xls files.

In your case, the solution is to:

  • make sure you are on a recent version of Pandas, at least 1.0.1, and preferably the latest release. 1.2 will make his even clearer.
  • install openpyxl: https://openpyxl.readthedocs.io/en/stable/
  • change your Pandas code to be:
    df1 = pd.read_excel(
         os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
         engine='openpyxl',
    )
    

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

This error occurs when versions of NodeJS and Node Sass are not matched.

you can resolve your issue by doing as below:

- Step 1: Remove Nodejs from your computer

- Step 2: Reinstall Nodejs version 14.15.1.

- Step 3: Uninstall Node sass by run the command npm uninstall node-sass

- Step 4: Reinstall Node sass version 4.14.1 by run the command npm install [email protected]

After all steps, you can run command ng serve -o to run your application.

Node sass version 5.0.0 is incompatible with ^4.0.0.

Target class controller does not exist - Laravel 8

If you are using laravel 8

just copy and paste my code

use App\Http\Controllers\UserController;

Route::get('/user', [UserController::class, 'index']);

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

In my case:

I had 4 configurations(+ DebugQa and ReleaseQa) Cocoapods is used as a dependency Manager

For Debug, I gathered on the device and in the simulator, and on qa only on the device.

It helped to set BuildActiveArchitecture to yes in PodsProject

iPhone is not available. Please reconnect the device

Xcode 11.4 does not support the new iOS 13.5. Updating to Xcode 11.5 fixed the issue for me

https://developer.apple.com/documentation/xcode_release_notes/xcode_11_4_release_notes

Known Issues Xcode 11.4 doesn’t work with devices running iOS 13.4 beta 1 and beta 2. (60055806)

DevTools failed to load SourceMap: Could not load content for chrome-extension

Extensions without enough permission on chrome can cause these warnings, for example for React developer tools, check if the following procedure solves your problem:

  1. Right click on the extension icon.

Or

  1. Go to extensions.
  2. Click the three-dot in the row of React developer tool.

Then choose "this can read and write site data". You should see 3 options in the list, pick one that is strict enough based on how much you trust the extension and also satisfies the extensions's needs.

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

If you are getting this error when you run stuffs on automated cluster and you are downloading the stable version of the google chrome every time then you can use the below shell script to download the compatible version of the chrome driver dynamically every time even if the stable version of the chrome gets updated.

%sh
#downloading compatible chrome driver version
#getting the current chrome browser version
**chromeVersion=$(google-chrome --product-version)**
#getting the major version value from the full version
**chromeMajorVersion=${chromeVersion%%.*}**
# setting the base url for getting the release url for the chrome driver
**baseDriverLatestReleaseURL=https://chromedriver.storage.googleapis.com/LATEST_RELEASE_**
#creating the latest release driver url based on the major version of the chrome
**latestDriverReleaseURL=$baseDriverLatestReleaseURL$chromeMajorVersion**
**echo $latestDriverReleaseURL**
#file name of the file that gets downloaded which would contain the full version of the chrome driver to download
**latestDriverVersionFileName="LATEST_RELEASE_"$chromeMajorVersion**
#downloading the file that would contain the full release version compatible with the major release of the chrome browser version
**wget $latestDriverReleaseURL** 
#reading the file to get the version of the chrome driver that we should download
**latestFullDriverVersion=$(cat $latestDriverVersionFileName)**
**echo $latestFullDriverVersion**
#creating the final URL by passing the compatible version of the chrome driver that we should download
**finalURL="https://chromedriver.storage.googleapis.com/"$latestFullDriverVersion"/chromedriver_linux64.zip"**
**echo $finalURL**
**wget $finalURL**

I was able to get the compatible version of chrome browser and chrome driver using the above approach when running scheduled job on the databricks environment and it worked like a charm without any issues.

Hope it helps others in one way or other.

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

I had the same issue running it in my pipeline.

For me, the issue was that I was using node version v10.0.0 in my docker container.

Updating it to v14.7.0 solved it for me

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

First please check in module.ts file that in @NgModule all properties are only one time. If any of are more than one time then also this error come. Because I had also occur this error but in module.ts file entryComponents property were two time that's why I was getting this error. I resolved this error by removing one time entryComponents from @NgModule. So, I recommend that first you check it properly.

TS1086: An accessor cannot be declared in ambient context

In my case, mismatch of version of two libraries.

I am using angular 7.0.0 and installed

"@swimlane/ngx-dnd": "^8.0.0"

and this caused the problem. Reverting this library to

"@swimlane/ngx-dnd": "6.0.0"

worked for me.

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

TensorFlow 2.3.0 works fine with CUDA 11. But you have to install tf-nightly-gpu (after you installed tensorflow and CUDA 11): https://pypi.org/project/tf-nightly-gpu/

Try:

pip install tf-nightly-gpu

Afterwards you'll get the message in your console:

I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cudart64_110.dll

Maven dependencies are failing with a 501 error

My current environment does not support HTTPS, so adding the insecure version of the repo solved my problem: http://insecure.repo1.maven.org as per Sonatype

    <repositories>
       <repository>
          <id>Central Maven repository</id>
          <name>Central Maven repository insecure</name>
          <url>http://insecure.repo1.maven.org</url>
       </repository>
    </repositories>

IntelliJ: Error:java: error: release version 5 not supported

You should do one more change by either below approaches:


1 Through IntelliJ GUI

As mentioned by 'tataelm':

Project Structure > Project Settings > Modules > Language level: > then change to your preferred language level


2 Edit IntelliJ config file directly

Open the <ProjectName>.iml file (it is created automatically in your project folder if you're using IntelliJ) directly by editing the following line,

From: <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5">

To: <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_11">

As your approach is also meaning to edit this file. :)


Approach 1 is actually asking IntelliJ to help edit the .iml file instead of doing by you directly.

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

If you are using ruby-2.7.0 on MacOS Catalina 10.15

$ brew reinstall [email protected]

or

$ rvm reinstall 2.7.0
$ brew tap --repair
$ brew doctor

@angular/material/index.d.ts' is not a module

Accepted Answer is correct, but it didn't fully work for me. I had to delete the package.lock file, re-run "npm install", and then close and reopen my visual studio. Hope this helps someone

SyntaxError: Cannot use import statement outside a module

just add --presets '@babel/preset-env'

e.g.

babel-node --trace-deprecation --presets '@babel/preset-env' ./yourscript.js

OR

in babel.config.js

module.exports = {
  presets: ['@babel/preset-env'],
};

SameSite warning Chrome 77

This console warning is not an error or an actual problem — Chrome is just spreading the word about this new standard to increase developer adoption.

It has nothing to do with your code. It is something their web servers will have to support.

Release date for a fix is February 4, 2020 per: https://www.chromium.org/updates/same-site

February, 2020: Enforcement rollout for Chrome 80 Stable: The SameSite-by-default and SameSite=None-requires-Secure behaviors will begin rolling out to Chrome 80 Stable for an initial limited population starting the week of February 17, 2020, excluding the US President’s Day holiday on Monday. We will be closely monitoring and evaluating ecosystem impact from this initial limited phase through gradually increasing rollouts.

For the full Chrome release schedule, see here.

I solved same problem by adding in response header

response.setHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");

SameSite prevents the browser from sending the cookie along with cross-site requests. The main goal is mitigating the risk of cross-origin information leakage. It also provides some protection against cross-site request forgery attacks. Possible values for the flag are Lax or Strict.

SameSite cookies explained here

Please refer this before applying any option.

Hope this helps you.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

In my case it was - no disk space left on the web server.

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

This error in REACT. following steps

  1. Go to Project Root Directory Package.json file

  2. add "type":"module";

  3. Save it and Restart Server

How to fix "set SameSite cookie to none" warning?

As the new feature comes, SameSite=None cookies must also be marked as Secure or they will be rejected.

One can find more information about the change on chromium updates and on this blog post

Note: not quite related directly to the question, but might be useful for others who landed here as it was my concern at first during development of my website:

if you are seeing the warning from question that lists some 3rd party sites (in my case it was google.com, huh) - that means they need to fix it and it's nothing to do with your site. Of course unless the warning mentions your site, in which case adding Secure should fix it.

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

I have run into this issue When I recently upgraded my IntelliJ version to 2020.3. I had to disable a plugin to solve this issue. The name of the plugin is Thrift Support.

Steps to disable the plugin is following:

  1. Open the Preferences of IntelliJ. You can do so by clicking on Command + , in mac.
  2. Navigate to plugins.
  3. Search for the Thrift Support plugin in the search window. Click on the tick box icon to deselect it.
  4. Click on the Apply icon.
  5. See this image for reference Disable_Thrift_support_plugin

For more detail please refer to this link java.lang.UnsupportedClassVersionError 2020.3 version intellij. I found this comment in the above link which has worked for me.

bin zhao commented 31 Dec 2020 08:00 @Lejia Chen @Tobias Schulmann Workflow My IDEA3.X didn't installed Erlang plugin, I disabled Thrift Support 1.4.0 and it worked. Both IDEA 3.0 and 3.1 have the same problem.

How to resolve the error on 'react-native start'

I have just update package.json to change from

"react-native": "https://github.com/expo/react-native/archive/sdk-35.0.0.tar.gz"

to

"react-native": "https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz"

It seems that the problem won't occur in sdk-36 !!

My node version is v12.16.0 and os is win10.

Why powershell does not run Angular commands?

I solved my problem by running below command

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Server Discovery And Monitoring engine is deprecated

You Can Try async await

_x000D_
_x000D_
const connectDB = async () => {_x000D_
    try {_x000D_
        await mongoose.connect(<database url>, {_x000D_
            useNewUrlParser: true,_x000D_
            useCreateIndex: true,_x000D_
            useUnifiedTopology: true,_x000D_
            useFindAndModify: false_x000D_
        });_x000D_
        console.log("MongoDB Conected")_x000D_
    } catch (err) {_x000D_
        console.error(err.message);_x000D_
        process.exit(1);_x000D_
    }_x000D_
};
_x000D_
_x000D_
_x000D_

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

In my case the issue was related to View Binding. It couldn't generate binding classes due to an invalid xml layout file. In the file I had a Switch with an id switch, which is a Java keyword. Renaming the Switch id resolved the issue.enter image description here

error: This is probably not a problem with npm. There is likely additional logging output above

Please delete package-lock.json and clear npm cache with npm cache clear --force and delete whole node_modules directory

Finally install or update packages again with npm install / npm update You can also add any new packages with npm install <package-name>

This fixed for me.

Thanks and happy coding.

Unable to allocate array with shape and data type

change the data type to another one which uses less memory works. For me, I change the data type to numpy.uint8:

data['label'] = data['label'].astype(np.uint8)

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

I made some small changes to Alex McKay's function/usage that I think make it a little easier to follow why it works and also adheres to the no-use-before-define rule.

First, define this function to use:

const getKeyValue = function<T extends object, U extends keyof T> (obj: T, key: U) { return obj[key] }

In the way I've written it, the generic for the function lists the object first, then the property on the object second (these can occur in any order, but if you specify U extends key of T before T extends object you break the no-use-before-define rule, and also it just makes sense to have the object first and its' property second. Finally, I've used the more common function syntax instead of the arrow operators (=>).

Anyways, with those modifications you can just use it like this:

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "John Smith",
  age: 20
};

getKeyValue(user, "name")

Which, again, I find to be a bit more readable.

dotnet ef not found in .NET Core 3

EDIT: If you are using a Dockerfile for deployments these are the steps you need to take to resolve this issue.

Change your Dockerfile to include the following:

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env
ENV PATH $PATH:/root/.dotnet/tools
RUN dotnet tool install -g dotnet-ef --version 3.1.1

Also change your dotnet ef commands to be dotnet-ef

"Permission Denied" trying to run Python on Windows 10

It's not a solution with PowerShell, but I had the same problem except with MINGW64. I got around it by switching to Windows Subsystem for Linux (which I wanted to do anyways) as my terminal, just generally and in VSCode. This post describes it well:

How to configure VS Code (windows) to use Ubuntu App as terminal

In summary:

1) Install Ubuntu from the Windows App Store

2) Change the default bash from CMD -> wslconfig /setdefault Ubuntu

--- For VSCode

3) Restart VSCode

4) In VSCode change "terminal.integrated.shell.windows" to "C:\WINDOWS\System32\bash.exe" (for further details see the post above)

Running smoothly now in VSCode and WSL (Bash on Ubuntu on Windows). Might be at least a temporary solution for you.

Adding Git-Bash to the new Windows Terminal

This is the complete answer (GitBash + color scheme + icon + context menu)

1) Set default profile:

"globals" : 
{
    "defaultProfile" : "{00000000-0000-0000-0000-000000000001}",
    ...

2) Add GitBash profile

"profiles" : 
[
    {
        "guid": "{00000000-0000-0000-0000-000000000001}",
        "acrylicOpacity" : 0.75,
        "closeOnExit" : true,
        "colorScheme" : "GitBash",
        "commandline" : "\"%PROGRAMFILES%\\Git\\usr\\bin\\bash.exe\" --login -i -l",
        "cursorColor" : "#FFFFFF",
        "cursorShape" : "bar",
        "fontFace" : "Consolas",
        "fontSize" : 10,
        "historySize" : 9001,
        "icon" : "%PROGRAMFILES%\\Git\\mingw64\\share\\git\\git-for-windows.ico", 
        "name" : "GitBash",
        "padding" : "0, 0, 0, 0",
        "snapOnInput" : true,
        "startingDirectory" : "%USERPROFILE%",
        "useAcrylic" : false        
    },

3) Add GitBash color scheme

"schemes" : 
[
    {
        "background" : "#000000",
        "black" : "#0C0C0C",
        "blue" : "#6060ff",
        "brightBlack" : "#767676",
        "brightBlue" : "#3B78FF",
        "brightCyan" : "#61D6D6",
        "brightGreen" : "#16C60C",
        "brightPurple" : "#B4009E",
        "brightRed" : "#E74856",
        "brightWhite" : "#F2F2F2",
        "brightYellow" : "#F9F1A5",
        "cyan" : "#3A96DD",
        "foreground" : "#bfbfbf",
        "green" : "#00a400",
        "name" : "GitBash",
        "purple" : "#bf00bf",
        "red" : "#bf0000",
        "white" : "#ffffff",
        "yellow" : "#bfbf00",
        "grey" : "#bfbfbf"
    },  

4) To add a right-click context menu "Windows Terminal Here"

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\Background\shell\wt]
@="Windows terminal here"
"Icon"="C:\\Users\\{YOUR_WINDOWS_USERNAME}\\AppData\\Local\\Microsoft\\WindowsApps\\{YOUR_ICONS_FOLDER}\\icon.ico"

[HKEY_CLASSES_ROOT\Directory\Background\shell\wt\command]
@="\"C:\\Users\\{YOUR_WINDOWS_USERNAME}\\AppData\\Local\\Microsoft\\WindowsApps\\wt.exe\""
  • replace {YOUR_WINDOWS_USERNAME}
  • create icon folder, put the icon there and replace {YOUR_ICONS_FOLDER}
  • save this in a whatever_filename.reg file and run it.

Angular @ViewChild() error: Expected 2 arguments, but got 1

In Angular 8, ViewChild always takes 2 param, and second params always has static: true or static: false

You can try like this:

@ViewChild('nameInput', {static: false}) component

Also,the static: false is going to be the default fallback behaviour in Angular 9.

What are static false/true: So as a rule of thumb you can go for the following:

  • { static: true } needs to be set when you want to access the ViewChild in ngOnInit.

    { static: false } can only be accessed in ngAfterViewInit. This is also what you want to go for when you have a structural directive (i.e. *ngIf) on your element in your template.

Invalid hook call. Hooks can only be called inside of the body of a function component

complementing the following comment

For those who use redux:

class AllowanceClass extends Component{
    ...
    render() {
        const classes = this.props.classes;
        ...
    }
}
    
const COMAllowanceClass = (props) =>
{
    const classes = useStyles();
    return (<AllowanceClass classes={classes} {...props} />);
};

const mapStateToProps = ({ InfoReducer }) => ({
    token: InfoReducer.token,
    user: InfoReducer.user,
    error: InfoReducer.error
});
export default connect(mapStateToProps, { actions })(COMAllowanceClass);

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

Don't Use Any, Use Generics

// bad
const _getKeyValue = (key: string) => (obj: object) => obj[key];
    
// better
const _getKeyValue_ = (key: string) => (obj: Record<string, any>) => obj[key];
    
// best
const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T) =>
      obj[key];

Bad - the reason for the error is the object type is just an empty object by default. Therefore it isn't possible to use a string type to index {}.

Better - the reason the error disappears is because now we are telling the compiler the obj argument will be a collection of string/value (string/any) pairs. However, we are using the any type, so we can do better.

Best - T extends empty object. U extends the keys of T. Therefore U will always exist on T, therefore it can be used as a look up value.

Here is a full example:

I have switched the order of the generics (U extends keyof T now comes before T extends object) to highlight that order of generics is not important and you should select an order that makes the most sense for your function.

const getKeyValue = <U extends keyof T, T extends object>(key: U) => (obj: T) =>
  obj[key];

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "John Smith",
  age: 20
};

const getUserName = getKeyValue<keyof User, User>("name")(user);

// => 'John Smith'

Alternative syntax

const getKeyValue = <T, K extends keyof T>(obj: T, key: K): T[K] => obj[key];

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

Most of the answers are correct in stating that this occurs either because of a mismatch between:

  • Nodejs version and Angular version

OR

  • @angular-devkit/build-angular version and angular version

Also, this issue is most likely to occur if you either:

  1. upgraded/downgraded Nodejs version (which is no longer compatible with the angular version)

  2. Upgraded Angular version

  3. Run npm audit fix

For 1, check the Nodejs version support needed here: https://angular.io/guide/setup-local and check the installed version. If you are using the latest version of angular, you should be able to make it work with the latest version of Nodejs.

For 2, did you follow instructions here: https://update.angular.io/ ? If yes, and still have issues, look for any issues already created or create an issue here: https://github.com/angular/angular/issues

For 3, npm audit fix updates the @angular-devkit/build-angular version to a higher version because @angular-devkit/build-angular does not follow proper versioning (major releases still update only the minor version). Check the link below to check the compatible version for your Angular version: https://www.npmjs.com/package/@angular-devkit/build-angular?activeTab=versions Use the correct version and the issue will be fixed.

P.S: This is a good read about angular versioning: https://angular.io/guide/releases

Make a VStack fill the width of the screen in SwiftUI

This is a useful bit of code:

extension View {
    func expandable () -> some View {
        ZStack {
            Color.clear
            self
        }
    }
}

Compare the results with and without the .expandable() modifier:

Text("hello")
    .background(Color.blue)

-

Text("hello")
    .expandable()
    .background(Color.blue)

enter image description here

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

Since the originating port 4200 is different than 8080,So before angular sends a create (PUT) request,it will send an OPTIONS request to the server to check what all methods and what all access-controls are in place. Server has to respond to that OPTIONS request with list of allowed methods and allowed origins.

Since you are using spring boot, the simple solution is to add ".allowedOrigins("http://localhost:4200");"

In your spring config,class

@Configuration
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:4200");
    }
}

However a better approach will be to write a Filter(interceptor) which adds the necessary headers to each response.

How to style components using makeStyles and still have lifecycle methods in Material UI?

useStyles is a React hook which are meant to be used in functional components and can not be used in class components.

From React:

Hooks let you use state and other React features without writing a class.

Also you should call useStyles hook inside your function like;

function Welcome() {
  const classes = useStyles();
...

If you want to use hooks, here is your brief class component changed into functional component;

import React from "react";
import { Container, makeStyles } from "@material-ui/core";

const useStyles = makeStyles({
  root: {
    background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
    border: 0,
    borderRadius: 3,
    boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
    color: "white",
    height: 48,
    padding: "0 30px"
  }
});

function Welcome() {
  const classes = useStyles();
  return (
    <Container className={classes.root}>
      <h1>Welcome</h1>
    </Container>
  );
}

export default Welcome;

on ↓ CodeSandBox ↓

Edit React hooks

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

Why am I getting Unknown error in line 1 of pom.xml?

As per the suggestion from @Shravani, in my pom.xml file, I changed my version number in the area from this:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

to this:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

I then right clicked on the project and did a 'Maven -> Update project...'. This made the problem go away for me.

How to fix ReferenceError: primordials is not defined in node

Use following commands and install node v11.15.0:

npm install -g n

sudo n 11.15.0

will solve

ReferenceError: primordials is not defined in node

Referred from @Terje Norderhaug @Tom Corelis answers.

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

The error also can occur if you try to save a python list of numpy arrays with np.save and load with np.load. I am only saying it for the sake of googler's to check out that this is not the issue. Also using allow_pickle=True fixed the issue if a list is indeed what you meant to save and load.

Module 'tensorflow' has no attribute 'contrib'

I used tensorflow 1.8 to train my model and there is no problem for now. Tensorflow 2.0 alpha is not suitable with object detection API

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

Components should start with capital letters. Also remember to change the first letter in the line to export!

How to fix missing dependency warning when using useEffect React Hook?

The solution is also given by react, they advice you use useCallback which will return a memoize version of your function :

The 'fetchBusinesses' function makes the dependencies of useEffect Hook (at line NN) change on every render. To fix this, wrap the 'fetchBusinesses' definition into its own useCallback() Hook react-hooks/exhaustive-deps

useCallback is simple to use as it has the same signature as useEffect the difference is that useCallback returns a function. It would look like this :

 const fetchBusinesses = useCallback( () => {
        return fetch("theURL", {method: "GET"}
    )
    .then(() => { /* some stuff */ })
    .catch(() => { /* some error handling */ })
  }, [/* deps */])
  // We have a first effect thant uses fetchBusinesses
  useEffect(() => {
    // do things and then fetchBusinesses
    fetchBusinesses(); 
  }, [fetchBusinesses]);
   // We can have many effect thant uses fetchBusinesses
  useEffect(() => {
    // do other things and then fetchBusinesses
    fetchBusinesses();
  }, [fetchBusinesses]);

How to update core-js to core-js@3 dependency?

For npm

 npm install --save core-js@^3

for yarn

yarn add core-js@^3

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

You haven't started the bundler yet. Run npm start or react-native start in the root directory of your project before react-native run-android.

Module not found: Error: Can't resolve 'core-js/es6'

Just change "target": "es2015" to "target": "es5" in your tsconfig.json.

Work for me with Angular 8.2.XX

Tested on IE11 and Edge

How to set value to form control in Reactive Forms in Angular

Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances.

patchValue does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls. On the other hand, setValue requires all Form Control values to be filled in, and it will return an error if any of your controls are not specified within the parameter.

In this scenario, we will want to use patchValue, since we are only updating user and questioning:

this.qService.editQue([params["id"]]).subscribe(res => {
  this.question = res;
  this.editqueForm.patchValue({
    user: this.question.user,
    questioning: this.question.questioning
  });
});

EDIT: If you feel like doing some of ES6's Object Destructuring, you may be interested to do this instead

const { user, questioning } = this.question;

this.editqueForm.patchValue({
  user,
  questioning
});

Ta-dah!

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

I found a short cut rather than going through vs code appData/webCompiler, I added it as a dependency to my project with this cmd npm i caniuse-lite browserslist. But you might install it globally to avoid adding it to each project.

After installation, you could remove it from your project package.json and do npm i.

Update:

In case, Above solution didn't fix it. You could run npm update, as this would upgrade deprecated/outdated packages.

Note:

After you've run the npm update, there may be missing dependencies. Trace the error and install the missing dependencies. Mine was nodemon, which I fix by npm i nodemon -g

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I suspect that the problem lies in the fact that you are calling your state setter immediately inside the function component body, which forces React to re-invoke your function again, with the same props, which ends up calling the state setter again, which triggers React to call your function again.... and so on.

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(false);
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    if (variant) {
        setSnackBarState(true); // HERE BE DRAGONS
    }
    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Instead, I recommend you just conditionally set the default value for the state property using a ternary, so you end up with:

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(variant ? true : false); 
                                  // or useState(!!variant); 
                                  // or useState(Boolean(variant));
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Comprehensive Demo

See this CodeSandbox.io demo for a comprehensive demo of it working, plus the broken component you had, and you can toggle between the two.

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

In my case everything solved after re-cloning the repo and launching it again.

Setup: Xcode 12.4 Mac M1

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

  1. download current stable release version of your chrome & install it ( to check your Google chrome version go to Help > about Google chrome & try to install that version on your local machine .

For Google chrome version downloading visit = chromedriver.chromium.org site

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

I've seen your code in web.php as follows: Route::post('/edit/{id}','ProjectController@update');

Step 1: remove the {id} random parameter so it would be like this: Route::post('/edit','ProjectController@update');

Step 2: Then remove the @method('PUT') in your form, so let's say we'll just plainly use the POST method

Then how can I pass the ID to my method?

Step 1: make an input field in your form with the hidden attribute for example

<input type="hidden" value="{{$project->id}}" name="id">

Step 2: in your update method in your controller, fetch that ID for example:

$id = $request->input('id');

then you may not use it to find which project to edit

$project = Project::find($id)
//OR
$project = Project::where('id',$id);

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

If this is your code, the correct solution is to rewrite it to not use Session(), since that's no longer necessary in TensorFlow 2

If this is just code you're running, you can downgrade to TensorFlow 1 by running

pip3 install --upgrade --force-reinstall tensorflow-gpu==1.15.0 

(or whatever the latest version of TensorFlow 1 is)

react hooks useEffect() cleanup for only componentWillUnmount?

Since the cleanup is not dependent on the username, you could put the cleanup in a separate useEffect that is given an empty array as second argument.

Example

_x000D_
_x000D_
const { useState, useEffect } = React;_x000D_
_x000D_
const ForExample = () => {_x000D_
  const [name, setName] = useState("");_x000D_
  const [username, setUsername] = useState("");_x000D_
_x000D_
  useEffect(_x000D_
    () => {_x000D_
      console.log("effect");_x000D_
    },_x000D_
    [username]_x000D_
  );_x000D_
_x000D_
  useEffect(() => {_x000D_
    return () => {_x000D_
      console.log("cleaned up");_x000D_
    };_x000D_
  }, []);_x000D_
_x000D_
  const handleName = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setName(value);_x000D_
  };_x000D_
_x000D_
  const handleUsername = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setUsername(value);_x000D_
  };_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <div>_x000D_
        <input value={name} onChange={handleName} />_x000D_
        <input value={username} onChange={handleUsername} />_x000D_
      </div>_x000D_
      <div>_x000D_
        <div>_x000D_
          <span>{name}</span>_x000D_
        </div>_x000D_
        <div>_x000D_
          <span>{username}</span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
function App() {_x000D_
  const [shouldRender, setShouldRender] = useState(true);_x000D_
_x000D_
  useEffect(() => {_x000D_
    setTimeout(() => {_x000D_
      setShouldRender(false);_x000D_
    }, 5000);_x000D_
  }, []);_x000D_
_x000D_
  return shouldRender ? <ForExample /> : null;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Jupyter Notebook not saving: '_xsrf' argument missing from post

When I click 'save' button, it has this error. Based on the answers in this post and other websites, I just found the solution. My jupyter notebook is installed from pip. So I access it by typing 'jupyter notebook' in the windows command line.

(1) open a new command window, then open a new jupyter notebook. try to save again in the old notebook, this time ,the error is 'fail: forbidden'

(2) Then in the old notebook, click 'download as', it will pop out a new windows ask you the token.

enter image description here

(3) open another command window, then open another jupyter notebook, type 'jupyter notebook list' copy the code after 'token=' and before :: to the box you just saw. You can save this time. If it fails, you can try another token in the list

How to use callback with useState hook in react

Another way to achieve this:

_x000D_
_x000D_
const [Name, setName] = useState({val:"", callback: null});_x000D_
React.useEffect(()=>{_x000D_
  console.log(Name)_x000D_
  const {callback} = Name;_x000D_
  callback && callback();_x000D_
}, [Name]);_x000D_
setName({val:'foo', callback: ()=>setName({val: 'then bar'})})
_x000D_
_x000D_
_x000D_

How can I solve the error 'TS2532: Object is possibly 'undefined'?

Edit / Update:

If you are using Typescript 3.7 or newer you can now also do:

    const data = change?.after?.data();

    if(!data) {
      console.error('No data here!');
       return null
    }

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }

Original Response

Typescript is saying that change or data is possibly undefined (depending on what onUpdate returns).

So you should wrap it in a null/undefined check:

if(change && change.after && change.after.data){
    const data = change.after.data();

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }
}

If you are 100% sure that your object is always defined then you can put this:

const data = change.after!.data();

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

I ran into this problem myself today, and found a really nifty plugin that will save you the hassle of trying to manually allow cleartext traffic in Android 9+ for your Apache Cordova application. Simply install cordova-plugin-cleartext, and the plugin should take care of all the behind the scenes Android stuff for you.

$ cordova plugin add cordova-plugin-cleartext
$ cordova prepare
$ cordova run android

Push method in React Hooks (useState)?

// Save search term state to React Hooks with spread operator and wrapper function

// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query))

// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query))

// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query])

// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query])

https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc

How to Install pip for python 3.7 on Ubuntu 18?

In general, don't do this:

pip install package

because, as you have correctly noticed, it's not clear what Python version you're installing package for.

Instead, if you want to install package for Python 3.7, do this:

python3.7 -m pip install package

Replace package with the name of whatever you're trying to install.

Took me a surprisingly long time to figure it out, too. The docs about it are here.

Your other option is to set up a virtual environment. Once your virtual environment is active, executable names like python and pip will point to the correct ones.

Flutter Countdown Timer

doesnt directly answer your question. But helpful for those who want to start something after some time.

Future.delayed(Duration(seconds: 1), () {
            print('yo hey');
          });

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

I got the same error message on GraphQL mutation input object then I found the problem, Actually in my case mutation expecting an object array as input but I'm trying to insert a single object as input. For example:

First try

const mutationName = await apolloClient.mutate<insert_mutation, insert_mutationVariables>({
      mutation: MUTATION,
      variables: {
        objects: {id: 1, name: "John Doe"},
      },
    });

Corrected mutation call as an array

const mutationName = await apolloClient.mutate<insert_mutation, insert_mutationVariables>({
      mutation: MUTATION,
      variables: {
        objects: [{id: 1, name: "John Doe"}],
      },
    });

Sometimes simple mistakes like this can cause the problems. Hope this'll help someone.

How do I prevent Conda from activating the base environment by default?

There're 3 ways to achieve this after conda 4.6. (The last method has the highest priority.)

  1. Use sub-command conda config to change the setting.

    conda config --set auto_activate_base false
    
  2. In fact, the former conda config sub-command is changing configuration file .condarc. We can modify .condarc directly. Add following content into .condarc under your home directory,

    # auto_activate_base (bool)
    #   Automatically activate the base environment during shell
    #   initialization. for `conda init`
    auto_activate_base: false
    
  3. Set environment variable CONDA_AUTO_ACTIVATE_BASE in the shell's init file. (.bashrc for bash, .zshrc for zsh)

    CONDA_AUTO_ACTIVATE_BASE=false
    

    To convert from the condarc file-based configuration parameter name to the environment variable parameter name, make the name all uppercase and prepend CONDA_. For example, conda’s always_yes configuration parameter can be specified using a CONDA_ALWAYS_YES environment variable.

    The environment settings take precedence over corresponding settings in .condarc file.

References

Gradle: Could not determine java version from '11.0.2'

In my case, I was trying to build and get APK for an old Unity 3D project (so that I can play the game in my Android phone). I was using the most recent Android Studio version, and all the SDK packages I could download via SDK Manager in Android Studio. SDK Packages was located in

C:/Users/Onat/AppData/Local/Android/Sdk 

And the error message I got was the same except the JDK (Java Development Kit) version "jdk-12.0.2" . JDK was located in

C:\Program Files\Java\jdk-12.0.2

And Environment Variable in Windows was JAVA_HOME : C:\Program Files\Java\jdk-12.0.2

After 3 hours of research, I found out that Unity does not support JDK 10. As told in https://forum.unity.com/threads/gradle-build-failed-error-could-not-determine-java-version-from-10-0-1.532169/ . My suggestion is:

  1. Uninstall unwanted JDK if you have one installed already. https://www.java.com/tr/download/help/uninstall_java.xml
  2. Head to http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
  3. Login to/Open a Oracle account if not already logged in.
  4. Download the older but functional JDK 8 for your computer set-up(32 bit/64 bit, Windows/Linux etc.)
  5. Install the JDK. Remember the installation path. (https://docs.oracle.com/cd/E19182-01/820-7851/inst_cli_jdk_javahome_t/)
  6. If you are using Windows, Open Environment Variables and change Java Path via Right click My Computer/This PC>Properties>Advanced System Settings>Environment Variables>New>Variable Name: JAVA_HOME>Variable Value: [YOUR JDK Path, Mine was "C:\Program Files\Java\jdk1.8.0_221"]
  7. In Unity 3D, press Edit > Preferences > External Tools and fill in the JDK path (Mine was "C:\Program Files\Java\jdk1.8.0_221").
  8. Also, in the same pop-up, edit SDK Path. (Get it from Android Studio > SDK Manager > Android SDK > Android SDK Location.)
  9. If needed, restart your computer for changes to take effect.

"Failed to install the following Android SDK packages as some licences have not been accepted" error

On Windows:

  1. Add USER Environment variables:

NOTE: Path should be appended

JAVA_HOME           %ProgramFiles%\Android\Android Studio\jre
ANDROID_SDK_ROOT    %LocalAppData%\Android\Sdk
Path                %LocalAppData%\Android\Sdk
  1. Run the below command to accept licenses:

NOTE: Accept all licenses (say y)

%ANDROID_SDK_ROOT%/tools/bin/sdkmanager.bat --licenses
  1. Now run your app:

(like below, or another command that failed for you):

cd \myapp\
react-native run-android

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

src is the first argument to cv2.cvtColor.

The error you are getting is because it is not the right form. cv2.Umat() is functionally equivalent to np.float32(), so your last line of code should read:

gray = cv2.cvtColor(np.float32(imgUMat), cv2.COLOR_RGB2GRAY)

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

Or download composer.phar from site: "https://getcomposer.org/download/" (manual download), and use command:

php composer.phar require your/package

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

React Hooks useState() with Object

I leave you a utility function to inmutably update objects

/**
 * Inmutable update object
 * @param  {Object} oldObject     Object to update
 * @param  {Object} updatedValues Object with new values
 * @return {Object}               New Object with updated values
 */
export const updateObject = (oldObject, updatedValues) => {
  return {
    ...oldObject,
    ...updatedValues
  };
};

So you can use it like this

const MyComponent = props => {

  const [orderForm, setOrderForm] = useState({
    specialities: {
      elementType: "select",
      elementConfig: {
        options: [],
        label: "Specialities"
      },
      touched: false
    }
  });


// I want to update the options list, to fill a select element

  // ---------- Update with fetched elements ---------- //

  const updateSpecialitiesData = data => {
    // Inmutably update elementConfig object. i.e label field is not modified
    const updatedOptions = updateObject(
      orderForm[formElementKey]["elementConfig"],
      {
        options: data
      }
    );
    // Inmutably update the relevant element.
    const updatedFormElement = updateObject(orderForm[formElementKey], {
      touched: true,
      elementConfig: updatedOptions
    });
    // Inmutably update the relevant element in the state.
    const orderFormUpdated = updateObject(orderForm, {
      [formElementKey]: updatedFormElement
    });
    setOrderForm(orderFormUpdated);
  };

  useEffect(() => {
      // some code to fetch data
      updateSpecialitiesData.current("specialities",fetchedData);
  }, [updateSpecialitiesData]);

// More component code
}

If not you have more utilities here : https://es.reactjs.org/docs/update.html

Error: Java: invalid target release: 11 - IntelliJ IDEA

I've got the same issue as stated by Grigoriy Yuschenko. Same Intellij 2018 3.3

I was able to start my project by setting (like stated by Grigoriy)

File->Project Structure->Modules ->> Language level to 8 ( my maven project was set to 1.8 java)

AND

File -> Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler -> 8 also there

I hope it would be useful

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

Solved by doing the following in my windows 10:

mklink "C:\Users\hal\AppData\Local\Continuum\anaconda3\DLLs\libssl-1_1-x64.dll" "C:\Users\hal\AppData\Local\Continuum\anaconda3\Library\bin\libssl-1_1-x64.dll"

mklink "C:\ProgramData\Anaconda3\DLLs\libcrypto-1_1-x64.dll" "C:\ProgramData\Anaconda3\Library\bin\libcrypto-1_1-x64.dll"

useState set method not reflecting change immediately

Much like setState in Class components created by extending React.Component or React.PureComponent, the state update using the updater provided by useState hook is also asynchronous, and will not be reflected immediately.

Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their current closures, and state updates will reflect in the next re-render by which the existing closures are not affected, but new ones are created. Now in the current state, the values within hooks are obtained by existing closures, and when a re-render happens, the closures are updated based on whether the function is recreated again or not.

Even if you add a setTimeout the function, though the timeout will run after some time by which the re-render would have happened, the setTimeout will still use the value from its previous closure and not the updated one.

setMovies(result);
console.log(movies) // movies here will not be updated

If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate in class components since the setter returned by useState doesn't have a callback pattern

useEffect(() => {
    // action on update of movies
}, [movies]);

As far as the syntax to update state is concerned, setMovies(result) will replace the previous movies value in the state with those available from the async request.

However, if you want to merge the response with the previously existing values, you must use the callback syntax of state updation along with the correct use of spread syntax like

setMovies(prevMovies => ([...prevMovies, ...result]));

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

Git fatal: protocol 'https' is not supported

You tried this:

clt + V

Just right click and click on paste

Hope this will work

Can't perform a React state update on an unmounted component

If above solutions dont work, try this and it works for me:

componentWillUnmount() {
    // fix Warning: Can't perform a React state update on an unmounted component
    this.setState = (state,callback)=>{
        return;
    };
}

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

.catch(error => { throw error}) is a no-op. It results in unhandled rejection in route handler.

As explained in this answer, Express doesn't support promises, all rejections should be handled manually:

router.get("/emailfetch", authCheck, async (req, res, next) => {
  try {
  //listing messages in users mailbox 
    let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
    emailFetch = emailFetch.data
    res.send(emailFetch)
  } catch (err) {
    next(err);
  }
})

React hooks useState Array

The accepted answer shows the correct way to setState but it does not lead to a well functioning select box.

import React, { useState } from "react"; 
import ReactDOM from "react-dom";

const initialValue = { id: 0,value: " --- Select a State ---" };

const options = [
    { id: 1, value: "Alabama" },
    { id: 2, value: "Georgia" },
    { id: 3, value: "Tennessee" }
];

const StateSelector = () => {   
   const [ selected, setSelected ] = useState(initialValue);  

     return (
       <div>
          <label>Select a State:</label>
          <select value={selected}>
            {selected === initialValue && 
                <option disabled value={initialValue}>{initialValue.value}</option>}
            {options.map((localState, index) => (
               <option key={localState.id} value={localState}>
                   {localState.value}
               </option>
             ))}
          </select>
        </div>
      ); 
};

const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);

HTTP Error 500.30 - ANCM In-Process Start Failure

This publish profile setting fixed for me:

Configure Publish Profile -> Settings -> Site Extensions Options ->

  • [x] Install ASP.NET Core Site Extension.

Can I set state inside a useEffect hook

Generally speaking, using setState inside useEffect will create an infinite loop that most likely you don't want to cause. There are a couple of exceptions to that rule which I will get into later.

useEffect is called after each render and when setState is used inside of it, it will cause the component to re-render which will call useEffect and so on and so on.

One of the popular cases that using useState inside of useEffect will not cause an infinite loop is when you pass an empty array as a second argument to useEffect like useEffect(() => {....}, []) which means that the effect function should be called once: after the first mount/render only. This is used widely when you're doing data fetching in a component and you want to save the request data in the component's state.

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

The easiest way I've found is delete Android Studio from the applications folder, then download & install it again.

TypeScript and React - children type?

I'm using the following

type Props = { children: React.ReactNode };

const MyComponent: React.FC<Props> = ({children}) => {
  return (
    <div>
      { children }
    </div>
  );

export default MyComponent;

FlutterError: Unable to load asset

Make sure the file names do not contain special characters such as ñ for example

Pandas Merging 101

A supplemental visual view of pd.concat([df0, df1], kwargs). Notice that, kwarg axis=0 or axis=1 's meaning is not as intuitive as df.mean() or df.apply(func)


on pd.concat([df0, df1])

What does double question mark (??) operator mean in PHP

It's the "null coalescing operator", added in php 7.0. The definition of how it works is:

It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

So it's actually just isset() in a handy operator.

Those two are equivalent1:

$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';

Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

And original RFC https://wiki.php.net/rfc/isset_ternary


EDIT: As this answer gets a lot of views, little clarification:

1There is a difference: In case of ??, the first expression is evaluated only once, as opposed to ? :, where the expression is first evaluated in the condition section, then the second time in the "answer" section.

Why do I keep getting Delete 'cr' [prettier/prettier]?

All the answers above are correct, but when I use windows and disable the Prettier ESLint extension rvest.vs-code-prettier-eslint the issue will be fixed.

Numpy, multiply array with scalar

You can multiply numpy arrays by scalars and it just works.

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

This is also a very fast and efficient operation. With your example:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

try

_x000D_
_x000D_
const MyFunctionnalComponent: React.FC = props => {_x000D_
  useEffect(() => {_x000D_
    // Using an IIFE_x000D_
    (async function anyNameFunction() {_x000D_
      await loadContent();_x000D_
    })();_x000D_
  }, []);_x000D_
  return <div></div>;_x000D_
};
_x000D_
_x000D_
_x000D_

Receiving "Attempted import error:" in react app

import { combineReducers } from '../../store/reducers';

should be

import combineReducers from '../../store/reducers';

since it's a default export, and not a named export.

There's a good breakdown of the differences between the two here.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

Enable cross-origin requests in ASP.NET Web API click for more info

Enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

Install-Package Microsoft.AspNet.WebApi.Cors

This command installs the latest package and updates all dependencies, including the core Web API libraries. Use the -Version flag to target a specific version. The CORS package requires Web API 2.0 or later.

Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Next, add the [EnableCors] attribute to your controller/ controller methods

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}

Enable Cross-Origin Requests (CORS) in ASP.NET Core

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

If you are doing Unity Project. You can get this error.

Command PhaseScriptExecution failed with a nonzero exit code

The solution is very simple

https://forum.unity.com/threads/error-on-build.561706/

Pre-requisites: Have cocoapods installed

Not Needed: 1. Install "cocoapods" for installing run following line in your terminal: $sudo gem install cocoapods

  1. Open your project folder using terminal
  2. Run this line: chmod +x MapFileParser.sh
  3. Run this line: chmod +x process_symbols.sh

It worked for me)

I think that installing "cocoapods" is not necessary, only step 3 and 4 enough to solve, but it does not work, you can try it.

How can I force component to re-render with hooks in React?

Generally, you can use any state handling approach you want to trigger an update.

With TypeScript

codesandbox example

useState

const forceUpdate: () => void = React.useState()[1].bind(null, {})  // see NOTE below

useReducer

const forceUpdate = React.useReducer(() => ({}), {})[1] as () => void

as custom hook

Just wrap whatever approach you prefer like this

function useForceUpdate(): () => void {
  return React.useReducer(() => ({}), {})[1] as () => void // <- paste here
}

How this works?

"To trigger an update" means to tell React engine that some value has changed and that it should rerender your component.

[, setState] from useState() requires a parameter. We get rid of it by binding a fresh object {}.
() => ({}) in useReducer is a dummy reducer that returns a fresh object each time an action is dispatched.
{} (fresh object) is required so that it triggers an update by changing a reference in the state.

PS: useState just wraps useReducer internally. source

NOTE: Using .bind with useState causes a change in function reference between renders. It is possible to wrap it inside useCallback as already explained here, but then it wouldn't be a sexy one-liner™. The Reducer version already keeps reference equality between renders. This is important if you want to pass the forceUpdate function in props.

plain JS

const forceUpdate = React.useState()[1].bind(null, {})  // see NOTE above
const forceUpdate = React.useReducer(() => ({}))[1]

What is the meaning of "Failed building wheel for X" in pip install?

I had the same problem while installing Brotli

ERROR

Failed building wheel for Brotli

I solved it by downloading the .whl file from here and installing it using the below command

C:\Users\{user_name}\Downloads>pip install Brotli-1.0.9-cp39-cp39-win_amd64.whl

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

As the error mentioned the class does not have a default constructor.

Adding @NoArgsConstructor to the entity class should fix it.

What is useState() in React?

React hooks are a new way (still being developed) to access the core features of react such as state without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the onClick prop, you could do something like:

...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...

const setCount = () => {
    setCounter(count + 1);
    setMoreStuff(...);
    ...
};

and onClick:

<button onClick={setCount}>
    Click me
</button>

Let's quickly explain what is going on in this line:

const [count, setCounter] = useState(0);

useState(0) returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the counter's state. We can use the setCounter method to update the state of count anywhere - In this case we are using it inside of the setCount function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.

I wrote a complete article about hooks with multiple examples (including counters) such as this codepen, I made use of useState, useEffect, useContext, and custom hooks. I could get into more details about how hooks work on this answer but the documentation does a very good job explaining the state hook and other hooks in detail, hope it helps.

update: Hooks are not longer a proposal, since version 16.8 they're now available to be used, there is a section in React's site that answers some of the FAQ.

Set the space between Elements in Row Flutter

Just add "Container(width: 5, color: Colors.transparent)," between elements

new Container(
      alignment: FractionalOffset.center,
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          new FlatButton(
            child: new Text('Don\'t have an account?', style: new TextStyle(color: Color(0xFF2E3233))),
          ),
            Container(width: 5, color: Colors.transparent),
          new FlatButton(
            child: new Text('Register.', style: new TextStyle(color: Color(0xFF84A2AF), fontWeight: FontWeight.bold),),
            onPressed: moveToRegister,
          )
        ],
      ),
    ),  

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

After making no changes to a production server we began receiving this error. After trying several different things and thinking that perhaps there were DNS issues, restarting IIS fixed the issue (restarting only the site did not fix the issue). It likely won't work for everyone but if we tried that first it would have saved a lot of time.

How to call loading function with React useEffect only once

TL;DR

useEffect(yourCallback, []) - will trigger the callback only after the first render.

Detailed explanation

useEffect runs by default after every render of the component (thus causing an effect).

When placing useEffect in your component you tell React you want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates.

If you pass only a callback - the callback will run after each render.

If passing a second argument (array), React will run the callback after the first render and every time one of the elements in the array is changed. for example when placing useEffect(() => console.log('hello'), [someVar, someOtherVar]) - the callback will run after the first render and after any render that one of someVar or someOtherVar are changed.

By passing the second argument an empty array, React will compare after each render the array and will see nothing was changed, thus calling the callback only after the first render.

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

I encountered the exact problem running on docker container (in build environment). After ssh into the container, I tried running the test manually and still encountered

(unknown error: DevToolsActivePort file doesn't exist)
     (The process started from chrome location /usr/bin/google-chrome-stable is 
      no longer running, so ChromeDriver is assuming that Chrome has crashed.)

When I tried running chrome locally /usr/bin/google-chrome-stable, error message

Running as root without --no-sandbox is not supported

I checked my ChromeOptions and it was missing --no-sandbox, which is why it couldn't spawn chrome.

capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
  chromeOptions: { args: %w(headless --no-sandbox disable-gpu window-size=1920,1080) }
)

expected assignment or function call: no-unused-expressions ReactJS

In my case, I got the error on the setState line:

increment(){
  this.setState(state => {
    count: state.count + 1
  });
}

I changed it to this, now it works

increment(){
  this.setState(state => {
    const count = state.count + 1

    return {
      count
    };
  });
}

ImageMagick security policy 'PDF' blocking conversion

Works in Ubuntu 20.04

Add this line inside <policymap>

<policy domain="module" rights="read|write" pattern="{PS,PDF,XPS}" />

Comment these lines:

  <!--
  <policy domain="coder" rights="none" pattern="PS" />
  <policy domain="coder" rights="none" pattern="PS2" />
  <policy domain="coder" rights="none" pattern="PS3" />
  <policy domain="coder" rights="none" pattern="EPS" />
  <policy domain="coder" rights="none" pattern="PDF" />
  <policy domain="coder" rights="none" pattern="XPS" />
   -->

Flutter: RenderBox was not laid out

Reason for the error:

Column tries to expands in vertical axis, and so does the ListView, hence you need to constrain the height of ListView.


Solutions

  1. Use either Expanded or Flexible if you want to allow ListView to take up entire left space in Column.

    Column(
      children: <Widget>[
        Expanded(
          child: ListView(...),
        )
      ],
    )
    

  1. Use SizedBox if you want to restrict the size of ListView to a certain height.

    Column(
      children: <Widget>[
        SizedBox(
          height: 200, // constrain height
          child: ListView(),
        )
      ],
    )
    

  1. Use shrinkWrap, if your ListView isn't too big.

    Column(
      children: <Widget>[
        ListView(
          shrinkWrap: true, // use it
        )
      ],
    )
    

Space between Column's children in Flutter

You can use Padding widget in between those two widget or wrap those widgets with Padding widget.

Update

SizedBox widget can be use in between two widget to add space between two widget and it makes code more readable than padding widget.

Ex:

Column(
  children: <Widget>[
    Widget1(),
    SizedBox(height: 10),
    Widget2(),
  ],
),

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

open command line cmd on your project.

1.command

php artisan config:cache

2.comand

php artisan route:clear

How to install OpenJDK 11 on Windows?

  1. Extract the zip file into a folder, e.g. C:\Program Files\Java\ and it will create a jdk-11 folder (where the bin folder is a direct sub-folder). You may need Administrator privileges to extract the zip file to this location.

  2. Set a PATH:

    • Select Control Panel and then System.
    • Click Advanced and then Environment Variables.
    • Add the location of the bin folder of the JDK installation to the PATH variable in System Variables.
    • The following is a typical value for the PATH variable: C:\WINDOWS\system32;C:\WINDOWS;"C:\Program Files\Java\jdk-11\bin"
  3. Set JAVA_HOME:

    • Under System Variables, click New.
    • Enter the variable name as JAVA_HOME.
    • Enter the variable value as the installation path of the JDK (without the bin sub-folder).
    • Click OK.
    • Click Apply Changes.
  4. Configure the JDK in your IDE (e.g. IntelliJ or Eclipse).

You are set.

To see if it worked, open up the Command Prompt and type java -version and see if it prints your newly installed JDK.

If you want to uninstall - just undo the above steps.

Note: You can also point JAVA_HOME to the folder of your JDK installations and then set the PATH variable to %JAVA_HOME%\bin. So when you want to change the JDK you change only the JAVA_HOME variable and leave PATH as it is.

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

How to change status bar color in Flutter?

I spent way to much time on this. When switching my theme from light to dark mode, I struggled. This package works, just add it to your build context. Works great for me on Android and iOs.

https://pub.dev/packages/statusbar

    sharedPrefs.darkTheme
    ? StatusBar.color(Colors.black)
    : StatusBar.color(Colors.white);

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

Change your Google Services version from your build.gradle:

dependencies {
  classpath 'com.google.gms:google-services:4.2.0'
}

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

In My case, I had a added async at app.js like shown below.

const App = async() => {
return(
<Text>Hello world</Text>
)
}

But it was not necessary, when testing something I had added it and it was no longer required. After removing it, as shown below, things started working.

 const App =() => {
    return(
    <Text>Hello world</Text>
    )
}

Xcode 10: A valid provisioning profile for this executable was not found

I had to change my team in provisioning profile for tests. AND

Changing my target device from my physical phone to a simulator fixed it for me!

Xcode 10, Command CodeSign failed with a nonzero exit code

It works for me by delete all the apple developer Certification in the keychain. and generate it in the Xcode.

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

Pyspark: Filter dataframe based on multiple conditions

faster way (without pyspark.sql.functions)

    df.filter((df.d<5)&((df.col1 != df.col3) |
                    (df.col2 != df.col4) & 
                    (df.col1 ==df.col3)))\
    .show()

Joining pairs of elements of a list

>>> lst =  ['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'] 
>>> print [lst[2*i]+lst[2*i+1] for i in range(len(lst)/2)]
['abcde', 'fghijklmn', 'opqr']

Batch files : How to leave the console window open

I just press enter and type Pause and it works fine

Using await outside of an async function

you can do top level await since typescript 3.8
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#-top-level-await
From the post:
This is because previously in JavaScript (along with most other languages with a similar feature), await was only allowed within the body of an async function. However, with top-level await, we can use await at the top level of a module.

const response = await fetch("...");
const greeting = await response.text();
console.log(greeting);

// Make sure we're a module
export {};

Note there’s a subtlety: top-level await only works at the top level of a module, and files are only considered modules when TypeScript finds an import or an export. In some basic cases, you might need to write out export {} as some boilerplate to make sure of this.

Top level await may not work in all environments where you might expect at this point. Currently, you can only use top level await when the target compiler option is es2017 or above, and module is esnext or system. Support within several environments and bundlers may be limited or may require enabling experimental support.

Include another JSP file

For a reason I don't yet understand, after I used <%@include file="includes/footer.jsp" %> in my index.jsp then in the other jsp files like register.jsp I had to use <%@ include file="footer.jsp"%>. As you see there was no more need to use full path, STS had store my initial path.

Combine two tables that have no common fields

Select 
DISTINCT  t1.col,t2col
From table1 t1, table2 t2

OR

Select 
DISTINCT  t1.col,t2col
From table1 t1 
cross JOIN  table2 t2

if its hug data , its take long time ..

Commit only part of a file in Git

Worth noting that to use git add --patch for a new file you need to first add the file to index with git add --intent-to-add:

git add -N file
git add -p file

Detect the Internet connection is offline?

You can try this will return true if network connected

function isInternetConnected(){return navigator.onLine;}

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

Mockito. Verify method arguments

The other method is to use the org.mockito.internal.matchers.Equals.Equals method instead of redefining one :

verify(myMock).myMethod((inputObject)Mockito.argThat(new Equals(inputObjectWanted)));

Scroll back to the top of scrollable div

2020 UPDATE

You can use .scroll() to easily scroll elements or window. It has a built-in smooth scroll effect so basically the code couldn't be simpler.

Standard properties:

var options = {
    top:       0,        // Number of pixels along the Y axis to scroll the window or element
    left:      0,        // Number of pixels along the X axis to scroll the window or element.
    behavior:  'smooth'  // ('smooth'|'auto') - animate smoothly, or move in a single jump
}

DOCS: https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll

SEE ALSO: .scrollIntoView() https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView


DEMO:

_x000D_
_x000D_
document.getElementById('btn').addEventListener('click',function(){

  document.getElementById('container').scroll({top:0,behavior:'smooth'});
  
});
_x000D_
/*DEMO*/
#container{
  width:300px;
  max-height:300px;
  padding:1rem;
  margin-left:auto;
  margin-right:auto;
  background-color:#222;
  color:#ccc;
  text-align:justify;
  overflow-y:auto;
}
#btn{
  width:100%;
  margin-top:1rem;
}
_x000D_
<div id="container">
  <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
  <button id="btn">Scroll to top</button>
</div>
_x000D_
_x000D_
_x000D_

How to tell if JRE or JDK is installed

according to JAVA documentation, the JDK should be installed in this path:

/Library/Java/JavaVirtualMachines/jdkmajor.minor.macro[_update].jdk

See the uninstall JDK part at https://docs.oracle.com/javase/8/docs/technotes/guides/install/mac_jdk.html

So if you can find such folder then the JDK is installed

Clearing all cookies with JavaScript

If you have access to the jquery.cookie plugin, you can erase all cookies this way:

for (var it in $.cookie()) $.removeCookie(it);

Pip install Matplotlib error with virtualenv

As a supplementary, on Amazon EC2, what I need to do is:

sudo yum install freetype-devel
sudo yum install libpng-devel
sudo pip install matplotlib

C# Encoding a text string with line breaks

Try \n\n , it will work! :)

public async Task AjudaAsync(IDialogContext context, LuisResult result){
await context.PostAsync("How can I help you? \n\n 1.To Schedule \n\n 2.Consult");
context.Wait(MessageReceived);
}

How to insert 1000 rows at a time

I create a student table with three column id, student,age. show you this example

declare @id int 
select @id = 1
while @id >=1 and @id <= 1000
begin
    insert into student values(@id, 'jack' + convert(varchar(5), @id), 12)
    select @id = @id + 1
end

this is the result about the example enter image description here

Function Pointers in Java

You can substitue a function pointer with an interface. Lets say you want to run through a collection and do something with each element.

public interface IFunction {
  public void execute(Object o);
}

This is the interface we could pass to some say CollectionUtils2.doFunc(Collection c, IFunction f).

public static void doFunc(Collection c, IFunction f) {
   for (Object o : c) {
      f.execute(o);
   }
}

As an example say we have a collection of numbers and you would like to add 1 to every element.

CollectionUtils2.doFunc(List numbers, new IFunction() {
    public void execute(Object o) {
       Integer anInt = (Integer) o;
       anInt++;
    }
});

Count the number of times a string appears within a string

Your regular expression should be \btrue\b to get around the 'miscontrue' issue Casper brings up. The full solution would look like this:

string searchText = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
string regexPattern = @"\btrue\b";
int numberOfTrues = Regex.Matches(searchText, regexPattern).Count;

Make sure the System.Text.RegularExpressions namespace is included at the top of the file.

nvm is not compatible with the npm config "prefix" option:

Note:
to remove, delete, or uninstall nvm - just remove the $NVM_DIR folder (usually ~/.nvm)
you can try :
rm -rf ~/.nvm

What is managed or unmanaged code in programming?

Managed code is what C#.Net, VB.Net, F#.Net etc compilers create. It runs on the CLR, which among other things offers services like garbage collection, and reference checking, and much more. So think of it as, my code is managed by the CLR.

On the other hand, unmanaged code compiles straight to machine code. It doesn't manage by CLR.

How to use DISTINCT and ORDER BY in same SELECT statement?

If the output of MAX(CreationDate) is not wanted - like in the example of the original question - the only answer is the second statement of Prashant Gupta's answer:

SELECT [Category] FROM [MonitoringJob] 
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC

Explanation: you can't use the ORDER BY clause in an inline function, so the statement in the answer of Prutswonder is not useable in this case, you can't put an outer select around it and discard the MAX(CreationDate) part.

If statements for Checkboxes

I suggest

if (checkbox.IsChecked == true)
{
    //do something
}

Hope it's helpful ^^

How to detect if CMD is running as Administrator/has elevated privileges?

Here's a slight modification of Harry's answer that focuses on elevated status; I'm using this at the start of an install.bat file:

set IS_ELEVATED=0
whoami /groups | findstr /b /c:"Mandatory Label\High Mandatory Level" | findstr /c:"Enabled group" > nul: && set IS_ELEVATED=1
if %IS_ELEVATED%==0 (
    echo You must run the command prompt as administrator to install.
    exit /b 1
)

This definitely worked for me and the principle seems to be sound; from MSFT's Chris Jackson:

When you are running elevated, your token contains an ACE called Mandatory Label\High Mandatory Level.

Javascript Date - set just the date, ignoring time?

How about .toDateString()?

Alternatively, use .getDate(), .getMonth(), and .getYear()?

In my mind, if you want to group things by date, you simply want to access the date, not set it. Through having some set way of accessing the date field, you can compare them and group them together, no?

Check out all the fun Date methods here: MDN Docs


Edit: If you want to keep it as a date object, just do this:

var newDate = new Date(oldDate.toDateString());

Date's constructor is pretty smart about parsing Strings (though not without a ton of caveats, but this should work pretty consistently), so taking the old Date and printing it to just the date without any time will result in the same effect you had in the original post.

Change Tomcat Server's timeout in Eclipse

I have tomcat 8 Update 25 and tomcat 7 but facing the same issue it shows the message Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.

How to exit if a command failed?

If you want that behavior for all commands in your script, just add

  set -e 
  set -o pipefail

at the beginning of the script. This pair of options tell the bash interpreter to exit whenever a command returns with a non-zero exit code.

This does not allow you to print an exit message, though.

Update select2 data without rebuilding the control

As best I can tell, it is not possible to update the select2 options without refreshing the entire list or entering some search text and using a query function.

What are those buttons supposed to do? If they are used to determine the select options, why not put them outside of the select box, and have them programmatically set the select box data and then open it? I don't understand why you would want to put them on top of the search box. If the user is not supposed to search, you can use the minimumResultsForSearch option to hide the search feature.

Edit: How about this...

HTML:

<input type="hidden" id="select2" class="select" />

Javascript

var data = [{id: 0, text: "Zero"}],
    select = $('#select2');

select.select2({
  query: function(query) {
    query.callback({results: data});
  },
  width: '150px'
});

console.log('Opening select2...');
select.select2('open');

setTimeout(function() {
  console.log('Updating data...');
  data = [{id: 1, text: 'One'}];
}, 1500);

setTimeout(function() {
  console.log('Fake keyup-change...');
  select.data().select2.search.trigger('keyup-change');
}, 3000);

Example: Plunker

Edit 2: That will at least get it to update the list, however there is still some weirdness if you have entered search text before triggering the keyup-change event.

how can I enable PHP Extension intl?

i had this prob but solved ! enable the extension=php_intl.dll now if you restart XAMPP this error will popup "msvcp110.dll is missing form your computer"

for solving this error: download this file from : https://www.dll-files.com/msvcp110.dll.html then put this file to C:windows and then restart xampp it will works.

How to retrieve the first word of the output of a command in bash?

I wondered how several of the top answers measured up in terms of speed. I tested the following:

1 @mattbh's

echo "..." | awk '{print $1;}'

2 @ghostdog74's

string="..."; set -- $string; echo $1

3 @boontawee-home's

echo "..." | { read -a array ; echo ${array[0]} ; }

and 4 @boontawee-home's

echo "..." | { read first _ ; echo $first ; }

I measured them with Python's timeit in a Bash script in a Zsh terminal on macOS, using a test string with 215 5-letter words. Did each measurement five times (the results were all for 100 loops, best of 3), and averaged the results:

method       time
--------------------------------
1. awk       9.2ms
2. set       11.6ms (1.26 * "1")
3. read -a   11.7ms (1.27 * "1")
4. read      13.6ms (1.48 * "1")

Nice job, voters The votes (as of this writing) match the solutions' speed!

How can I print out all possible letter combinations a given phone number can represent?

I am rather a newbie so please correct me wherever I am wrong.

First thing is looking into space & time complexity. Which is really bad since it's factorial so for factorial(7) = 5040 any recursive algorithm would do. But for factorial(12) ~= 4 * 10^8 which can cause stack overflow in recursive solution.

So I would not attempt a recursive algorithm. Looping solution is very straight forward using "Next Permutation".

So I would create and array {0, 1, 2, 3, 4, 5} and generate all permutation and while printing replace them with respective characters eg. 0=A, 5=F

Next Perm algorithm works as follows. eg Given 1,3,5,4 next permutation is 1,4,3,5

Steps for finding next perm.

  1. From right to left, find first decreasing number. eg 3

  2. From left to right, find lowest number bigger than 3 eg. 4

  3. Swap these numbers as reverse the subset. 1,4,5,3 reverse subset 1,4,3,5

Using Next permutation ( or rotation) you generate specific subset of permutations, say you want to show 1000 permutations starting from a particular phone number. This can save you from having all numbers in memory. If I store numbers as 4 byte integers, 10^9 bytes = 1 GB !.

relative path in BAT script

either bin\Iris.exe (no leading slash - because that means start right from the root)
or \Program\bin\Iris.exe (full path)

How to stop a JavaScript for loop?

Use for of loop instead which is part of ES2015 release. Unlike forEach, we can use return, break and continue. See https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/

let arr = [1,2,3,4,5];
for (let ele of arr) {
  if (ele > 3) break;
  console.log(ele);
}

How to dynamically create columns in datatable and assign values to it?

What have you tried, what was the problem?

Creating DataColumns and add values to a DataTable is straight forward:

Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
    dt.Rows.Add(i, "Row #" & i)
Next

Edit:

If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml.

How do I use arrays in C++?

Programmers often confuse multidimensional arrays with arrays of pointers.

Multidimensional arrays

Most programmers are familiar with named multidimensional arrays, but many are unaware of the fact that multidimensional array can also be created anonymously. Multidimensional arrays are often referred to as "arrays of arrays" or "true multidimensional arrays".

Named multidimensional arrays

When using named multidimensional arrays, all dimensions must be known at compile time:

int H = read_int();
int W = read_int();

int connect_four[6][7];   // okay

int connect_four[H][7];   // ISO C++ forbids variable length array
int connect_four[6][W];   // ISO C++ forbids variable length array
int connect_four[H][W];   // ISO C++ forbids variable length array

This is how a named multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
connect_four: |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+

Note that 2D grids such as the above are merely helpful visualizations. From the point of view of C++, memory is a "flat" sequence of bytes. The elements of a multidimensional array are stored in row-major order. That is, connect_four[0][6] and connect_four[1][0] are neighbors in memory. In fact, connect_four[0][7] and connect_four[1][0] denote the same element! This means that you can take multi-dimensional arrays and treat them as large, one-dimensional arrays:

int* p = &connect_four[0][0];
int* q = p + 42;
some_int_sequence_algorithm(p, q);

Anonymous multidimensional arrays

With anonymous multidimensional arrays, all dimensions except the first must be known at compile time:

int (*p)[7] = new int[6][7];   // okay
int (*p)[7] = new int[H][7];   // okay

int (*p)[W] = new int[6][W];   // ISO C++ forbids variable length array
int (*p)[W] = new int[H][W];   // ISO C++ forbids variable length array

This is how an anonymous multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
        +---> |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |
      +-|-+
   p: | | |
      +---+

Note that the array itself is still allocated as a single block in memory.

Arrays of pointers

You can overcome the restriction of fixed width by introducing another level of indirection.

Named arrays of pointers

Here is a named array of five pointers which are initialized with anonymous arrays of different lengths:

int* triangle[5];
for (int i = 0; i < 5; ++i)
{
    triangle[i] = new int[5 - i];
}

// ...

for (int i = 0; i < 5; ++i)
{
    delete[] triangle[i];
}

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
triangle: | | | | | | | | | | |
          +---+---+---+---+---+

Since each line is allocated individually now, viewing 2D arrays as 1D arrays does not work anymore.

Anonymous arrays of pointers

Here is an anonymous array of 5 (or any other number of) pointers which are initialized with anonymous arrays of different lengths:

int n = calculate_five();   // or any other number
int** p = new int*[n];
for (int i = 0; i < n; ++i)
{
    p[i] = new int[n - i];
}

// ...

for (int i = 0; i < n; ++i)
{
    delete[] p[i];
}
delete[] p;   // note the extra delete[] !

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
          | | | | | | | | | | |
          +---+---+---+---+---+
            ^
            |
            |
          +-|-+
       p: | | |
          +---+

Conversions

Array-to-pointer decay naturally extends to arrays of arrays and arrays of pointers:

int array_of_arrays[6][7];
int (*pointer_to_array)[7] = array_of_arrays;

int* array_of_pointers[6];
int** pointer_to_pointer = array_of_pointers;

However, there is no implicit conversion from T[h][w] to T**. If such an implicit conversion did exist, the result would be a pointer to the first element of an array of h pointers to T (each pointing to the first element of a line in the original 2D array), but that pointer array does not exist anywhere in memory yet. If you want such a conversion, you must create and fill the required pointer array manually:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = connect_four[i];
}

// ...

delete[] p;

Note that this generates a view of the original multidimensional array. If you need a copy instead, you must create extra arrays and copy the data yourself:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = new int[7];
    std::copy(connect_four[i], connect_four[i + 1], p[i]);
}

// ...

for (int i = 0; i < 6; ++i)
{
    delete[] p[i];
}
delete[] p;

How to check if an object implements an interface?

Use

if (gor instanceof Monster) {
    //...
}

What is an instance variable in Java?

Instance variable is the variable declared inside a class, but outside a method: something like:

class IronMan {

    /** These are all instance variables **/
    public String realName;
    public String[] superPowers;
    public int age;

    /** Getters and setters here **/
}

Now this IronMan Class can be instantiated in another class to use these variables. Something like:

class Avengers {

    public static void main(String[] a) {
        IronMan ironman = new IronMan();
        ironman.realName = "Tony Stark";
        // or
        ironman.setAge(30);
    }

}

This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

How do I set a textbox's text to bold at run time?

Depending on your application, you'll probably want to use that Font assignment either on text change or focus/unfocus of the textbox in question.

Here's a quick sample of what it could look like (empty form, with just a textbox. Font turns bold when the text reads 'bold', case-insensitive):

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

    private void RegisterEvents()
    {
        _tboTest.TextChanged += new EventHandler(TboTest_TextChanged);
    }

    private void TboTest_TextChanged(object sender, EventArgs e)
    {
        // Change the text to bold on specified condition
        if (_tboTest.Text.Equals("Bold", StringComparison.OrdinalIgnoreCase))
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Bold);
        }
        else
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Regular);
        }
    }
}

What is the use of hashCode in Java?

hashCode() is a unique code which is generated by the JVM for every object creation.

We use hashCode() to perform some operation on hashing related algorithm like Hashtable, Hashmap etc..

The advantages of hashCode() make searching operation easy because when we search for an object that has unique code, it helps to find out that object.

But we can't say hashCode() is the address of an object. It is a unique code generated by JVM for every object.

That is why nowadays hashing algorithm is the most popular search algorithm.

Server certificate verification failed: issuer is not trusted

can you try to run svn checkout once manually to your URL https://yoururl/trunk C:\ant-1.8.1\Test_Checkout using command line and accept certificate.

Or as @AndrewSpear says below

Rather than checking out manually run svn list https://your.repository.url from Terminal (Mac) / Command Line (Win) to get the option to accept the certificate permanently

svn will ask you for confirmation. accept it permanently.

After that this should work for subsequent requests from ant script.

jQuery find events handlers registered with an object

jQuery is not letting you just simply access the events for a given element. You can access them using undocumented internal method

$._data(element, "events")

But it still won't give you all the events, to be precise won't show you events assigned with

$([selector|element]).on()

These events are stored inside document, so you can fetch them by browsing through

$._data(document, "events")

but that is hard work, as there are events for whole webpage.

Tom G above created function that filters document for only events of given element and merges output of both methods, but it had a flaw of duplicating events in the output (and effectively on the element's jQuery internal event list messing with your application). I fixed that flaw and you can find the code below. Just paste it into your dev console or into your app code and execute it when needed to get nice list of all events for given element.

What is important to notice, element is actually HTMLElement, not jQuery object.

function getEvents(element) {
    var elemEvents = $._data(element, "events");
    var allDocEvnts = $._data(document, "events");
    function equalEvents(evt1, evt2)
    {
        return evt1.guid === evt2.guid;
    }

    for(var evntType in allDocEvnts) {
        if(allDocEvnts.hasOwnProperty(evntType)) {
            var evts = allDocEvnts[evntType];
            for(var i = 0; i < evts.length; i++) {
                if($(element).is(evts[i].selector)) {
                    if(elemEvents == null) {
                        elemEvents = {};
                    }
                    if(!elemEvents.hasOwnProperty(evntType)) {
                        elemEvents[evntType] = [];
                    }
                    if(!elemEvents[evntType].some(function(evt) { return equalEvents(evt, evts[i]); })) {
                        elemEvents[evntType].push(evts[i]);
                    }
                }
            }
        }
    }
    return elemEvents;
}

Immutable array in Java

Since Guava 22, from package com.google.common.primitives you can use three new classes, which have a lower memory footprint compared to ImmutableList.

They also have a builder. Example:

int size = 2;
ImmutableLongArray longArray = ImmutableLongArray.builder(size)
  .add(1L)
  .add(2L)
  .build();

or, if the size is known at compile-time:

ImmutableLongArray longArray = ImmutableLongArray.of(1L, 2L);

This is another way of getting an immutable view of an array for Java primitives.

How to cin to a vector

You can simply do this with the help of for loop
->Ask on runtime from a user (how many inputs he want to enter) and the treat same like arrays.

int main() {
        int sizz,input;
        std::vector<int> vc1;

        cout<< "How many Numbers you want to enter : ";
        cin >> sizz;
        cout << "Input Data : " << endl;
        for (int i = 0; i < sizz; i++) {//for taking input form the user
            cin >> input;
            vc1.push_back(input);
        }
        cout << "print data of vector : " << endl;
        for (int i = 0; i < sizz; i++) {
            cout << vc1[i] << endl;
        }
     }

Using GitLab token to clone without authentication

These days (Oct 2020) you can use just the following

git clone $CI_REPOSITORY_URL

Which will expand to something like:

git clone https://gitlab-ci-token:[MASKED]@gitlab.com/gitlab-examples/ci-debug-trace.git

Where the "token" password is ephemeral token, it should be revoked after a build is complete.

Git merge with force overwrite

These commands will help in overwriting code of demo branch into master

git fetch --all

Pull Your demo branch on local

git pull origin demo

Now checkout to master branch. This branch will be completely changed with the code on demo branch

git checkout master

Stay in the master branch and run this command.

git reset --hard origin/demo

reset means you will be resetting current branch

--hard is a flag that means it will be reset without raising any merge conflict

origin/demo will be the branch that will be considered to be the code that will forcefully overwrite current master branch

The output of the above command will show you your last commit message on origin/demo or demo branch enter image description here

Then, in the end, force push the code on the master branch to your remote repo.

git push --force

How do I download the Android SDK without downloading Android Studio?

Well the folks who are trying to download either on *ix or Ec2 machine would suggest to clean approach in below steps:

$ mkdir android-sdk
$ cd android-sdk
$ mkdir cmdline-tools
$ cd cmdline-tools
$ wget https://dl.google.com/android/repository/commandlinetools-linux-*.zip
$ unzip commandlinetools-linux-*.zip

The king - sdkmanager lives inside

cmdline-tools/tools/bin

, you'd better set in PATH environment variable.

but cmdline-tools should not be set as ANDROID_HOME. Because later, when updating Android SDK, or installing more packages, the other packages will be placed under ANDROID_HOME, but not under cmdline-tools.

The final, complete ANDROID_HOME directory structure should look like below, consist of quite a few sub-directories:

build-tools, cmdline-tools, emulator, licenses, patcher, platform-tools, platforms, tools. You can easily point out that build-tools and cmdline-tools are siblings, all resides inside the parent ANDROID_HOME.

Add SDK tools directory in PATH environment variable to make executable available globally. Add below line either in ~/.bashrc or ~/.profile file to make it permanent.

In order to edit the ~/.bashrc simply can be editable in vim mode

$ vim .bashrc

Now set your preferred ANDROID_HOME in .bashrc file :

export ANDROID_HOME=/home/<user>/android-sdk
export PATH=${PATH}:$ANDROID_HOME/cmdline-tools/tools/bin:$ANDROID_HOME/platform-tools

here strange thing that we haven't download the platform-tools directory as of now but mentoning it under path but let it be as it will help you avoid remodification on the same file later.

Now go inside the same directory:

$ cd android-sdk

NOTE: well in first attempt sdkmanager command didnt found for me so I close the terminal and again created the connection or you can also refresh the same if it works for you.

after that use the sdkmanager to list and install the packages needed:

$ sdkmanager "platform-tools" "platforms;android-27" "build-tools;27.0.3"

Hence Sdkmanager path is already set it will be accessible from anywhere:

$ sdkmanager --update


$ sdkmanager --list
Installed packages:=====================] 100% Computing updates...             
  Path                 | Version | Description                    | Location             
  -------              | ------- | -------                        | -------              
  build-tools;27.0.3   | 27.0.3  | Android SDK Build-Tools 27.0.3 | build-tools/27.0.3/  
  emulator             | 30.0.12 | Android Emulator               | emulator/            
  patcher;v4           | 1       | SDK Patch Applier v4           | patcher/v4/          
  platform-tools       | 30.0.1  | Android SDK Platform-Tools     | platform-tools/      
  platforms;android-27 | 3       | Android SDK Platform 27        | platforms/android-27/

How to go back to previous page if back button is pressed in WebView?

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // Check if the key event was the Back button and if there's history
    if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
        myWebView.goBack();
        return true;
    }
    // If it wasn't the Back key or there's no web page history, bubble up to the default
    // system behavior (probably exit the activity)
    return super.onKeyDown(keyCode, event);
}

JavaScript isset() equivalent

I always use this generic function to prevent errrors on primitive variables as well as arrays and objects.

isset = function(obj) {
  var i, max_i;
  if(obj === undefined) return false;
  for (i = 1, max_i = arguments.length; i < max_i; i++) {
    if (obj[arguments[i]] === undefined) {
        return false;
    }
    obj = obj[arguments[i]];
  }
  return true;
};

console.log(isset(obj));                   // returns false
var obj = 'huhu';
console.log(isset(obj));                   // returns true
obj = {hallo:{hoi:'hoi'}};
console.log(isset(obj, 'niet'));           // returns false
console.log(isset(obj, 'hallo'));          // returns true
console.log(isset(obj, 'hallo', 'hallo')); // returns false
console.log(isset(obj, 'hallo', 'hoi'));   // returns true

How to host a Node.Js application in shared hosting

I installed Node.js on bluehost.com (a shared server) using:

wget <path to download file>
tar -xf <gzip file>
mv <gzip_file_dir> node

This will download the tar file, extract to a directory and then rename that directory to the name 'node' to make it easier to use.

then

./node/bin/npm install jt-js-sample

Returns:
npm WARN engine [email protected]: wanted: {"node":"0.10.x"} (current: {"node":"0.12.4","npm":"2.10.1"})
[email protected] node_modules/jt-js-sample
+-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])

I can now use the commands:

# ~/node/bin/node -v
v0.12.4

# ~/node/bin/npm -v
2.10.1

For security reasons, I have renamed my node directory to something else.

Is there a real solution to debug cordova apps

If you use phonegap build, there is an option to enable debug.


For local builds, you can install weinre with npm : https://npmjs.org/package/weinre

And the link to the weinre docs : http://people.apache.org/~pmuellr/weinre/docs/latest/


And there is something called chrome remote debugging but I don't know much about it, you can have a look at Raymond Camden's article : http://www.raymondcamden.com/index.cfm/2014/1/2/Apache-Cordova-33-and-Remote-Debugging-for-Android

Docs for the chrome remote debugging : https://developers.google.com/chrome-developer-tools/docs/remote-debugging (if I understood correctly you need an android device with chrome as default browser) Maybe the closest to your dream solution?

The action or event has been blocked by Disabled Mode

No. Go to database tools (for 2007) and click checkmark on the Message Bar. Then, after the message bar apears, click on Options, and then Enable. Hope this helps.

Dimitri

How to call a vue.js function on page load

You need to do something like this (If you want to call the method on page load):

new Vue({
    // ...
    methods:{
        getUnits: function() {...}
    },
    created: function(){
        this.getUnits()
    }
});

How to display all methods of an object?

var methods = [];
for (var m in obj) {
    if (typeof obj[m] == "function") {
        methods.push(m);
    }
}
alert(methods.join(","));

This way, you will get all methods that you can call on obj. This includes the methods that it "inherits" from its prototype (like getMethods() in java). If you only want to see those methods defined directly by obj you can check with hasOwnProperty:

var methods = [];
for (var m in obj) {        
    if (typeof obj[m] == "function" && obj.hasOwnProperty(m)) {
        methods.push(m);
    }
}
alert(methods.join(","));

Is it possible to sort a ES6 map object?

Short answer

 new Map([...map].sort((a, b) => 
   // Some sort function comparing keys with a[0] b[0] or values with a[1] b[1]
 ))

If you're expecting strings: As normal for .sort you need to return -1 if lower and 0 if equal; for strings, the recommended way is using .localeCompare() which does this correctly and automatically handles awkward characters like ä where the position varies by user locale.

So here's how to sort a map by string keys:

 new Map([...map].sort((a, b) => String(a[0]).localeCompare(b[0])))

...and by string values:

 new Map([...map].sort((a, b) => String(a[1]).localeCompare(b[1])))

In detail with examples

tldr: ...map.entries() is redundant, just ...map is fine; and a lazy .sort() without passing a sort function risks weird edge case bugs caused by string coercion.

The .entries() in [...map.entries()] (suggested in many answers) is redundant, probably adding an extra iteration of the map unless the JS engine optimises that away for you.

In the simple test case, you can do what the question asks for with:

new Map([...map].sort())

...which, if the keys are all strings, compares squashed and coerced comma-joined key-value strings like '2-1,foo' and '0-1,[object Object]', returning a new Map with the new insertion order:

Note: if you see only {} in SO's console output, look in your real browser console

_x000D_
_x000D_
const map = new Map([
  ['2-1', 'foo'],
  ['0-1', { bar: 'bar' }],
  ['3-5', () => 'fuz'],
  ['3-2', [ 'baz' ]]
])

console.log(new Map([...map].sort()))
_x000D_
_x000D_
_x000D_

HOWEVER, it's not a good practice to rely on coercion and stringification like this. You can get surprises like:

_x000D_
_x000D_
const map = new Map([
  ['2', '3,buh?'],
  ['2,1', 'foo'],
  ['0,1', { bar: 'bar' }],
  ['3,5', () => 'fuz'],
  ['3,2', [ 'baz' ]],
])

// Compares '2,3,buh?' with '2,1,foo'
// Therefore sorts ['2', '3,buh?'] ******AFTER****** ['2,1', 'foo']
console.log('Buh?', new Map([...map].sort()))

// Let's see exactly what each iteration is using as its comparator
for (const iteration of map) {
  console.log(iteration.toString())
}
_x000D_
_x000D_
_x000D_

Bugs like this are really hard to debug - don't risk it!

If you want to sort on keys or values, it's best to access them explicitly with a[0] and b[0] in the sort function, like this. Note that we should return -1 and 1 for before and after, not false or 0 as with raw a[0] > b[0] because that is treated as equals:

_x000D_
_x000D_
const map = new Map([
  ['2,1', 'this is overwritten'],
  ['2,1', '0,1'],
  ['0,1', '2,1'],
  ['2,2', '3,5'],
  ['3,5', '2,1'],
  ['2', ',9,9']
])

const sortStringKeys = (a, b) => String(a[0]).localeCompare(b[0])
const sortStringValues = (a, b) => String(a[1]).localeCompare(b[1])

console.log('By keys:', new Map([...map].sort(sortStringKeys)))
console.log('By values:', new Map([...map].sort(sortStringValues)))
_x000D_
_x000D_
_x000D_

jQuery select box validation

Since you cannot set value="" within your first option, you'll need to create your own rule using the built-in addMethod() method.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            year: {
                selectcheck: true
            }
        }
    });

    jQuery.validator.addMethod('selectcheck', function (value) {
        return (value != '0');
    }, "year required");

});

HTML:

<select name="year">
    <option value="0">Year</option>
    <option value="1">1955</option>
    <option value="2">1956</option>
</select>

Working Demo: http://jsfiddle.net/tPRNd/


Original Answer: (Only if you can set value="" within the first option)

To properly validate a select element with the jQuery Validate plugin simply requires that the first option contains value="". So remove the 0 from value="0" and it's fixed.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            year: {
                required: true,
            }
        }
    });

});

HTML:

<select name="year">
    <option value="">Year</option>
    <option value="1">1955</option>
    <option value="2">1956</option>
</select>

Demo: http://jsfiddle.net/XGtEr/

Is there an effective tool to convert C# code to Java code?

Try to look at Net2Java It seems to me the best option for automatic (or semi-automatic at least) conversion from C# to Java

Check if cookie exists else set cookie to Expire in 10 days

You need to read and write document.cookie

if (document.cookie.indexOf("visited=") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}

How to get query parameters from URL in Angular 5?

Just stumbled upon the same problem and most answers here seem to only solve it for Angular internal routing, and then some of them for route parameters which is not the same as request parameters.

I am guessing that I have a similar use case to the original question by Lars.

For me the use case is e.g. referral tracking:

Angular running on mycoolpage.com, with hash routing, so mycoolpage.com redirects to mycoolpage.com/#/. For referral, however, a link such as mycoolpage.com?referrer=foo should also be usable. Unfortunately, Angular immediately strips the request parameters, going directly to mycoolpage.com/#/.

Any kind of 'trick' with using an empty component + AuthGuard and getting queryParams or queryParamMap did, unfortunately, not work for me. They were always empty.

My hacky solution ended up being to handle this in a small script in index.html which gets the full URL, with request parameters. I then get the request param value via string manipulation and set it on window object. A separate service then handles getting the id from the window object.

index.html script

const paramIndex = window.location.href.indexOf('referrer=');
if (!window.myRef && paramIndex > 0) {
  let param = window.location.href.substring(paramIndex);
  param = param.split('&')[0];
  param = param.substr(param.indexOf('=')+1);
  window.myRef = param;
}

Service

declare var window: any;

@Injectable()
export class ReferrerService {

  getReferrerId() {
    if (window.myRef) {
      return window.myRef;
    }
    return null;
  }
}

What is a plain English explanation of "Big O" notation?

Not sure I'm further contributing to the subject but still thought I'd share: I once found this blog post to have some quite helpful (though very basic) explanations & examples on Big O:

Via examples, this helped get the bare basics into my tortoiseshell-like skull, so I think it's a pretty descent 10-minute read to get you headed in the right direction.

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

The only difference : synchronized blocks allows granular locking unlike synchronized method

Basically synchronized block or methods have been used to write thread safe code by avoiding memory inconsistency errors.

This question is very old and many things have been changed during last 7 years. New programming constructs have been introduced for thread safety.

You can achieve thread safety by using advanced concurrency API instead of synchronied blocks. This documentation page provides good programming constructs to achieve thread safety.

Lock Objects support locking idioms that simplify many concurrent applications.

Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.

Concurrent Collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.

Atomic Variables have features that minimize synchronization and help avoid memory consistency errors.

ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.

Better replacement for synchronized is ReentrantLock, which uses Lock API

A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

Example with locks:

class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }
 }

Refer to java.util.concurrent and java.util.concurrent.atomic packages too for other programming constructs.

Refer to this related question too:

Synchronization vs Lock

MsgBox "" vs MsgBox() in VBScript

To my knowledge these are the rules for calling subroutines and functions in VBScript:

  • When calling a subroutine or a function where you discard the return value don't use parenthesis
  • When calling a function where you assign or use the return value enclose the arguments in parenthesis
  • When calling a subroutine using the Call keyword enclose the arguments in parenthesis

Since you probably wont be using the Call keyword you only need to learn the rule that if you call a function and want to assign or use the return value you need to enclose the arguments in parenthesis. Otherwise, don't use parenthesis.

Here are some examples:

  • WScript.Echo 1, "two", 3.3 - calling a subroutine

  • WScript.Echo(1, "two", 3.3) - syntax error

  • Call WScript.Echo(1, "two", 3.3) - keyword Call requires parenthesis

  • MsgBox "Error" - calling a function "like" a subroutine

  • result = MsgBox("Continue?", 4) - calling a function where the return value is used

  • WScript.Echo (1 + 2)*3, ("two"), (((3.3))) - calling a subroutine where the arguments are computed by expressions involving parenthesis (note that if you surround a variable by parenthesis in an argument list it changes the behavior from call by reference to call by value)

  • WScript.Echo(1) - apparently this is a subroutine call using parenthesis but in reality the argument is simply the expression (1) and that is what tends to confuse people that are used to other programming languages where you have to specify parenthesis when calling subroutines

  • I'm not sure how to interpret your example, Randomize(). Randomize is a subroutine that accepts a single optional argument but even if the subroutine didn't have any arguments it is acceptable to call it with an empty pair of parenthesis. It seems that the VBScript parser has a special rule for an empty argument list. However, my advice is to avoid this special construct and simply call any subroutine without using parenthesis.

I'm quite sure that these syntactic rules applies across different versions of operating systems.

Getting DOM elements by classname

There is also another approach without the use of DomXPath or Zend_Dom_Query.

Based on dav's original function, I wrote the following function that returns all the children of the parent node whose tag and class match the parameters.

function getElementsByClass(&$parentNode, $tagName, $className) {
    $nodes=array();

    $childNodeList = $parentNode->getElementsByTagName($tagName);
    for ($i = 0; $i < $childNodeList->length; $i++) {
        $temp = $childNodeList->item($i);
        if (stripos($temp->getAttribute('class'), $className) !== false) {
            $nodes[]=$temp;
        }
    }

    return $nodes;
}

suppose you have a variable $html the following HTML:

<html>
 <body>
  <div id="content_node">
    <p class="a">I am in the content node.</p>
    <p class="a">I am in the content node.</p>
    <p class="a">I am in the content node.</p>    
  </div>
  <div id="footer_node">
    <p class="a">I am in the footer node.</p>
  </div>
 </body>
</html>

use of getElementsByClass is as simple as:

$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);
$content_node=$dom->getElementById("content_node");

$div_a_class_nodes=getElementsByClass($content_node, 'div', 'a');//will contain the three nodes under "content_node".

Is there a command line utility for rendering GitHub flavored Markdown?

I've not found a quick and easy method for GitHub-flavoured Markdown, but I have found a slightly more generic version - Pandoc. It converts from/to a number of formats, including Markdown, Rest, HTML and others.

I've also developed a Makefile to convert all .md files to .html (in large part to the example at Writing, Markdown and Pandoc):

# 'Makefile'
MARKDOWN = pandoc --from gfm --to html --standalone
all: $(patsubst %.md,%.html,$(wildcard *.md)) Makefile

clean:
    rm -f $(patsubst %.md,%.html,$(wildcard *.md))
    rm -f *.bak *~

%.html: %.md
    $(MARKDOWN) $< --output $@

Append to string variable

var str1 = 'abc';
var str2 = str1+' def'; // str2 is now 'abc def'

Web scraping with Java

For tasks of this type I usually use Crawller4j + Jsoup.

With crawler4j I download the pages from a domain, you can specify which ULR with a regular expression.

With jsoup, I "parsed" the html data you have searched for and downloaded with crawler4j.

Normally you can also download data with jsoup, but Crawler4J makes it easier to find links. Another advantage of using crawler4j is that it is multithreaded and you can configure the number of concurrent threads

https://github.com/yasserg/crawler4j/wiki

Read file content from S3 bucket with boto3

If you already know the filename, you can use the boto3 builtin download_fileobj

import boto3

from io import BytesIO

session = boto3.Session()
s3_client = session.client("s3")

f = BytesIO()
s3_client.download_fileobj(bucket_name, filename, f)
f.seek(0)
print(f.getvalue())

How do I open a Visual Studio project in design view?

From the Solution Explorer window select your form, right-click, click on View Designer. Voila! The form should display.

I tried posting a couple screenshots, but this is my first post; therefore, I could not post any images.

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

You are catching the error but then you are re throwing it. You should try and handle it more gracefully, otherwise your user is going to see 500, internal server, errors.

You may want to send back a response telling the user what went wrong as well as logging the error on your server.

I am not sure exactly what errors the request might return, you may want to return something like.

router.get("/emailfetch", authCheck, async (req, res) => {
  try {
    let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
      emailFetch = emailFetch.data
      res.send(emailFetch)
   } catch(error) {
      res.status(error.response.status)
      return res.send(error.message);
    })

})

This code will need to be adapted to match the errors that you get from the axios call.

I have also converted the code to use the try and catch syntax since you are already using async.

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

I suggest a convenient way to solve this problem. Just assign the attribute "android:configChanges" value as followed in the Mainfest.xml for your errored activity. like this:

<activity android:name=".main.MainActivity"
              android:label="mainActivity"
              android:configChanges="orientation|keyboardHidden|navigation">
</activity>

the first solution I gave out had really reduced the frequency of OOM error to a low level. But, it did not solve the problem totally. And then I will give out the 2nd solution:

As the OOM detailed, I have used too much runtime memory. So, I reduce the picture size in ~/res/drawable of my project. Such as an overqualified picture which has a resolution of 128X128, could be resized to 64x64 which would also be suitable for my application. And after I did so with a pile of pictures, the OOM error doesn't occur again.

How can I get the list of files in a directory using C or C++?

Since files and sub directories of a directory are generally stored in a tree structure, an intuitive way is to use DFS algorithm to recursively traverse each of them. Here is an example in windows operating system by using basic file functions in io.h. You can replace these functions in other platform. What I want to express is that the basic idea of DFS perfectly meets this problem.

#include<io.h>
#include<iostream.h>
#include<string>
using namespace std;

void TraverseFilesUsingDFS(const string& folder_path){
   _finddata_t file_info;
   string any_file_pattern = folder_path + "\\*";
   intptr_t handle = _findfirst(any_file_pattern.c_str(),&file_info);
   //If folder_path exsist, using any_file_pattern will find at least two files "." and "..", 
   //of which "." means current dir and ".." means parent dir
   if (handle == -1){
       cerr << "folder path not exist: " << folder_path << endl;
       exit(-1);
   }
   //iteratively check each file or sub_directory in current folder
   do{
       string file_name=file_info.name; //from char array to string
       //check whtether it is a sub direcotry or a file
       if (file_info.attrib & _A_SUBDIR){
            if (file_name != "." && file_name != ".."){
               string sub_folder_path = folder_path + "\\" + file_name;                
               TraverseFilesUsingDFS(sub_folder_path);
               cout << "a sub_folder path: " << sub_folder_path << endl;
            }
       }
       else
            cout << "file name: " << file_name << endl;
    } while (_findnext(handle, &file_info) == 0);
    //
    _findclose(handle);
}

ERROR! MySQL manager or server PID file could not be found! QNAP

After a lot of searching, I was able to fix the "PID file cannot be found" issue on my machine. I'm on OS X 10.9.3 and installed mysql via Homebrew.

First, I found my PID file here:

/usr/local/var/mysql/{username}.pid

Next, I located my my.cnf file here:

/usr/local/Cellar/mysql/5.6.19/my.cnf

Finally, I added this line to the bottom of my.cnf:

pid-file = /usr/local/var/mysql/{username}.pid

Hopefully this works for someone else, and saves you a headache! Don't forget to replace {username} with your machine's name (jeffs-air-2 in my case).

Remove an item from an IEnumerable<T> collection

You can not remove an item from an IEnumerable; it can only be enumerated, as described here: http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx

You have to use an ICollection if you want to add and remove items. Maybe you can try and casting your IEnumerable; this will off course only work if the underlying object implements ICollection`.

See here for more on ICollection: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx

You can, of course, just create a new list from your IEnumerable, as pointed out by lante, but this might be "sub optimal", depending on your actual use case, of course.

ICollection is probably the way to go.

The 'json' native gem requires installed build tools

My solution is simplier and checked on Ruby 2.0. It also enable download Json. (run CMD.exe as administrator)

    C:\RubyDev>devkitvars.bat
    Adding the DevKit to PATH...

And then write again gem command.

How to convert Observable<any> to array[]

Using HttpClient (Http's replacement) in Angular 4.3+, the entire mapping/casting process is made simpler/eliminated.

Using your CountryData class, you would define a service method like this:

getCountries()  {
  return this.httpClient.get<CountryData[]>('http://theUrl.com/all');
}

Then when you need it, define an array like this:

countries:CountryData[] = [];

and subscribe to it like this:

this.countryService.getCountries().subscribe(countries => this.countries = countries);

A complete setup answer is posted here also.

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

Quick Explanation

VALID: Don't apply any padding, i.e., assume that all dimensions are valid so that input image fully gets covered by filter and stride you specified.

SAME: Apply padding to input (if needed) so that input image gets fully covered by filter and stride you specified. For stride 1, this will ensure that output image size is same as input.

Notes

  • This applies to conv layers as well as max pool layers in same way
  • The term "valid" is bit of a misnomer because things don't become "invalid" if you drop part of the image. Sometime you might even want that. This should have probably be called NO_PADDING instead.
  • The term "same" is a misnomer too because it only makes sense for stride of 1 when output dimension is same as input dimension. For stride of 2, output dimensions will be half, for example. This should have probably be called AUTO_PADDING instead.
  • In SAME (i.e. auto-pad mode), Tensorflow will try to spread padding evenly on both left and right.
  • In VALID (i.e. no padding mode), Tensorflow will drop right and/or bottom cells if your filter and stride doesn't full cover input image.

Unable to specify the compiler with CMake

Never try to set the compiler in the CMakeLists.txt file.

See the CMake FAQ about how to use a different compiler:

https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

(Note that you are attempting method #3 and the FAQ says "(avoid)"...)

We recommend avoiding the "in the CMakeLists" technique because there are problems with it when a different compiler was used for a first configure, and then the CMakeLists file changes to try setting a different compiler... And because the intent of a CMakeLists file should be to work with multiple compilers, according to the preference of the developer running CMake.

The best method is to set the environment variables CC and CXX before calling CMake for the very first time in a build tree.

After CMake detects what compilers to use, it saves them in the CMakeCache.txt file so that it can still generate proper build systems even if those variables disappear from the environment...

If you ever need to change compilers, you need to start with a fresh build tree.

Android Fragment no view found for ID?

This error also occurs when having nested Fragments and adding them with getSupportFragmentManager() instead of getChildFragmentManager().

Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:

public class ThreadProvider implements CustomInterface{
...
}

Then in your controller try this:

@Controller
public class ChiusuraController {

    @Autowired
    private CustomInterface chiusuraProvider;
}

The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider extend ThreadProvider Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).

When you DID extend from ThreadProvider assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider type.

If you absolutely need to use ChisuraProvider you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:

<aop:aspectj-autoproxy proxy-target-class="true"/>

Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb

What's the scope of a variable initialized in an if statement?

Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.

(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)

How do I update zsh to the latest version?

If you're not using Homebrew, this is what I just did on MAC OS X Lion (10.7.5):

  1. Get the latest version of the ZSH sourcecode

  2. Untar the download into its own directory then install: ./configure && make && make test && sudo make install

  3. This installs the the zsh binary at /usr/local/bin/zsh.

  4. You can now use the shell by loading up a new terminal and executing the binary directly, but you'll want to make it your default shell...

  5. To make it your default shell you must first edit /etc/shells and add the new path. Then you can either run chsh -s /usr/local/bin/zsh or go to System Preferences > Users & Groups > right click your user > Advanced Options... > and then change "Login shell".

  6. Load up a terminal and check you're now in the correct version with echo $ZSH_VERSION. (I wasn't at first, and it took me a while to figure out I'd configured iTerm to use a specific shell instead of the system default).

Pipe output and capture exit status in Bash

There's an array that gives you the exit status of each command in a pipe.

$ cat x| sed 's///'
cat: x: No such file or directory
$ echo $?
0
$ cat x| sed 's///'
cat: x: No such file or directory
$ echo ${PIPESTATUS[*]}
1 0
$ touch x
$ cat x| sed 's'
sed: 1: "s": substitute pattern can not be delimited by newline or backslash
$ echo ${PIPESTATUS[*]}
0 1

How to position a div scrollbar on the left hand side?

I have the same problem. but when i add direction: rtl; in tabs and accordion combo but it crashes my structure.

The way to do it is add div with direction: rtl; as parent element, and for child div set direction: ltr;.

I use this first https://api.jquery.com/wrap/

$( ".your selector of child element" ).wrap( "<div class='scroll'></div>" );

then just simply work with css :)

In children div add to css

 .your_class {
            direction: ltr;    
        }

And to parent div added by jQuery with class .scroll

.scroll {
            unicode-bidi:bidi-override;
            direction: rtl;
            overflow: scroll;
            overflow-x: hidden!important;
        }

Works prefect for me

http://jsfiddle.net/jw3jsz08/1/

Git On Custom SSH Port

Above answers are nice and great, but not clear for new git users like me. So after some investigation, i offer this new answer.

1 what's the problem with the ssh config file way?

When the config file does not exists, you can create one. Besides port the config file can include other ssh config option:user IdentityFile and so on, the config file looks like

Host mydomain.com
    User git
    Port 12345

If you are running linux, take care the config file must have strict permission: read/write for the user, and not accessible by others

2 what about the ssh url way?

It's cool, the only thing we should know is that there two syntaxes for ssh url in git

  • standard syntax ssh://[user@]host.xz[:port]/path/to/repo.git/
  • scp like syntax [user@]host.xz:path/to/repo.git/

By default Gitlab and Github will show the scp like syntax url, and we can not give the custom ssh port. So in order to change ssh port, we need use the standard syntax

How to configure static content cache per folder and extension in IIS7?

I had the same issue.For me the problem was how to configure a cache limit to images.And i came across this site which gave some insights to the procedure on how the issue can be handled.Hope it will be helpful for you too Link:[https://varvy.com/pagespeed/cache-control.html]

Lodash - difference between .extend() / .assign() and .merge()

If you want a deep copy without override while retaining the same obj reference

obj = _.assign(obj, _.merge(obj, [source]))

How to calculate DATE Difference in PostgreSQL?

This is how I usually do it. A simple number of days perspective of B minus A.

DATE_PART('day', MAX(joindate) - MIN(joindate)) as date_diff

Excel VBA, How to select rows based on data in a column?

The easiest way to do it is to use the End method, which is gives you the cell that you reach by pressing the end key and then a direction when you're on a cell (in this case B6). This won't give you what you expect if B6 or B7 is empty, though.

Dim start_cell As Range
Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Range(start_cell, start_cell.End(xlDown)).Copy Range("[Workbook2.xlsx]Sheet1!A2")

If you can't use End, then you would have to use a loop.

Dim start_cell As Range, end_cell As Range

Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Set end_cell = start_cell

Do Until IsEmpty(end_cell.Offset(1, 0))
    Set end_cell = end_cell.Offset(1, 0)
Loop

Range(start_cell, end_cell).Copy Range("[Workbook2.xlsx]Sheet1!A2")

MySQL error 1449: The user specified as a definer does not exist

You can try this:

$ mysql -u root -p 
> grant all privileges on *.* to `root`@`%` identified by 'password'; 
> flush privileges;

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

How to add extra whitespace in PHP?

you can use the <pre> tag to prevent multiple spaces and linebreaks from being collapsed into one. Or you could use &nbsp; for a typical space (non-breaking space) and <br /> (or <br>) for line breaks.

But don't do <br><br><br><br> just use a <p> tag and adjust the margins with CSS.

<p style="margin-top: 20px;">Some copy...</p>

Although, you should define the styles globally, and not inline as I have done in this example.

When you are outputting strings from PHP you can use "\n" for a new line, and "\t" for a tab.

<?php echo "This is one line\nThis is another line"; ?>

Although, flags like \n or \t only work in double quotes (") not single wuotes (').

ObjectiveC Parse Integer from String

Keep in mind that international users may be using a decimal separator other than . in which case values can get mixed up or just become nil when using intValue on a string.

For example, in the UK 1.23 is written 1,23, so the number 1.777 would be input by user as 1,777, which, as .intValue, will be 1777 not 1 (truncated).


I've made a macro that will convert input text to an NSNumber based on a locale argument which can be nil (if nil it uses device current locale).

#define stringToNumber(__string, __nullable_locale) (\
(^NSNumber *(void){\
NSLocale *__locale = __nullable_locale;\
if (!__locale) {\
__locale = [NSLocale currentLocale];\
}\
NSString *__string_copy = [__string stringByReplacingOccurrencesOfString:__locale.groupingSeparator withString:@""];\
__string_copy = [__string_copy stringByReplacingOccurrencesOfString:__locale.decimalSeparator withString:@"."];\
return @([__string_copy doubleValue]);\
})()\
)

How do I use a C# Class Library in a project?

You need to add a reference to your class library from your project. Right click on the references folder and click add reference. You can either browse for the DLL or, if your class libaray is a project in your solution you can add a project reference.

Get human readable version of file size?

What you're about to find below is by no means the most performant or shortest solution among the ones already posted. Instead, it focuses on one particular issue that many of the other answers miss.

Namely the case when input like 999_995 is given:

Python 3.6.1 ...
...
>>> value = 999_995
>>> base = 1000
>>> math.log(value, base)
1.999999276174054

which, being truncated to the nearest integer and applied back to the input gives

>>> order = int(math.log(value, base))
>>> value/base**order
999.995

This seems to be exactly what we'd expect until we're required to control output precision. And this is when things start to get a bit difficult.

With the precision set to 2 digits we get:

>>> round(value/base**order, 2)
1000 # K

instead of 1M.

How can we counter that?

Of course, we can check for it explicitly:

if round(value/base**order, 2) == base:
    order += 1

But can we do better? Can we get to know which way the order should be cut before we do the final step?

It turns out we can.

Assuming 0.5 decimal rounding rule, the above if condition translates into:

enter image description here

resulting in

def abbreviate(value, base=1000, precision=2, suffixes=None):
    if suffixes is None:
        suffixes = ['', 'K', 'M', 'B', 'T']

    if value == 0:
        return f'{0}{suffixes[0]}'

    order_max = len(suffixes) - 1
    order = log(abs(value), base)
    order_corr = order - int(order) >= log(base - 0.5/10**precision, base)
    order = min(int(order) + order_corr, order_max)

    factored = round(value/base**order, precision)

    return f'{factored:,g}{suffixes[order]}'

giving

>>> abbreviate(999_994)
'999.99K'
>>> abbreviate(999_995)
'1M'
>>> abbreviate(999_995, precision=3)
'999.995K'
>>> abbreviate(2042, base=1024)
'1.99K'
>>> abbreviate(2043, base=1024)
'2K'

What is the bit size of long on 64-bit Windows?

In the Unix world, there were a few possible arrangements for the sizes of integers and pointers for 64-bit platforms. The two mostly widely used were ILP64 (actually, only a very few examples of this; Cray was one such) and LP64 (for almost everything else). The acronynms come from 'int, long, pointers are 64-bit' and 'long, pointers are 64-bit'.

Type           ILP64   LP64   LLP64
char              8      8       8
short            16     16      16
int              64     32      32
long             64     64      32
long long        64     64      64
pointer          64     64      64

The ILP64 system was abandoned in favour of LP64 (that is, almost all later entrants used LP64, based on the recommendations of the Aspen group; only systems with a long heritage of 64-bit operation use a different scheme). All modern 64-bit Unix systems use LP64. MacOS X and Linux are both modern 64-bit systems.

Microsoft uses a different scheme for transitioning to 64-bit: LLP64 ('long long, pointers are 64-bit'). This has the merit of meaning that 32-bit software can be recompiled without change. It has the demerit of being different from what everyone else does, and also requires code to be revised to exploit 64-bit capacities. There always was revision necessary; it was just a different set of revisions from the ones needed on Unix platforms.

If you design your software around platform-neutral integer type names, probably using the C99 <inttypes.h> header, which, when the types are available on the platform, provides, in signed (listed) and unsigned (not listed; prefix with 'u'):

  • int8_t - 8-bit integers
  • int16_t - 16-bit integers
  • int32_t - 32-bit integers
  • int64_t - 64-bit integers
  • uintptr_t - unsigned integers big enough to hold pointers
  • intmax_t - biggest size of integer on the platform (might be larger than int64_t)

You can then code your application using these types where it matters, and being very careful with system types (which might be different). There is an intptr_t type - a signed integer type for holding pointers; you should plan on not using it, or only using it as the result of a subtraction of two uintptr_t values (ptrdiff_t).

But, as the question points out (in disbelief), there are different systems for the sizes of the integer data types on 64-bit machines. Get used to it; the world isn't going to change.

How to print a stack trace in Node.js?

With a readily available Node module, it is possible to get full-length stack traces out of Node (albeit with a minor performance penalty): http://www.mattinsler.com/post/26396305882/announcing-longjohn-long-stack-traces-for-node-js

What is the difference between C and embedded C?

Embedded environment, sometime, there is no MMU, less memory, less storage space. In C programming level, almost same, cross compiler do their job.

Efficient way to rotate a list in python

def solution(A, K):
    if len(A) == 0:
        return A

    K = K % len(A)

    return A[-K:] + A[:-K]

# use case
A = [1, 2, 3, 4, 5, 6]
K = 3
print(solution(A, K))

For example, given

A = [3, 8, 9, 7, 6]
K = 3

the function should return [9, 7, 6, 3, 8]. Three rotations were made:

[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]

For another example, given

A = [0, 0, 0]
K = 1

the function should return [0, 0, 0]

Given

A = [1, 2, 3, 4]
K = 4

the function should return [1, 2, 3, 4]

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

This is the approach to do this: -

  1. Check whether the table or column exists or not.
  2. If yes, then alter the column. e.g:-
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE 
            TABLE_CATALOG = 'DBName' AND 
            TABLE_SCHEMA = 'SchemaName' AND
            TABLE_NAME = 'TableName' AND
            COLUMN_NAME = 'ColumnName')
BEGIN
    ALTER TABLE DBName.SchemaName.TableName ALTER COLUMN ColumnName [data type] NULL
END  

If you don't have any schema then delete the schema line because you don't need to give the default schema.

How do I get NuGet to install/update all the packages in the packages.config?

For those arriving here due to the build server falling foul of this, you can create an MSBuild target running the exec command to run the nuget restore command, as below (in this case nuget.exe is in the .nuget folder, rather than on the path), which can then be run in a TeamCity build step immediately prior to building the solution

<Target Name="BeforeBuild">
  <Exec Command="..\.nuget\nuget restore ..\MySolution.sln"/>
</Target>

How to set standard encoding in Visual Studio

I don't know of a global setting nither but you can try this:

  1. Save all Visual Studio templates in UTF-8
  2. Write a Visual Studio Macro/Addin that will listen to the DocumentSaved event and will save the file in UTF-8 format (if not already).
  3. Put a proxy on your source control that will make sure that new files are always UTF-8.

What is the difference between a framework and a library?

Your interpretation sounds pretty good to me... A library could be anything that's compiled and self-contained for re-use in other code, there's literally no restriction on its content.

A framework on the other hand is expected to have a range of facilities for use in some specific arena of application development, just like your example, MVC.

SQL Server : fetching records between two dates?

You need to be more explicit and add the start and end times as well, down to the milliseconds:

select * 
from xxx 
where dates between '2012-10-26 00:00:00.000' and '2012-10-27 23:59:59.997'

The database can very well interpret '2012-10-27' as '2012-10-27 00:00:00.000'.

When should I use the Visitor Design Pattern?

The reason for your confusion is probably that the Visitor is a fatal misnomer. Many (prominent1!) programmers have stumbled over this problem. What it actually does is implement double dispatching in languages that don't support it natively (most of them don't).


1) My favourite example is Scott Meyers, acclaimed author of “Effective C++”, who called this one of his most important C++ aha! moments ever.

Pip install - Python 2.7 - Windows 7

This is one way of installing pip on a Windows system.

  1. Download the "get-pip" python script from here: https://bootstrap.pypa.io/get-pip.py

  2. Save the file as getpip.py

  3. Run it from cmd: python getpip.py install

Create session factory in Hibernate 4

The following expresses the experience I had with hibernate 4.0.0.Final.

The javadoc (distributed under LGPL license) of org.hibernate.cfg.Configuration class states that:

NOTE : This will be replaced by use of ServiceRegistryBuilder and org.hibernate.metamodel.MetadataSources instead after the 4.0 release at which point this class will become deprecated and scheduled for removal in 5.0. See HHH-6183, HHH-2578 and HHH-6586 for details

After looking at issue 2578, i used something like this:

ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().configure().buildServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addResource("some_mapping.hbm.xml")
SessionFactory sessionFactory = metadataSources.buildMetadata().buildSessionFactory();

For it to start reading configuration, i had to modify my hibernate 3.2.6 configuration and mapping files to use xmlns="http://www.hibernate.org/xsd/hibernate-configuration" and xmlns="http://www.hibernate.org/xsd/hibernate-mapping" and also remove the dtd specifications.

I couldn't find a way for it to inspect mappings defined in hibernate.cfg.xml and hibernate. prefix for hibernate-related properties in hibernate.cfg.xml is no longer optional.

This might work for some.

I, for one, ran into some error because mapping files contained <cache usage="read-write" /> and ended up using deprecated Configuration way:

Configuration configuration = new Configuration().configure();
SessionFactoryImpl sessionFactory = (SessionFactoryImpl) configuration.buildSessionFactory();
EventListenerRegistry listenerRegistry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
SolrIndexEventListener indexListener = new SolrIndexEventListener(); // a SaveOrUpdateEventListener i wanted to attach
listenerRegistry.appendListeners(EventType.SAVE_UPDATE, indexListener);

I had to programatically append event listeners because Configuration no longer looks for them in hibernate.cfg.xml

Insert a line at specific line number with sed or awk

sed -e '8iProject_Name=sowstest' -i start using GNU sed

Sample run:

[root@node23 ~]# for ((i=1; i<=10; i++)); do echo "Line #$i"; done > a_file
[root@node23 ~]# cat a_file
Line #1
Line #2
Line #3
Line #4
Line #5
Line #6
Line #7
Line #8
Line #9
Line #10
[root@node23 ~]# sed -e '3ixxx inserted line xxx' -i a_file 
[root@node23 ~]# cat -An a_file 
     1  Line #1$
     2  Line #2$
     3  xxx inserted line xxx$
     4  Line #3$
     5  Line #4$
     6  Line #5$
     7  Line #6$
     8  Line #7$
     9  Line #8$
    10  Line #9$
    11  Line #10$
[root@node23 ~]# 
[root@node23 ~]# sed -e '5ixxx (inserted) "line" xxx' -i a_file
[root@node23 ~]# cat -n a_file 
     1  Line #1
     2  Line #2
     3  xxx inserted line xxx
     4  Line #3
     5  xxx (inserted) "line" xxx
     6  Line #4
     7  Line #5
     8  Line #6
     9  Line #7
    10  Line #8
    11  Line #9
    12  Line #10
[root@node23 ~]# 

AngularJS UI Router - change url without reloading state

If you need only change url but prevent change state:

Change location with (add .replace if you want to replace in history):

this.$location.path([Your path]).replace();

Prevent redirect to your state:

$transitions.onBefore({}, function($transition$) {
 if ($transition$.$to().name === '[state name]') {
   return false;
 }
});

How do I detect a page refresh using jquery?

$('body').bind('beforeunload',function(){
   //do something
});

But this wont save any info for later, unless you were planning on saving that in a cookie somewhere (or local storage) and the unload event does not always fire in all browsers.


Example: http://jsfiddle.net/maniator/qpK7Y/

Code:

$(window).bind('beforeunload',function(){

     //save info somewhere

    return 'are you sure you want to leave?';

});

How do I free memory in C?

You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc(), the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap(). Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc(), it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free() the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.

If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc(). Thus, if you make a lot of calls to malloc() and free() with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc() fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.

How to SELECT by MAX(date)?

It works great for me

SELECT report_id,computer_id,MAX(date_entered) FROM reports GROUP BY computer_id

ModelState.IsValid == false, why?

About "can it be that 0 errors and IsValid == false": here's MVC source code from https://github.com/Microsoft/referencesource/blob/master/System.Web/ModelBinding/ModelStateDictionary.cs#L37-L41

public bool IsValid {
    get {
        return Values.All(modelState => modelState.Errors.Count == 0);
    }
}

Now, it looks like it can't be. Well, that's for ASP.NET MVC v1.

Is it ok to run docker from inside docker?

Running Docker inside Docker (a.k.a. dind), while possible, should be avoided, if at all possible. (Source provided below.) Instead, you want to set up a way for your main container to produce and communicate with sibling containers.

Jérôme Petazzoni — the author of the feature that made it possible for Docker to run inside a Docker container — actually wrote a blog post saying not to do it. The use case he describes matches the OP's exact use case of a CI Docker container that needs to run jobs inside other Docker containers.

Petazzoni lists two reasons why dind is troublesome:

  1. It does not cooperate well with Linux Security Modules (LSM).
  2. It creates a mismatch in file systems that creates problems for the containers created inside parent containers.

From that blog post, he describes the following alternative,

[The] simplest way is to just expose the Docker socket to your CI container, by bind-mounting it with the -v flag.

Simply put, when you start your CI container (Jenkins or other), instead of hacking something together with Docker-in-Docker, start it with:

docker run -v /var/run/docker.sock:/var/run/docker.sock ...

Now this container will have access to the Docker socket, and will therefore be able to start containers. Except that instead of starting "child" containers, it will start "sibling" containers.

How to remove the arrows from input[type="number"] in Opera

There is no way.

This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.

If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.

For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}"> could be adequate. It is of course implementation-dependent how it will be handled.

What does the "@" symbol do in Powershell?

PowerShell will actually treat any comma-separated list as an array:

"server1","server2"

So the @ is optional in those cases. However, for associative arrays, the @ is required:

@{"Key"="Value";"Key2"="Value2"}

Officially, @ is the "array operator." You can read more about it in the documentation that installed along with PowerShell, or in a book like "Windows PowerShell: TFM," which I co-authored.

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

If your application needs to react on request of type post, use this:

if(strtoupper($_SERVER['REQUEST_METHOD']) === 'POST') { // if form submitted with post method
    // validate request, 
    // manage post request differently, 
    // log or don't log request,
    // redirect to avoid resubmition on F5 etc
}

If your application needs to react on any data received through post request, use this:

if(!empty($_POST)) {  // if received any post data
   // process $_POST values, 
   // save data to DB,
   // ... 
}

if(!empty($_FILES)) { // if received any "post" files
   // validate uploaded FILES
   // move to uploaded dir
   // ...
}

It is implementation specific, but you a going to use both, + $_FILES superglobal.

Missing styles. Is the correct theme chosen for this layout?

I solved it by changing "classpath" in "dependencies" in build.gradles.

Just change:

dependencies {
    classpath 'com.android.tools.build:gradle:2.3.0-alpha2'

or something like that to:

dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'

C# list.Orderby descending

Sure:

var newList = list.OrderByDescending(x => x.Product.Name).ToList();

Doc: OrderByDescending(IEnumerable, Func).

In response to your comment:

var newList = list.OrderByDescending(x => x.Product.Name)
                  .ThenBy(x => x.Product.Price)
                  .ToList();

Set variable with multiple values and use IN

Use a Temp Table or a Table variable, e.g.

select 'A' as [value]
into #tmp
union
select 'B'
union 
select 'C'

and then

SELECT   
blah 
FROM    foo 
WHERE   myField IN (select [value] from #tmp) 

or

SELECT   
f.blah 
FROM foo f INNER JOIN #tmp t ON f.myField = t.[value]

Typescript import/as vs import/require?

These are mostly equivalent, but import * has some restrictions that import ... = require doesn't.

import * as creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or newable - it only has properties. If you're trying to import a function or class, you should use

import express = require('express');

or (depending on your module loader)

import express from 'express';

Attempting to use import * as express and then invoking express() is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.

Java: How to stop thread?

JavaSun recomendation is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread to terminate.

You can that way kill the other process, and the current one afterwards.

Autoplay audio files on an iPad with HTML5

Try calling the .load() method before the .play() method on the audio or video tag... which will be HTMLAudioElement or HTMLVideoElement respectively. That was the only way it would work on the iPad for me!

Status bar and navigation bar appear over my view's bounds in iOS 7

The simplest trick is to open the NIB file and do these two simple steps:

  1. Just toggle that and set it to the one you prefer:

Enter image description here

  1. Select those UIView's/UIIMageView's/... that you want to be moved down. In my case only the logo was overlapped an I've set the delta to +15; (OR -15 if you chose iOS 7 in step 1)

Enter image description here

And the result:

Before After

Python - Locating the position of a regex match in a string?

You could use .find("is"), it would return position of "is" in the string

or use .start() from re

>>> re.search("is", String).start()
2

Actually its match "is" from "This"

If you need to match per word, you should use \b before and after "is", \b is the word boundary.

>>> re.search(r"\bis\b", String).start()
5
>>>

for more info about python regular expressions, docs here

How to display a content in two-column layout in LaTeX?

Use two minipages.

\begin{minipage}[position]{width}
  text
 \end{minipage}

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

exit(0) generally used to indicate successful termination. exit(1) or exit(-1) or any other non-zero value indicates unsuccessful termination in general.

How to find largest objects in a SQL Server database?

I've found this query also very helpful in SqlServerCentral, here is the link to original post

Sql Server largest tables

  select name=object_schema_name(object_id) + '.' + object_name(object_id)
, rows=sum(case when index_id < 2 then row_count else 0 end)
, reserved_kb=8*sum(reserved_page_count)
, data_kb=8*sum( case 
     when index_id<2 then in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count 
     else lob_used_page_count + row_overflow_used_page_count 
    end )
, index_kb=8*(sum(used_page_count) 
    - sum( case 
           when index_id<2 then in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count 
        else lob_used_page_count + row_overflow_used_page_count 
        end )
     )    
, unused_kb=8*sum(reserved_page_count-used_page_count)
from sys.dm_db_partition_stats
where object_id > 1024
group by object_id
order by 
rows desc   

In my database they gave different results between this query and the 1st answer.

Hope somebody finds useful

How to Add a Dotted Underline Beneath HTML Text

Reformatted the answer by @epascarello:

_x000D_
_x000D_
u.dotted {_x000D_
  border-bottom: 1px dashed #999;_x000D_
  text-decoration: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<u class="dotted">I like cheese</u>
_x000D_
_x000D_
_x000D_

Copying text to the clipboard using Java

I found a better way of doing it so you can get a input from a txtbox or have something be generated in that text box and be able to click a button to do it.!

import java.awt.datatransfer.*;
import java.awt.Toolkit;

private void /* Action performed when the copy to clipboard button is clicked */ {
    String ctc = txtCommand.getText().toString();
    StringSelection stringSelection = new StringSelection(ctc);
    Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
    clpbrd.setContents(stringSelection, null);
}

// txtCommand is the variable of a text box

Open files always in a new tab

For those who using Windows OS:

  • Press Ctrl + Shift + P
  • Select Preferences: Open Settings (JSON) from the list
  • Select all and Paste this { "workbench.editor.enablePreview": false }

That's it now it will open in a new tab instead of replacing on the existing one.

For reference look at the screenshot below:

enter image description here

Jquery Ajax Loading image

Description

You should do this using jQuery.ajaxStart and jQuery.ajaxStop.

  1. Create a div with your image
  2. Make it visible in jQuery.ajaxStart
  3. Hide it in jQuery.ajaxStop

Sample

<div id="loading" style="display:none">Your Image</div>

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script>
    $(function () {
        var loading = $("#loading");
        $(document).ajaxStart(function () {
            loading.show();
        });

        $(document).ajaxStop(function () {
            loading.hide();
        });

        $("#startAjaxRequest").click(function () {
            $.ajax({
                url: "http://www.google.com",
                // ... 
            });
        });
    });
</script>

<button id="startAjaxRequest">Start</button>

More Information

How to integrate SAP Crystal Reports in Visual Studio 2017

I had a workaround for this problem. I created dll project with viewer in vs2015 and used this dll in vs2017. Report showing perfectly.

mysqli_select_db() expects parameter 1 to be mysqli, string given

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error($connection));
}

You got the order of the arguments to mysqli_select_db() backwards. And mysqli_error() requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.

Note also that with mysqli you can specify the DB in mysqli_connect():

$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
  die("Database connection failed: " . mysqli_connect_error();
}

You must use mysqli_connect_error(), not mysqli_error(), to get the error from mysqli_connect(), since the latter requires you to supply a valid connection.

Percentage calculation

You can hold onto the percentage as decimal (value \ total) and then when you want to render to a human you can make use of Habeeb's answer or using string interpolation you could have something even cleaner:

var displayPercentage = $"{(decimal)value / total:P}";

or

//Calculate percentage earlier in code
decimal percentage = (decimal)value / total;
...
//Now render percentage
var displayPercentage = $"{percentage:P}";

Merging 2 branches together in GIT

Case: If you need to ignore the merge commit created by default, follow these steps.

Say, a new feature branch is checked out from master having 2 commits already,

  • "Added A" , "Added B"

Checkout a new feature_branch

  • "Added C" , "Added D"

Feature branch then adds two commits-->

  • "Added E", "Added F"

enter image description here

Now if you want to merge feature_branch changes to master, Do git merge feature_branch sitting on the master.

This will add all commits into master branch (4 in master + 2 in feature_branch = total 6) + an extra merge commit something like 'Merge branch 'feature_branch'' as the master is diverged.

If you really need to ignore these commits (those made in FB) and add the whole changes made in feature_branch as a single commit like 'Integrated feature branch changes into master', Run git merge feature_merge --no-commit.

With --no-commit, it perform the merge and stop just before creating a merge commit, We will have all the added changes in feature branch now in master and get a chance to create a new commit as our own.

Read here for more : https://git-scm.com/docs/git-merge

Setting up enviromental variables in Windows 10 to use java and javac

if you have any version problems (javac -version=15.0.1, java -version=1.8.0)
windows search : edit environment variables for your account
then delete these in your windows Environment variable: system variable: Path
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
C:\Program Files\Common Files\Oracle\Java\javapath

then if you're using java 15
environment variable: system variable : Path
add path C:\Program Files\Java\jdk-15.0.1\bin
is enough

if you're using java 8

  • create JAVA_HOME
  • environment variable: system variable : JAVA_HOME
    JAVA_HOME = C:\Program Files\Java\jdk1.8.0_271
  • environment variable: system variable : Path
    add path = %JAVA_HOME%\bin
  • How to set an image as a background for Frame in Swing GUI of java?

    This is easily done by replacing the frame's content pane with a JPanel which draws your image:

    try {
        final Image backgroundImage = javax.imageio.ImageIO.read(new File(...));
        setContentPane(new JPanel(new BorderLayout()) {
            @Override public void paintComponent(Graphics g) {
                g.drawImage(backgroundImage, 0, 0, null);
            }
        });
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    

    This example also sets the panel's layout to BorderLayout to match the default content pane layout.

    (If you have any trouble seeing the image, you might need to call setOpaque(false) on some other components so that you can see through to the background.)

    How to add style from code behind?

    Try this:

    Html Markup

    <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="#">HyperLink</asp:HyperLink>
    

    Code

    using System.Drawing;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        Style style = new Style();
        style.ForeColor = Color.Green;
        this.Page.Header.StyleSheet.CreateStyleRule(style, this, "#" + HyperLink1.ClientID + ":hover");
    }
    

    Thymeleaf using path variables to th:href

    You can use like

    1. My table is bellow like..

      <table>
         <thead>
          <tr>
              <th>Details</th>
          </tr>
      </thead>
      <tbody>
          <tr th:each="user: ${staffList}">
              <td><a th:href="@{'/details-view/'+ ${user.userId}}">Details</a></td>
          </tr>
       </tbody>
      </table>
      
    2. Here is my controller ..

      @GetMapping(value = "/details-view/{userId}")
      public String details(@PathVariable String userId) { 
      
          Logger.getLogger(getClass().getName()).info("userId-->" + userId);
      
       return "user-details";
      }
      

    How to properly use the "choices" field option in Django

    You can't have bare words in the code, that's the reason why they created variables (your code will fail with NameError).

    The code you provided would create a database table named month (plus whatever prefix django adds to that), because that's the name of the CharField.

    But there are better ways to create the particular choices you want. See a previous Stack Overflow question.

    import calendar
    tuple((m, m) for m in calendar.month_name[1:])
    

    Update with two tables?

    Your query does not work because you have no FROM clause that specifies the tables you are aliasing via A/B.

    Please try using the following:

    UPDATE A
        SET A.NAME = B.NAME
    FROM TableNameA A, TableNameB B
    WHERE A.ID = B.ID
    

    Personally I prefer to use more explicit join syntax for clarity i.e.

    UPDATE A
        SET A.NAME = B.NAME
    FROM TableNameA A
        INNER JOIN TableName B ON 
            A.ID = B.ID
    

    How to synchronize a static variable among threads running different instances of a class in Java?

    If you're simply sharing a counter, consider using an AtomicInteger or another suitable class from the java.util.concurrent.atomic package:

    public class Test {
    
        private final static AtomicInteger count = new AtomicInteger(0); 
    
        public void foo() {  
            count.incrementAndGet();
        }  
    }
    

    Getting a POST variable

    Use this for GET values:

    Request.QueryString["key"]
    

    And this for POST values

    Request.Form["key"]
    

    Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:

    Request["key"]
    

    Another thing to note (if you need it) is you can check the type of request by using:

    Request.RequestType
    

    Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.

    'Field required a bean of type that could not be found.' error spring restful API using mongodb

    I encountered the same issue and all I had to do was to place the Application in a package one level higher than the service, dao and domain packages.

    Get current URL with jQuery?

    See purl.js. This will really help and can also be used, depending on jQuery. Use it like this:

    $.url().param("yourparam");
    

    Is there a way to retrieve the view definition from a SQL Server using plain ADO?

    For users of SQL 2000, the actual command that will provide this information is:

    select c.text
    from sysobjects     o
    join syscomments    c on c.id = o.id
    where o.name = '<view_name_here>'
      and o.type      = 'V'
    

    Cannot create SSPI context

    Had a really weird instance of this; All the web products that had connection strings containing the windows computer name of the SQL server worked fine, but the products that had a FQDN with the internal domain attached gave an SSPI error. i.e. COMPUTERNAME vs COMPUTERNAME.DOMAIN (ping always worked as expected)

    This ONLY gave problems when a new SQL server was being used and hosts files pointed both the computer name and the computername as a FQDN for the connection strings.

    Solution in this case was to set all the connection strings to the computer name only, removing the domain references.

    SQL : 2008R2 SQL2012

    IIS : 2008R2

    Padding zeros to the left in postgreSQL

    The to_char() function is there to format numbers:

    select to_char(column_1, 'fm000') as column_2
    from some_table;
    

    The fm prefix ("fill mode") avoids leading spaces in the resulting varchar. The 000 simply defines the number of digits you want to have.

    psql (9.3.5)
    Type "help" for help.
    
    postgres=> with sample_numbers (nr) as (
    postgres(>     values (1),(11),(100)
    postgres(> )
    postgres-> select to_char(nr, 'fm000')
    postgres-> from sample_numbers;
     to_char
    ---------
     001
     011
     100
    (3 rows)
    
    postgres=>

    For more details on the format picture, please see the manual:
    http://www.postgresql.org/docs/current/static/functions-formatting.html

    Simple PHP form: Attachment to email (code golf)

    I haven't tested the email part of this (my test box does not send email) but I think it will work.

    <?php
    if ($_POST) {
    $s = md5(rand());
    mail('[email protected]', 'attachment', "--$s
    
    {$_POST['m']}
    --$s
    Content-Type: application/octet-stream; name=\"f\"
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment
    
    ".chunk_split(base64_encode(join(file($_FILES['f']['tmp_name']))))."
    --$s--", "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$s\"");
    exit;
    }
    ?>
    <form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>">
    <textarea name="m"></textarea><br>
    <input type="file" name="f"/><br>
    <input type="submit">
    </form>
    

    Logger slf4j advantages of formatting with {} instead of string concatenation

    I think from the author's point of view, the main reason is to reduce the overhead for string concatenation.I just read the logger's documentation, you could find following words:

    /**
    * <p>This form avoids superfluous string concatenation when the logger
    * is disabled for the DEBUG level. However, this variant incurs the hidden
    * (and relatively small) cost of creating an <code>Object[]</code> before 
      invoking the method,
    * even if this logger is disabled for DEBUG. The variants taking
    * {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
    * arguments exist solely in order to avoid this hidden cost.</p>
    */
    *
     * @param format    the format string
     * @param arguments a list of 3 or more arguments
     */
    public void debug(String format, Object... arguments);
    

    Finding the source code for built-in Python functions?

    Here is a cookbook answer to supplement @Chris' answer, CPython has moved to GitHub and the Mercurial repository will no longer be updated:

    1. Install Git if necessary.
    2. git clone https://github.com/python/cpython.git

    3. Code will checkout to a subdirectory called cpython -> cd cpython

    4. Let's say we are looking for the definition of print()...
    5. egrep --color=always -R 'print' | less -R
    6. Aha! See Python/bltinmodule.c -> builtin_print()

    Enjoy.

    Python JSON dump / append to .txt with each variable on new line

    To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

    with g as outfile:
      json.dump(hostDict, outfile,indent=2)
    

    Using indent = 2 helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.

    jQuery check if an input is type checkbox?

    $('#myinput').is(':checkbox')
    

    this is the only work, to solve the issue to detect if checkbox checked or not. It returns true or false, I search it for hours and try everything, now its work to be clear I use EDG as browser and W2UI

    Changing Vim indentation behavior by file type

    Today, you could try editorconfig, there is also a vim plugin for it. With this, you are able not only change indentation size in vim, but in many other editors, keep consistent coding styles.

    Below is a simple editorconfig, as you can see, the python files will have 4 spaces for indentation, and pug template files will only have 2.

    # 4 space indentation for python files
    [*.py]
    indent_style = space
    indent_size = 4
    
    # 2 space indentation for pug templates
    [*.pug]
    indent_size = 2
    

    Making a Bootstrap table column fit to content

    Tested on Bootstrap 4.5 and 5.0

    None of the solution works for me. The td last column still takes the full width. So here's the solution works.

    Add table-fit to your table

    table.table-fit {
        width: auto !important;
        table-layout: auto !important;
    }
    table.table-fit thead th, table.table-fit tfoot th {
        width: auto !important;
    }
    table.table-fit tbody td, table.table-fit tfoot td {
        width: auto !important;
    }
    

    Here's the one for sass uses.

    @mixin width {
        width: auto !important;
    }
    
    table {
        &.table-fit {
            @include width;
            table-layout: auto !important;
            thead th, tfoot th  {
                @include width;
            }
            tbody td, tfoot td {
                @include width;
            }
        }
    }
    

    presentViewController and displaying navigation bar

    Swift 5.*

    Navigation:

    guard let myVC = self.storyboard?.instantiateViewController(withIdentifier: "MyViewController") else { return }
    let navController = UINavigationController(rootViewController: myVC)
    
    self.navigationController?.present(navController, animated: true, completion: nil)
    

    Going Back:

    self.dismiss(animated: true, completion: nil)
    

    Swift 2.0

    Navigation:

    let myVC = self.storyboard?.instantiateViewControllerWithIdentifier("MyViewController");
    let navController = UINavigationController(rootViewController: myVC!)
    
    self.navigationController?.presentViewController(navController, animated: true, completion: nil)
    

    Going Back:

    self.dismissViewControllerAnimated(true, completion: nil)
    

    C++ static virtual members?

    With c++ you can use static inheritance with the crt method. For the example, it is used widely on window template atl & wtl.

    See https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

    To be simple, you have a class that is templated from itself like class myclass : public myancestor. From this point the myancestor class can now call your static T::YourImpl function.

    Compute mean and standard deviation by group for multiple variables in a data.frame

    This is an aggregation problem, not a reshaping problem as the question originally suggested -- we wish to aggregate each column into a mean and standard deviation by ID. There are many packages that handle such problems. In the base of R it can be done using aggregate like this (assuming DF is the input data frame):

    ag <- aggregate(. ~ ID, DF, function(x) c(mean = mean(x), sd = sd(x)))
    

    Note 1: A commenter pointed out that ag is a data frame for which some columns are matrices. Although initially that may seem strange, in fact it simplifies access. ag has the same number of columns as the input DF. Its first column ag[[1]] is ID and the ith column of the remainder ag[[i+1]] (or equivalanetly ag[-1][[i]]) is the matrix of statistics for the ith input observation column. If one wishes to access the jth statistic of the ith observation it is therefore ag[[i+1]][, j] which can also be written as ag[-1][[i]][, j] .

    On the other hand, suppose there are k statistic columns for each observation in the input (where k=2 in the question). Then if we flatten the output then to access the jth statistic of the ith observation column we must use the more complex ag[[k*(i-1)+j+1]] or equivalently ag[-1][[k*(i-1)+j]] .

    For example, compare the simplicity of the first expression vs. the second:

    ag[-1][[2]]
    ##        mean      sd
    ## [1,] 36.333 10.2144
    ## [2,] 32.250  4.1932
    ## [3,] 43.500  4.9497
    
    ag_flat <- do.call("data.frame", ag) # flatten
    ag_flat[-1][, 2 * (2-1) + 1:2]
    ##   Obs_2.mean Obs_2.sd
    ## 1     36.333  10.2144
    ## 2     32.250   4.1932
    ## 3     43.500   4.9497
    

    Note 2: The input in reproducible form is:

    Lines <- "ID  Obs_1   Obs_2   Obs_3
    1   43      48      37
    1   27      29      22
    1   36      32      40
    2   33      38      36
    2   29      32      27
    2   32      31      35
    2   25      28      24
    3   45      47      42
    3   38      40      36"
    DF <- read.table(text = Lines, header = TRUE)
    

    Read properties file outside JAR file

    Here if you mention .getPath() then that will return the path of Jar and I guess you will need its parent to refer to all other config files placed with the jar. This code works on Windows. Add the code within the main class.

    File jarDir = new File(MyAppName.class.getProtectionDomain().getCodeSource().getLocation().getPath());
    String jarDirpath = jarDir.getParent();
    
    System.out.println(jarDirpath);
    

    Convert special characters to HTML in Javascript

    Yes, but if you need to insert the resulting string somewhere without it being converted back, you need to do:

    str.replace(/'/g,"&amp;amp;#39;"); // and so on
    

    Delimiters in MySQL

    Delimiters other than the default ; are typically used when defining functions, stored procedures, and triggers wherein you must define multiple statements. You define a different delimiter like $$ which is used to define the end of the entire procedure, but inside it, individual statements are each terminated by ;. That way, when the code is run in the mysql client, the client can tell where the entire procedure ends and execute it as a unit rather than executing the individual statements inside.

    Note that the DELIMITER keyword is a function of the command line mysql client (and some other clients) only and not a regular MySQL language feature. It won't work if you tried to pass it through a programming language API to MySQL. Some other clients like PHPMyAdmin have other methods to specify a non-default delimiter.

    Example:

    DELIMITER $$
    /* This is a complete statement, not part of the procedure, so use the custom delimiter $$ */
    DROP PROCEDURE my_procedure$$
    
    /* Now start the procedure code */
    CREATE PROCEDURE my_procedure ()
    BEGIN    
      /* Inside the procedure, individual statements terminate with ; */
      CREATE TABLE tablea (
         col1 INT,
         col2 INT
      );
    
      INSERT INTO tablea
        SELECT * FROM table1;
    
      CREATE TABLE tableb (
         col1 INT,
         col2 INT
      );
      INSERT INTO tableb
        SELECT * FROM table2;
      
    /* whole procedure ends with the custom delimiter */
    END$$
    
    /* Finally, reset the delimiter to the default ; */
    DELIMITER ;
    

    Attempting to use DELIMITER with a client that doesn't support it will cause it to be sent to the server, which will report a syntax error. For example, using PHP and MySQLi:

    $mysqli = new mysqli('localhost', 'user', 'pass', 'test');
    $result = $mysqli->query('DELIMITER $$');
    echo $mysqli->error;
    

    Errors with:

    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER $$' at line 1

    How can I remove duplicate rows?

    Another way of doing this :--

    DELETE A
    FROM   TABLE A,
           TABLE B
    WHERE  A.COL1 = B.COL1
           AND A.COL2 = B.COL2
           AND A.UNIQUEFIELD > B.UNIQUEFIELD 
    

    How to create my json string by using C#?

    No real need for the JSON.NET package. You could use JavaScriptSerializer. The Serialize method will turn a managed type instance into a JSON string.

    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(instanceOfThing);
    

    fatal: Not a valid object name: 'master'

    Git creates a master branch once you've done your first commit. There's nothing to have a branch for if there's no code in the repository.

    How to use WHERE IN with Doctrine 2

    The best way doing this - especially if you're adding more than one condition - is:

    $values = array(...); // array of your values
    $qb->andWhere('where', $qb->expr()->in('r.winner', $values));
    

    If your array of values contains strings, you can't use the setParameter method with an imploded string, because your quotes will be escaped!

    Getting "unixtime" in Java

    Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

    As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

    long unixTime = System.currentTimeMillis() / 1000L;
    

    conditional Updating a list using LINQ

            li.Where(w => w.name == "di" )
              .Select(s => { s.age = 10; return s; })
              .ToList();
    

    Can local storage ever be considered secure?

    Not accessible to any webpage (true) but is easily accessible and easily editible via dev tools, such as chrome (ctl-shift-J). Therefore, custom crypto required before storing the value.

    But, if javascript needs to decrypt (to validate) then the decrypt algorithm is exposed and can be manipulated.

    Javascript needs a fully secure container and the ability to properly implement private variables and functions that are available only to the js interpreter. But, this violates user security - since tracking data can be used with impunity.

    Consequently, javascript will never be fully secure.

    UITableView Cell selected Color?

    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    

    Make sure you have used the above line to use the selection effect

    TypeError: ufunc 'add' did not contain a loop with signature matching types

    You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

    try:

    return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
    

    However, you don't need numpy here at all. You can really just do:

    return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
    

    Or if you're really set on using numpy.

    return np.asarray(listOfEmb, dtype=float).mean()
    

    Select2 doesn't work when embedded in a bootstrap modal

    In my case I had the same problem with two modals and all was resolved using:

    $('.select2').each(function() { 
        $(this).select2({ dropdownParent: $(this).parent()});
    })
    

    As in the project issue #41 an user said.

    Correct way to write loops for promise.

    Given

    • asyncFn function
    • array of items

    Required

    • promise chaining .then()'s in series (in order)
    • native es6

    Solution

    let asyncFn = (item) => {
      return new Promise((resolve, reject) => {
        setTimeout( () => {console.log(item); resolve(true)}, 1000 )
      })
    }
    
    // asyncFn('a')
    // .then(()=>{return async('b')})
    // .then(()=>{return async('c')})
    // .then(()=>{return async('d')})
    
    let a = ['a','b','c','d']
    
    a.reduce((previous, current, index, array) => {
      return previous                                    // initiates the promise chain
      .then(()=>{return asyncFn(array[index])})      //adds .then() promise for each item
    }, Promise.resolve())
    

    How do I trim whitespace from a string?

    How do I remove leading and trailing whitespace from a string in Python?

    So below solution will remove leading and trailing whitespaces as well as intermediate whitespaces too. Like if you need to get a clear string values without multiple whitespaces.

    >>> str_1 = '     Hello World'
    >>> print(' '.join(str_1.split()))
    Hello World
    >>>
    >>>
    >>> str_2 = '     Hello      World'
    >>> print(' '.join(str_2.split()))
    Hello World
    >>>
    >>>
    >>> str_3 = 'Hello World     '
    >>> print(' '.join(str_3.split()))
    Hello World
    >>>
    >>>
    >>> str_4 = 'Hello      World     '
    >>> print(' '.join(str_4.split()))
    Hello World
    >>>
    >>>
    >>> str_5 = '     Hello World     '
    >>> print(' '.join(str_5.split()))
    Hello World
    >>>
    >>>
    >>> str_6 = '     Hello      World     '
    >>> print(' '.join(str_6.split()))
    Hello World
    >>>
    >>>
    >>> str_7 = 'Hello World'
    >>> print(' '.join(str_7.split()))
    Hello World
    

    As you can see this will remove all the multiple whitespace in the string(output is Hello World for all). Location doesn't matter. But if you really need leading and trailing whitespaces, then strip() would be find.

    SQL SERVER DATETIME FORMAT

    In MS SQL Server you can do:

    SET DATEFORMAT ymd
    

    Selecting text in an element (akin to highlighting with your mouse)

    According to the jQuery documentation of select():

    Trigger the select event of each matched element. This causes all of the functions that have been bound to that select event to be executed, and calls the browser's default select action on the matching element(s).

    There is your explanation why the jQuery select() won't work in this case.

    How do I create a Python function with optional arguments?

    Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" ). After the required positional arguments, you can specify specific optional arguments by name.

    What does AND 0xFF do?

    & 0xFF by itself only ensures that if bytes are longer than 8 bits (allowed by the language standard), the rest are ignored.

    And that seems to work fine too?

    If the result ends up greater than SHRT_MAX, you get undefined behavior. In that respect both will work equally poorly.

    Autowiring fails: Not an managed Type

    For Controllers, @SpringBootApplication(scanBasePackages = {"com.school.controllers"})

    For Respositories, @EnableJpaRepositories(basePackages = {"com.school.repos"})

    For Entities, @EntityScan(basePackages = {"com.school.models"})

    This will slove

    "Can't Autowire @Repository annotated interface"

    problem as well as

    Not an managed Type

    problem. Sample configuration below

    package com.school.boot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.autoconfigure.domain.EntityScan;
    import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
    
    
    @SpringBootApplication(scanBasePackages = {"com.school.controllers"})
    @EnableJpaRepositories(basePackages = {"com.school.repos"})
    @EntityScan(basePackages = {"com.school.models"})
    public class SchoolApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SchoolApplication.class, args);
        }
    
    }
    

    How to fix "could not find a base address that matches schema http"... in WCF

    The solution is to define a custom binding inside your Web.Config file and set the security mode to "Transport". Then you just need to use the bindingConfiguration property inside your endpoint definition to point to your custom binding.

    See here: Scott's Blog: WCF Bindings Needed For HTTPS

    Add my custom http header to Spring RestTemplate request / extend RestTemplate

    Add a "User-Agent" header to your request.

    Some servers attempt to block spidering programs and scrapers from accessing their server because, in earlier days, requests did not send a user agent header.

    You can either try to set a custom user agent value or use some value that identifies a Browser like "Mozilla/5.0 Firefox/26.0"

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("user-agent", "Mozilla/5.0 Firefox/26.0");
    headers.set("user-key", "your-password-123"); // optional - in case you auth in headers
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
    ResponseEntity<Game[]> respEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Game[].class);
    
    logger.info(respEntity.toString());
    

    How do you execute SQL from within a bash script?

    If you do not want to install sqlplus on your server/machine then the following command-line tool can be your friend. It is a simple Java application, only Java 8 that you need in order to you can execute this tool.

    The tool can be used to run any SQL from the Linux bash or Windows command line.

    Example:

    java -jar sql-runner-0.2.0-with-dependencies.jar \
         -j jdbc:oracle:thin:@//oracle-db:1521/ORCLPDB1.localdomain \
         -U "SYS as SYSDBA" \
         -P Oradoc_db1 \
          "select 1 from dual"
    

    Documentation is here.

    You can download the binary file from here.

    Preventing iframe caching in browser

    I found this problem in the latest Chrome as well as the latest Safari on the Mac OS X as of Mar 17, 2016. None of the fixes above worked for me, including assigning src to empty and then back to some site, or adding in some randomly-named "name" parameter, or adding in a random number on the end of the URL after the hash, or assigning the content window href to the src after assigning the src.

    In my case, it was because I was using Javascript to update the IFRAME, and only switching the hash in the URL.

    The workaround in my case was that I created an interim URL that had a 0 second meta redirect to that other page. It happens so fast that I hardly notice the screen flash. Plus, I made the background color of the interim page the same as the other page, and so you notice it even less.

    Creating multiple objects with different names in a loop to store in an array list

    ArrayList<Customer> custArr = new ArrayList<Customer>();
    while(youWantToContinue) {
        //get a customerName
        //get an amount
        custArr.add(new Customer(customerName, amount);
    }
    

    For this to work... you'll have to fix your constructor...


    Assuming your Customer class has variables called name and sale, your constructor should look like this:

    public Customer(String customerName, double amount) {
        name = customerName;
        sale = amount;
    }
    

    Change your Store class to something more like this:

    public class Store {
    
        private ArrayList<Customer> custArr;
    
        public new Store() {
            custArr = new ArrayList<Customer>();
        }
    
        public void addSale(String customerName, double amount) {
            custArr.add(new Customer(customerName, amount));
        }
    
        public Customer getSaleAtIndex(int index) {
            return custArr.get(index);
        }
    
        //or if you want the entire ArrayList:
        public ArrayList getCustArr() {
            return custArr;
        }
    }
    

    php var_dump() vs print_r()

    With large arrays, print_r can show far more information than is useful. You can truncate it like this, showing the first 2000 characters or however many you need.

      echo "<pre>" . substr(print_r($dataset, 1), 0, 2000) . "</pre>";
    

    Center Oversized Image in Div

    based on @Guffa answer
    because I lost more than 2 hours to center a very wide image,
    for me with a image dimendion of 2500x100px and viewport 1600x1200 or Full HD 1900x1200 works centered like that:

     .imageContainer {
      height: 100px;
      overflow: hidden;
      position: relative;
     }
     .imageCenter {
      width: auto;
      position: absolute;
      left: -10%;
      top: 0;
      margin-left: -500px;
     }
    .imageCenter img {
     display: block;
     margin: 0 auto;
     }
    

    I Hope this helps others to finish faster the task :)

    Android EditText view Floating Hint in Material Design

    Floating hint EditText:

    Add below dependency in gradle:

    compile 'com.android.support:design:22.2.0'
    

    In layout:

    <android.support.design.widget.TextInputLayout
        android:id="@+id/text_input_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    
            <EditText
                android:id="@+id/editText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="UserName"/>
        </android.support.design.widget.TextInputLayout>
    

    Access Session attribute on jstl

    You should definitely avoid using <jsp:...> tags. They're relics from the past and should always be avoided now.

    Use the JSTL.

    Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a

    public SomeType getQuestionPaperID() {
        //...
    }
    

    method in your bean.

    Once you have that, you can display the value of this property using this code :

    <c:out value="${Questions.questionPaperID}" />
    

    or, to specifically target the session scoped attributes (in case of conflicts between scopes) :

    <c:out value="${sessionScope.Questions.questionPaperID}" />
    

    Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.

    jQuery autohide element after 5 seconds

    Please note you may need to display div text again after it has disappeared. So you will need to also empty and then re-show the element at some point.

    You can do this with 1 line of code:

    $('#element_id').empty().show().html(message).delay(3000).fadeOut(300);
    

    If you're using jQuery you don't need setTimeout, at least not to autohide an element.

    How to add "Maven Managed Dependencies" library in build path eclipse?

    Follow these steps

    1) Go in projects class path

    2) Go in library tab

    3) click on Add Library

    4) In opened dialogue select Maven Managed Dependencies

    5) Click on Next

    6) In the new dialogue click on Manage Project Settings

    7) In opened dialogue select the check box Resolve dependencies from workspace

    8) Click on Restore defaults

    9) It will do some process and you will have all your dependencies in your library now.

    What is the bower (and npm) version syntax?

    Bower uses semver syntax, but here are a few quick examples:

    You can install a specific version:

    $ bower install jquery#1.11.1
    

    You can use ~ to specify 'any version that starts with this':

    $ bower install jquery#~1.11
    

    You can specify multiple version requirements together:

    $ bower install "jquery#<2.0 >1.10"
    

    Error inflating class android.support.v7.widget.Toolbar?

    I removed these lines as below :

    before :

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar1"
        android:layout_width="match_parent"
        android:layout_height="@attr/actionBarSize"
        android:minHeight="@attr/actionBarSize"
        android:layout_alignParentTop="true" >
    

    after :

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentTop="true" >
    

    Instead of "@attr/actionBarSize" put specific dimens it works for me.

    How to check the presence of php and apache on ubuntu server through ssh

    Another way to find out if a program is installed is by using the which command. It will show the path of the program you're searching for. For example if when your searching for apache you can use the following command:

    $ which apache2ctl
    /usr/sbin/apache2ctl
    

    And if you searching for PHP try this:

    $ which php
    /usr/bin/php
    

    If the which command doesn't give any result it means the software is not installed (or is not in the current $PATH):

    $ which php
    $
    

    T-SQL stored procedure that accepts multiple Id values

    A superfast XML Method, if you want to use a stored procedure and pass the comma separated list of Department IDs :

    Declare @XMLList xml
    SET @XMLList=cast('<i>'+replace(@DepartmentIDs,',','</i><i>')+'</i>' as xml)
    SELECT x.i.value('.','varchar(5)') from @XMLList.nodes('i') x(i))
    

    All credit goes to Guru Brad Schulz's Blog

    Consider defining a bean of type 'service' in your configuration [Spring boot]

    @SpringBootApplication @ComponentScan(basePackages = {"io.testapi"})

    In the main class below springbootapplication annotation i have written componentscan and it worked for me.

    How to save and extract session data in codeigniter

    CI Session Class track information about each user while they browse site.Ci Session class generates its own session data, offering more flexibility for developers.

    Initializing a Session

    To initialize the Session class manually in our controller constructor use following code.

    Adding Custom Session Data

    We can add our custom data in session array.To add our data to the session array involves passing an array containing your new data to this function.

    $this->session->set_userdata($newarray);
    

    Where $newarray is an associative array containing our new data.

    $newarray = array( 'name' => 'manish', 'email' => '[email protected]'); $this->session->set_userdata($newarray); 
    

    Retrieving Session

    $session_id = $this->session->userdata('session_id');

    Above function returns FALSE (boolean) if the session array does not exist.

    Retrieving All Session Data

    $this->session->all_userdata()

    I have taken reference from http://www.tutsway.com/codeigniter-session.php.

    Find the least number of coins required that can make any change from 1 to 99 cents

    After failing to find a good solution to this type of problem in PHP, I developed this function.

    It takes any amount of money (up to $999.99) and returns an array of the minimum number of each bill / coin required to get to that value.

    It first converts the value to an int in pennies (for some reason I would get errors at the very end when using standard float values).

    The returned denominations are also in pennies (ie: 5000 = $50, 100 = $1, etc).

    function makeChange($val)
    {
        $amountOfMoney = intval($val*100);
        $cashInPennies = array(10000,5000,2000,1000,500,100,25,10,5,1);
        $outputArray = array();
        $currentSum = 0;
        $currentDenom = 0;
    
        while ($currentSum < $amountOfMoney) {
            if( ( $currentSum + $cashInPennies[$currentDenom] ) <= $amountOfMoney  ) {
                $currentSum = $currentSum + $cashInPennies[$currentDenom];
                $outputArray[$cashInPennies[$currentDenom]]++;
            } else {
                $currentDenom++;
            }
        }
    
        return $outputArray;
    
    }
    
    $change = 56.93;
    $output = makeChange($change);
    
    print_r($output);
    echo "<br>Total number of bills & coins: ".array_sum($output);
    
    === OUTPUT ===
    
    Array ( [5000] => 1 [500] => 1 [100] => 1 [25] => 3 [10] => 1 [5] => 1 [1] => 3 ) 
    Total number of bills & coins: 11
    

    C-like structures in Python

    How about a dictionary?

    Something like this:

    myStruct = {'field1': 'some val', 'field2': 'some val'}
    

    Then you can use this to manipulate values:

    print myStruct['field1']
    myStruct['field2'] = 'some other values'
    

    And the values don't have to be strings. They can be pretty much any other object.

    Generating all permutations of a given string

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Scanner;
    public class hello {
        public static void main(String[] args) throws IOException {
            hello h = new hello();
            h.printcomp();
        }
          int fact=1;
        public void factrec(int a,int k){
            if(a>=k)
            {fact=fact*k;
            k++;
            factrec(a,k);
            }
            else
            {System.out.println("The string  will have "+fact+" permutations");
            }
            }
        public void printcomp(){
            String str;
            int k;
            Scanner in = new Scanner(System.in);
            System.out.println("enter the string whose permutations has to b found");
            str=in.next();
            k=str.length();
            factrec(k,1);
            String[] arr =new String[fact];
            char[] array = str.toCharArray();
            while(p<fact)
            printcomprec(k,array,arr);
                // if incase u need array containing all the permutation use this
                //for(int d=0;d<fact;d++)         
            //System.out.println(arr[d]);
        }
        int y=1;
        int p = 0;
        int g=1;
        int z = 0;
        public void printcomprec(int k,char array[],String arr[]){
            for (int l = 0; l < k; l++) {
                for (int b=0;b<k-1;b++){
                for (int i=1; i<k-g; i++) {
                    char temp;
                    String stri = "";
                    temp = array[i];
                    array[i] = array[i + g];
                    array[i + g] = temp;
                    for (int j = 0; j < k; j++)
                        stri += array[j];
                    arr[z] = stri;
                    System.out.println(arr[z] + "   " + p++);
                    z++;
                }
                }
                char temp;
                temp=array[0];
                array[0]=array[y];
                array[y]=temp;
                if (y >= k-1)
                    y=y-(k-1);
                else
                    y++;
            }
            if (g >= k-1)
                g=1;
            else
                g++;
        }
    
    }