Programs & Examples On #Header only

Create a dictionary with list comprehension

Python version >= 2.7, do the below:

d = {i: True for i in [1,2,3]}

Python version < 2.7(RIP, 3 July 2010 - 31 December 2019), do the below:

d = dict((i,True) for i in [1,2,3])

Moving Panel in Visual Studio Code to right side

"Wokbench.panel.defaultLocation": "right"

Open settings using CTRL+., search for terminal and you should see this setting at the top. From the drop down below the settings explanation, choose right. See the screenshot below.

enter image description here

Fixed height and width for bootstrap carousel

In your main styles.css file change height/auto to whatever settings you desire. For example, 500px:

#myCarousel {
  height: auto;
  width: auto;
  overflow: hidden;
}

Make virtualenv inherit specific packages from your global site-packages

You can use the --system-site-packages and then "overinstall" the specific stuff for your virtualenv. That way, everything you install into your virtualenv will be taken from there, otherwise it will be taken from your system.

How to split a string into an array of characters in Python?

Unpack them:

word = "Paralelepipedo"
print([*word])

JavaScript property access: dot notation vs. brackets?

An example where the dot notation fails

json = { 
   "value:":4,
   'help"':2,
   "hello'":32,
   "data+":2,
   "":'',
   "a[]":[ 
      2,
      2
   ]
};

// correct
console.log(json['value:']);
console.log(json['help"']);
console.log(json["help\""]);
console.log(json['hello\'']);
console.log(json["hello'"]);
console.log(json["data+"]);
console.log(json[""]);
console.log(json["a[]"]);

// wrong
console.log(json.value:);
console.log(json.help");
console.log(json.hello');
console.log(json.data+);
console.log(json.);
console.log(json.a[]);

The property names shouldn't interfere with the syntax rules of javascript for you to be able to access them as json.property_name

How do I rotate a picture in WinForms

This will work as long as the image you want to rotate is already in your Properties resources folder.

In Partial Class:

Bitmap bmp2;

OnLoad:

 bmp2 = new Bitmap(Tycoon.Properties.Resources.save2);
            pictureBox6.SizeMode = PictureBoxSizeMode.StretchImage;
            pictureBox6.Image = bmp2;

Button or Onclick

private void pictureBox6_Click(object sender, EventArgs e)
        {
            if (bmp2 != null)
            {
                bmp2.RotateFlip(RotateFlipType.Rotate90FlipNone);
                pictureBox6.Image = bmp2;
            }
        }

Node.js - Maximum call stack size exceeded

Regarding increasing the max stack size, on 32 bit and 64 bit machines V8's memory allocation defaults are, respectively, 700 MB and 1400 MB. In newer versions of V8, memory limits on 64 bit systems are no longer set by V8, theoretically indicating no limit. However, the OS (Operating System) on which Node is running can always limit the amount of memory V8 can take, so the true limit of any given process cannot be generally stated.

Though V8 makes available the --max_old_space_size option, which allows control over the amount of memory available to a process, accepting a value in MB. Should you need to increase memory allocation, simply pass this option the desired value when spawning a Node process.

It is often an excellent strategy to reduce the available memory allocation for a given Node instance, especially when running many instances. As with stack limits, consider whether massive memory needs are better delegated to a dedicated storage layer, such as an in-memory database or similar.

How to iterate over array of objects in Handlebars?

I had a similar issue I was getting the entire object in this but the value was displaying while doing #each.

Solution: I re-structure my array of object like this:

let list = results.map((item)=>{
    return { name:item.name, author:item.author }
});

and then in template file:

{{#each list}}
    <tr>
        <td>{{name }}</td>
        <td>{{author}}</td>      
    </tr>
{{/each}} 

What causes a java.lang.StackOverflowError

I created a program with hibernate, in which I created two POJO classes, both with an object of each other as data members. When in the main method I tried to save them in the database I also got this error.

This happens because both of the classes are referring each other, hence creating a loop which causes this error.

So, check whether any such kind of relationships exist in your program.

How to capture a backspace on the onkeydown event

event.key === "Backspace" or "Delete"

More recent and much cleaner: use event.key. No more arbitrary number codes!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Mozilla Docs

Supported Browsers

PowerShell and the -contains operator

The -Contains operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.

From the documentation you linked to:

-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.

In the example you provided you're working with a collection containing just one string item.

If you read the documentation you linked to you'll see an example that demonstrates this behaviour:

Examples:

PS C:\> "abc", "def" -Contains "def"
True

PS C:\> "Windows", "PowerShell" -Contains "Shell"
False  #Not an exact match

I think what you want is the -Match operator:

"12-18" -Match "-"

Which returns True.

Important: As pointed out in the comments and in the linked documentation, it should be noted that the -Match operator uses regular expressions to perform text matching.

Easy way to get a test file into JUnit

If you want to load a test resource file as a string with just few lines of code and without any extra dependencies, this does the trick:

public String loadResourceAsString(String fileName) throws IOException {
    Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(fileName));
    String contents = scanner.useDelimiter("\\A").next();
    scanner.close();
    return contents;
}

"\\A" matches the start of input and there's only ever one. So this parses the entire file contents and returns it as a string. Best of all, it doesn't require any 3rd party libraries (like IOUTils).

Finding import static statements for Mockito constructs

Here's what I've been doing to cope with the situation.

I use global imports on a new test class.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:

import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;

This allows you to code away without getting 'stuck' trying to find the correct package to import.

How to query for today's date and 7 days before data?

Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):

select * from tab
where DateCol between adddate(now(),-7) and now() 

VNC viewer with multiple monitors

RealVNC 5.0.x now offers a VNCViewer that will do dual displays on Windows without having to buy a license. (Licensing now covers the SERVER portion of their tools).

When to use self over $this?

self:: keyword used for the current class and basically it is used to access static members, methods, and constants. But in case of $this you cannot call the static member, method and functions.

You can use the self:: keyword in another class and access the static members, method and constants. When it will be extends from parent class and same in case of $this keyword. You can access the non static members, method and function in another class when it will be extends from parent class.

The code given below is a example of self:: and $this keyword. Just copy and paste the code in your code file and see the output.

class cars{
    var $doors=4;   
    static $car_wheel=4;

  public function car_features(){
    echo $this->doors." Doors <br>";
    echo self::$car_wheel." Wheels <br>"; 
  }
}

class spec extends cars{
    function car_spec(){
        print(self::$car_wheel." Doors <br>");
        print($this->doors." Wheels <br>");
    }
}

/********Parent class output*********/

$car = new cars;
print_r($car->car_features());

echo "------------------------<br>";

/********Extend class from another class output**********/


$car_spec_show=new spec;

print($car_spec_show->car_spec());

Is it really impossible to make a div fit its size to its content?

You can use:

width: -webkit-fit-content;
height: -webkit-fit-content;
width: -moz-fit-content;
height: -moz-fit-content;

EDIT: No. see http://red-team-design.com/horizontal-centering-using-css-fit-content-value/

ALSO: http://dev.w3.org/csswg/css-box-3/

CMake link to external library

I assume you want to link to a library called foo, its filename is usually something link foo.dll or libfoo.so.

1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB use

    find_library(FOO_LIB foo)

CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib, /usr/lib64 and the paths in PATH.

You already know the location of your library. Add it to the CMAKE_PREFIX_PATH when you call CMake, then CMake will look for your library in the passed paths, too.

Sometimes you need to add hints or path suffixes, see the documentation for details: https://cmake.org/cmake/help/latest/command/find_library.html

2. Link the library From 1. you have the full library name in FOO_LIB. You use this to link the library to your target GLBall as in

  target_link_libraries(GLBall PRIVATE "${FOO_LIB}")

You should add PRIVATE, PUBLIC, or INTERFACE after the target, cf. the documentation: https://cmake.org/cmake/help/latest/command/target_link_libraries.html

If you don't add one of these visibility specifiers, it will either behave like PRIVATE or PUBLIC, depending on the CMake version and the policies set.

3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path similar to find_library and search for a header file. Then add the include directory with target_include_directories similar to target_link_libraries.

Documentation: https://cmake.org/cmake/help/latest/command/find_path.html and https://cmake.org/cmake/help/latest/command/target_include_directories.html

If available for the external software, you can replace find_library and find_path by find_package.

How to use CURL via a proxy?

Here is a working version with your bugs removed.

$url = 'http://dynupdate.no-ip.com/ip.php';
$proxy = '127.0.0.1:8888';
//$proxyauth = 'user:password';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);

echo $curl_scraped_page;

I have added CURLOPT_PROXYUSERPWD in case any of your proxies require a user name and password. I set CURLOPT_RETURNTRANSFER to 1, so that the data will be returned to $curl_scraped_page variable.

I removed a second extra curl_exec($ch); which would stop the variable being returned. I consolidated your proxy IP and port into one setting.

I also removed CURLOPT_HTTPPROXYTUNNEL and CURLOPT_CUSTOMREQUEST as it was the default.

If you don't want the headers returned, comment out CURLOPT_HEADER.

To disable the proxy simply set it to null.

curl_setopt($ch, CURLOPT_PROXY, null);

Any questions feel free to ask, I work with cURL every day.

saving a file (from stream) to disk using c#

For file Type you can rely on FileExtentions and for writing it to disk you can use BinaryWriter. or a FileStream.

Example (Assuming you already have a stream):

FileStream fileStream = File.Create(fileFullPath, (int)stream.Length);
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);    
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
//Close the filestream
fileStream.Close();

What is the difference between bool and Boolean types in C#

bool is an alias for System.Boolean just as int is an alias for System.Int32. See a full list of aliases here: Built-In Types Table (C# Reference).

Nested Recycler view height doesn't wrap its content

I have tried all solutions, they are very useful but this only works fine for me

public class  LinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {

    public LinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
        super(context, orientation, reverseLayout);
    }

    private int[] mMeasuredDimension = new int[2];

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                          int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);
        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {


            if (getOrientation() == HORIZONTAL) {

                measureScrapChild(recycler, i,
                        View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                        heightSpec,
                        mMeasuredDimension);

                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                measureScrapChild(recycler, i,
                        widthSpec,
                        View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                        mMeasuredDimension);
                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }

        if (height < heightSize || width < widthSize) {

            switch (widthMode) {
                case View.MeasureSpec.EXACTLY:
                    width = widthSize;
                case View.MeasureSpec.AT_MOST:
                case View.MeasureSpec.UNSPECIFIED:
            }

            switch (heightMode) {
                case View.MeasureSpec.EXACTLY:
                    height = heightSize;
                case View.MeasureSpec.AT_MOST:
                case View.MeasureSpec.UNSPECIFIED:
            }

            setMeasuredDimension(width, height);
        } else {
            super.onMeasure(recycler, state, widthSpec, heightSpec);
        }
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        View view = recycler.getViewForPosition(position);
        recycler.bindViewToPosition(view, position);
        if (view != null) {
            RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight(), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom(), p.height);
            view.measure(childWidthSpec, childHeightSpec);
            measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
            measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
            recycler.recycleView(view);
        }
    }
}

How do I make text bold in HTML?

use <strong> or <b> tag

also, you can try with css <span style="font-weight:bold">text</span>

Custom Card Shape Flutter SDK

You can also customize the card theme globally with ThemeData.cardTheme:

MaterialApp(
  title: 'savvy',
  theme: ThemeData(
    cardTheme: CardTheme(
      shape: RoundedRectangleBorder(
        borderRadius: const BorderRadius.all(
          Radius.circular(8.0),
        ),
      ),
    ),
    // ...

How to effectively work with multiple files in Vim

You may want to use Vim global marks.

This way you can quickly bounce between files, and even to the marked location in the file. Also, the key commands are short: 'C takes me to the code I'm working with, 'T takes me to the unit test I'm working with.

When you change places, resetting the marks is quick too: mC marks the new code spot, mT marks the new test spot.

"Use the new keyword if hiding was intended" warning

Your class has a base class, and this base class also has a property (which is not virtual or abstract) called Events which is being overridden by your class. If you intend to override it put the "new" keyword after the public modifier. E.G.

public new EventsDataTable Events
{
  ..
}

If you don't wish to override it change your properties' name to something else.

How to redirect to logon page when session State time out is completed in asp.net mvc

I discover very simple way to redirect Login Page When session end in MVC. I have already tested it and this works without problems.

In short, I catch session end in _Layout 1 minute before and make redirection.

I try to explain everything step by step.

If we want to session end 30 minute after and redirect to loginPage see this steps:

  1. Change the web config like this (set 31 minute):

     <system.web>
        <sessionState timeout="31"></sessionState>
     </system.web>
    
  2. Add this JavaScript in _Layout (when session end 1 minute before this code makes redirect, it makes count time after user last action, not first visit on site)

    <script>
        //session end 
        var sessionTimeoutWarning = @Session.Timeout- 1;
    
        var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
        setTimeout('SessionEnd()', sTimeout);
    
        function SessionEnd() {
            window.location = "/Account/LogOff";
        }
    </script>
    
  3. Here is my LogOff Action, which makes only LogOff and redirect LoginIn Page

    public ActionResult LogOff()
    {
        Session["User"] = null; //it's my session variable
        Session.Clear();
        Session.Abandon();
        FormsAuthentication.SignOut(); //you write this when you use FormsAuthentication
        return RedirectToAction("Login", "Account");
    } 
    

I hope this is a very useful code for you.

Why do I get a C malloc assertion failure?

99.9% likely that you have corrupted memory (over- or under-flowed a buffer, wrote to a pointer after it was freed, called free twice on the same pointer, etc.)

Run your code under Valgrind to see where your program did something incorrect.

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

I can highly recommend checking out the Visual Studio plugin ReSharper. It has a QuickFix feature that does the same (and a lot more).

But ReSharper doesn't require the cursor to be located on the actual code that requires a new namespace. Say, you copy/paste some code into the source file, and just a few clicks of Alt + Enter, and all the required usings are included.

Oh, and it also makes sure that the required assembly reference is added to your project. Say for example, you create a new project containing NUnit unit tests. The first class you write, you add the [TestFixture] attribute. If you already have one project in your solution that references the NUnit DLL file, then ReSharper is able to see that the TestFixtureAttribute comes from that DLL file, so it will automatically add that assembly reference to your new project.

And it also adds required namespaces for extension methods. At least the ReSharper version 5 beta does. I'm pretty sure that Visual Studio's built-in resolve function doesn't do that.

On the down side, it's a commercial product, so you have to pay for it. But if you work with software commercially, the gained productivity (the plug in does a lot of other cool stuff) outweighs the price tag.

Yes, I'm a fan ;)

How to get featured image of a product in woocommerce

I did this and it works great

<?php if ( has_post_thumbnail() ) { ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail(); ?></a>
<?php } ?>

Lining up labels with radio buttons in bootstrap

If you add the 'radio inline' class to the control label in the solution provided by user1938475 it should line up correctly with the other labels. Or if you're only using 'radio' like your 2nd example just include the 'radio' class.

<label class="radio control-label">Some label</label>

OR for 'radio inline'

<label class="radio-inline control-label">Some label</label>

Truncate number to two decimal places without rounding

I used (num-0.05).toFixed(1) to get the second decimal floored.

How to determine an object's class?

checking with isinstance() would not be enough if you want to know in run time. use:

if(someObject.getClass().equals(C.class){
    // do something
}

How to Configure SSL for Amazon S3 bucket

As mentioned before, you cannot create free certificates for S3 buckets. However, you can create Cloud Front distribution and then assign the certificate for the Cloud Front instead. You request the certificate for your domain and then just assign it to the Cloud Front distribution in the Cloud Front settings. I've used this method to serve static websites via SSL as well as serve static files.

For static website creation Amazon is the go to place. It is really affordable to get a static website with SSL.

Convert string to title case with JavaScript

Simpler more performant version, with simple caching.

_x000D_
_x000D_
  var TITLE_CASE_LOWER_MAP = {_x000D_
    'a': 1, 'an': 1, 'and': 1, 'as': 1, 'at': 1, 'but': 1, 'by': 1, 'en':1, 'with': 1,_x000D_
    'for': 1, 'if': 1, 'in': 1, 'of': 1, 'on': 1, 'the': 1, 'to': 1, 'via': 1_x000D_
  };_x000D_
_x000D_
  // LEAK/CACHE TODO: evaluate using LRU._x000D_
  var TITLE_CASE_CACHE = new Object();_x000D_
_x000D_
  toTitleCase: function (title) {_x000D_
    if (!title) return null;_x000D_
_x000D_
    var result = TITLE_CASE_CACHE[title];_x000D_
    if (result) {_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    result = "";_x000D_
    var split = title.toLowerCase().split(" ");_x000D_
    for (var i=0; i < split.length; i++) {_x000D_
_x000D_
      if (i > 0) {_x000D_
        result += " ";_x000D_
      }_x000D_
_x000D_
      var word = split[i];_x000D_
      if (i == 0 || TITLE_CASE_LOWER_MAP[word] != 1) {_x000D_
        word = word.substr(0,1).toUpperCase() + word.substr(1);_x000D_
      }_x000D_
_x000D_
      result += word;_x000D_
    }_x000D_
_x000D_
    TITLE_CASE_CACHE[title] = result;_x000D_
_x000D_
    return result;_x000D_
  },
_x000D_
_x000D_
_x000D_

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

The first error

java.lang.Exception; must be caught or declared to be thrown byte[] encrypted = encrypt(concatURL);

means that your encrypt method throws an exception that is not being handled or declared by the actionPerformed method where you are calling it. Read all about it at the Java Exceptions Tutorial.

You have a couple of choices that you can pick from to get the code to compile.

  • You can remove throws Exception from your encrypt method and actually handle the exception inside encrypt.
  • You can remove the try/catch block from encrypt and add throws Exception and the exception handling block to your actionPerformed method.

It's generally better to handle an exception at the lowest level that you can, instead of passing it up to a higher level.

The second error just means that you need to add a return statement to whichever method contains line 109 (also encrypt, in this case). There is a return statement in the method, but if an exception is thrown it might not be reached, so you either need to return in the catch block, or remove the try/catch from encrypt, as I mentioned before.

Add A Year To Today's Date

//This piece of code will handle the leap year addition as well.

function updateExpiryDate(controlID, value) {
    if ( $("#ICMEffectiveDate").val() != '' &&
        $("#ICMTermYears").val() != '') {

        var effectiveDate = $("#ICMEffectiveDate").val();
        var date = new Date(effectiveDate);
        var termYears = $("#ICMTermYears").val();

        date = new Date(date.setYear(date.getFullYear() + parseInt(termYears)));
        var expiryDate = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
        $('#ICMExpiryDate').val(expiryDate);
    }
}

What's the difference between ViewData and ViewBag?

ViewBag vs ViewData in MVC

http://royalarun.blogspot.in/2013/08/viewbag-viewdata-tempdata-and-view.html

Similarities between ViewBag & ViewData :

Helps to maintain data when you move from controller to view. Used to pass data from controller to corresponding view. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:

ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. ViewData requires typecasting for complex data type and check for null values to avoid error. ViewBag doesn’t require typecasting for complex data type.

ViewBag & ViewData Example:

public ActionResult Index()
{   
    ViewBag.Name = "Arun Prakash";   
    return View();
}

public ActionResult Index()
{  
    ViewData["Name"] = "Arun Prakash";  
    return View();
}   

Calling in View

@ViewBag.Name    
@ViewData["Name"]

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

I had the same error and I started the SQL Server Express service and it worked. Hope this helps.

How do you send a Firebase Notification to all devices via CURL?

I was looking solution for my Ionic Cordova app push notification.

Thanks to Syed Rafay's answer.

in app.component.ts

const options: PushOptions = {
  android: {
    topics: ['all']
  },

in Server file

"to" => "/topics/all",

How come I can't remove the blue textarea border in Twitter Bootstrap?

Bootstrap 3

If you just want to change the color, change the variable (recommended):

Less or Customizer

@input-border-focus: red;

variables.less

Sass

$input-border-focus: red;

variables.sass

If you wan't to remove it completely, you'll have to overwrite the Mixin that sets the outline.

.form-control-focus(@color: @input-border-focus) {}

CSS

If you are using css overwrite it via:

.form-control:focus{
    border-color: #cccccc;
    -webkit-box-shadow: none;
    box-shadow: none;
}

Link to implementation

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]

What is __main__.py?

What is the __main__.py file for?

When creating a Python module, it is common to make the module execute some functionality (usually contained in a main function) when run as the entry point of the program. This is typically done with the following common idiom placed at the bottom of most Python files:

if __name__ == '__main__':
    # execute only if run as the entry point into the program
    main()

You can get the same semantics for a Python package with __main__.py, which might have the following structure:

.
+-- demo
    +-- __init__.py
    +-- __main__.py

To see this, paste the below into a Python 3 shell:

from pathlib import Path

demo = Path.cwd() / 'demo'
demo.mkdir()

(demo / '__init__.py').write_text("""
print('demo/__init__.py executed')

def main():
    print('main() executed')
""")

(demo / '__main__.py').write_text("""
print('demo/__main__.py executed')

from demo import main

main()
""")

We can treat demo as a package and actually import it, which executes the top-level code in the __init__.py (but not the main function):

>>> import demo
demo/__init__.py executed

When we use the package as the entry point to the program, we perform the code in the __main__.py, which imports the __init__.py first:

$ python -m demo
demo/__init__.py executed
demo/__main__.py executed
main() executed

You can derive this from the documentation. The documentation says:

__main__ — Top-level script environment

'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:

if __name__ == '__main__':
     # execute only if run as a script
     main()

For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m.

Zipped

You can also zip up this directory, including the __main__.py, into a single file and run it from the command line like this - but note that zipped packages can't execute sub-packages or submodules as the entry point:

from pathlib import Path

demo = Path.cwd() / 'demo2'
demo.mkdir()

(demo / '__init__.py').write_text("""
print('demo2/__init__.py executed')

def main():
    print('main() executed')
""")

(demo / '__main__.py').write_text("""
print('demo2/__main__.py executed')

from __init__ import main

main()
""")

Note the subtle change - we are importing main from __init__ instead of demo2 - this zipped directory is not being treated as a package, but as a directory of scripts. So it must be used without the -m flag.

Particularly relevant to the question - zipapp causes the zipped directory to execute the __main__.py by default - and it is executed first, before __init__.py:

$ python -m zipapp demo2 -o demo2zip
$ python demo2zip
demo2/__main__.py executed
demo2/__init__.py executed
main() executed

Note again, this zipped directory is not a package - you cannot import it either.

Setting Spring Profile variable

as System environment Variable:

Windows: Start -> type "envi" select environment variables and add a new: Name: spring_profiles_active Value: dev (or whatever yours is)

Linux: add following line to /etc/environment under PATH:

spring_profiles_active=prod (or whatever profile is)

then also export spring_profiles_active=prod so you have it in the runtime now.

Getting attributes of a class

myfunc is an attribute of MyClass. That's how it's found when you run:

myinstance = MyClass()
myinstance.myfunc()

It looks for an attribute on myinstance named myfunc, doesn't find one, sees that myinstance is an instance of MyClass and looks it up there.

So the complete list of attributes for MyClass is:

>>> dir(MyClass)
['__doc__', '__module__', 'a', 'b', 'myfunc']

(Note that I'm using dir just as a quick and easy way to list the members of the class: it should only be used in an exploratory fashion, not in production code)

If you only want particular attributes, you'll need to filter this list using some criteria, because __doc__, __module__, and myfunc aren't special in any way, they're attributes in exactly the same way that a and b are.

I've never used the inspect module referred to by Matt and Borealid, but from a brief link it looks like it has tests to help you do this, but you'll need to write your own predicate function, since it seems what you want is roughly the attributes that don't pass the isroutine test and don't start and end with two underscores.

Also note: by using class MyClass(): in Python 2.7 you're using the wildly out of date old-style classes. Unless you're doing so deliberately for compatibility with extremely old libraries, you should be instead defining your class as class MyClass(object):. In Python 3 there are no "old-style" classes, and this behaviour is the default. However, using newstyle classes will get you a lot more automatically defined attributes:

>>> class MyClass(object):
        a = "12"
        b = "34"
        def myfunc(self):
            return self.a
>>> dir(MyClass)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'myfunc']

How to present a modal atop the current view in Swift

The only way I able to get this to work was by doing this on the presenting view controller:

    func didTapButton() {
    self.definesPresentationContext = true
    self.modalTransitionStyle = .crossDissolve
    let yourVC = self.storyboard?.instantiateViewController(withIdentifier: "YourViewController") as! YourViewController
    let navController = UINavigationController(rootViewController: yourVC)
    navController.modalPresentationStyle = .overCurrentContext
    navController.modalTransitionStyle = .crossDissolve
    self.present(navController, animated: true, completion: nil)
}

Calculate days between two Dates in Java 8

You can use DAYS.between from java.time.temporal.ChronoUnit

e.g.

import java.time.temporal.ChronoUnit;

public long getDaysCountBetweenDates(LocalDate dateBefore, LocalDate dateAfter) {
    return DAYS.between(dateBefore, dateAfter);
}

How to specify line breaks in a multi-line flexbox layout?

@Oriol has an excellent answer, sadly as of October 2017, neither display:contents, neither page-break-after is widely supported, better said it's about Firefox which supports this but not the other players, I have come up with the following "hack" which I consider better than hard coding in a break after every 3rd element, because that will make it very difficult to make the page mobile friendly.

As said it's a hack and the drawback is that you need to add quite a lot of extra elements for nothing, but it does the trick and works cross browser even on the dated IE11.

The "hack" is to simply add an additional element after each div, which is set to display:none and then used the css nth-child to decide which one of this should be actually made visible forcing a line brake like this:

_x000D_
_x000D_
.container {
  background: tomato;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}
.item {
  width: 100px;
  background: gold;
  height: 100px;
  border: 1px solid black;
  font-size: 30px;
  line-height: 100px;
  text-align: center;
  margin: 10px
}
.item:nth-child(3n-1) {
  background: silver;
}
.breaker {
  display: none;
}
.breaker:nth-child(3n) {
  display: block;
  width: 100%;
  height: 0;
}
_x000D_
<div class="container">
  <div class="item">1</div>
  <p class="breaker"></p>
  
  <div class="item">2</div>
  <p class="breaker"></p>
  
  <div class="item">3</div>
  <p class="breaker"></p>
  
  <div class="item">4</div>
  <p class="breaker"></p>
  
  <div class="item">5</div>
  <p class="breaker"></p>
  
  <div class="item">6</div>
  <p class="breaker"></p>
  
  <div class="item">7</div>
  <p class="breaker"></p>
  
  <div class="item">8</div>
  <p class="breaker"></p>
  
  <div class="item">9</div>
  <p class="breaker"></p>
  
  <div class="item">10</div>
  <p class="breaker"></p>
</div>
_x000D_
_x000D_
_x000D_

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

All objects are instances of at least one class – Object – in ECMAScript. You can only differentiate between instances of built-in classes and normal objects using Object#toString. They all have the same level of complexity, for instance, whether they are created using {} or the new operator.

Object.prototype.toString.call(object) is your best bet to differentiate between normal objects and instances of other built-in classes, as object === Object(object) doesn't work here. However, I can't see a reason why you would need to do what you're doing, so perhaps if you share the use case I can offer a little more help.

Display all post meta keys and meta values of the same post ID in wordpress

To get all rows, don't specify the key. Try this:

$meta_values = get_post_meta( get_the_ID() );

var_dump( $meta_values );

Hope it helps!

Adding the "Clear" Button to an iPhone UITextField

Swift 4+:

textField.clearButtonMode = UITextField.ViewMode.whileEditing

or even shorter:

textField.clearButtonMode = .whileEditing

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

In new Xcode 7.0 use

//: Playground - noun: a place where people can play

import UIKit

var name = "How do you use String.substringWithRange?"
let range = name.startIndex.advancedBy(0)..<name.startIndex.advancedBy(10)
name.substringWithRange(range)

//OUT:

enter image description here

Garbage collector in Android

Generally speaking, in the presence of a garbage collector, it is never good practice to manually call the GC. A GC is organized around heuristic algorithms which work best when left to their own devices. Calling the GC manually often decreases performance.

Occasionally, in some relatively rare situations, one may find that a particular GC gets it wrong, and a manual call to the GC may then improves things, performance-wise. This is because it is not really possible to implement a "perfect" GC which will manage memory optimally in all cases. Such situations are hard to predict and depend on many subtle implementation details. The "good practice" is to let the GC run by itself; a manual call to the GC is the exception, which should be envisioned only after an actual performance issue has been duly witnessed.

[Vue warn]: Cannot find element

I get the same error. the solution is to put your script code before the end of body, not in the head section.

How to copy files from host to Docker container?

You can just trace the IP address of your local machine using

ifconfig

Then just enter into your Docker container and type

scp user_name@ip_address:/path_to_the_file destination

In any case if you don't have an SSH client and server installed, just install it using:

sudo apt-get install openssh-server

onclick event function in JavaScript

Check you are calling same function or not.

<script>function greeting(){document.write("hi");}</script>

<input type="button" value="Click Here" onclick="greeting();"/>

jQuery: set selected value of dropdown list?

UPDATED ANSWER:

Old answer, correct method nowadays is to use jQuery's .prop(). IE, element.prop("selected", true)

OLD ANSWER:

Use this instead:

$("#routetype option[value='quietest']").attr("selected", "selected");

Fiddle'd: http://jsfiddle.net/x3UyB/4/

Generate an HTML Response in a Java Servlet

Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:

public void doGet(HttpServletRequest request,
       HttpServletResponse response)
       throws IOException, ServletException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("HTML from an external file:");     
   request.getRequestDispatcher("/pathToFile/fragment.html")
          .include(request, response); 
   out.close();
}

push multiple elements to array

You can use Array.concat:

var result = a.concat(b);

What do I do when my program crashes with exception 0xc0000005 at address 0?

Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).

So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.

Generate a dummy-variable

Another option that can work better if you have many variables is factor and model.matrix.

> year.f = factor(year)
> dummies = model.matrix(~year.f)

This will include an intercept column (all ones) and one column for each of the years in your data set except one, which will be the "default" or intercept value.

You can change how the "default" is chosen by messing with contrasts.arg in model.matrix.

Also, if you want to omit the intercept, you can just drop the first column or add +0 to the end of the formula.

Hope this is useful.

How to use export with Python on Linux

Kind of a hack because it's not really python doing anything special here, but if you run the export command in the same sub-shell, you will probably get the result you want.

import os

cmd = "export MY_DATA='1234'; echo $MY_DATA" # or whatever command
os.system(cmd)

How can I render a list select box (dropdown) with bootstrap?

I'm currently fighting with dropdowns and I'd like to share my experiences:

There are specific situations where <select> can't be used and must be 'emulated' with dropdown.

For example if you want to create bootstrap input groups, like Buttons with dropdowns (see http://getbootstrap.com/components/#input-groups-buttons-dropdowns). Unfortunately <select> is not supported in input groups, it will not be rendered properly.

Or does anybody solved this already? I would be very interested on the solution.

And to make it even more complicated, you can't use so simply $(this).text() to catch what user selected in dropdown if you're using glypicons or font awesome icons as content for dropdown. For example: <li id="someId"><a href="#0"><i class="fa fa-minus"></i></a></li> Because in this case there is no text and if you will add some then it will be also displayed in dropdown element and this is unwanted.

I found two possible solutions:

1) Use $(this).html() to get content of the selected <li> element and then to examine it, but you will get something like <a href="#0"><i class="fa fa-minus"></i></a> so you need to play with this to extract what you need.

2) Use $(this).text() and hide the text in element in hidden span: <li id="someId"><a href="#0"><i class="fa fa-minus"><span class="hidden">text</span></i></a></li>. For me this is simple and elegant solution, you can put any text you need, text will be hidden, and you don't need to do any transformations of $(this).html() result like in option 1) to get what you need.

I hope it's clear and can help somebody :-)

How to change MySQL column definition?

Do you mean altering the table after it has been created? If so you need to use alter table, in particular:

ALTER TABLE tablename MODIFY COLUMN new-column-definition

e.g.

ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);

How can I be notified when an element is added to the page?

ETA 24 Apr 17 I wanted to simplify this a bit with some async/await magic, as it makes it a lot more succinct:

Using the same promisified-observable:

const startObservable = (domNode) => {
  var targetNode = domNode;

  var observerConfig = {
    attributes: true,
    childList: true,
    characterData: true
  };

  return new Promise((resolve) => {
      var observer = new MutationObserver(function (mutations) {
         // For the sake of...observation...let's output the mutation to console to see how this all works
         mutations.forEach(function (mutation) {
             console.log(mutation.type);
         });
         resolve(mutations)
     });
     observer.observe(targetNode, observerConfig);
   })
} 

Your calling function can be as simple as:

const waitForMutation = async () => {
    const button = document.querySelector('.some-button')
    if (button !== null) button.click()
    try {
      const results = await startObservable(someDomNode)
      return results
    } catch (err) { 
      console.error(err)
    }
}

If you wanted to add a timeout, you could use a simple Promise.race pattern as demonstrated here:

const waitForMutation = async (timeout = 5000 /*in ms*/) => {
    const button = document.querySelector('.some-button')
    if (button !== null) button.click()
    try {

      const results = await Promise.race([
          startObservable(someDomNode),
          // this will throw after the timeout, skipping 
          // the return & going to the catch block
          new Promise((resolve, reject) => setTimeout(
             reject, 
             timeout, 
             new Error('timed out waiting for mutation')
          )
       ])
      return results
    } catch (err) { 
      console.error(err)
    }
}

Original

You can do this without libraries, but you'd have to use some ES6 stuff, so be cognizant of compatibility issues (i.e., if your audience is mostly Amish, luddite or, worse, IE8 users)

First, we'll use the MutationObserver API to construct an observer object. We'll wrap this object in a promise, and resolve() when the callback is fired (h/t davidwalshblog)david walsh blog article on mutations:

const startObservable = (domNode) => {
    var targetNode = domNode;

    var observerConfig = {
        attributes: true,
        childList: true,
        characterData: true
    };

    return new Promise((resolve) => {
        var observer = new MutationObserver(function (mutations) {
            // For the sake of...observation...let's output the mutation to console to see how this all works
            mutations.forEach(function (mutation) {
                console.log(mutation.type);
            });
            resolve(mutations)
        });
        observer.observe(targetNode, observerConfig);
    })
} 

Then, we'll create a generator function. If you haven't used these yet, then you're missing out--but a brief synopsis is: it runs like a sync function, and when it finds a yield <Promise> expression, it waits in a non-blocking fashion for the promise to be fulfilled (Generators do more than this, but this is what we're interested in here).

// we'll declare our DOM node here, too
let targ = document.querySelector('#domNodeToWatch')

function* getMutation() {
    console.log("Starting")
    var mutations = yield startObservable(targ)
    console.log("done")
}

A tricky part about generators is they don't 'return' like a normal function. So, we'll use a helper function to be able to use the generator like a regular function. (again, h/t to dwb)

function runGenerator(g) {
    var it = g(), ret;

    // asynchronously iterate over generator
    (function iterate(val){
        ret = it.next( val );

        if (!ret.done) {
            // poor man's "is it a promise?" test
            if ("then" in ret.value) {
                // wait on the promise
                ret.value.then( iterate );
            }
            // immediate value: just send right back in
            else {
                // avoid synchronous recursion
                setTimeout( function(){
                    iterate( ret.value );
                }, 0 );
            }
        }
    })();
}

Then, at any point before the expected DOM mutation might happen, simply run runGenerator(getMutation).

Now you can integrate DOM mutations into a synchronous-style control flow. How bout that.

CSS: Background image and padding

You can just add the padding to tour block element and add background-origin style like so:

.block {
  position: relative;
  display: inline-block;
  padding: 10px 12px;
  border:1px solid #e5e5e5;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  background-origin: content-box;
  background-image: url(_your_image_);
  height: 14rem;
  width: 10rem;
}

You can check several https://www.w3schools.com/cssref/css3_pr_background-origin.asp

read string from .resx file in C#

I added my resource file to my project directly, and so I was able to access the strings inside just fine with the resx file name.

Example: in Resource1.resx, key "resourceKey" -> string "dataString". To get the string "dataString", I just put Resource1.resourceKey.

There may be reasons not to do this that I don't know about, but it worked for me.

How to add and get Header values in WebApi

You need to get the HttpRequestMessage from the current OperationContext. Using OperationContext you can do it like so

OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;

HttpRequestMessageProperty requestProperty = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;

string customHeaderValue = requestProperty.Headers["Custom"];

firefox proxy settings via command line

I needed to set an additional option to allow SSO passthrough to our intranet site. I added some code to an example above.

pushd "%APPDATA%\Mozilla\Firefox\Profiles\*.default"
echo user_pref("network.proxy.type", 4);>>prefs.js
echo user_pref("network.automatic-ntlm-auth.trusted-uris","site.domain.com, sites.domain.com");>>prefs.js
popd

Activity has leaked window that was originally added

here is a solution when you do want to dismiss AlertDialog but do not want to keep a reference to it inside activity.

solution requires you to have androidx.lifecycle dependency in your project (i believe at the moment of the comment it's a common requirement)

this lets you to delegate dialog's dismiss to external object (observer), and you dont need to care about it anymore, because it's auto-unsubscribed when activity dies. (here is proof: https://github.com/googlecodelabs/android-lifecycles/issues/5).

so, the observer keeps the reference to dialog, and activity keeps reference to observer. when "onPause" happens - observer dismisses the dialog, and when "onDestroy" happens - activity removes observer, so no leak happens (well, at least i dont see error in logcat anymore)

// observer
class DialogDismissLifecycleObserver( private var dialog: AlertDialog? ) : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        dialog?.dismiss()
        dialog = null
    }
}
// activity code
private fun showDialog() {
        if( isDestroyed || isFinishing ) return
        val dialog = AlertDialog
            .Builder(this, R.style.DialogTheme)
            // dialog setup skipped
            .create()
        lifecycle.addObserver( DialogDismissLifecycleObserver( dialog ) )
        dialog.show()
}

Android - Handle "Enter" in an EditText

Add these depencendy, and it should work:

import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

How to add minutes to my Date

you can use DateUtils class in org.apache.commons.lang3.time package

int addMinuteTime = 5;
Date targetTime = new Date(); //now
targetTime = DateUtils.addMinutes(targetTime, addMinuteTime); //add minute

Export table from database to csv file

rsubmit;
options missing=0;
ods listing close;
ods csv file='\\FILE_PATH_and_Name_of_report.csv';

proc sql;
SELECT *
FROM `YOUR_FINAL_TABLE_NAME';
quit;
ods csv close;

endrsubmit;

How do I download a file using VBA (without Internet Explorer)

I was struggling for hours on this until I figured out it can be done in one line of powershell:

invoke-webrequest -Uri "http://myserver/Reports/Pages/ReportViewer.aspx?%2fClients%2ftest&rs:Format=PDF&rs:ClearSession=true&CaseCode=12345678" -OutFile "C:\Temp\test.pdf" -UseDefaultCredentials

I looked into doing it purely in VBA but it runs to several pages, so I just call my powershell script from VBA every time I want to download a file.

Simple.

UICollectionView - Horizontal scroll, horizontal layout?

You can write a custom UICollectionView layout to achieve this, here is demo image of my implementation:

demo image

Here's code repository: KSTCollectionViewPageHorizontalLayout

@iPhoneDev (this maybe help you too)

Check if multiple strings exist in another string

flog = open('test.txt', 'r')
flogLines = flog.readlines()
strlist = ['SUCCESS', 'Done','SUCCESSFUL']
res = False
for line in flogLines:
     for fstr in strlist:
         if line.find(fstr) != -1:
            print('found') 
            res = True


if res:
    print('res true')
else: 
    print('res false')

output example image

What is the difference between synchronous and asynchronous programming (in node.js)

This would become a bit more clear if you add a line to both examples:

var result = database.query("SELECT * FROM hugetable");
console.log(result.length);
console.log("Hello World");

The second one:

database.query("SELECT * FROM hugetable", function(rows) {
   var result = rows;
   console.log(result.length);
});
console.log("Hello World");

Try running these, and you’ll notice that the first (synchronous) example, the result.length will be printed out BEFORE the 'Hello World' line. In the second (the asynchronous) example, the result.length will (most likely) be printed AFTER the "Hello World" line.

That's because in the second example, the database.query is run asynchronously in the background, and the script continues straightaway with the "Hello World". The console.log(result.length) is only executed when the database query has completed.

Java: how to convert HashMap<String, Object> to array

If you have HashMap<String, SomeObject> hashMap then:

hashMap.values().toArray();

Will return an Object[]. If instead you want an array of the type SomeObject, you could use:

hashMap.values().toArray(new SomeObject[0]);

Source file 'Properties\AssemblyInfo.cs' could not be found

delete the assemeblyinfo.cs file from project under properties menu and rebulid it.

Overriding !important style

element.style has a setProperty method that can take the priority as a third parameter:

element.style.setProperty("display", "inline", "important")

It didn't work in old IEs but it should be fine in current browsers.

How can I view array structure in JavaScript with alert()?

pass your js array to the function below and it will do the same as php print_r() function

 alert(print_r(your array));  //call it like this

function print_r(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects 
    for(var item in arr) {
        var value = arr[item];

        if(typeof(value) == 'object') { //If it is an array,
            dumped_text += level_padding + "'" + item + "' ...\n";
            dumped_text += print_r(value,level+1);
        } else {
            dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
        }
    }
} else { //Stings/Chars/Numbers etc.
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}

How to deal with http status codes other than 200 in Angular 2

Include required imports and you can make ur decision in handleError method Error status will give the error code

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {Observable, throwError} from "rxjs/index";
import { catchError, retry } from 'rxjs/operators';
import {ApiResponse} from "../model/api.response";
import { TaxType } from '../model/taxtype.model'; 

private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
  // A client-side or network error occurred. Handle it accordingly.
  console.error('An error occurred:', error.error.message);
} else {
  // The backend returned an unsuccessful response code.
  // The response body may contain clues as to what went wrong,
  console.error(
    `Backend returned code ${error.status}, ` +
    `body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
  'Something bad happened; please try again later.');
  };

  getTaxTypes() : Observable<ApiResponse> {
return this.http.get<ApiResponse>(this.baseUrl).pipe(
  catchError(this.handleError)
);
  }

Find objects between two dates MongoDB

Use this code to find the record between two dates using $gte and $lt:

db.CollectionName.find({"whenCreated": {
    '$gte': ISODate("2018-03-06T13:10:40.294Z"),
    '$lt': ISODate("2018-05-06T13:10:40.294Z")
}});

Importing a csv into mysql via command line

You can simply import by

mysqlimport --ignore-lines=1 --lines-terminated-by='\n' --fields-terminated-by=',' --fields-enclosed-by='"' --verbose --local -uroot -proot db_name csv_import.csv

Note: Csv File name and Table name should be same

Git and nasty "error: cannot lock existing info/refs fatal"

Before pull you need to clean your local changes. following command help me to solve.

git remote prune origin

and then after

git pull origin develop

Hopes this helps!

How do I fix PyDev "Undefined variable from import" errors?

I was having a similar problem with an Eclipse/PyDev project. In this project the root directory of the python code was a sub-directory of the project.

--> MyProject
 + --> src         Root of python code
   + --> module1     A module 
   + --> module2     Another module
 + --> docs
 + --> test

When the project was debugged or run everything was fine as the working directory was set to the correct place. However the PyDev code analysis was failing to find any imports from module1 or module2.

Solution was to edit the project properties -> PyDev - PYTHONPATH section and remove /MyProject from the source folders tab and add /MyProject/src to it instead.

Read a file one line at a time in node.js?

For such a simple operation there shouldn't be any dependency on third-party modules. Go easy.

var fs = require('fs'),
    readline = require('readline');

var rd = readline.createInterface({
    input: fs.createReadStream('/path/to/file'),
    output: process.stdout,
    console: false
});

rd.on('line', function(line) {
    console.log(line);
});

Check if value is in select list with JQuery

I know this is kind of an old question by this one works better.

if(!$('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"] option[value="'+data['item'][i]['id']+'"]')[0]){
  //Doesn't exist, so it isn't a repeat value being added. Go ahead and append.
  $('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"]').append(option);
}

As you can see in this example, I am searching by unique tags data-dropdown name and the value of the selected option. Of course you don't need these for these to work but I included them so that others could see you can search multi values, etc.

UITextField border color

Here's a Swift implementation. You can make an extension so that it will be usable by other views if you like.

extension UIView {
    func addBorderAndColor(color: UIColor, width: CGFloat, corner_radius: CGFloat = 0, clipsToBounds: Bool = false) {
        self.layer.borderWidth  = width
        self.layer.borderColor  = color.cgColor
        self.layer.cornerRadius = corner_radius
        self.clipsToBounds      = clipsToBounds
    }
}

Call this like: email.addBorderAndColor(color: UIColor.white, width: 0.5, corner_radius: 5, clipsToBounds: true).

Unable to compile class for JSP

In my case, I was using the 6.0.24 Tomcat version (with JDK 1.8) and resolved the problem by upgrading to the 6.0.37 version.

Also, if you install the new tomcat version in a different folder, do not forget to copy your previous version /conf folder to the new installation folder.

Get the last insert id with doctrine 2?

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

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

Count number of files within a directory in Linux?

this is one:

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

Note:

ls -1 | wc -l

Which means: ls: list files in dir

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

|: pipe output onto...

wc: "wordcount"

-l: count lines.

C++ printing boolean, what is displayed?

The standard streams have a boolalpha flag that determines what gets displayed -- when it's false, they'll display as 0 and 1. When it's true, they'll display as false and true.

There's also an std::boolalpha manipulator to set the flag, so this:

#include <iostream>
#include <iomanip>

int main() {
    std::cout<<false<<"\n";
    std::cout << std::boolalpha;   
    std::cout<<false<<"\n";
    return 0;
}

...produces output like:

0
false

For what it's worth, the actual word produced when boolalpha is set to true is localized--that is, <locale> has a num_put category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true and false as they're represented in that locale. For example,

#include <iostream>
#include <iomanip>
#include <locale>

int main() {
    std::cout.imbue(std::locale("fr"));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux instead of false. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false for every language I've checked.

The names that get used are defined in a numpunct facet though, so if you really want them to print out correctly for particular language, you can create a numpunct facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:

#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>

class my_fr : public std::numpunct< char > {
protected:
    char do_decimal_point() const { return ','; }
    char do_thousands_sep() const { return '.'; }
    std::string do_grouping() const { return "\3"; }
    std::string do_truename() const { return "vrai";  }
    std::string do_falsename() const { return "faux"; }
};

int main() {
    std::cout.imbue(std::locale(std::locale(), new my_fr));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

And the result is (as you'd probably expect):

0
faux

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

You can use 'IF EXISTS' to check if the view exists and drop if it does.

IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
        WHERE TABLE_NAME = 'MyView')
    DROP VIEW MyView
GO

CREATE VIEW MyView
AS 
     ....
GO

How to convert int to string on Arduino?

Use like this:

String myString = String(n);

You can find more examples here.

Can't push to remote branch, cannot be resolved to branch

Maybe your forgot to run git fetch? it's required to fetch data from the remote repo! Try running git fetch remote/branch

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

I suppose it's reasonable to want this behavior in some cases, but I would argue that code not triggering a form submission should (always) be the default behavior. Suppose you want to catch a form's submission with

$("form").submit(function(e){
    e.preventDefault();
});

and then do some validation on the input. If code could trigger submit handlers, you could never include

$("form").submit()

inside this handler because it would result in an infinite loop (the SAME handler would be called, prevent the submission, validate, and resubmit). You need to be able to manually submit a form inside a submit handler without triggering the same handler.

I realize this doesn't ANSWER the question directly, but there are lots of other answers on this page about how this functionality can be hacked, and I felt that this needed to be pointed out (and it's too long for a comment).

Check if string begins with something?

You can use string.match() and a regular expression for this too:

if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes

string.match() will return an array of matching substrings if found, otherwise null.

With android studio no jvm found, JAVA_HOME has been set

Just delete the folder highlighted below. Depending on your Android Studio version, mine is 3.5 and reopen Android studio.

enter image description here

iterate through a map in javascript

Don't use iterators to do this. Maintain your own loop by incrementing a counter in the callback, and recursively calling the operation on the next item.

$.each(myMap, function(_, arr) {
    processArray(arr, 0);
});

function processArray(arr, i) {
    if (i >= arr.length) return;

    setTimeout(function () {
        $('#variant').fadeOut("slow", function () {
            $(this).text(i + "-" + arr[i]).fadeIn("slow");

            // Handle next iteration
            processArray(arr, ++i);
        });
    }, 6000);
}

Though there's a logic error in your code. You're setting the same container to more than one different value at (roughly) the same time. Perhaps you mean for each one to update its own container.

Get pixel color from canvas, on mousemove

Here's a complete, self-contained example. First, use the following HTML:

<canvas id="example" width="200" height="60"></canvas>
<div id="status"></div>

Then put some squares on the canvas with random background colors:

var example = document.getElementById('example');
var context = example.getContext('2d');
context.fillStyle = randomColor();
context.fillRect(0, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(55, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(110, 0, 50, 50);

And print each color on mouseover:

$('#example').mousemove(function(e) {
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;
    var coord = "x=" + x + ", y=" + y;
    var c = this.getContext('2d');
    var p = c.getImageData(x, y, 1, 1).data; 
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    $('#status').html(coord + "<br>" + hex);
});

The code above assumes the presence of jQuery and the following utility functions:

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

function rgbToHex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

function randomInt(max) {
  return Math.floor(Math.random() * max);
}

function randomColor() {
    return `rgb(${randomInt(256)}, ${randomInt(256)}, ${randomInt(256)})`
}

See it in action here:

_x000D_
_x000D_
// set up some sample squares with random colors
var example = document.getElementById('example');
var context = example.getContext('2d');
context.fillStyle = randomColor();
context.fillRect(0, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(55, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(110, 0, 50, 50);

$('#example').mousemove(function(e) {
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;
    var coord = "x=" + x + ", y=" + y;
    var c = this.getContext('2d');
    var p = c.getImageData(x, y, 1, 1).data; 
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    $('#status').html(coord + "<br>" + hex);
});

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

function rgbToHex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

function randomInt(max) {
  return Math.floor(Math.random() * max);
}

function randomColor() {
    return `rgb(${randomInt(256)}, ${randomInt(256)}, ${randomInt(256)})`
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="example" width="200" height="60"></canvas>
<div id="status"></div>

    
_x000D_
_x000D_
_x000D_

Is it possible to hide the cursor in a webpage using CSS or Javascript?

If you want to hide the cursor in the entire webpage, using body will not work unless it covers the entire visible page, which is not always the case. To make sure the cursor is hidden everywhere in the page, use:

document.documentElement.style.cursor = 'none';

To reenable it:

document.documentElement.style.cursor = 'auto';

The analogue with static CSS notation is in the answer by Pavel Salaquarda (in essence: html * {cursor:none})

How to deserialize a JObject to .NET object

According to this post, it's much better now:

// pick out one album
JObject jalbum = albums[0] as JObject;

// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();

Documentation: Convert JSON to a Type

find first sequence item that matches a criterion

a=[100,200,300,400,500]
def search(b):
 try:
  k=a.index(b)
  return a[k] 
 except ValueError:
    return 'not found'
print(search(500))

it'll return the object if found else it'll return "not found"

File to byte[] in Java

Guava has Files.toByteArray() to offer you. It has several advantages:

  1. It covers the corner case where files report a length of 0 but still have content
  2. It's highly optimized, you get a OutOfMemoryException if trying to read in a big file before even trying to load the file. (Through clever use of file.length())
  3. You don't have to reinvent the wheel.

Defined Edges With CSS3 Filter Blur

The simplest way is just adding a transparent border to the div that contains the image and setting its display property to inline-block just like this:

CSS:

div{
margin: 2rem;
height: 100vh;
overflow: hidden;
display: inline-block;
border: 1px solid #00000000;
}

img {
-webkit-filter: blur(2rem);
filter: blur(2rem);
}

HTML

<div><img src='https://images.unsplash.com/photo-1557853197-aefb550b6fdc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=375&q=80' /></div>

Here's a codepen depicting the same: https://codepen.io/arnavozil/pen/ExPYKNZ

How to create a directive with a dynamic template in AngularJS?

i've used the $templateCache to accomplish something similar. i put several ng-templates in a single html file, which i reference using the directive's templateUrl. that ensures the html is available to the template cache. then i can simply select by id to get the ng-template i want.

template.html:

<script type="text/ng-template" id=“foo”>
foo
</script>

<script type="text/ng-template" id=“bar”>
bar
</script>

directive:

myapp.directive(‘foobardirective’, ['$compile', '$templateCache', function ($compile, $templateCache) {

    var getTemplate = function(data) {
        // use data to determine which template to use
        var templateid = 'foo';
        var template = $templateCache.get(templateid);
        return template;
    }

    return {
        templateUrl: 'views/partials/template.html',
        scope: {data: '='},
        restrict: 'E',
        link: function(scope, element) {
            var template = getTemplate(scope.data);

            element.html(template);
            $compile(element.contents())(scope);
        }
    };
}]);

How to pass a view's onClick event to its parent on Android?

Sometime only this helps:

View child = parent.findViewById(R.id.btnMoreText);
    child.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            View parent = (View) v.getParent();
            parent.performClick();
        }
    });

Another variant, works not always:

child.setOnClickListener(null);

How get data from material-ui TextField, DropDownMenu components?

Faced to this issue after a long time since question asked here. when checking material-ui code I found it's now accessible through inputRef property.

...
<CssTextField
  inputRef={(c) => {this.myRefs.username = c}}
  label="Username"
  placeholder="xxxxxxx"
  margin="normal"
  className={classes.textField}
  variant="outlined"
  fullWidth
/>
...

Then Access value like this.

  onSaveUser = () => {
    console.log('Saving user');
    console.log(this.myRefs.username.value);
  }

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

Failed loading english.pickle with nltk.data.load

From bash command line, run:

$ python -c "import nltk; nltk.download('punkt')"

In PowerShell, how do I test whether or not a specific variable exists in global scope?

Test the existence of variavle MyVariable. Returns boolean true or false.

Test-Path variable:\MyVariable

Automatic exit from Bash shell script on error

Use the set -e builtin:

#!/bin/bash
set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately

Alternatively, you can pass -e on the command line:

bash -e my_script.sh

You can also disable this behavior with set +e.

You may also want to employ all or some of the the -e -u -x and -o pipefail options like so:

set -euxo pipefail

-e exits on error, -u errors on undefined variables, and -o (for option) pipefail exits on command pipe failures. Some gotchas and workarounds are documented well here.

(*) Note:

The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !

(from man bash)

Is it possible to clone html element objects in JavaScript / JQuery?

You can use clone() method to create a copy..

$('#foo1').html( $('#foo2 > div').clone())?;

FIDDLE HERE

Gradient borders

Here's a nice semi cross-browser way to have gradient borders that fade out half way down. Simply by setting the color-stop to rgba(0, 0, 0, 0)

.fade-out-borders {
min-height: 200px; /* for example */

-webkit-border-image: -webkit-gradient(linear, 0 0, 0 50%, from(black), to(rgba(0, 0, 0, 0))) 1 100%;
-webkit-border-image: -webkit-linear-gradient(black, rgba(0, 0, 0, 0) 50%) 1 100%;
-moz-border-image: -moz-linear-gradient(black, rgba(0, 0, 0, 0) 50%) 1 100%;
-o-border-image: -o-linear-gradient(black, rgba(0, 0, 0, 0) 50%) 1 100%;
border-image: linear-gradient(to bottom, black, rgba(0, 0, 0, 0) 50%) 1 100%;
}

<div class="fade-out-border"></div>

Usage explained:

Formal grammar: linear-gradient(  [ <angle> | to <side-or-corner> ,]? <color-stop> [, <color-stop>]+ )
                              \---------------------------------/ \----------------------------/
                                Definition of the gradient line         List of color stops  

More here: https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient

Laravel: Auth::user()->id trying to get a property of a non-object

you must check is user loggined ?

Auth::check() ? Auth::user()->id : null

Change date format in a Java string

Other answers are correct, basically you had the wrong number of "y" characters in your pattern.

Time Zone

One more problem though… You did not address time zones. If you intended UTC, then you should have said so. If not, the answers are not complete. If all you want is the date portion without the time, then no issue. But if you do further work that may involve time, then you should be specifying a time zone.

Joda-Time

Here is the same kind of code but using the third-party open-source Joda-Time 2.3 library

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

String date_s = "2011-01-18 00:00:00.0";

org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss.SSS" );
// By the way, if your date-time string conformed strictly to ISO 8601 including a 'T' rather than a SPACE ' ', you could
// use a formatter built into Joda-Time rather than specify your own: ISODateTimeFormat.dateHourMinuteSecondFraction().
// Like this:
//org.joda.time.DateTime dateTimeInUTC = org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecondFraction().withZoneUTC().parseDateTime( date_s );

// Assuming the date-time string was meant to be in UTC (no time zone offset).
org.joda.time.DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( date_s );
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "dateTimeInUTC (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInUTC ) );
System.out.println( "" ); // blank line.

// Assuming the date-time string was meant to be in Kolkata time zone (formerly known as Calcutta). Offset is +5:30 from UTC (note the half-hour).
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
org.joda.time.DateTime dateTimeInKolkata = formatter.withZone( kolkataTimeZone ).parseDateTime( date_s );
System.out.println( "dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println( "dateTimeInKolkata (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInKolkata ) );
// This date-time in Kolkata is a different point in the time line of the Universe than the dateTimeInUTC instance created above. The date is even different.
System.out.println( "dateTimeInKolkata adjusted to UTC: " + dateTimeInKolkata.toDateTime( org.joda.time.DateTimeZone.UTC ) );

When run…

dateTimeInUTC: 2011-01-18T00:00:00.000Z
dateTimeInUTC (date only): 2011-01-18

dateTimeInKolkata: 2011-01-18T00:00:00.000+05:30
dateTimeInKolkata (date only): 2011-01-18
dateTimeInKolkata adjusted to UTC: 2011-01-17T18:30:00.000Z

How to create a horizontal loading progress bar?

It is Widget.ProgressBar.Horizontal on my phone, if I set android:indeterminate="true"

Get div's offsetTop positions in React

A better solution with ref to avoid findDOMNode that is discouraged.

...
onScroll() {
    let offsetTop  = this.instance.getBoundingClientRect().top;
}
...
render() {
...
<Component ref={(el) => this.instance = el } />
...

How can I upload fresh code at github?

Just to add on to the other answers, before i knew my way around git, i was looking for some way to upload existing code to a new github (or other git) repo. Here's the brief that would save time for newbs:-

Assuming you have your NEW empty github or other git repo ready:-

cd "/your/repo/dir"
git clone https://github.com/user_AKA_you/repoName # (creates /your/repo/dir/repoName)
cp "/all/your/existing/code/*" "/your/repo/dir/repoName/"
git add -A
git commit -m "initial commit"
git push origin master

Alternatively if you have an existing local git repo

cd "/your/repo/dir/repoName"
#add your remote github or other git repo
git remote set-url origin https://github.com/user_AKA_you/your_repoName
git commit -m "new origin commit"
git push origin master

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

Code for best fit straight line of a scatter plot in python

Assuming line of best fit for a set of points is:

y = a + b * x
where:
b = ( sum(xi * yi) - n * xbar * ybar ) / sum((xi - xbar)^2)
a = ybar - b * xbar

Code and plot

# sample points 
X = [0, 5, 10, 15, 20]
Y = [0, 7, 10, 13, 20]

# solve for a and b
def best_fit(X, Y):

    xbar = sum(X)/len(X)
    ybar = sum(Y)/len(Y)
    n = len(X) # or len(Y)

    numer = sum([xi*yi for xi,yi in zip(X, Y)]) - n * xbar * ybar
    denum = sum([xi**2 for xi in X]) - n * xbar**2

    b = numer / denum
    a = ybar - b * xbar

    print('best fit line:\ny = {:.2f} + {:.2f}x'.format(a, b))

    return a, b

# solution
a, b = best_fit(X, Y)
#best fit line:
#y = 0.80 + 0.92x

# plot points and fit line
import matplotlib.pyplot as plt
plt.scatter(X, Y)
yfit = [a + b * xi for xi in X]
plt.plot(X, yfit)

enter image description here

UPDATE:

notebook version

CSS to hide INPUT BUTTON value text

Instead, just do a hook_form_alter and make the button an image button and you are done!

SimpleXml to string

You can use ->child to get a child element named child.

This element will contain the text of the child element.

But if you try var_dump() on that variable, you will see it is not actually a PHP string.

The easiest way around this is to perform a strval(xml->child); That will convert it to an actual PHP string.

This is useful when debugging when looping your XML and using var_dump() to check the result.

So $s = strval($xml->child);.

PostgreSQL Exception Handling

Use the DO statement, a new option in version 9.0:

DO LANGUAGE plpgsql
$$
BEGIN
CREATE TABLE "Logs"."Events"
    (
        EventId BIGSERIAL NOT NULL PRIMARY KEY,
        PrimaryKeyId bigint NOT NULL,
        EventDateTime date NOT NULL DEFAULT(now()),
        Action varchar(12) NOT NULL,
        UserId integer NOT NULL REFERENCES "Office"."Users"(UserId),
        PrincipalUserId varchar(50) NOT NULL DEFAULT(user)
    );

    CREATE TABLE "Logs"."EventDetails"
    (
        EventDetailId BIGSERIAL NOT NULL PRIMARY KEY,
        EventId bigint NOT NULL REFERENCES "Logs"."Events"(EventId),
        Resource varchar(64) NOT NULL,
        OldVal varchar(4000) NOT NULL,
        NewVal varchar(4000) NOT NULL
    );

    RAISE NOTICE 'Task completed sucessfully.';    
END;
$$;

Is mathematics necessary for programming?

Certian kinds of math I think are indispensible. For instance, every software engineer should know and understand De Morgan's laws, and O notation.

Other kinds are just very useful. In simulation we often have to do a lot of physics modeling. If you are doing graphics work, you will often find yourself needing to write coordinate transformation algorithms. I've had many other situations in my 20 year career where I needed to write up and solve simultanious linear equations to figure out what constants to put into an algorithm.

Web.Config Debug/Release

To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).

Then I register a pre- or post-build event in Visual Studio...

$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"

For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).

Terminating a Java Program

  • Well, first System.exit(0) is used to terminate the program and having statements below it is not correct, although the compiler does not throw any errors.
  • a plain return; is used in a method of void return type to return the control of execution to its parent method.

How do I make a LinearLayout scrollable?

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center|left"
        android:orientation="vertical">

        Your views go here...

    </LinearLayout>

</ScrollView>

Checking if an input field is required using jQuery

The required property is boolean:

$('form#register').find('input').each(function(){
    if(!$(this).prop('required')){
        console.log("NR");
    } else {
        console.log("IR");
    }
});

Reference: HTMLInputElement

What's the difference between Visual Studio Community and other, paid versions?

Check the following: https://www.visualstudio.com/vs/compare/ Visual studio community is free version for students and other academics, individual developers, open-source projects, and small non-enterprise teams (see "Usage" section at bottom of linked page). While VSUltimate is for companies. You also get more things with paid versions!

VBA for clear value in specific range of cell and protected cell from being wash away formula

You could define a macro containing the following code:

Sub DeleteA5X50()   
    Range("A5:X50").Select
    Selection.ClearContents
end sub

Running the macro would select the range A5:x50 on the active worksheet and clear all the contents of the cells within that range.

To leave your formulas intact use the following instead:

Sub DeleteA5X50()   
    Range("A5:X50").Select
    Selection.SpecialCells(xlCellTypeConstants, 23).Select
    Selection.ClearContents
end sub

This will first select the overall range of cells you are interested in clearing the contents from and will then further limit the selection to only include cells which contain what excel considers to be 'Constants.'

You can do this manually in excel by selecting the range of cells, hitting 'f5' to bring up the 'Go To' dialog box and then clicking on the 'Special' button and choosing the 'Constants' option and clicking 'Ok'.

How to represent a DateTime in Excel

You can do the following:

=Datevalue(text)+timevalue(text) .

Go into different types of date formats and choose:

dd-mm-yyyy mm:ss am/pm .

Javascript array value is undefined ... how do I test for that

There are more (many) ways to Rome:

//=>considering predQuery[preId] is undefined:
predQuery[preId] === undefined; //=> true
undefined === predQuery[preId] //=> true
predQuery[preId] || 'it\'s unbelievable!' //=> it's unbelievable
var isdef = predQuery[preId] ? predQuery[preId] : null //=> isdef = null

cheers!

How do I calculate percentiles with python/numpy?

check for scipy.stats module:

 scipy.stats.scoreatpercentile

Python Script Uploading files via FTP

Use ftplib, you can write it like this:

import ftplib
session = ftplib.FTP('server.address.com','USERNAME','PASSWORD')
file = open('kitten.jpg','rb')                  # file to send
session.storbinary('STOR kitten.jpg', file)     # send the file
file.close()                                    # close file and FTP
session.quit()

Use ftplib.FTP_TLS instead if you FTP host requires TLS.


To retrieve it, you can use urllib.retrieve:

import urllib 

urllib.urlretrieve('ftp://server/path/to/file', 'file')

EDIT:

To find out the current directory, use FTP.pwd():

FTP.pwd(): Return the pathname of the current directory on the server.

To change the directory, use FTP.cwd(pathname):

FTP.cwd(pathname): Set the current directory on the server.

jquery smooth scroll to an anchor?

I would use the simple code snippet from CSS-Tricks.com:

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

Source: http://css-tricks.com/snippets/jquery/smooth-scrolling/

Finding blocking/locking queries in MS SQL (mssql)

Use the script: sp_blocker_pss08 or SQL Trace/Profiler and the Blocked Process Report event class.

Java Array Sort descending?

I know that this is a quite old thread, but here is an updated version for Integers and Java 8:

Arrays.sort(array, (o1, o2) -> o2 - o1);

Note that it is "o1 - o2" for the normal ascending order (or Comparator.comparingInt()).

This also works for any other kinds of Objects. Say:

Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());

Getting a "This application is modifying the autolayout engine from a background thread" error?

For me the issue was the following. Make sure performSegueWithIdentifier: is performed on the main thread:

dispatch_async (dispatch_get_main_queue(), ^{
  [self performSegueWithIdentifier:@"ViewController" sender:nil];
});

How to use LDFLAGS in makefile

Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:

CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm

.PHONY: all
all: client

.PHONY: clean
clean:
    $(RM) *~ *.o client

OBJECTS=client.o
client: $(OBJECTS)
    $(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)

In the line defining the client target change the order of $(LDFLAGS) as needed.

How to stop event bubbling on checkbox click

Credit to @mehras for the code. I just created a snippet to demonstrate it because I thought that would be appreciated and I wanted an excuse to try that feature.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#container').addClass('hidden');_x000D_
  $('#header').click(function() {_x000D_
    if ($('#container').hasClass('hidden')) {_x000D_
      $('#container').removeClass('hidden');_x000D_
    } else {_x000D_
      $('#container').addClass('hidden');_x000D_
    }_x000D_
  });_x000D_
  $('#header input[type=checkbox]').click(function(event) {_x000D_
    if (event.stopPropagation) { // standard_x000D_
      event.stopPropagation();_x000D_
    } else { // IE6-8_x000D_
      event.cancelBubble = true;_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
div {_x000D_
  text-align: center;_x000D_
  padding: 2em;_x000D_
  font-size: 1.2em_x000D_
}_x000D_
_x000D_
.hidden {_x000D_
  display: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="header"><input type="checkbox" />Checkbox won't bubble the event, but this text will.</div>_x000D_
<div id="container">click() bubbled up!</div>
_x000D_
_x000D_
_x000D_

difference between width auto and width 100 percent

It's about margins and border. If you use width: auto, then add border, your div won't become bigger than its container. On the other hand, if you use width: 100% and some border, the element's width will be 100% + border or margin. For more info see this.

How do I rename the android package name?

  1. Goto your AndroidManifest.xml.
  2. place your cursor in the package name like shown below don't select it just place it.

Just place your cursor on it

  1. Then press shift+F6 you will get a popup window as shown below select Rename package.

enter image description here

  1. Enter your new name and select Refactor. (Note since my cursor is on "something" only something is renamed.)

That's it done.

Converting Columns into rows with their respective data in sql server

declare @T table (ScripName varchar(50), ScripCode varchar(50), Price int)
insert into @T values ('20 MICRONS', '533022', 39)

select 
  'ScripName' as ColName,
  ScripName as ColValue
from @T
union all
select 
  'ScripCode' as ColName,
  ScripCode as ColValue
from @T
union all
select 
  'Price' as ColName,
  cast(Price as varchar(50)) as ColValue
from @T

The project type is not supported by this installation

You might need to install the "Microsoft Web Platform Installer" from http://www.microsoft.com/web/downloads/platform.aspx

CSS / HTML Navigation and Logo on same line

1) you can float the image to the left:

<img style="float:left" src="http://i.imgur.com/hCrQkJi.png">

2)You can use an HTML table to place elements on one line.

Code below

  <div class="navigation-bar">
    <div id="navigation-container">
      <table>
        <tr>
          <td><img src="http://i.imgur.com/hCrQkJi.png"></td>
          <td><ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Projects</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">Get in Touch</a></li>
        </ul>
          </td></tr></table>
    </div>

installing urllib in Python3.6

The corrected code is

import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand: 
    words = line.decode().split() 
for word in words: 
    counts[word] = counts.get(word, 0) + 1 
print(counts) 

running the code above produces

{'Who': 1, 'is': 1, 'already': 1, 'sick': 1, 'and': 1, 'pale': 1, 'with': 1, 'grief': 1}

What is log4j's default log file dumping path

You have copy this sample code from Here,right?
now, as you can see there property file they have define, have you done same thing? if not then add below code in your project with property file for log4j

So the content of log4j.properties file would be as follows:

# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

make changes as per your requirement like log path

What is Type-safe?

Try this explanation on...

TypeSafe means that variables are statically checked for appropriate assignment at compile time. For example, consder a string or an integer. These two different data types cannot be cross-assigned (ie, you can't assign an integer to a string nor can you assign a string to an integer).

For non-typesafe behavior, consider this:

object x = 89;
int y;

if you attempt to do this:

y = x;

the compiler throws an error that says it can't convert a System.Object to an Integer. You need to do that explicitly. One way would be:

y = Convert.ToInt32( x );

The assignment above is not typesafe. A typesafe assignement is where the types can directly be assigned to each other.

Non typesafe collections abound in ASP.NET (eg, the application, session, and viewstate collections). The good news about these collections is that (minimizing multiple server state management considerations) you can put pretty much any data type in any of the three collections. The bad news: because these collections aren't typesafe, you'll need to cast the values appropriately when you fetch them back out.

For example:

Session[ "x" ] = 34;

works fine. But to assign the integer value back, you'll need to:

int i = Convert.ToInt32( Session[ "x" ] );

Read about generics for ways that facility helps you easily implement typesafe collections.

C# is a typesafe language but watch for articles about C# 4.0; interesting dynamic possibilities loom (is it a good thing that C# is essentially getting Option Strict: Off... we'll see).

Collection was modified; enumeration operation may not execute

When a subscriber unsubscribes you are changing contents of the collection of Subscribers during enumeration.

There are several ways to fix this, one being changing the for loop to use an explicit .ToList():

public void NotifySubscribers(DataRecord sr)  
{
    foreach(Subscriber s in subscribers.Values.ToList())
    {
                                              ^^^^^^^^^  
        ...

Why is my Button text forced to ALL CAPS on Lollipop?

This is fixable in the application code by setting the button's TransformationMethod, e.g.

mButton.setTransformationMethod(null);

Is there any good dynamic SQL builder library in Java?

You can use the following library:

https://github.com/pnowy/NativeCriteria

The library is built on the top of the Hibernate "create sql query" so it supports all databases supported by Hibernate (the Hibernate session and JPA providers are supported). The builder patter is available and so on (object mappers, result mappers).

You can find the examples on github page, the library is available at Maven central of course.

NativeCriteria c = new NativeCriteria(new HibernateQueryProvider(hibernateSession), "table_name", "alias");
c.addJoin(NativeExps.innerJoin("table_name_to_join", "alias2", "alias.left_column", "alias2.right_column"));
c.setProjection(NativeExps.projection().addProjection(Lists.newArrayList("alias.table_column","alias2.table_column")));

Reverse each individual word of "Hello World" string with Java

if its to reverse each letter than this for loop works nicely:

for(int i = 0; i < input.length(); i++){
    output = output + input.substring((input.length()-i)-1, input.length()-i);
}

Set the selected index of a Dropdown using jQuery

Just found this, it works for me and I personally find it easier to read.

This will set the actual index just like gnarf's answer number 3 option.

// sets selected index of a select box the actual index of 0 
$("select#elem").attr('selectedIndex', 0);

This didn't used to work but does now... see bug: http://dev.jquery.com/ticket/1474

Addendum

As recommended in the comments use :

$("select#elem").prop('selectedIndex', 0);

How can I avoid running ActiveRecord callbacks?

None of these points to without_callbacks plugin that just does what you need ...

class MyModel < ActiveRecord::Base
  before_save :do_something_before_save

  def after_save
    raise RuntimeError, "after_save called"
  end

  def do_something_before_save
    raise RuntimeError, "do_something_before_save called"
  end
end

o = MyModel.new
MyModel.without_callbacks(:before_save, :after_save) do
  o.save # no exceptions raised
end

http://github.com/cjbottaro/without_callbacks works with Rails 2.x

How do I copy a string to the clipboard?

For some reason I've never been able to get the Tk solution to work for me. kapace's solution is much more workable, but the formatting is contrary to my style and it doesn't work with Unicode. Here's a modified version.

import ctypes

OpenClipboard = ctypes.windll.user32.OpenClipboard
EmptyClipboard = ctypes.windll.user32.EmptyClipboard
GetClipboardData = ctypes.windll.user32.GetClipboardData
SetClipboardData = ctypes.windll.user32.SetClipboardData
CloseClipboard = ctypes.windll.user32.CloseClipboard
CF_UNICODETEXT = 13

GlobalAlloc = ctypes.windll.kernel32.GlobalAlloc
GlobalLock = ctypes.windll.kernel32.GlobalLock
GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock
GlobalSize = ctypes.windll.kernel32.GlobalSize
GMEM_MOVEABLE = 0x0002
GMEM_ZEROINIT = 0x0040

unicode_type = type(u'')

def get():
    text = None
    OpenClipboard(None)
    handle = GetClipboardData(CF_UNICODETEXT)
    pcontents = GlobalLock(handle)
    size = GlobalSize(handle)
    if pcontents and size:
        raw_data = ctypes.create_string_buffer(size)
        ctypes.memmove(raw_data, pcontents, size)
        text = raw_data.raw.decode('utf-16le').rstrip(u'\0')
    GlobalUnlock(handle)
    CloseClipboard()
    return text

def put(s):
    if not isinstance(s, unicode_type):
        s = s.decode('mbcs')
    data = s.encode('utf-16le')
    OpenClipboard(None)
    EmptyClipboard()
    handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, len(data) + 2)
    pcontents = GlobalLock(handle)
    ctypes.memmove(pcontents, data, len(data))
    GlobalUnlock(handle)
    SetClipboardData(CF_UNICODETEXT, handle)
    CloseClipboard()

paste = get
copy = put

The above has changed since this answer was first created, to better cope with extended Unicode characters and Python 3. It has been tested in both Python 2.7 and 3.5, and works even with emoji such as \U0001f601 ().

Convert Decimal to Varchar

Here's one way:

create table #work
(
  something decimal(8,3) not null 
)

insert #work values ( 0 )
insert #work values ( 12345.6789 )
insert #work values ( 3.1415926 )
insert #work values ( 45 )
insert #work values ( 9876.123456 )
insert #work values ( -12.5678 )

select convert(varchar,convert(decimal(8,2),something))
from #work

if you want it right-aligned, something like this should do you:

select str(something,8,2) from #work

There has been an error processing your request, Error log record number

Go to magento/var/report and open the file with the Error log record number name i.e 673618173351 in your case. In that file you can find the complete description of the error.

For log files like system.log and exception.log, go to magento/var/log/.

Twitter Bootstrap tabs not working: when I click on them nothing happens

I tried the codes from bootstrap's document as follows:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>tab demo</title>
  <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
<div class="span9">
    <div class="tabbable"> <!-- Only required for left/right tabs -->
      <ul class="nav nav-tabs">
        <li class="active"><a href="#tab1" data-toggle="tab">Section 1</a></li>
        <li><a href="#tab2" data-toggle="tab">Section 2</a></li>
      </ul>
      <div class="tab-content">
        <div class="tab-pane active" id="tab1">
          <p>I'm in Section 1.</p>
        </div>
        <div class="tab-pane" id="tab2">
          <p>Howdy, I'm in Section 2.</p>
        </div>
      </div>
    </div>
</div> 
<script src="jquery.min.js"></script>
<script src="bootstrap.js"></script>
</body>
</html>

and it works. But when I switch these two <script src...>'s postion, it do not work. So please remember to load your jquery script before bootstrap.js.

How to set a CMake option() at command line

An additional option is to go to your build folder and use the command ccmake .

This is like the GUI but terminal based. This obviously won't help with an installation script but at least it can be run without a UI.

The one warning I have is it won't let you generate sometimes when you have warnings. if that is the case, exit the interface and call cmake .

Onclick event to remove default value in a text input field

As stated before I even saw this question placeholder is the answer. HTML5 for the win! But for those poor unfortunate souls that cannot rely on that functionality take a look at the jquery plugin as an augmentation as well. HTML5 Placeholder jQuery Plugin

<input name="Name" placeholder="Enter Your Name">

Setting max width for body using Bootstrap

I don't know if this was pointed out here. The settings for .container width have to be set on the Bootstrap website. I personally did not have to edit or touch anything within CSS files to tune my .container size which is 1600px. Under Customize tab, there are three sections responsible for media and the responsiveness of the web:

  • Media queries breakpoints
  • Grid system
  • Container sizes

Besides Media queries breakpoints, which I believe most people refer to, I've also changed @container-desktop to (1130px + @grid-gutter-width) and @container-large-desktop to (1530px + @grid-gutter-width). Now, the .container changes its width if my browser is scaled up to ~1600px and ~1200px. Hope it can help.

How to delete all instances of a character in a string in python?

# s1 == source string
# char == find this character
# repl == replace with this character
def findreplace(s1, char, repl):
    s1 = s1.replace(char, repl)
    return s1

# find each 'i' in the string and replace with a 'u'
print findreplace('it is icy', 'i', 'u')
# output
''' ut us ucy '''

Read data from a text file using Java

Simple code for reading file in JAVA:

import java.io.*;

class ReadData
{
    public static void main(String args[])
    {
        FileReader fr = new FileReader(new File("<put your file path here>"));
        while(true)
        {
            int n=fr.read();
            if(n>-1)
            {
                char ch=(char)fr.read();
                System.out.print(ch);
            }
        }
    }
}

What is the current directory in a batch file?

Just my 2 cents. The following command fails if called from batch file (Windows 7) placed on pendrive:

xcopy /s /e /i %cd%Ala C:\KS\Ala

But this does the job:

xcopy /s /e /i %~dp0Ala C:\KS\Ala

Python script to do something at the same time every day

You can do that like this:

from datetime import datetime
from threading import Timer

x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x

secs=delta_t.seconds+1

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()

This will execute a function (eg. hello_world) in the next day at 1a.m.

EDIT:

As suggested by @PaulMag, more generally, in order to detect if the day of the month must be reset due to the reaching of the end of the month, the definition of y in this context shall be the following:

y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)

With this fix, it is also needed to add timedelta to the imports. The other code lines maintain the same. The full solution, using also the total_seconds() function, is therefore:

from datetime import datetime, timedelta
from threading import Timer

x=datetime.today()
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
delta_t=y-x

secs=delta_t.total_seconds()

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()

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

In IntelliJ, the default maven compiler version is less than version 5, which is not supported, so we have to manually change the version of the maven compiler.

We have two ways to define version.

First way:

<properties>
  <maven.compiler.target>1.8</maven.compiler.target>
  <maven.compiler.source>1.8</maven.compiler.source>
</properties>

Second way:

<build>
  <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
            <source>8</source>
            <target>8</target>
        </configuration>
    </plugin>
  </plugins>
</build>

Remove duplicated rows using dplyr

For completeness’ sake, the following also works:

df %>% group_by(x) %>% filter (! duplicated(y))

However, I prefer the solution using distinct, and I suspect it’s faster, too.

How to find index of all occurrences of element in array?

Another approach using Array.prototype.map() and Array.prototype.filter():

var indices = array.map((e, i) => e === value ? i : '').filter(String)

How to get a resource id with a known resource name?

Kotlin Version via Extension Function

To find a resource id by its name In Kotlin, add below snippet in a kotlin file:

ExtensionFunctions.kt

import android.content.Context
import android.content.res.Resources

fun Context.resIdByName(resIdName: String?, resType: String): Int {
    resIdName?.let {
        return resources.getIdentifier(it, resType, packageName)
    }
    throw Resources.NotFoundException()
}


Usage

Now all resource ids are accessible wherever you have a context reference using resIdByName method:

val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.    

Maven: how to override the dependency added by a library

What you put inside the </dependencies> tag of the root pom will be included by all child modules of the root pom. If all your modules use that dependency, this is the way to go.

However, if only 3 out of 10 of your child modules use some dependency, you do not want this dependency to be included in all your child modules. In that case, you can just put the dependency inside the </dependencyManagement>. This will make sure that any child module that needs the dependency must declare it in their own pom file, but they will use the same version of that dependency as specified in your </dependencyManagement> tag.

You can also use the </dependencyManagement> to modify the version used in transitive dependencies, because the version declared in the upper most pom file is the one that will be used. This can be useful if your project A includes an external project B v1.0 that includes another external project C v1.0. Sometimes it happens that a security breach is found in project C v1.0 which is corrected in v1.1, but the developers of B are slow to update their project to use v1.1 of C. In that case, you can simply declare a dependency on C v1.1 in your project's root pom inside `, and everything will be good (assuming that B v1.0 will still be able to compile with C v1.1).

How do I disable "missing docstring" warnings at a file-level in Pylint?

I found this here.

You can add "--errors-only" flag for Pylint to disable warnings.

To do this, go to settings. Edit the following line:

"python.linting.pylintArgs": []

As

"python.linting.pylintArgs": ["--errors-only"]

And you are good to go!

How to count lines in a document?

I know this is old but still: Count filtered lines

My file looks like:

Number of files sent
Company 1 file: foo.pdf OK
Company 1 file: foo.csv OK
Company 1 file: foo.msg OK
Company 2 file: foo.pdf OK
Company 2 file: foo.csv OK
Company 2 file: foo.msg Error
Company 3 file: foo.pdf OK
Company 3 file: foo.csv OK
Company 3 file: foo.msg Error
Company 4 file: foo.pdf OK
Company 4 file: foo.csv OK
Company 4 file: foo.msg Error

If I want to know how many files are sent OK:

grep "OK" <filename> | wc -l

OR

grep -c "OK" filename

How do I check if a string contains another string in Swift?

Here you go! Ready for Xcode 8 and Swift 3.

import UIKit

let mString = "This is a String that contains something to search."
let stringToSearchUpperCase = "String"
let stringToSearchLowerCase = "string"

mString.contains(stringToSearchUpperCase) //true
mString.contains(stringToSearchLowerCase) //false
mString.lowercased().contains(stringToSearchUpperCase) //false
mString.lowercased().contains(stringToSearchLowerCase) //true

Have a variable in images path in Sass?

Adding something to the above correct answers. I am using netbeans IDE and it shows error while using url(#{$assetPath}/site/background.jpg) this method. It was just netbeans error and no error in sass compiling. But this error break code formatting in netbeans and code become ugly. But when I use it inside quotes like below, it show wonder!

url("#{$assetPath}/site/background.jpg")

How can I control the speed that bootstrap carousel slides in items?

Just write data-interval in the div containing the carousel:

<div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="500">

Example taken from w3schools.

How to convert numpy arrays to standard TensorFlow format?

You can use tf.convert_to_tensor():

import tensorflow as tf
import numpy as np

data = [[1,2,3],[4,5,6]]
data_np = np.asarray(data, np.float32)

data_tf = tf.convert_to_tensor(data_np, np.float32)

sess = tf.InteractiveSession()  
print(data_tf.eval())

sess.close()

Here's a link to the documentation for this method:

https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor

Reading CSV file and storing values into an array

I am just student working on my master's thesis, but this is the way I solved it and it worked well for me. First you select your file from directory (only in csv format) and then you put the data into the lists.

List<float> t = new List<float>();
List<float> SensorI = new List<float>();
List<float> SensorII = new List<float>();
List<float> SensorIII = new List<float>();
using (OpenFileDialog dialog = new OpenFileDialog())
{
    try
    {
        dialog.Filter = "csv files (*.csv)|*.csv";
        dialog.Multiselect = false;
        dialog.InitialDirectory = ".";
        dialog.Title = "Select file (only in csv format)";
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            var fs = File.ReadAllLines(dialog.FileName).Select(a => a.Split(';'));
            int counter = 0;
            foreach (var line in fs)
            {
                counter++;
                if (counter > 2)    // Skip first two headder lines
                {
                    this.t.Add(float.Parse(line[0]));
                    this.SensorI.Add(float.Parse(line[1]));
                    this.SensorII.Add(float.Parse(line[2]));
                    this.SensorIII.Add(float.Parse(line[3]));
                }
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(
            "Error while opening the file.\n" + exc.Message, 
            this.Text, 
            MessageBoxButtons.OK, 
            MessageBoxIcon.Error
        );
    }
}

Converting java date to Sql timestamp

The problem is with the way you are printing the Time data

java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
System.out.println(sa); //this will print the milliseconds as the toString() has been written in that format

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(timestamp)); //this will print without ms

How do I import other TypeScript files?

Quick Easy Process in Visual Studio

Drag and Drop the file with .ts extension from solution window to editor, it will generate inline reference code like..

/// <reference path="../../components/someclass.ts"/>

C# : assign data to properties via constructor vs. instantiating

Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:

public class Album 
{
    // Note that we make the setter 'private'
    public string Name { get; private set; }
    public string Artist { get; private set; }
    public int Year { get; private set; }

    public Album(string name, string artist, int year)
    {
        this.Name = name;
        this.Artist = artist;
        this.Year = year;
    }
}

If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:

new { 
    Name = "Some Name",
    Artist = "Some Artist",
    Year = 1994
};

the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const(C++) or final (Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.

That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:

public void Configure(ConfigurationSetup setup);

and I have a class that has a number of members such as:

class ConfigurationSetup {
    public String Name { get; set; }
    public String Location { get; set; }
    public Int32 Size { get; set; }
    public DateTime Time { get; set; }

    // ... and some other configuration stuff... 
}

Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name and Location, I can just do:

ConfigurationSetup setup = new ConfigurationSetup {
    Name = "Some Name",
    Location = "San Jose"
};

and this allows me to set up some combination without having to define a new constructor for every possibly permutation.

On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.

Convert object string to JSON

There's a much simpler way to accomplish this feat, just hijack the onclick attribute of a dummy element to force a return of your string as a JavaScript object:

var jsonify = (function(div){
  return function(json){
    div.setAttribute('onclick', 'this.__json__ = ' + json);
    div.click();
    return div.__json__;
  }
})(document.createElement('div'));

// Let's say you had a string like '{ one: 1 }' (malformed, a key without quotes)
// jsonify('{ one: 1 }') will output a good ol' JS object ;)

Here's a demo: http://codepen.io/csuwldcat/pen/dfzsu (open your console)

How do you discover model attributes in Rails?

There is a rails plugin called Annotate models, that will generate your model attributes on the top of your model files here is the link:

https://github.com/ctran/annotate_models

to keep the annotation in sync, you can write a task to re-generate annotate models after each deploy.

C# "No suitable method found to override." -- but there is one

Your code as given (after the edit) compiles fine, so something else is wrong that isn't in what you posted.

Some things to check, is everything public? That includes both the class and the method.

Overload with different parameters?

Are you sure that Base is the class you think it is? I.e. is there another class by the same name that it's actually referencing?

Edit:

To answer the question in your comment, you can't override a method with different parameters, nor is there a need to. You can create a new method (with the new parameter) without the override keyword and it will work just fine.

If your intention is to prohibit calling of the base method without the parameter you can mark the method as protected instead of public. That way it can only be called from classes that inherit from Base

Angular-cli from css to scss

A quick and easy way to perform the migration is to use the schematic NPM package schematics-scss-migrate. this package rename all css to scss file :

ng add schematics-scss-migrate

https://github.com/Teebo/scss-migrate#readme

javascript check for not null

It is possibly because the value of val is actually the string "null" rather than the value null.

How to yum install Node.JS on Amazon Linux

For those who want to have the accepted answer run in Ansible without further searches, I post the task here for convenience and future reference.

Accepted answer recommendation: https://stackoverflow.com/a/35165401/78935

Ansible task equivalent

tasks:
  - name: Setting up the NodeJS yum repository
    shell: curl --silent --location https://rpm.nodesource.com/setup_10.x | bash -
    args:
      warn: no
  # ...

setTimeout / clearTimeout problems

The problem is that the timer variable is local, and its value is lost after each function call.

You need to persist it, you can put it outside the function, or if you don't want to expose the variable as global, you can store it in a closure, e.g.:

var endAndStartTimer = (function () {
  var timer; // variable persisted here
  return function () {
    window.clearTimeout(timer);
    //var millisecBeforeRedirect = 10000; 
    timer = window.setTimeout(function(){alert('Hello!');},10000); 
  };
})();

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

Insted of

drawer.setDrawerListener(toggle);

You can use

drawer.addDrawerListener(toggle);

How to set selected item of Spinner by value, not by position?

Based on Merrill's answer here is how to do with a CursorAdapter

CursorAdapter myAdapter = (CursorAdapter) spinner_listino.getAdapter(); //cast
    for(int i = 0; i < myAdapter.getCount(); i++)
    {
        if (myAdapter.getItemId(i) == ordine.getListino() )
        {
            this.spinner_listino.setSelection(i);
            break;
        }
    }

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Try:

SELECT convert(nvarchar(10), SA.[RequestStartDate], 103) as 'Service Start Date', 
       convert(nvarchar(10), SA.[RequestEndDate], 103) as 'Service End Date', 
FROM
(......)SA
WHERE......

Or:

SELECT format(SA.[RequestStartDate], 'dd/MM/yyyy') as 'Service Start Date', 
       format(SA.[RequestEndDate], 'dd/MM/yyyy') as 'Service End Date', 
FROM
(......)SA
WHERE......

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

A Simply Swift,

Step 1: Create One SubClass of UITableViewCell
Step 2: Add this method to SubClass of UITableViewCell

override func layoutSubviews() {
    super.layoutSubviews()
    self.imageView?.frame = CGRectMake(0, 0, 10, 10)
}

Step 3: Create cell object using that SubClass in cellForRowAtIndexPath,

Ex: let customCell:CustomCell = CustomCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

Step 4: Enjoy

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;

Create two threads, one display odd & other even numbers

Concurrent Package:

    import java.util.concurrent.ExecutorService;

    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    //=========== Task1 class prints odd =====
    class TaskClass1 implements Runnable
    {

    private Condition condition;
    private Lock lock;
    boolean exit = false;
    int i;
    TaskClass1(Condition condition,Lock lock)
    {
        this.condition = condition;
        this.lock = lock;
    }
    @Override
    public void run() {
        try
        {
            lock.lock();
            for(i = 1;i<11;i++)
            {
                if(i%2 == 0)
                {
                    condition.signal();
                    condition.await();

                }
                if(i%2 != 0)
                {
                    System.out.println(Thread.currentThread().getName()+" == "+i);

                }

            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
            lock.unlock();
        }

    }

}
//==== Task2 : prints even =======
class TaskClass2 implements Runnable
{

    private Condition condition;
    private Lock lock;
    boolean exit = false;
    TaskClass2(Condition condition,Lock lock)
    {
        this.condition = condition;
        this.lock = lock;
    }
    @Override
    public void run() {
        int i;
        // TODO Auto-generated method stub
        try
        {
            lock.lock();
            for(i = 2;i<11;i++)

            {

                if(i%2 != 0)
                {
                    condition.signal();
                    condition.await();
                }
                if(i%2 == 0)
                {
                    System.out.println(Thread.currentThread().getName()+" == "+i);

                }

            }

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
            lock.unlock();

        }

    }

}
public class OddEven {

    public static void main(String[] a)
    {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        Future future1;
        Future future2;
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        future1 = executorService.submit(new TaskClass1(condition,lock));
        future2 = executorService.submit(new TaskClass2(condition,lock));
        executorService.shutdown();


    }


}