Programs & Examples On #Keil

Keil IDE and compiler tools for ARM and other embedded microcontrollers. This includes: ARM Development Tools C166 Development Tools C51 Development Tools C251 Development Tools Debug Adapters Evaluation Boards

Casting int to bool in C/C++

There some kind of old school 'Marxismic' way to the cast int -> bool without C4800 warnings of Microsoft's cl compiler - is to use negation of negation.

int  i  = 0;
bool bi = !!i;

int  j  = 1;
bool bj = !!j;

How do I execute code AFTER a form has loaded?

This an old question and depends more upon when you need to start your routines. Since no one wants a null reference exception it is always best to check for null first then use as needed; that alone may save you a lot of grief.

The most common reason for this type of question is when a container or custom control type attempts to access properties initialized outside of a custom class where those properties have not yet been initialized thus potentially causing null values to populate and can even cause a null reference exceptions on object types. It means your class is running before it is fully initialized - before you have finished setting your properties etc. Another possible reason for this type of question is when to perform custom graphics.

To best answer the question about when to start executing code following the form load event is to monitor the WM_Paint message or hook directly in to the paint event itself. Why? The paint event only fires when all modules have fully loaded with respect to your form load event. Note: This.visible == true is not always true when it is set true so it is not used at all for this purpose except to hide a form.

The following is a complete example of how to start executing you code following the form load event. It is recommended that you do not unnecessarily tie up the paint message loop so we'll create an event that will start executing your code outside that loop.

using System.Windows.Forms;

namespace MyProgramStartingPlaceExample {

/// <summary>
/// Main UI form object
/// </summary>
public class Form1 : Form
{

    /// <summary>
    /// Main form load event handler
    /// </summary>
    public Form1()
    {
        // Initialize ONLY. Setup your controls and form parameters here. Custom controls should wait for "FormReady" before starting up too.
        this.Text = "My Program title before form loaded";
        // Size need to see text. lol
        this.Width = 420;

        // Setup the sub or fucntion that will handle your "start up" routine
        this.StartUpEvent += StartUPRoutine;

        // Optional: Custom control simulation startup sequence:
        // Define your class or control in variable. ie. var MyControlClass new CustomControl;
        // Setup your parameters only. ie. CustomControl.size = new size(420, 966); Do not validate during initialization wait until "FormReady" is set to avoid possible null values etc. 
        // Inside your control or class have a property and assign it as bool FormReady - do not validate anything until it is true and you'll be good! 
    }

    /// <summary>
    /// The main entry point for the application which sets security permissions when set.
    /// </summary>
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }


    #region "WM_Paint event hooking with StartUpEvent"            
    //
    // Create a delegate for our "StartUpEvent"
    public delegate void StartUpHandler();
    //
    // Create our event handle "StartUpEvent"
    public event StartUpHandler StartUpEvent;
    //
    // Our FormReady will only be set once just he way we intendded
    // Since it is a global variable we can poll it else where as well to determine if we should begin code execution !!
    bool FormReady;
    //
    // The WM_Paint message handler: Used mostly to paint nice things to controls and screen
    protected override void OnPaint(PaintEventArgs e)
    {
        // Check if Form is ready for our code ?
        if (FormReady == false) // Place a break point here to see the initialized version of the title on the form window
        {
            // We only want this to occur once for our purpose here.
            FormReady = true;
            //
            // Fire the start up event which then will call our "StartUPRoutine" below.
            StartUpEvent();
        }
        //
        // Always call base methods unless overriding the entire fucntion
        base.OnPaint(e);
    }
    #endregion


    #region "Your StartUp event Entry point"
    //
    // Begin executuing your code here to validate properties etc. and to run your program. Enjoy!
    // Entry point is just following the very first WM_Paint message - an ideal starting place following form load
    void StartUPRoutine()
    {
        // Replace the initialized text with the following
        this.Text = "Your Code has executed after the form's load event";
        //
        // Anyway this is the momment when the form is fully loaded and ready to go - you can also use these methods for your classes to synchronize excecution using easy modifications yet here is a good starting point. 
        // Option: Set FormReady to your controls manulaly ie. CustomControl.FormReady = true; or subscribe to the StartUpEvent event inside your class and use that as your entry point for validating and unleashing its code.
        //
        // Many options: The rest is up to you!
    }
    #endregion

}

}

Getting the difference between two sets

If you are using Java 8, you could try something like this:

public Set<Number> difference(final Set<Number> set1, final Set<Number> set2){
    final Set<Number> larger = set1.size() > set2.size() ? set1 : set2;
    final Set<Number> smaller = larger.equals(set1) ? set2 : set1;
    return larger.stream().filter(n -> !smaller.contains(n)).collect(Collectors.toSet());
}

PowerShell Script to Find and Replace for all Files with a Specific Extension

I have written a little helper function to replace text in a file:

function Replace-TextInFile
{
    Param(
        [string]$FilePath,
        [string]$Pattern,
        [string]$Replacement
    )

    [System.IO.File]::WriteAllText(
        $FilePath,
        ([System.IO.File]::ReadAllText($FilePath) -replace $Pattern, $Replacement)
    )
}

Example:

Get-ChildItem . *.config -rec | ForEach-Object { 
    Replace-TextInFile -FilePath $_ -Pattern 'old' -Replacement 'new' 
}

onclick go full screen

I realize this is a very old question, and that the answers provided were adequate, since is active and I came across this by doing some research on fullscreen, I leave here one update to this topic:

There is a way to "simulate" the F11 key, but cannot be automated, the user actually needs to click a button for example, in order to trigger the full screen mode.

  • Toggle Fullscreen status on button click

    With this example, the user can switch to and from fullscreen mode by clicking a button:

    HTML element to act as trigger:

    <input type="button" value="click to toggle fullscreen" onclick="toggleFullScreen()">
    

    JavaScript:

    function toggleFullScreen() {
      if ((document.fullScreenElement && document.fullScreenElement !== null) ||    
       (!document.mozFullScreen && !document.webkitIsFullScreen)) {
        if (document.documentElement.requestFullScreen) {  
          document.documentElement.requestFullScreen();  
        } else if (document.documentElement.mozRequestFullScreen) {  
          document.documentElement.mozRequestFullScreen();  
        } else if (document.documentElement.webkitRequestFullScreen) {  
          document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);  
        }  
      } else {  
        if (document.cancelFullScreen) {  
          document.cancelFullScreen();  
        } else if (document.mozCancelFullScreen) {  
          document.mozCancelFullScreen();  
        } else if (document.webkitCancelFullScreen) {  
          document.webkitCancelFullScreen();  
        }  
      }  
    }
    
  • Go to Fullscreen on button click

    This example allows you to enable full screen mode without making alternation, ie you switch to full screen but to return to the normal screen will have to use the F11 key:

    HTML element to act as trigger:

    <input type="button" value="click to go fullscreen" onclick="requestFullScreen()">
    

    JavaScript:

    function requestFullScreen() {
    
      var el = document.body;
    
      // Supports most browsers and their versions.
      var requestMethod = el.requestFullScreen || el.webkitRequestFullScreen 
      || el.mozRequestFullScreen || el.msRequestFullScreen;
    
      if (requestMethod) {
    
        // Native full screen.
        requestMethod.call(el);
    
      } else if (typeof window.ActiveXObject !== "undefined") {
    
        // Older IE.
        var wscript = new ActiveXObject("WScript.Shell");
    
        if (wscript !== null) {
          wscript.SendKeys("{F11}");
        }
      }
    }
    

Sources found along with useful information on this subject:

Mozilla Developer Network

How to make in Javascript full screen windows (stretching all over the screen)

How to make browser full screen using F11 key event through JavaScript

Chrome Fullscreen API

jQuery fullscreen event plugin, version 0.2.0

jquery-fullscreen-plugin

react-router - pass props to handler component

The problem with the React Router is that it renders your components and so stops you passsing in props. The Navigation router, on the other hand, lets you render your own components. That means you don't have to jump through any hoops to pass in props as the following code and accompanying JsFiddle show.

var Comments = ({myProp}) => <div>{myProp}</div>;

var stateNavigator = new Navigation.StateNavigator([
  {key:'comments', route:''}
]);

stateNavigator.states.comments.navigated = function(data) {
  ReactDOM.render(
    <Comments myProp="value" />,
    document.getElementById('content')
  );
}

stateNavigator.start();

How to pass multiple checkboxes using jQuery ajax post

The following from Paul Tarjan worked for me,

var data = { 'user_ids[]' : []};
$(":checked").each(function() {
  data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);

but I had multiple forms on my page and it pulled checked boxes from all forms, so I made the following modification so it only pulled from one form,

var data = { 'user_ids[]' : []};
$('#name_of_your_form input[name="user_ids[]"]:checked').each(function() {
  data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);

Just change name_of_your_form to the name of your form.

I'll also mention that if a user doesn't check any boxes then no array isset in PHP. I needed to know if a user unchecked all the boxes, so I added the following to the form,

<input style="display:none;" type="checkbox" name="user_ids[]" value="none" checked="checked"></input>

This way if no boxes are checked, it will still set the array with a value of "none".

versionCode vs versionName in Android Manifest

android:versionCode — An integer value that represents the version of the application code, relative to other versions.

The value is an integer so that other applications can programmatically evaluate it, for example to check an upgrade or downgrade relationship. You can set the value to any integer you want, however you should make sure that each successive release of your application uses a greater value. The system does not enforce this behavior, but increasing the value with successive releases is normative.

android:versionName — A string value that represents the release version of the application code, as it should be shown to users.

The value is a string so that you can describe the application version as a .. string, or as any other type of absolute or relative version identifier.

As with android:versionCode, the system does not use this value for any internal purpose, other than to enable applications to display it to users. Publishing services may also extract the android:versionName value for display to users.

Typically, you would release the first version of your application with versionCode set to 1, then monotonically increase the value with each release, regardless whether the release constitutes a major or minor release. This means that the android:versionCode value does not necessarily have a strong resemblance to the application release version that is visible to the user (see android:versionName, below). Applications and publishing services should not display this version value to users.

How to Split Image Into Multiple Pieces in Python

As an alternative to other solutions, we will construct the tiles by generating a grid of coordinates using itertools.product. We will ignore partial tiles on the edges, only iterating through the Cartesian product between the two intervals, i.e. range(0, h-h%d, d) X range(0, w-w%d, d).

Given fp: the file name to the image, d: the tile size, opt.path: the path to the directory containing the images, and opt.out: is the directory where tiles will be outputted:

def tile(filename, dir_in, dir_out, d):
    name, ext = os.path.splitext(filename)
    img = Image.open(os.path.join(dir_in, fp))
    w, h = img.size
    
    grid = list(product(range(0, h-h%d, d), range(0, w-w%d, d)))
    for i, j in grid:
        box = (j, i, j+d, i+d)
        out = os.path.join(dir_out, f'{name}_{i}_{j}{ext}')
        img.crop(box).save(out)

enter image description here

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Probably in this case you obtained your account object using the merge logic, and persist is used to persist new objects and it will complain if the hierarchy is having an already persisted object. You should use saveOrUpdate in such cases, instead of persist.

is there any way to force copy? copy without overwrite prompt, using windows?

MOVE /-Y Source Destination

Note:/-y will make the announcement of yes/no for overwrite

How to assign string to bytes array

For example,

package main

import "fmt"

func main() {
    s := "abc"
    var a [20]byte
    copy(a[:], s)
    fmt.Println("s:", []byte(s), "a:", a)
}

Output:

s: [97 98 99] a: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

How to configure Visual Studio to use Beyond Compare

In Visual Studio, go to the Tools menu, select Options, expand Source Control, (In a TFS environment, click Visual Studio Team Foundation Server), and click on the Configure User Tools button.

image to show location of the Configure User Tools button

Click the Add button.

Enter/select the following options for Compare:

  • Extension: .*
  • Operation: Compare
  • Command: C:\Program Files\Beyond Compare 3\BComp.exe (replace with the proper path for your machine, including version number)
  • Arguments: %1 %2 /title1=%6 /title2=%7

If using Beyond Compare Professional (3-way Merge):

  • Extension: .*
  • Operation: Merge
  • Command: C:\Program Files\Beyond Compare 3\BComp.exe (replace with the proper path for your machine, including version number)
  • Arguments: %1 %2 %3 %4 /title1=%6 /title2=%7 /title3=%8 /title4=%9

If using Beyond Compare v3/v4 Standard or Beyond Compare v2 (2-way Merge):

  • Extension: .*
  • Operation: Merge
  • Command: C:\Program Files\Beyond Compare 3\BComp.exe (replace with the proper path for your machine, including version number)
  • Arguments: %1 %2 /savetarget=%4 /title1=%6 /title2=%7

If you use tabs in Beyond Compare

If you run Beyond Compare in tabbed mode, it can get confused when you diff or merge more than one set of files at a time from Visual Studio. To fix this, you can add the argument /solo to the end of the arguments; this ensures each comparison opens in a new window, working around the issue with tabs.

How do I update a Mongo document after inserting it?

According to the latest documentation about PyMongo titled Insert a Document (insert is deprecated) and following defensive approach, you should insert and update as follows:

result = mycollection.insert_one(post)
post = mycollection.find_one({'_id': result.inserted_id})

if post is not None:
    post['newfield'] = "abc"
    mycollection.save(post)

Get age from Birthdate

Try this function...

function calculate_age(birth_month,birth_day,birth_year)
{
    today_date = new Date();
    today_year = today_date.getFullYear();
    today_month = today_date.getMonth();
    today_day = today_date.getDate();
    age = today_year - birth_year;

    if ( today_month < (birth_month - 1))
    {
        age--;
    }
    if (((birth_month - 1) == today_month) && (today_day < birth_day))
    {
        age--;
    }
    return age;
}

OR

function getAge(dateString) 
{
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) 
    {
        age--;
    }
    return age;
}

See Demo.

Selenium WebDriver: Wait for complex page with JavaScript to load

Here's how I do it:

new WebDriverWait(driver, 20).until(
       ExpectedConditions.jsReturnsValue(
                   "return document.readyState === 'complete' ? true : false"));

How do I enable logging for Spring Security?

Spring security logging for webflux reactive apps is now available starting with version 5.4.0-M2 (as mentionned by @bzhu in comment How do I enable logging for Spring Security?)

Until this gets into a GA release, here is how to get this milestone release in gradle

repositories {
    mavenCentral()
    if (!version.endsWith('RELEASE')) {
        maven { url "https://repo.spring.io/milestone" }
    }
}

// Force earlier milestone release to get securing logging preview
// https://docs.spring.io/spring-security/site/docs/current/reference/html5/#getting-gradle-boot
// https://github.com/spring-projects/spring-security/pull/8504
// https://github.com/spring-projects/spring-security/releases/tag/5.4.0-M2
ext['spring-security.version']='5.4.0-M2'
dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }

}

Facebook API "This app is in development mode"

App Review > Make {Your App} public? > Yes

Click app review and Turn on the Make your app Public toggle. Save changes

MVC 4 Razor adding input type date

I managed to do it by using the following code.

@Html.TextBoxFor(model => model.EndTime, new { type = "time" })

Send a ping to each IP on a subnet

#!/bin/sh

COUNTER=$1

while [ $COUNTER -lt 254 ]
do
 echo $COUNTER
 ping -c 1 192.168.1.$COUNTER | grep 'ms'
 COUNTER=$(( $COUNTER + 1 ))
done

#specify start number like this: ./ping.sh 1
#then run another few instances to cover more ground
#aka one at 1, another at 100, another at 200
#this just finds addresses quicker. will only print ttl info when an address resolves

How do I resolve git saying "Commit your changes or stash them before you can merge"?

I tried the first answer: git stash with the highest score but the error message still popped up, and then I found this article to commit the changes instead of stash 'Reluctant Commit'

and the error message disappeared finally:

1: git add .

2: git commit -m "this is an additional commit"

3: git checkout the-other-file-name

then it worked. hope this answer helps.:)

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

It's helped me, I uninstalled EF, restarted VS and I added 'using':

using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;

SQL Server: Difference between PARTITION BY and GROUP BY

It provides rolled-up data without rolling up

i.e. Suppose I want to return the relative position of sales region

Using PARTITION BY, I can return the sales amount for a given region and the MAX amount across all sales regions in the same row.

This does mean you will have repeating data, but it may suit the end consumer in the sense that data has been aggregated but no data has been lost - as would be the case with GROUP BY.

How do I compare two strings in python?

Equality in direct comparing:

string1 = "sample"
string2 = "sample"

if string1 == string2 :
    print("Strings are equal with text : ", string1," & " ,string2)
else :
    print ("Strings are not equal")

Equality in character sets:

string1 = 'abc def ghi'
string2 = 'def ghi abc'

set1 = set(string1.split(' '))
set2 = set(string2.split(' '))

print set1 == set2

if string1 == string2 :
    print("Strings are equal with text : ", string1," & " ,string2)
else :
    print ("Strings are not equal")

TypeScript: Property does not exist on type '{}'

Access the field with array notation to avoid strict type checking on single field:

data['propertyName']; //will work even if data has not declared propertyName

Alternative way is (un)cast the variable for single access:

(<any>data).propertyName;//access propertyName like if data has no type

The first is shorter, the second is more explicit about type (un)casting


You can also totally disable type checking on all variable fields:

let untypedVariable:any= <any>{}; //disable type checking while declaring the variable
untypedVariable.propertyName = anyValue; //any field in untypedVariable is assignable and readable without type checking

Note: This would be more dangerous than avoid type checking just for a single field access, since all consecutive accesses on all fields are untyped

The type or namespace name 'DbContext' could not be found

Download http://www.dll-found.com/download/e/EntityFramework.dll

Paste it in (for x86)

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\

Then Right click on project -> add reference -> select EntityFramework

Bingo......

Javascript code for showing yesterday's date and todays date

One liner:

var yesterday = new Date(Date.now() - 864e5); // 864e5 == 86400000 == 24*60*60*1000

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

List files recursively in Linux CLI with path relative to the current directory

Try find. You can look it up exactly in the man page, but it's sorta like this:

find [start directory] -name [what to find]

so for your example

find . -name "*.txt"

should give you what you want.

Find the max of 3 numbers in Java with different data types

Like mentioned before, Math.max() only takes two arguments. It's not exactly compatible with your current syntax but you could try Collections.max().

If you don't like that you can always create your own method for it...

public class test {
    final static int MY_INT1 = 25;
    final static int MY_INT2 = -10;
    final static double MY_DOUBLE1 = 15.5;

    public static void main(String args[]) {
        double maxOfNums = multiMax(MY_INT1, MY_INT2, MY_DOUBLE1);
    }

    public static Object multiMax(Object... values) {
        Object returnValue = null;
        for (Object value : values)
            returnValue = (returnValue != null) ? ((((value instanceof Integer) ? (Integer) value
                    : (value instanceof Double) ? (Double) value
                            : (Float) value) > ((returnValue instanceof Integer) ? (Integer) returnValue
                    : (returnValue instanceof Double) ? (Double) returnValue
                            : (Float) returnValue)) ? value : returnValue)
                    : value;
        return returnValue;
    }
}

This will take any number of mixed numeric arguments (Integer, Double and Float) but the return value is an Object so you would have to cast it to Integer, Double or Float.

It might also be throwing an error since there is no such thing as "MY_DOUBLE2".

How can I export tables to Excel from a webpage

First, I would not recommend trying export Html and hope that the user's instance of Excel picks it up. My experience that this solution is fraught with problems including incompatibilities with Macintosh clients and throwing an error to the user that the file in question is not of the format specified. The most bullet-proof, user-friendly solution is a server-side one where you use a library to build an actual Excel file and send that back to the user. The next best solution and more universal solution would be to use the Open XML format. I've run into a few rare compatibility issues with older versions of Excel but on the whole this should give you a solution that will work on any version of Excel including Macs.

Open XML

How to export table as CSV with headings on Postgresql?

When I don't have permission to write a file out from Postgres I find that I can run the query from the command line.

psql -U user -d db_name -c "Copy (Select * From foo_table LIMIT 10) To STDOUT With CSV HEADER DELIMITER ',';" > foo_data.csv

How to upload a file and JSON data in Postman?

At Back-end part

Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
consumes = {"multipart/form-data"})

@ResponseBody
public boolean yourEndpointMethod(
    @RequestPart("properties") @Valid ConnectionProperties properties,
    @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
return projectService.executeSampleService(properties, file);
}

At front-end :

formData = new FormData();

formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
            "name": "root",
            "password": "root"                    
        })], {
            type: "application/json"
        }));

See in the image (POSTMAN request):

Click to view Postman request in form data for both file and json

Is there a way to iterate over a range of integers?

While I commiserate with your concern about lacking this language feature, you're probably just going to want to use a normal for loop. And you'll probably be more okay with that than you think as you write more Go code.

I wrote this iter package — which is backed by a simple, idiomatic for loop that returns values over a chan int — in an attempt to improve on the design found in https://github.com/bradfitz/iter, which has been pointed out to have caching and performance issues, as well as a clever, but strange and unintuitive implementation. My own version operates the same way:

package main

import (
    "fmt"
    "github.com/drgrib/iter"
)

func main() {
    for i := range iter.N(10) {
        fmt.Println(i)
    }
}

However, benchmarking revealed that the use of a channel was a very expensive option. The comparison of the 3 methods, which can be run from iter_test.go in my package using

go test -bench=. -run=.

quantifies just how poor its performance is

BenchmarkForMany-4                   5000       329956 ns/op           0 B/op          0 allocs/op
BenchmarkDrgribIterMany-4               5    229904527 ns/op         195 B/op          1 allocs/op
BenchmarkBradfitzIterMany-4          5000       337952 ns/op           0 B/op          0 allocs/op

BenchmarkFor10-4                500000000         3.27 ns/op           0 B/op          0 allocs/op
BenchmarkDrgribIter10-4            500000      2907 ns/op             96 B/op          1 allocs/op
BenchmarkBradfitzIter10-4       100000000        12.1 ns/op            0 B/op          0 allocs/op

In the process, this benchmark also shows how the bradfitz solution underperforms in comparison to the built-in for clause for a loop size of 10.

In short, there appears to be no way discovered so far to duplicate the performance of the built-in for clause while providing a simple syntax for [0,n) like the one found in Python and Ruby.

Which is a shame because it would probably be easy for the Go team to add a simple rule to the compiler to change a line like

for i := range 10 {
    fmt.Println(i)
}

to the same machine code as for i := 0; i < 10; i++.

However, to be fair, after writing my own iter.N (but before benchmarking it), I went back through a recently written program to see all the places I could use it. There actually weren't many. There was only one spot, in a non-vital section of my code, where I could get by without the more complete, default for clause.

So while it may look like this is a huge disappointment for the language in principle, you may find — like I did — that you actually don't really need it in practice. Like Rob Pike is known to say for generics, you might not actually miss this feature as much as you think you will.

How do I create a HTTP Client Request with a cookie?

The use of http.createClient is now deprecated. You can pass Headers in options collection as below.

var options = { 
    hostname: 'example.com',
    path: '/somePath.php',
    method: 'GET',
    headers: {'Cookie': 'myCookie=myvalue'}
};
var results = ''; 
var req = http.request(options, function(res) {
    res.on('data', function (chunk) {
        results = results + chunk;
        //TODO
    }); 
    res.on('end', function () {
        //TODO
    }); 
});

req.on('error', function(e) {
        //TODO
});

req.end();

How to change python version in anaconda spyder

You can launch the correct version of Spyder by launching from Ananconda's Navigator. From the dropdown, switch to your desired environment and then press the launch Spyder button. You should be able to check the results right away.

passing several arguments to FUN of lapply (and others *apply)

As suggested by Alan, function 'mapply' applies a function to multiple Multiple Lists or Vector Arguments:

mapply(myfun, arg1, arg2)

See man page: https://stat.ethz.ch/R-manual/R-devel/library/base/html/mapply.html

ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

Kiran's answer is definetely the answer for my case.

In code part I split string to 4000 char strings and try to put them in to db.

Explodes with this error.

The cause of the error is using utf chars, those counts 2 bytes each. Even I truncate to 4000 chars in code(sth. like String.Take(4000)), oracle considers 4001 when string contains 'ö' or any other non-eng(non ascii to be precise, which are represented with two or bytes in utf8) characters.

How to use Typescript with native ES6 Promises

The current lib.d.ts doesn't have promises in it defined so you need a extra definition file for it that is why you are getting compilation errors.

You could for example use (like @elclanrs says) use the es6-promise package with the definition file from DefinitelyTyped: es6-promise definition

You can then use it like this:

var p = new Promise<string>((resolve, reject) => { 
    resolve('a string'); 
});

edit You can use it without a definition when targeting ES6 (with the TypeScript compiler) - Note you still require the Promise to exists in the runtime ofcourse (so it won't work in old browsers :)) Add/Edit the following to your tsconfig.json :

"compilerOptions": {
    "target": "ES6"
}

edit 2 When TypeScript 2.0 will come out things will change a bit (though above still works) but definition files can be installed directly with npm like below:

npm install --save @types/es6-promise - source

edit3 Updating answer with more info for using the types.

Create a package.json file with only { } as the content (if you don't have a package.json already. Call npm install --save @types/es6-promise and tsc --init. The first npm install command will change your package.json to include the es6-promise as a dependency. tsc --init will create a tsconfig.json file for you.

You can now use the promise in your typescript file var x: Promise<any>;. Execute tsc -p . to compile your project. You should have no errors.

What do &lt; and &gt; stand for?

  • &lt; stands for the less-than sign: <
  • &gt; stands for the greater-than sign: >
  • &le; stands for the less-than or equals sign: =
  • &ge; stands for the greater-than or equals sign: =

PHP preg_replace special characters

If you by writing "non letters and numbers" exclude more than [A-Za-z0-9] (ie. considering letters like åäö to be letters to) and want to be able to accurately handle UTF-8 strings \p{L} and \p{N} will be of aid.

  1. \p{N} will match any "Number"
  2. \p{L} will match any "Letter Character", which includes
    • Lower case letter
    • Modifier letter
    • Other letter
    • Title case letter
    • Upper case letter

Documentation PHP: Unicode Character Properties


$data = "Thäre!wouldn't%bé#äny";

$new_data = str_replace  ("'", "", $data);
$new_data = preg_replace ('/[^\p{L}\p{N}]/u', '_', $new_data);

var_dump (
  $new_data
);

output

string(23) "Thäre_wouldnt_bé_äny"

Can Powershell Run Commands in Parallel?

If you're using latest cross platform powershell (which you should btw) https://github.com/powershell/powershell#get-powershell, you can add single & to run parallel scripts. (Use ; to run sequentially)

In my case I needed to run 2 npm scripts in parallel: npm run hotReload & npm run dev


You can also setup npm to use powershell for its scripts (by default it uses cmd on windows).

Run from project root folder: npm config set script-shell pwsh --userconfig ./.npmrc and then use single npm script command: npm run start

"start":"npm run hotReload & npm run dev"

How do I connect to an MDF database file?

Alternative solution, where you can have the database in the folder you want inside the solution. That worked for me:

.ConnectionString(@"Data Source=LocalDB)\MSSQLLocalDB;
                    AttachDbFilename="+AppDomain.CurrentDomain.BaseDirectory+"Folder1\\Folder2\\SampleDatabase.mdf" + ";
                    Integrated Security=True;")

What does the percentage sign mean in Python

Modulus operator; gives the remainder of the left value divided by the right value. Like:

3 % 1 would equal zero (since 3 divides evenly by 1)

3 % 2 would equal 1 (since dividing 3 by 2 results in a remainder of 1).

Sql Server return the value of identity column after insert statement

SELECT SCOPE_IDENTITY()

after the insert statement

Please refer the following links

http://msdn.microsoft.com/en-us/library/ms190315.aspx

"You may need an appropriate loader to handle this file type" with Webpack and Babel

You need to install the es2015 preset:

npm install babel-preset-es2015

and then configure babel-loader:

{
    test: /\.jsx?$/,
    loader: 'babel-loader',
    exclude: /node_modules/,
    query: {
        presets: ['es2015']
    }
}

How do I delete everything in Redis?

redis-cli -h <host> -p <port> flushall

It will remove all data from client connected(with host and port)

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

These are GCC functions for the programmer to give a hint to the compiler about what the most likely branch condition will be in a given expression. This allows the compiler to build the branch instructions so that the most common case takes the fewest number of instructions to execute.

How the branch instructions are built are dependent upon the processor architecture.

Handling a Menu Item Click Event - Android

simple code for creating menu..

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}

simple code for menu selected

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.new_game:
        newGame();
        return true;
    case R.id.help:
        showHelp();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

for more detail go below link..

Link1

Link2

Package opencv was not found in the pkg-config search path

From your question I guess you are using Ubuntu (or a derivate). If you use:

apt-file search opencv.pc

then you see that you have to install libopencv-dev.

After you do so, pkg-config --cflags opencv and pkg-config --libs opencv should work as expected.

how to add lines to existing file using python

Use 'a', 'a' means append. Anything written to a file opened with 'a' attribute is written at the end of the file.

with open('file.txt', 'a') as file:
    file.write('input')

How to copy commits from one branch to another?

The cherry-pick command can read the list of commits from the standard input.

The following command cherry-picks commits authored by the user John that exist in the "develop" branch but not in the "release" branch, and does so in the chronological order.

git log develop --not release --format=%H --reverse --author John | git cherry-pick --stdin

How to save LogCat contents to file?

Open command prompt and locate your adb.exe(it will be in your android-sdk/platform-tools)

adb logcat -d > <path-where-you-want-to-save-file>/filename.txt

If you omit path, it will save logcat in current working directory

The -d option indicates that you are dumping the current contents and then exiting. Prefer notepad++ to open this file so that you can get everything in a proper readable format.

get the latest fragment in backstack

Looks like something has changed for the better, because code below works perfectly for me, but I didn't find it in already provided answers.

Kotlin:

supportFragmentManager.fragments[supportFragmentManager.fragments.size - 1]

Java:

getSupportFragmentManager().getFragments()
.get(getSupportFragmentManager().getFragments().size() - 1)

JSON Post with Customized HTTPHeader Field

What you posted has a syntax error, but it makes no difference as you cannot pass HTTP headers via $.post().

Provided you're on jQuery version >= 1.5, switch to $.ajax() and pass the headers (docs) option. (If you're on an older version of jQuery, I will show you how to do it via the beforeSend option.)

$.ajax({
    url: 'https://url.com',
    type: 'post',
    data: {
        access_token: 'XXXXXXXXXXXXXXXXXXX'
    },
    headers: {
        Header_Name_One: 'Header Value One',   //If your header name has spaces or any other char not appropriate
        "Header Name Two": 'Header Value Two'  //for object property name, use quoted notation shown in second
    },
    dataType: 'json',
    success: function (data) {
        console.info(data);
    }
});

How can I get column names from a table in Oracle?

SELECT A.COLUMN_NAME, A.* FROM all_tab_columns a 
WHERE table_name = 'Your Table Name'
AND A.COLUMN_NAME = 'COLUMN NAME' AND a.owner = 'Schema'

Can linux cat command be used for writing text to file?

That's what echo does:

echo "Some text here." > myfile.txt

Android layout replacing a view with another view on run time

it work in my case, oldSensor and newSnsor - oldView and newView:

private void replaceSensors(View oldSensor, View newSensor) {
            ViewGroup parent = (ViewGroup) oldSensor.getParent();

            if (parent == null) {
                return;
            }

            int indexOldSensor = parent.indexOfChild(oldSensor);
            int indexNewSensor = parent.indexOfChild(newSensor);
            parent.removeView(oldSensor);
            parent.addView(oldSensor, indexNewSensor);
            parent.removeView(newSensor);
            parent.addView(newSensor, indexOldSensor);
        }

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

This is for 32 bit, we need to change the size if we consider 8 bits.

    void bitReverse(int num)
    {
        int num_reverse = 0;
        int size = (sizeof(int)*8) -1;
        int i=0,j=0;
        for(i=0,j=size;i<=size,j>=0;i++,j--)
        {
            if((num >> i)&1)
            {
                num_reverse = (num_reverse | (1<<j));
            }
        }
        printf("\n rev num = %d\n",num_reverse);
    }

Reading the input integer "num" in LSB->MSB order and storing in num_reverse in MSB->LSB order.

How to enable authentication on MongoDB through Docker?

I want to comment but don't have enough reputation.

The user-adding executable script shown above has to be modified with --authenticationDatabase admin and NEWDATABASENAME.

mongo --authenticationDatabase admin --host localhost -u USER_PREVIOUSLY_DEFINED -p PASS_YOU_PREVIOUSLY_DEFINED NEWDATABASENAME --eval "db.createUser({user: 'NEWUSERNAME', pwd: 'PASSWORD', roles: [{role: 'readWrite', db: 'NEWDATABASENAME'}]});"

https://i.stack.imgur.com/MdyXo.png

NullInjectorError: No provider for AngularFirestore

I had same issue and below is resolved.

Old Service Code:

@Injectable()

Updated working Service Code:

@Injectable({
  providedIn: 'root'
})

Chart.js v2 - hiding grid lines

options: {
    scales: {
        xAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }],
        yAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }]
    }
}

Reading serial data in realtime in Python

You need to set the timeout to "None" when you open the serial port:

ser = serial.Serial(**bco_port**, timeout=None, baudrate=115000, xonxoff=False, rtscts=False, dsrdtr=False) 

This is a blocking command, so you are waiting until you receive data that has newline (\n or \r\n) at the end: line = ser.readline()

Once you have the data, it will return ASAP.

Remove Safari/Chrome textinput/textarea glow

On textarea resizing in webkit based browsers:

Setting max-height and max-width on the textarea will not remove the visual resize handle. Try:

resize: none;

(and yes I agree with "try to avoid doing anything which breaks the user's expectation", but sometimes it does make sense, i.e. in the context of a web application)

To customize the look and feel of webkit form elements from scratch:

-webkit-appearance: none;

Detecting when user scrolls to bottom of div with jQuery

If anyone gets scrollHeight as undefined, then select elements' 1st subelement: mob_top_menu[0].scrollHeight

How to set default values for Angular 2 component properties?

Here is the best solution for this. (ANGULAR All Version)

Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.

I have provided solution for this kind of similar question. You can find the full solution from here

export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

JavaScript push to array

That is an object, not an array. So you would do:

var json = { cool: 34.33, alsocool: 45454 };
json.supercool = 3.14159;
console.dir(json);

Can you recommend a free light-weight MySQL GUI for Linux?

Why not try MySQL GUI Tools? It's light, and does its job well.

Error when checking Java version: could not find java.dll

Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable

Type in command line

echo %JAVA_HOME%

and

java -version

To verify whether your installation was done successfully.


This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.

Steps to resolve:

  1. Open the Run window:

    Press windows+R

  2. Open registry window:

    Type regedit and enter.

  3. Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\

  4. If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.

  5. For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:

JRE regedit entry

  1. Create a new subkey of 1.8.

  2. For 1.8 create a String Key with name JavaHome with the value of JRE home:

    JRE regedit entry 2

Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html

mailto link multiple body lines

This is what I do, just add \n and use encodeURIComponent

Example

var emailBody = "1st line.\n 2nd line \n 3rd line";

emailBody = encodeURIComponent(emailBody);

href = "mailto:[email protected]?body=" + emailBody;

Check encodeURIComponent docs

How to use a RELATIVE path with AuthUserFile in htaccess?

I know this is an old question, but I just searched for the same thing and probably there are many others searching for a quick, mobile solution. Here is what I finally come up with:

# We set production environment by default
SetEnv PROD_ENV 1

<IfDefine DEV_ENV>
  # If 'DEV_ENV' has been defined, then unset the PROD_ENV
  UnsetEnv PROD_ENV

  AuthType Basic
  AuthName "Protected Area"
  AuthUserFile /var/www/foo.local/.htpasswd
  Require valid-user
</IfDefine>

<IfDefine PROD_ENV>
  AuthType Basic
  AuthName "Protected Area"
  AuthUserFile /home/foo/public_html/.htpasswd
  Require valid-user
</IfDefine>

How to read fetch(PDO::FETCH_ASSOC);

To read the result you can read it like a simple php array.

For example, getting the name can be done like $user['name'], and so on. The method fetch(PDO::FETCH_ASSOC) will only return 1 tuple tho. If you want to get all tuples, you can use fetchall(PDO::FETCH_ASSOC). You can go through the multidimensional array and get the values just the same.

Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

or

case 
    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

Installing ADB on macOS

If you've already installed Android Studio --

Add the following lines to the end of ~/.bashrc or ~/.zshrc (if using Oh My ZSH):

export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Restart Terminal and you're good to go.

jQuery count number of divs with a certain class?

You can use jQuery.children property.

var numItems = $('.wrapper').children('div').length;

for more information refer http://api.jquery.com/

How can I debug a .BAT script?

Or.... Call your main .bat file from another .bat file and output the result to a result file i.e.

runner.bat > mainresults.txt

Where runner.bat calls the main .bat file

You should see all the actions performed in the main .bat file now

How to list all Git tags?

Try to make git tag it should be enough if not try to make git fetch then git tag.

curl_init() function not working

For Windows, if anybody is interested, uncomment the following line (by removing the ;) from php.ini

;extension=php_curl.dll

Restart apache server.

What is the proper way to display the full InnerException?

@Jon's answer is the best solution when you want full detail (all the messages and the stack trace) and the recommended one.

However, there might be cases when you just want the inner messages, and for these cases I use the following extension method:

public static class ExceptionExtensions
{
    public static string GetFullMessage(this Exception ex)
    {
        return ex.InnerException == null 
             ? ex.Message 
             : ex.Message + " --> " + ex.InnerException.GetFullMessage();
    }
}

I often use this method when I have different listeners for tracing and logging and want to have different views on them. That way I can have one listener which sends the whole error with stack trace by email to the dev team for debugging using the .ToString() method and one that writes a log on file with the history of all the errors that happened each day without the stack trace with the .GetFullMessage() method.

case statement in SQL, how to return multiple variables?

You could use a subselect combined with a UNION. Whenever you can return the same fields for more than one condition use OR with the parenthesis as in this example:

SELECT * FROM
  (SELECT val1, val2 FROM table1 WHERE (condition1 is true) 
                                    OR (condition2 is true))
UNION
SELECT * FROM
  (SELECT val5, val6 FROM table7 WHERE (condition9 is true) 
                                    OR (condition4 is true))

Appending an id to a list if not already present in a string

Your list just contains a string. Convert it to integer IDs:

L = ['350882 348521 350166\r\n']

ids = [int(i) for i in L[0].strip().split()]
print(ids)
id = 348521
if id not in ids:
    ids.append(id)
print(ids)
id = 348522
if id not in ids:
    ids.append(id)
print(ids)
# Turn it back into your odd format
L = [' '.join(str(id) for id in ids) + '\r\n']
print(L)

Output:

[350882, 348521, 350166]
[350882, 348521, 350166]
[350882, 348521, 350166, 348522]
['350882 348521 350166 348522\r\n']

How to save and load cookies using Python + Selenium WebDriver

When you need cookies from session to session, there is another way to do it. Use the Chrome options user-data-dir in order to use folders as profiles. I run:

# You need to: from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")

Here you can do the logins that check for human interaction. I do this and then the cookies I need now every time I start the Webdriver with that folder everything is in there. You can also manually install the Extensions and have them in every session.

The second time I run, all the cookies are there:

# You need to: from selenium.webdriver.chrome.options import Options    
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") # Now you can see the cookies, the settings, extensions, etc., and the logins done in the previous session are present here. 

The advantage is you can use multiple folders with different settings and cookies, Extensions without the need to load, unload cookies, install and uninstall Extensions, change settings, change logins via code, and thus no way to have the logic of the program break, etc.

Also, this is faster than having to do it all by code.

Max parallel http connections in a browser?

Various browsers have various limits for maximum connections per host name; you can find the exact numbers at http://www.browserscope.org/?category=network and here is an interesting article about connection limitations from web performance expert Steve Souders http://www.stevesouders.com/blog/2008/03/20/roundup-on-parallel-connections/

Force youtube embed to start in 720p

None of the above solutions seem to work if the width/height is less than the line resolution of quality you select. For example, the following doesn't work for me in Chrome:

<iframe width="720" height="480" src="//youtube.com/embed/hUezoHa1ZF4?autoplay=true&rel=0&vq=hd720" frameborder="0" allowfullscreen></iframe>

I want to show the high quality video, but not use up 1280 x 720 pixels on the webpage.

When I go to youtube itself, playing 720p video in a 720x480 window looks better than 480p at the same size. I want to play 720p in a 720x480 window (downsampled better quality). There is no good solution yet afaik.

What is the difference between an expression and a statement in Python?

Expressions:

  • Expressions are formed by combining objects and operators.
  • An expression has a value, which has a type.
  • Syntax for a simple expression:<object><operator><object>

2.0 + 3 is an expression which evaluates to 5.0 and has a type float associated with it.

Statements

Statements are composed of expression(s). It can span multiple lines.

How to zero pad a sequence of integers in bash so that all have the same width?

One way without using external process forking is string manipulation, in a generic case it would look like this:

#start value
CNT=1

for [whatever iterative loop, seq, cat, find...];do
   # number of 0s is at least the amount of decimals needed, simple concatenation
   TEMP="000000$CNT"
   # for example 6 digits zero padded, get the last 6 character of the string
   echo ${TEMP:(-6)}
   # increment, if the for loop doesn't provide the number directly
   TEMP=$(( TEMP + 1 ))
done

This works quite well on WSL as well, where forking is a really heavy operation. I had a 110000 files list, using printf "%06d" $NUM took over 1 minute, the solution above ran in about 1 second.

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

I'm unsing ubuntu 14.04

Below command solved this problem for me.

sudo apt-get install php-mysql

In my case, after updating my php version from 5.5.9 to 7.0.8 i received this error including two other errors.

errors:

  1. laravel/framework v5.2.14 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.

  2. phpunit/phpunit 4.8.22 requires ext-dom * -> the requested PHP extension dom is missing from your system.

  3. [PDOException]
    could not find driver

Solutions:

I installed this packages and my problems are gone.

sudo apt-get install php-mbstring

sudo apt-get install php-xml

sudo apt-get install php-mysql

Using Cygwin to Compile a C program; Execution error

This file (cygwin1.dll) is cygwin dependency similar to qt dependency.you must copy this file and similar files that appear in such messages error, from "cygwin/bin" to folder of the your program .Also this is necessary to run in another computer that have NOT cygwin!

align images side by side in html

I suggest to use a container for each img p like this:

<div class="image123">
    <div style="float:left;margin-right:5px;">
        <img src="/images/tv.gif" height="200" width="200"  />
        <p style="text-align:center;">This is image 1</p>
    </div>
    <div style="float:left;margin-right:5px;">
        <img class="middle-img" src="/images/tv.gif/" height="200" width="200" />
        <p style="text-align:center;">This is image 2</p>
    </div>
    <div style="float:left;margin-right:5px;">
        <img src="/images/tv.gif/" height="200" width="200" />
        <p style="text-align:center;">This is image 3</p>
    </div>
</div>

Then apply float:left to each container. I add and 5px margin right so there is a space between each image. Also alway close your elements. Maybe in html img tag is not important to close but in XHTML is.

fiddle

Also a friendly advice. Try to avoid inline styles as much as possible. Take a look here:

html

<div class="image123">
    <div>
        <img src="/images/tv.gif" />
        <p>This is image 1</p>
    </div>
    <div>
        <img class="middle-img" src="/images/tv.gif/" />
        <p>This is image 2</p>
    </div>
    <div>
        <img src="/images/tv.gif/" />
        <p>This is image 3</p>
    </div>
</div>

css

div{
    float:left;
    margin-right:5px;
}

div > img{
   height:200px;
    width:200px;
}

p{
    text-align:center;
}

It's generally recommended that you use linked style sheets because:

  • They can be cached by browsers for performance
  • Generally a lot easier to maintain for a development perspective

source

fiddle

Netbeans - Error: Could not find or load main class

Try to rename the package name and the class/jframe names... The clean and build the application.

  1. Right Click on the package name
  2. Go to Refactor
  3. Select Rename
  4. Give it a meaningful name, preferably all in small letters
  5. Click on Refactor

    Do the same for the class/jframe names.

  6. Last Select Run from Menu 7.Select Clean and build main project

That should do it!!! All best

Access images inside public folder in laravel

Just put your Images in Public Directory (public/...folder or direct images).
Public directory is by default rendered by laravel application.
Let's suppose I stored images in public/images/myimage.jpg.
Then in your HTML view, page like: (image.blade.php)

<img src="{{url('/images/myimage.jpg')}}" alt="Image"/>

Uncaught TypeError: .indexOf is not a function

Basically indexOf() is a method belongs to string(array object also), But while calling the function you are passing a number, try to cast it to a string and pass it.

document.getElementById("oset").innerHTML = timeD2C(timeofday + "");

_x000D_
_x000D_
 var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
 function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)_x000D_
    var pos = time.indexOf('.');_x000D_
    var hrs = time.substr(1, pos - 1);_x000D_
    var min = (time.substr(pos, 2)) * 60;_x000D_
_x000D_
    if (hrs > 11) {_x000D_
        hrs = (hrs - 12) + ":" + min + " PM";_x000D_
    } else {_x000D_
        hrs += ":" + min + " AM";_x000D_
    }_x000D_
    return hrs;_x000D_
}_x000D_
alert(timeD2C(timeofday+""));
_x000D_
_x000D_
_x000D_


And it is good to do the string conversion inside your function definition,

function timeD2C(time) { 
  time = time + "";
  var pos = time.indexOf('.');

So that the code flow won't break at times when devs forget to pass a string into this function.

Convert columns to string in Pandas

pandas >= 1.0: It's time to stop using astype(str)!

Prior to pandas 1.0 (well, 0.25 actually) this was the defacto way of declaring a Series/column as as string:

# pandas <= 0.25
# Note to pedants: specifying the type is unnecessary since pandas will 
# automagically infer the type as object
s = pd.Series(['a', 'b', 'c'], dtype=str)
s.dtype
# dtype('O')

From pandas 1.0 onwards, consider using "string" type instead.

# pandas >= 1.0
s = pd.Series(['a', 'b', 'c'], dtype="string")
s.dtype
# StringDtype

Here's why, as quoted by the docs:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. It’s better to have a dedicated dtype.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than 'string'.

See also the section on Behavioral Differences between "string" and object.

Extension types (introduced in 0.24 and formalized in 1.0) are closer to pandas than numpy, which is good because numpy types are not powerful enough. For example NumPy does not have any way of representing missing data in integer data (since type(NaN) == float). But pandas can using Nullable Integer columns.


Why should I stop using it?

Accidentally mixing dtypes
The first reason, as outlined in the docs is that you can accidentally store non-text data in object columns.

# pandas <= 0.25
pd.Series(['a', 'b', 1.23])   # whoops, this should have been "1.23"

0       a
1       b
2    1.23
dtype: object

pd.Series(['a', 'b', 1.23]).tolist()
# ['a', 'b', 1.23]   # oops, pandas was storing this as float all the time.
# pandas >= 1.0
pd.Series(['a', 'b', 1.23], dtype="string")

0       a
1       b
2    1.23
dtype: string

pd.Series(['a', 'b', 1.23], dtype="string").tolist()
# ['a', 'b', '1.23']   # it's a string and we just averted some potentially nasty bugs.

Challenging to differentiate strings and other python objects
Another obvious example example is that it's harder to distinguish between "strings" and "objects". Objects are essentially the blanket type for any type that does not support vectorizable operations.

Consider,

# Setup
df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': [{}, [1, 2, 3], 123]})
df
 
   A          B
0  a         {}
1  b  [1, 2, 3]
2  c        123

Upto pandas 0.25, there was virtually no way to distinguish that "A" and "B" do not have the same type of data.

# pandas <= 0.25  
df.dtypes

A    object
B    object
dtype: object

df.select_dtypes(object)

   A          B
0  a         {}
1  b  [1, 2, 3]
2  c        123

From pandas 1.0, this becomes a lot simpler:

# pandas >= 1.0
# Convenience function I call to help illustrate my point.
df = df.convert_dtypes()
df.dtypes

A    string
B    object
dtype: object

df.select_dtypes("string")

   A
0  a
1  b
2  c

Readability
This is self-explanatory ;-)


OK, so should I stop using it right now?

...No. As of writing this answer (version 1.1), there are no performance benefits but the docs expect future enhancements to significantly improve performance and reduce memory usage for "string" columns as opposed to objects. With that said, however, it's never too early to form good habits!

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

Well, the <head> tag has nothing to do with the <header> tag. In the head comes all the metadata and stuff, while the header is just a layout component.
And layout comes into body. So I disagree with you.

sql server convert date to string MM/DD/YYYY

select convert(varchar(10), cast(fmdate as date), 101) from sery

Without cast I was not getting fmdate converted, so fmdate was a string.

How to break out of a loop from inside a switch?

It amazes me how simple this is considering the depth of explanations... Here's all you need...

bool imLoopin = true;

while(imLoopin) {

    switch(msg->state) {

        case MSGTYPE: // ... 
            break;

        // ... more stuff ...

        case DONE:
            imLoopin = false;
            break;

    }

}

LOL!! Really! That's all you need! One extra variable!

Invariant Violation: _registerComponent(...): Target container is not a DOM element

the ready function can be used like this:

$(document).ready(function () {
  React.render(<App />, document.body);
});

If you don't want to use jQuery, you can use the onload function:

<body onload="initReact()">...</body>

Align div with fixed position on the right side

You can simply do this:

.test {
  position: -webkit-sticky; /* Safari */
  position: sticky;
  right: 0;
}

JavaScript Promises - reject vs. throw

Another important fact is that reject() DOES NOT terminate control flow like a return statement does. In contrast throw does terminate control flow.

Example:

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  throw "err";_x000D_
  console.log("NEVER REACHED");_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

vs

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  reject(); // resolve() behaves similarly_x000D_
  console.log("ALWAYS REACHED"); // "REJECTED" will print AFTER this_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

What happened to console.log in IE8?

I like this method (using jquery's doc ready)... it lets you use console even in ie... only catch is that you need to reload the page if you open ie's dev tools after the page loads...

it could be slicker by accounting for all the functions, but I only use log so this is what I do.

//one last double check against stray console.logs
$(document).ready(function (){
    try {
        console.log('testing for console in itcutils');
    } catch (e) {
        window.console = new (function (){ this.log = function (val) {
            //do nothing
        }})();
    }
});

String contains - ignore case

If you won't go with regex:

"ABCDEFGHIJKLMNOP".toLowerCase().contains("gHi".toLowerCase())

What is N-Tier architecture?

Wikipedia:

In software engineering, multi-tier architecture (often referred to as n-tier architecture) is a client-server architecture in which, the presentation, the application processing and the data management are logically separate processes. For example, an application that uses middleware to service data requests between a user and a database employs multi-tier architecture. The most widespread use of "multi-tier architecture" refers to three-tier architecture.

It's debatable what counts as "tiers," but in my opinion it needs to at least cross the process boundary. Or else it's called layers. But, it does not need to be in physically different machines. Although I don't recommend it, you can host logical tier and database on the same box.

alt text

Edit: One implication is that presentation tier and the logic tier (sometimes called Business Logic Layer) needs to cross machine boundaries "across the wire" sometimes over unreliable, slow, and/or insecure network. This is very different from simple Desktop application where the data lives on the same machine as files or Web Application where you can hit the database directly.

For n-tier programming, you need to package up the data in some sort of transportable form called "dataset" and fly them over the wire. .NET's DataSet class or Web Services protocol like SOAP are few of such attempts to fly objects over the wire.

How to style input and submit button with CSS?

For reliability I'd suggest giving class-names, or ids to the elements to style (ideally a class for the text-inputs, since there will presumably be several) and an id to the submit button (though a class would work as well):

<form action="#" method="post">
    <label for="text1">Text 1</label>
    <input type="text" class="textInput" id="text1" />
    <label for="text2">Text 2</label>
    <input type="text" class="textInput" id="text2" />
    <input id="submitBtn" type="submit" />
</form>

With the CSS:

.textInput {
    /* styles the text input elements with this class */
}

#submitBtn {
    /* styles the submit button */
}

For more up-to-date browsers, you can select by attributes (using the same HTML):

.input {
    /* styles all input elements */
}

.input[type="text"] {
     /* styles all inputs with type 'text' */
}

.input[type="submit"] {
     /* styles all inputs with type 'submit' */
}

You could also just use sibling combinators (since the text-inputs to style seem to always follow a label element, and the submit follows a textarea (but this is rather fragile)):

label + input,
label + textarea {
    /* styles input, and textarea, elements that follow a label */
}

input + input,
textarea + input {
    /* would style the submit-button in the above HTML */
}

How to make git mark a deleted and a new file as a file move?

The other answers already cover that you can simply git add NEW && git rm OLD in order to make git recognize the move.

However, if you have already modified the file in the working directory, the add+rm approach will add the modifications to the index, which may be undesired in some cases (e.g. in case of substantial modifications, git might not recognize anymore that it is a file rename).

Let's assume you want to add the rename to the index, but not any modifications. The obvious way to achieve this, is to do a back and forth rename mv NEW OLD && git mv OLD NEW.

But there is also a (slighty more complicated) way to do this directly in the index without renaming the file in the working tree:

info=$(git ls-files -s -- "OLD" | cut -d' ' -f-2 | tr ' ' ,)
git update-index --add --cacheinfo "$info,NEW" &&
git rm --cached "$old"

This can also be put as an alias in your ~/.gitconfig:

[alias]
    mv-index = "!f() { \
      old=\"$1\"; \
      new=\"$2\"; \
      info=$(git ls-files -s -- \"$old\" | cut -d' ' -f-2 | tr ' ' ,); \
      git update-index --add --cacheinfo \"$info,$new\" && \
      git rm --cached \"$old\"; \
    }; f"

In Unix, how do you remove everything in the current directory and below it?

make sure you are in the correct directory

rm -rf *

Detect if user is scrolling

window.addEventListener("scroll",function(){
    window.lastScrollTime = new Date().getTime()
});
function is_scrolling() {
    return window.lastScrollTime && new Date().getTime() < window.lastScrollTime + 500
}

Change the 500 to the number of milliseconds after the last scroll event at which you consider the user to be "no longer scrolling".

(addEventListener is better than onScroll because the former can coexist nicely with any other code that uses onScroll.)

How to add link to flash banner

If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.

on (release) {
  getURL("http://someurl/");
}

To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.

I think it would go too far to explain into depth with pictures how to go about in stackoverflow.

Disable/Enable Submit Button until all forms have been filled

Just use

document.getElementById('submitbutton').disabled = !cansubmit;

instead of the the if-clause that works only one-way.

Also, for the users who have JS disabled, I'd suggest to set the initial disabled by JS only. To do so, just move the script behind the <form> and call checkform(); once.

How can I change the Bootstrap default font family using font from Google?

The bootstrap-live-customizer is a good resource for customising your own bootstrap theme and seeing the results live as you customise. Using this website its very easy to just edit the font and then download the updated .css file.

Android device chooser - My device seems offline

I had the same problem with my Galaxy S4, when connected to a Win 7 64 machine, not showing up as an available device in Eclipse. Tried rebooting phone, starting/restarting adb, switching from usb 3 to usb 2 port... none of which helped. Downloaded Samsung drivers from here: http://www.samsung.com/us/support/owners/product/SGH-I337ZWAATT

installed drivers and then when I reconnected my phone, windows installed the new drivers (took a min or so). I then restarted Eclipse and was able to see the phone and run the app.

I also tried this with the usb 3 port and it works as well.

Printing long int value in C

To take input " long int " and output " long int " in C is :

long int n;
scanf("%ld", &n);
printf("%ld", n);

To take input " long long int " and output " long long int " in C is :

long long int n;
scanf("%lld", &n);
printf("%lld", n);

Hope you've cleared..

Ruby objects and JSON serialization (without Rails)

If rendering performance is critical, you might also want to look at yajl-ruby, which is a binding to the C yajl library. The serialization API for that one looks like:

require 'yajl'
Yajl::Encoder.encode({"foo" => "bar"}) #=> "{\"foo\":\"bar\"}"

How to do Select All(*) in linq to sql

Assuming TableA as an entity of table TableA, and TableADBEntities as DB Entity class,

  1. LINQ Method
IQueryable<TableA> result;
using (var context = new TableADBEntities())
{
   result = context.TableA.Select(s => s);
}
  1. LINQ-to-SQL Query
IQueryable<TableA> result;
using (var context = new TableADBEntities())
{
   var qry = from s in context.TableA
               select s;
   result = qry.Select(s => s);
}

Native SQL can also be used as:

  1. Native SQL
IList<TableA> resultList;
using (var context = new TableADBEntities())
{
   resultList = context.TableA.SqlQuery("Select * from dbo.TableA").ToList();
}

Note: dbo is a default schema owner in SQL Server. One can construct a SQL SELECT query as per the database in the context.

How do you post to the wall on a facebook page (not profile)

You can not post to Facebook walls automatically without creating an application and using the templated feed publisher as Frank pointed out.

The only thing you can do is use the 'share' widgets that they provide, which require user interaction.

How do I concatenate or merge arrays in Swift?

My favorite method since Swift 2.0 is flatten

var a:[CGFloat] = [1, 2, 3]
var b:[CGFloat] = [4, 5, 6]

let c = [a, b].flatten()

This will return FlattenBidirectionalCollection so if you just want a CollectionType this will be enough and you will have lazy evaluation for free. If you need exactly the Array you can do this:

let c = Array([a, b].flatten())

Why is Dictionary preferred over Hashtable in C#?

Dictionary <<<>>> Hashtable differences:

  • Generic <<<>>> Non-Generic
  • Needs own thread synchronization <<<>>> Offers thread safe version through Synchronized() method
  • Enumerated item: KeyValuePair <<<>>> Enumerated item: DictionaryEntry
  • Newer (> .NET 2.0) <<<>>> Older (since .NET 1.0)
  • is in System.Collections.Generic <<<>>> is in System.Collections
  • Request to non-existing key throws exception <<<>>> Request to non-existing key returns null
  • potentially a bit faster for value types <<<>>> bit slower (needs boxing/unboxing) for value types

Dictionary / Hashtable similarities:

  • Both are internally hashtables == fast access to many-item data according to key
  • Both need immutable and unique keys
  • Keys of both need own GetHashCode() method

Similar .NET collections (candidates to use instead of Dictionary and Hashtable):

  • ConcurrentDictionary - thread safe (can be safely accessed from several threads concurrently)
  • HybridDictionary - optimized performance (for few items and also for many items)
  • OrderedDictionary - values can be accessed via int index (by order in which items were added)
  • SortedDictionary - items automatically sorted
  • StringDictionary - strongly typed and optimized for strings

Open a workbook using FileDialog and manipulate it in Excel VBA

Thankyou Frank.i got the idea. Here is the working code.

Option Explicit
Private Sub CommandButton1_Click()

  Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
  Dim fd As Office.FileDialog

  Set fd = Application.FileDialog(msoFileDialogFilePicker)

  With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2003", "*.xls?"

    If .Show = True Then
      fileName = Dir(.SelectedItems(1))

    End If
  End With

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks.Open (fileName)

  For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("import-sheets.xlsm").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("import-sheets.xlsm").Worksheets(total)
  Next sheet

  Workbooks(fileName).Close

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

DateTime.TryParse issue with dates of yyyy-dd-MM format

If you give the user the opportunity to change the date/time format, then you'll have to create a corresponding format string to use for parsing. If you know the possible date formats (i.e. the user has to select from a list), then this is much easier because you can create those format strings at compile time.

If you let the user do free-format design of the date/time format, then you'll have to create the corresponding DateTime format strings at runtime.

How to make matrices in Python?

Looping helps:

for row in matrix:
    print ' '.join(row)

or use nested str.join() calls:

print '\n'.join([' '.join(row) for row in matrix])

Demo:

>>> matrix = [['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E']]
>>> for row in matrix:
...     print ' '.join(row)
... 
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E
>>> print '\n'.join([' '.join(row) for row in matrix])
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E

If you wanted to show the rows and columns transposed, transpose the matrix by using the zip() function; if you pass each row as a separate argument to the function, zip() recombines these value by value as tuples of columns instead. The *args syntax lets you apply a whole sequence of rows as separate arguments:

>>> for cols in zip(*matrix):  # transposed
...     print ' '.join(cols)
... 
A A A A A
B B B B B
C C C C C
D D D D D
E E E E E

How to store Java Date to Mysql datetime with JPA

mysql datetime -> GregorianCalendar

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse("2012-12-13 14:54:30"); // mysql datetime format
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
System.out.println(calendar.getTime());

GregorianCalendar -> mysql datetime

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = format.format(calendar.getTime());
System.out.println(string);

angularjs to output plain text instead of html

jQuery is about 40 times SLOWER, please do not use jQuery for that simple task.

function htmlToPlaintext(text) {
  return text ? String(text).replace(/<[^>]+>/gm, '') : '';
}

usage :

var plain_text = htmlToPlaintext( your_html );

With angular.js :

angular.module('myApp.filters', []).
  filter('htmlToPlaintext', function() {
    return function(text) {
      return  text ? String(text).replace(/<[^>]+>/gm, '') : '';
    };
  }
);

use :

<div>{{myText | htmlToPlaintext}}</div>  

JavaScript string newline character?

You can use `` quotes (wich are below Esc button) with ES6. So you can write something like this:

var text = `fjskdfjslfjsl
skfjslfkjsldfjslfjs
jfsfkjslfsljs`;

Cannot install signed apk to device manually, got error "App not installed"

Go To Build.Gradle(module:app)

use this - minifyEnabled false

How to overlay images

If you're only wanting the magnifing glass on hover then you can use

a:hover img { cursor: url(glass.cur); }

http://www.javascriptkit.com/dhtmltutors/csscursors.shtml

If you want it there permanently you should probably either have it included in the original thumnail, or add it using JavaScript rather than adding it to the HTML (this is purely style and shouldn't be in the content).

Let me know if you want help on the JavaScript side.

Angular, content type is not being sent with $http

Great! The solution given above worked for me. Had the same problem with a GET call.

 method: 'GET',
 data: '',
 headers: {
        "Content-Type": "application/json"
 }

How to var_dump variables in twig templates?

So I got it working, partly a bit hackish:

  1. Set twig: debug: 1 in app/config/config.yml
  2. Add this to config_dev.yml

    services:
        debug.twig.extension:
            class: Twig_Extensions_Extension_Debug
            tags: [{ name: 'twig.extension' }]
    
  3. sudo rm -fr app/cache/dev

  4. To use my own debug function instead of print_r(), I opened vendor/twig-extensions/lib/Twig/Extensions/Node/Debug.php and changed print_r( to d(

PS. I would still like to know how/where to grab the $twig environment to add filters and extensions.

Difference between `constexpr` and `const`

According to book of "The C++ Programming Language 4th Editon" by Bjarne Stroustrup
const: meaning roughly ‘‘I promise not to change this value’’ (§7.5). This is used primarily to specify interfaces, so that data can be passed to functions without fear of it being modified.
The compiler enforces the promise made by const.
constexpr: meaning roughly ‘‘to be evaluated at compile time’’ (§10.4). This is used primarily to specify constants, to allow
For example:

const int dmv = 17; // dmv is a named constant
int var = 17; // var is not a constant
constexpr double max1 = 1.4*square(dmv); // OK if square(17) is a constant expression
constexpr double max2 = 1.4*square(var); // error : var is not a constant expression
const double max3 = 1.4*square(var); //OK, may be evaluated at run time
double sum(const vector<double>&); // sum will not modify its argument (§2.2.5)
vector<double> v {1.2, 3.4, 4.5}; // v is not a constant
const double s1 = sum(v); // OK: evaluated at run time
constexpr double s2 = sum(v); // error : sum(v) not constant expression

For a function to be usable in a constant expression, that is, in an expression that will be evaluated by the compiler, it must be defined constexpr.
For example:

constexpr double square(double x) { return x*x; }


To be constexpr, a function must be rather simple: just a return-statement computing a value. A constexpr function can be used for non-constant arguments, but when that is done the result is not a constant expression. We allow a constexpr function to be called with non-constant-expression arguments in contexts that do not require constant expressions, so that we don’t hav e to define essentially the same function twice: once for constant expressions and once for variables.
In a few places, constant expressions are required by language rules (e.g., array bounds (§2.2.5, §7.3), case labels (§2.2.4, §9.4.2), some template arguments (§25.2), and constants declared using constexpr). In other cases, compile-time evaluation is important for performance. Independently of performance issues, the notion of immutability (of an object with an unchangeable state) is an important design concern (§10.4).

How can I control Chromedriver open window size?

#use chrome webdriver

driver = webdriver.Chrome('path to /chromedriver')
driver.set_window_size(1400,1000)

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

bash: mkvirtualenv: command not found

In order to successfully install the virtualenvwrapper on Ubuntu 18.04.3 you need to do the following:

  1. Install virtualenv

    sudo apt install virtualenv
    
  2. Install virtualenvwrapper

    sudo pip install virtualenv
    sudo pip install virtualenvwrapper
    
  3. Add the following to the end of the .bashrc file

    export WORKON_HOME=~/virtualenvs
    export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python
    source ~/.local/bin/virtualenvwrapper.sh
    
  4. Execute the .bashrc file

    source ~/.bashrc
    
  5. Create your virtualenv

    mkvirtualenv your_virtualenv
    

Redirect from an HTML page

As far as I understand them, all the methods I have seen so far for this question seem to add the old location to the history. To redirect the page, but do not have the old location in the history, I use the replace method:

<script>
    window.location.replace("http://example.com");
</script>

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

I got this error when I was trying to access a url using curl:

curl 'https://example.com:80/some/page'

The solution was to change https to http

curl 'http://example.com:80/some/page'

Tensorflow: Using Adam optimizer

run init after AdamOptimizer,and without define init before or run init

sess.run(tf.initialize_all_variables())

or

sess.run(tf.global_variables_initializer())

Cleanest way to write retry logic?

Or how about doing it a bit neater....

int retries = 3;
while (retries > 0)
{
  if (DoSomething())
  {
    retries = 0;
  }
  else
  {
    retries--;
  }
}

I believe throwing exceptions should generally be avoided as a mechanism unless your a passing them between boundaries (such as building a library other people can use). Why not just have the DoSomething() command return true if it was successful and false otherwise?

EDIT: And this can be encapsulated inside a function like others have suggested as well. Only problem is if you are not writing the DoSomething() function yourself

Is it better to use NOT or <> when comparing values?

Because "not ... =" is two operations and "<>" is only one, it is faster to use "<>".

Here is a quick experiment to prove it:

StartTime = Timer
For x = 1 to 100000000
   If 4 <> 3 Then
   End if
Next
WScript.echo Timer-StartTime

StartTime = Timer
For x = 1 to 100000000
   If Not (4 = 3) Then
   End if
Next
WScript.echo Timer-StartTime

The results I get on my machine:

4.783203
5.552734

Deleting array elements in JavaScript - delete vs splice

If the desired element to delete is in the middle (say we want to delete 'c', which its index is 1), you can use:

var arr = ['a','b','c'];
var indexToDelete = 1;
var newArray = arr.slice(0,indexToDelete).combine(arr.slice(indexToDelete+1, arr.length))

What are the differences between the urllib, urllib2, urllib3 and requests module?

urllib2 provides some extra functionality, namely the urlopen() function can allow you to specify headers (normally you'd have had to use httplib in the past, which is far more verbose.) More importantly though, urllib2 provides the Request class, which allows for a more declarative approach to doing a request:

r = Request(url='http://www.mysite.com')
r.add_header('User-Agent', 'awesome fetcher')
r.add_data(urllib.urlencode({'foo': 'bar'})
response = urlopen(r)

Note that urlencode() is only in urllib, not urllib2.

There are also handlers for implementing more advanced URL support in urllib2. The short answer is, unless you're working with legacy code, you probably want to use the URL opener from urllib2, but you still need to import into urllib for some of the utility functions.

Bonus answer With Google App Engine, you can use any of httplib, urllib or urllib2, but all of them are just wrappers for Google's URL Fetch API. That is, you are still subject to the same limitations such as ports, protocols, and the length of the response allowed. You can use the core of the libraries as you would expect for retrieving HTTP URLs, though.

Git vs Team Foundation Server

If your team uses TFS and you want to use Git you might want to consider a "git to tfs" bridge. Essentially you work day to day using Git on your computer, then when you want to push your changes you push them to the TFS server.

There are a couple out there (on github). I used one at my last place (along with another developer) with some success. See:

https://github.com/spraints/git-tfs

https://github.com/git-tfs/git-tfs

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:

Delivery -> Package (One -> Many)

CREATE TABLE Delivery(
    Id INT IDENTITY PRIMARY KEY,
    NoteNumber NVARCHAR(255) NOT NULL
)

CREATE TABLE Package(
    Id INT IDENTITY PRIMARY KEY,
    Status INT NOT NULL DEFAULT 0,
    Delivery_Id INT NOT NULL,
    CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)

The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).

So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.

How do I write data to csv file in columns and rows from a list in python?

>>> import csv
>>> with open('test.csv', 'wb') as f:
...     wtr = csv.writer(f, delimiter= ' ')
...     wtr.writerows( [[1, 2], [2, 3], [4, 5]])
...
>>> with open('test.csv', 'r') as f:
...     for line in f:
...         print line,
...
1 2 <<=== Exactly what you said that you wanted.
2 3
4 5
>>>

To get it so that it can be loaded sensibly by Excel, you need to use a comma (the csv default) as the delimiter, unless you are in a locale (e.g. Europe) where you need a semicolon.

How Long Does it Take to Learn Java for a Complete Newbie?

The main problem you're having is that you're learning programming for the first time with Java and I think Java isn't the best language to start.

I suppose that you're addressing a work project, Is this the case? That pressure might make things worse. Depending on how complex the project is you might success but learning Java in 10 weeks without background knowledge is another issue.

SVN - Checksum mismatch while updating

I had a simllar problem. Main provider was antivirus "FortiClient" (antivirus + VPN CLient). When I disabled it - all update/checkout was made correctly

Update query with PDO and MySQL

Your update syntax is incorrect. Please check Update Syntax for the correct syntax.

$sql = "UPDATE `access_users` set `contact_first_name` = :firstname,  `contact_surname` = :surname, `contact_email` = :email, `telephone` = :telephone";

How to convert String to DOM Document object in java?

you can try

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));

Document doc = db.parse(is);

refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm

Is there a limit on an Excel worksheet's name length?

I use the following vba code where filename is a string containing the filename I want, and Function RemoveSpecialCharactersAndTruncate is defined below:

worksheet1.Name = RemoveSpecialCharactersAndTruncate(filename)

'Function to remove special characters from file before saving

Private Function RemoveSpecialCharactersAndTruncate$(ByVal FormattedString$)
    Dim IllegalCharacterSet$
    Dim i As Integer
'Set of illegal characters
    IllegalCharacterSet$ = "*." & Chr(34) & "//\[]:;|=,"
    'Iterate through illegal characters and replace any instances
    For i = 1 To Len(IllegalCharacterSet) - 1
        FormattedString$ = Replace(FormattedString$, Mid(IllegalCharacterSet, i, 1), "")
    Next
    'Return the value capped at 31 characters (Excel limit)
    RemoveSpecialCharactersAndTruncate$ = Left(FormattedString$, _
                           Application.WorksheetFunction.Min(Len(FormattedString), 31))
End Function

How to connect to remote Oracle DB with PL/SQL Developer?

In the "database" section of the logon dialog box, enter //hostname.domain:port/database, in your case //123.45.67.89:1521/TEST - this assumes that you don't want to set up a tnsnames.ora file/entry for some reason.

Also make sure the firewall settings on your server are not blocking port 1521.

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

I tried a few things in this scenario.

I removed ios and installed many times. Went down the path of deleting Splash screens to no avail! Bitcode on/off so many times.

However, after selecting a iOS provisioning team, and running pod update inside ./platforms/ios, I am pleased to announce this resolved my problems.

Hopefully you can try the same and get some resolution?

Spring .properties file: get element as an Array

If you define your array in properties file like:

base.module.elementToSearch=1,2,3,4,5,6

You can load such array in your Java class like this:

  @Value("${base.module.elementToSearch}")
  private String[] elementToSearch;

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

I want to declare an empty array in java and then I want do update it but the code is not working

You can do some thing like this,

Initialize with empty array and assign the values later

String importRt = "23:43 43:34";
if(null != importRt) {
            importArray = Arrays.stream(importRt.split(" "))
                    .map(String::trim)
                    .toArray(String[]::new);
        }

System.out.println(Arrays.toString(exportImportArray));

Hope it helps..

Send message to specific client with socket.io and node.js

each socket joins a room with a socket id for a name, so you can just

io.to(socket#id).emit('hey')

docs: http://socket.io/docs/rooms-and-namespaces/#default-room

Cheers

Pass command parameter to method in ViewModel in WPF?

"ViewModel" implies MVVM. If you're doing MVVM you shouldn't be passing views into your view models. Typically you do something like this in your XAML:

<Button Content="Edit" 
        Command="{Binding EditCommand}"
        CommandParameter="{Binding ViewModelItem}" >

And then this in your view model:

private ViewModelItemType _ViewModelItem;
public ViewModelItemType ViewModelItem
{
    get
    {
        return this._ViewModelItem;
    }
    set
    {
        this._ViewModelItem = value;
        RaisePropertyChanged(() => this.ViewModelItem);
    }
}

public ICommand EditCommand { get { return new RelayCommand<ViewModelItemType>(OnEdit); } }
private void OnEdit(ViewModelItemType itemToEdit)
{
    ... do something here...
}

Obviously this is just to illustrate the point, if you only had one property to edit called ViewModelItem then you wouldn't need to pass it in as a command parameter.

How to set level logging to DEBUG in Tomcat?

JULI logging levels for Tomcat

SEVERE - Serious failures

WARNING - Potential problems

INFO - Informational messages

CONFIG - Static configuration messages

FINE - Trace messages

FINER - Detailed trace messages

FINEST - Highly detailed trace messages

You can find here more https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/pasoe-admin/tomcat-logging.html

Remove leading or trailing spaces in an entire column of data

I was able to use Find & Replace with the "Find what:" input field set to:

" * "

(space asterisk space with no double-quotes)

and "Replace with:" set to:

""

(nothing)

Find empty or NaN entry in Pandas Dataframe

you also do something good:

text_empty = df['column name'].str.len() > -1

df.loc[text_empty].index

The results will be the rows which are empty & it's index number.

Return value from nested function in Javascript

you have to call a function before it can return anything.

function mainFunction() {
      function subFunction() {
            var str = "foo";
            return str;
      }
      return subFunction();
}

var test = mainFunction();
alert(test);

Or:

function mainFunction() {
      function subFunction() {
            var str = "foo";
            return str;
      }
      return subFunction;
}

var test = mainFunction();
alert( test() );

for your actual code. The return should be outside, in the main function. The callback is called somewhere inside the getLocations method and hence its return value is not recieved inside your main function.

function reverseGeocode(latitude,longitude){
    var address = "";
    var country = "";
    var countrycode = "";
    var locality = "";

    var geocoder = new GClientGeocoder();
    var latlng = new GLatLng(latitude, longitude);

    geocoder.getLocations(latlng, function(addresses) {
     address = addresses.Placemark[0].address;
     country = addresses.Placemark[0].AddressDetails.Country.CountryName;
     countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
     locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
    });   
    return country
   }

What is the point of "Initial Catalog" in a SQL Server connection string?

Setting an Initial Catalog allows you to set the database that queries run on that connection will use by default. If you do not set this for a connection to a server in which multiple databases are present, in many cases you will be required to have a USE statement in every query in order to explicitly declare which database you are trying to run the query on. The Initial Catalog setting is a good way of explicitly declaring a default database.

Why are there no ++ and --? operators in Python?

Clarity!

Python is a lot about clarity and no programmer is likely to correctly guess the meaning of --a unless s/he's learned a language having that construct.

Python is also a lot about avoiding constructs that invite mistakes and the ++ operators are known to be rich sources of defects. These two reasons are enough not to have those operators in Python.

The decision that Python uses indentation to mark blocks rather than syntactical means such as some form of begin/end bracketing or mandatory end marking is based largely on the same considerations.

For illustration, have a look at the discussion around introducing a conditional operator (in C: cond ? resultif : resultelse) into Python in 2005. Read at least the first message and the decision message of that discussion (which had several precursors on the same topic previously).

Trivia: The PEP frequently mentioned therein is the "Python Extension Proposal" PEP 308. LC means list comprehension, GE means generator expression (and don't worry if those confuse you, they are none of the few complicated spots of Python).

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

Unsupported major.minor version 52.0

Upgrade your Andorra version to JDK 1.8.

This is a version mismatch that your compiler is looking for Java version 8 and you have Java version 7.

You can run an app build in version 7 in version 8, but you can't do vice versa because when it comes to higher levels, versions are embedded with more features, enhancements rather than previous versions.

Download JDK version from this link

And set your JDK path for this

Static Final Variable in Java

Just having final will have the intended effect.

final int x = 5;

...
x = 10; // this will cause a compilation error because x is final

Declaring static is making it a class variable, making it accessible using the class name <ClassName>.x

How to set Android camera orientation properly?

check out this solution

 public static void setCameraDisplayOrientation(Activity activity,
                                                   int cameraId, android.hardware.Camera camera) {
        android.hardware.Camera.CameraInfo info =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break;
            case Surface.ROTATION_90: degrees = 90; break;
            case Surface.ROTATION_180: degrees = 180; break;
            case Surface.ROTATION_270: degrees = 270; break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }

Use JavaScript to place cursor at end of text in text input element

Try the following code:

$('input').focus(function () {
    $(this).val($(this).val());
}).focus()

java: HashMap<String, int> not working

You can use reference type in generic arguments, not primitive type. So here you should use

Map<String, Integer> myMap = new HashMap<String, Integer>();

and store value as

myMap.put("abc", 5);

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

I just found a simple and reliable solution if you are using the system UI approach (https://developer.android.com/training/system-ui/immersive.html).

It works in the case when you are using View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN, e.g. if you are using CoordinatorLayout.

It won't work for WindowManager.LayoutParams.FLAG_FULLSCREEN (The one you can also set in theme with android:windowFullscreen), but you can achieve similar effect with SYSTEM_UI_FLAG_LAYOUT_STABLE (which "has the same visual effect" according to the docs) and this solution should work again.

getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION /* If you want to hide navigation */
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE)

I've tested it on my device running Marshmallow.

The key is that soft keyboards are also one of the system windows (such as status bar and navigation bar), so the WindowInsets dispatched by system contains accurate and reliable information about it.

For the use case such as in DrawerLayout where we are trying to draw behind the status bar, We can create a layout that ignores only the top inset, and applies the bottom inset which accounts for the soft keyboard.

Here is my custom FrameLayout:

/**
 * Implements an effect similar to {@code android:fitsSystemWindows="true"} on Lollipop or higher,
 * except ignoring the top system window inset. {@code android:fitsSystemWindows="true"} does not
 * and should not be set on this layout.
 */
public class FitsSystemWindowsExceptTopFrameLayout extends FrameLayout {

    public FitsSystemWindowsExceptTopFrameLayout(Context context) {
        super(context);
    }

    public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs,
                                                 int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs,
                                                 int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setPadding(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(),
                    insets.getSystemWindowInsetBottom());
            return insets.replaceSystemWindowInsets(0, insets.getSystemWindowInsetTop(), 0, 0);
        } else {
            return super.onApplyWindowInsets(insets);
        }
    }
}

And to use it:

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

    <!-- Your original layout here -->
</com.example.yourapplication.FitsSystemWindowsExceptTopFrameLayout>

This should theoretically work for any device without insane modification, much better than any hack that tries to take a random 1/3 or 1/4 of screen size as reference.

(It requires API 16+, but I'm using fullscreen only on Lollipop+ for drawing behind the status bar so it's the best solution in this case.)

Python Pandas : pivot table with aggfunc = count unique distinct

You can construct a pivot table for each distinct value of X. In this case,

for xval, xgroup in g:
    ptable = pd.pivot_table(xgroup, rows='Y', cols='Z', 
        margins=False, aggfunc=numpy.size)

will construct a pivot table for each value of X. You may want to index ptable using the xvalue. With this code, I get (for X1)

     X        
Z   Z1  Z2  Z3
Y             
Y1   2   1 NaN
Y2 NaN NaN   1

What is this date format? 2011-08-12T20:17:46.384Z

@John-Skeet gave me the clue to fix my own issue around this. As a younger programmer this small issue is easy to miss and hard to diagnose. So Im sharing it in the hopes it will help someone.

My issue was that I wanted to parse the following string contraining a time stamp from a JSON I have no influence over and put it in more useful variables. But I kept getting errors.

So given the following (pay attention to the string parameter inside ofPattern();

String str = "20190927T182730.000Z"

LocalDateTime fin;
fin = LocalDateTime.parse( str, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss.SSSZ") );

Error:

Exception in thread "main" java.time.format.DateTimeParseException: Text 
'20190927T182730.000Z' could not be parsed at index 19

The problem? The Z at the end of the Pattern needs to be wrapped in 'Z' just like the 'T' is. Change "yyyyMMdd'T'HHmmss.SSSZ" to "yyyyMMdd'T'HHmmss.SSS'Z'" and it works.

Removing the Z from the pattern alltogether also led to errors.

Frankly, I'd expect a Java class to have anticipated this.

How do I tar a directory of files and folders without including the directory itself?

tar -czvf mydir.tgz -C my_dir/ `ls -A mydir`

Run it one level above mydir. This won't include any [.] or stuff.

Learning to write a compiler

Generally speaking, there's no five minutes tutorial for compilers, because it's a complicated topic and writing a compiler can take months. You will have to do your own search.

Python and Ruby are usually interpreted. Perhaps you want to start with an interpreter as well. It's generally easier.

The first step is to write a formal language description, the grammar of your programming language. Then you have to transform the source code that you want to compile or interpret according to the grammar into an abstract syntax tree, an internal form of the source code that the computer understands and can operate on. This step is usually called parsing and the software that parses the source code is called a parser. Often the parser is generated by a parser generator which transform a formal grammar into source oder machine code. For a good, non-mathematical explanation of parsing I recommend Parsing Techniques - A Practical Guide. Wikipedia has a comparison of parser generators from which you can choose that one that is suitable for you. Depending on the parser generator you chose, you will find tutorials on the Internet and for really popular parser generators (like GNU bison) there are also books.

Writing a parser for your language can be really hard, but this depends on your grammar. So I suggest to keep your grammar simple (unlike C++); a good example for this is LISP.

In the second step the abstract syntax tree is transformed from a tree structure into a linear intermediate representation. As a good example for this Lua's bytecode is often cited. But the intermediate representation really depends on your language.

If you are building an interpreter, you will simply have to interpret the intermediate representation. You could also just-in-time-compile it. I recommend LLVM and libjit for just-in-time-compilation. To make the language usable you will also have to include some input and output functions and perhaps a small standard library.

If you are going to compile the language, it will be more complicated. You will have to write backends for different computer architectures and generate machine code from the intermediate representation in those backends. I recommend LLVM for this task.

There are a few books on this topic, but I can recommend none of them for general use. Most of them are too academic or too practical. There's no "Teach yourself compiler writing in 21 days" and thus, you will have to buy several books to get a good understanding of this entire topic. If you search the Internet, you will come across some some online books and lecture notes. Maybe there's a university library nearby you where you can borrow books on compilers.

I also recommend a good background knowledge in theoretical computer science and graph theory, if you are going to make your project serious. A degree in computer science will also be helpful.

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

You should always refrain from increasing the timeouts, I doubt your backend server response time is the issue here in any case.

I got around this issue by clearing the connection keep-alive flag and specifying http version as per the answer here: https://stackoverflow.com/a/36589120/479632

server {
    location / {
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   Host      $http_host;

        # these two lines here
        proxy_http_version 1.1;
        proxy_set_header Connection "";

        proxy_pass http://localhost:5000;
    }
}

Unfortunately I can't explain why this works and didn't manage to decipher it from the docs mentioned in the answer linked either so if anyone has an explanation I'd be very interested to hear it.

Bash script to run php script

#!/usr/bin/env bash
PHP=`which php`
$PHP /path/to/php/file.php

Centering a canvas

Looking at the current answers I feel that one easy and clean fix is missing. Just in case someone passes by and looks for the right solution. I am quite successful with some simple CSS and javascript.

Center canvas to middle of the screen or parent element. No wrapping.

HTML:

<canvas id="canvas" width="400" height="300">No canvas support</canvas>

CSS:

#canvas {
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin:auto;
}

Javascript:

window.onload = window.onresize = function() {
    var canvas = document.getElementById('canvas');
    canvas.width = window.innerWidth * 0.8;
    canvas.height = window.innerHeight * 0.8;
}

Works like a charm - tested: firefox, chrome

fiddle: http://jsfiddle.net/djwave28/j6cffppa/3/

Group query results by month and year in postgresql

bma answer is great! I have used it with ActiveRecords, here it is if anybody needs it in Rails:

Model.find_by_sql(
  "SELECT TO_CHAR(created_at, 'Mon') AS month,
   EXTRACT(year from created_at) as year,
   SUM(desired_value) as desired_value
   FROM desired_table
   GROUP BY 1,2
   ORDER BY 1,2"
)

How do I cast a JSON Object to a TypeScript class?

If you are using ES6, try this:

class Client{
  name: string

  displayName(){
    console.log(this.name)
  }
}

service.getClientFromAPI().then(clientData => {
  
  // Here the client data from API only have the "name" field
  // If we want to use the Client class methods on this data object we need to:
  let clientWithType = Object.assign(new Client(), clientData)

  clientWithType.displayName()
})

But this method will not work on nested objects, sadly.

How to get difference between two rows for a column field?

select t1.rowInt,t1.Value,t2.Value-t1.Value as diff
from (select * from myTable) as t1,
     (select * from myTable where rowInt!=1
      union all select top 1 rowInt=COUNT(*)+1,Value=0 from myTable) as t2
where t1.rowInt=t2.rowInt-1

implementing merge sort in C++

I've rearranged the selected answer, used pointers for arrays and user input for number count is not pre-defined.

#include <iostream>

using namespace std;

void merge(int*, int*, int, int, int);

void mergesort(int *a, int*b, int start, int end) {
  int halfpoint;
  if (start < end) {
    halfpoint = (start + end) / 2;
    mergesort(a, b, start, halfpoint);
    mergesort(a, b, halfpoint + 1, end);
    merge(a, b, start, halfpoint, end);
  }
}

void merge(int *a, int *b, int start, int halfpoint, int end) {
  int h, i, j, k;
  h = start;
  i = start;
  j = halfpoint + 1;

  while ((h <= halfpoint) && (j <= end)) {
    if (a[h] <= a[j]) {
      b[i] = a[h];
      h++;
    } else {
      b[i] = a[j];
      j++;
    }
    i++;
  }
  if (h > halfpoint) {
    for (k = j; k <= end; k++) {
      b[i] = a[k];
      i++;
    }
  } else {
    for (k = h; k <= halfpoint; k++) {
      b[i] = a[k];
      i++;
    }
  }

  // Write the final sorted array to our original one
  for (k = start; k <= end; k++) {
    a[k] = b[k];
  }
}

int main(int argc, char** argv) {
  int num;
  cout << "How many numbers do you want to sort: ";
  cin >> num;
  int a[num];
  int b[num];
  for (int i = 0; i < num; i++) {
    cout << (i + 1) << ": ";
    cin >> a[i];
  }

  // Start merge sort
  mergesort(a, b, 0, num - 1);

  // Print the sorted array
  cout << endl;
  for (int i = 0; i < num; i++) {
    cout << a[i] << " ";
  }
  cout << endl;

  return 0;
}

Java switch statement multiple cases

// Noncompliant Code Example

switch (i) {
  case 1:
    doFirstThing();
    doSomething();
    break;
  case 2:
    doSomethingDifferent();
    break;
  case 3:  // Noncompliant; duplicates case 1's implementation
    doFirstThing();
    doSomething();
    break;
  default:
    doTheRest();
}

if (a >= 0 && a < 10) {
  doFirstThing();

  doTheThing();
}
else if (a >= 10 && a < 20) {
  doTheOtherThing();
}
else if (a >= 20 && a < 50) {
  doFirstThing();
  doTheThing();  // Noncompliant; duplicates first condition
}
else {
  doTheRest();
}

//Compliant Solution

switch (i) {
  case 1:
  case 3:
    doFirstThing();
    doSomething();
    break;
  case 2:
    doSomethingDifferent();
    break;
  default:
    doTheRest();
}

if ((a >= 0 && a < 10) || (a >= 20 && a < 50)) {
  doFirstThing();
  doTheThing();
}
else if (a >= 10 && a < 20) {
  doTheOtherThing();
}
else {
  doTheRest();
}

How to play video with AVPlayerViewController (AVKit) in Swift

Swift 5

  @IBAction func buttonPressed(_ sender: Any) {
    let videoURL = course.introductionVideoURL
    let player = AVPlayer(url: videoURL)
    let playerViewController = AVPlayerViewController()
    playerViewController.player = player

    present(playerViewController, animated: true, completion: {

        playerViewController.player!.play()
    })

// here the course includes a model file, inside it I have given the url, so I am calling the function from model using course function.

// also introductionVideoUrl is a URL which I declared inside model .

 var introductionVideoURL: URL

Also alternatively you can use the below code instead of calling the function from model

Replace this code

  let videoURL = course.introductionVideoURL

with

  guard let videoURL = URL(string: "https://something.mp4) else {
        return

Moving Panel in Visual Studio Code to right side

VSCode 1.42 (January 2020) introduces:

Panel on the left/right

The panel can now be moved to the left side of the editor with the setting:

"workbench.panel.defaultLocation": "left"

This removes the command View: Toggle Panel Position (workbench.action.togglePanelPosition) in favor of the following new commands:

  • View: Move Panel Left (workbench.action.positionPanelLeft)
  • View: Move Panel Right (workbench.action.positionPanelRight)
  • View: Move Panel To Bottom (workbench.action.positionPanelBottom)

How to show full height background image?

You can do it with the code you have, you just need to ensure that html and body are set to 100% height.

Demo: http://jsfiddle.net/kevinPHPkevin/a7eGN/

html, body {
    height:100%;
} 

body {
    background-color: white;
    background-image: url('http://www.canvaz.com/portrait/charcoal-1.jpg');
    background-size: auto 100%;
    background-repeat: no-repeat;
    background-position: left top;
}

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

Another one solution can be used for class components - just override default MUI Theme properties with MuiThemeProvider. This will give more flexibility in comparison with other methods - you can use more than one MuiThemeProvider inside your parent component.

simple steps:

  1. import MuiThemeProvider to your class component
  2. import createMuiTheme to your class component
  3. create new theme
  4. wrap target MUI component you want to style with MuiThemeProvider and your custom theme

please, check this doc for more details: https://material-ui.com/customization/theming/

_x000D_
_x000D_
import React from 'react';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';

import { MuiThemeProvider } from '@material-ui/core/styles';
import { createMuiTheme } from '@material-ui/core/styles';

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

class HigherOrderComponent extends React.Component {

    render(){
        const { classes } = this.props;
        return (
            <MuiThemeProvider theme={InputTheme}>
                <Button className={classes.root}>Higher-order component</Button>
            </MuiThemeProvider>
        );
    }
}

HigherOrderComponent.propTypes = {
    classes: PropTypes.object.isRequired,
};

export default HigherOrderComponent;
_x000D_
_x000D_
_x000D_

Django Forms: if not valid, show form with error message

@AamirAdnan's answer missing field.label; the other way to show the errors in few lines.

{% if form.errors %}
    <!-- Error messaging -->
    <div id="errors">
        <div class="inner">
            <p>There were some errors in the information you entered. Please correct the following:</p>
            <ul>
                {% for field in form %}
                    {% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
                {% endfor %}
            </ul>
        </div>
    </div>
    <!-- /Error messaging -->
{% endif %}

jQuery: Currency Format Number

Divide by 1000, and use .toFixed(3) to fix the number of decimal places.

var output = (input/1000).toFixed(3);

[EDIT]

The above solution only applies if the dot in the original question is for a decimal point. However the OP's comment below implies that it is intended as a thousands separator.

In this case, there isn't a single line solution (Javascript doesn't have it built in), but it can be achieved with a fairly short function.

A good example can be found here: http://www.mredkj.com/javascript/numberFormat.html#addcommas

Alternatively, a more complex string formatting function which mimics the printf() function from the C language can be found here: http://www.diveintojavascript.com/projects/javascript-sprintf

Rendering HTML in a WebView with custom CSS

You can Use Online Css link To set Style over existing content.

For That you have to load data in webview and enable JavaScript Support.

See Below Code:

   WebSettings webSettings=web_desc.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDefaultTextEncodingName("utf-8");
    webSettings.setTextZoom(55);
    StringBuilder sb = new StringBuilder();
    sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
    sb.append(currentHomeContent.getDescription());
    sb.append("</body></HTML>");
    currentWebView.loadDataWithBaseURL("file:///android_asset/", sb.toString(), "text/html", "utf-8", null);

Here Use StringBuilder to append String for Style.

sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
sb.append(currentHomeContent.getDescription());

Increase max_execution_time in PHP?

Add this to an htaccess file (and see edit notes added below):

<IfModule mod_php5.c>
   php_value post_max_size 200M
   php_value upload_max_filesize 200M
   php_value memory_limit 300M
   php_value max_execution_time 259200
   php_value max_input_time 259200
   php_value session.gc_maxlifetime 1200
</IfModule>

Additional resources and information:


2021 EDIT:

As PHP and Apache evolve and grow, I think it is important for me to take a moment to mention a few things to consider and possible "gotchas" to consider:

  • PHP can be run as a module or as CGI. It is not recommended to run as CGI as it creates a lot of opportunities for attack vectors [Read More]. Running as a module (the safer option) will trigger the settings to be used if the specific module from <IfModule is loaded.
  • The answer indicates to write mod_php5.c in the first line. If you are using PHP 7, you would replace that with mod_php7.c.
  • Sometimes after you make changes to your .htaccess file, restarting Apache or NGINX will not work. The most common reason for this is you are running PHP-FPM, which runs as a separate process. You need to restart that as well.
  • Remember these are settings that are normally defined in your php.ini config file(s). This method is usually only useful in the event your hosting provider does not give you access to change those files. In circumstances where you can edit the PHP configuration, it is recommended that you apply these settings there.
  • Finally, it's important to note that not all php.ini settings can be configured via an .htaccess file. A file list of php.ini directives can be found here, and the only ones you can change are the ones in the changeable column with the modes PHP_INI_ALL or PHP_INI_PERDIR.

jQuery How do you get an image to fade in on load?

Simply set the logo's style to display:hidden and call fadeIn, instead of first calling hide:

$(document).ready(function() {
    $('#logo').fadeIn("normal");
});

<img src="logo.jpg" style="display:none"/>

Select distinct values from a large DataTable column

dt- your data table name

ColumnName- your columnname i.e id

DataView view = new DataView(dt);
DataTable distinctValues = new DataTable();
distinctValues = view.ToTable(true, ColumnName);

HTTP POST with URL query parameters -- good idea or not?

From a programmatic standpoint, for the client it's packaging up parameters and appending them onto the url and conducting a POST vs. a GET. On the server-side, it's evaluating inbound parameters from the querystring instead of the posted bytes. Basically, it's a wash.

Where there could be advantages/disadvantages might be in how specific client platforms work with POST and GET routines in their networking stack, as well as how the web server deals with those requests. Depending on your implementation, one approach may be more efficient than the other. Knowing that would guide your decision here.

Nonetheless, from a programmer's perspective, I prefer allowing either a POST with all parameters in the body, or a GET with all params on the url, and explicitly ignoring url parameters with any POST request. It avoids confusion.

How can I remove specific rules from iptables?

The best solution that works for me without any problems looks this way:
1. Add temporary rule with some comment:

comment=$(cat /proc/sys/kernel/random/uuid | sed 's/\-//g')
iptables -A ..... -m comment --comment "${comment}" -j REQUIRED_ACTION

2. When the rule added and you wish to remove it (or everything with this comment), do:

iptables-save | grep -v "${comment}" | iptables-restore

So, you'll 100% delete all rules that match the $comment and leave other lines untouched. This solution works for last 2 months with about 100 changes of rules per day - no issues.Hope, it helps

How to drop columns by name in a data frame

Here's a quick solution for this. Say, you have a data frame X with three columns A, B and C:

> X<-data.frame(A=c(1,2),B=c(3,4),C=c(5,6))
> X
  A B C
1 1 3 5
2 2 4 6

If I want to remove a column, say B, just use grep on colnames to get the column index, which you can then use to omit the column.

> X<-X[,-grep("B",colnames(X))]

Your new X data frame would look like the following (this time without the B column):

> X
  A C
1 1 5
2 2 6

The beauty of grep is that you can specify multiple columns that match the regular expression. If I had X with five columns (A,B,C,D,E):

> X<-data.frame(A=c(1,2),B=c(3,4),C=c(5,6),D=c(7,8),E=c(9,10))
> X
  A B C D  E
1 1 3 5 7  9
2 2 4 6 8 10

Take out columns B and D:

> X<-X[,-grep("B|D",colnames(X))]
> X
  A C  E
1 1 5  9
2 2 6 10

EDIT: Considering the grepl suggestion of Matthew Lundberg in the comments below:

> X<-data.frame(A=c(1,2),B=c(3,4),C=c(5,6),D=c(7,8),E=c(9,10))
> X
  A B C D  E
1 1 3 5 7  9
2 2 4 6 8 10
> X<-X[,!grepl("B|D",colnames(X))]
> X
  A C  E
1 1 5  9
2 2 6 10

If I try to drop a column that's non-existent,nothing should happen:

> X<-X[,!grepl("G",colnames(X))]
> X
  A C  E
1 1 5  9
2 2 6 10

.includes() not working in Internet Explorer

You can do the same with !! and ~ operators

 var myString = 'this is my string';

 !!~myString.indexOf('string');
 // -> true

 !!~myString.indexOf('hello');
 // -> false

here's the explanation of the two operators (!! and ~ )

What is the !! (not not) operator in JavaScript?

https://www.joezimjs.com/javascript/great-mystery-of-the-tilde/

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

You could try this registry hack:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]
"DeadGWDetectDefault"=dword:00000001
"KeepAliveTime"=dword:00120000

If it works, just keep increasing the KeepAliveTime. It is currently set for 2 minutes.

What are some ways of accessing Microsoft SQL Server from Linux?

There is an abstraction lib available for PHP. Not sure what your client's box will support but if its Linux then certainly should support building a PHP query interface with this: http://adodb.sourceforge.net/ Hope that helps you.

Converting 'ArrayList<String> to 'String[]' in Java

List <String> list = ...
String[] array = new String[list.size()];
int i=0;
for(String s: list){
  array[i++] = s;
}

Return index of greatest value in an array

Here is another solution, If you are using ES6 using spread operator:

var arr = [0, 21, 22, 7];

const indexOfMaxValue = arr.indexOf(Math.max(...arr));

Simulate a click on 'a' element using javascript/jquery

Try to use document.createEvent described here https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent

The code for function that simulates click should look something like this:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var a = document.getElementById("gift-close"); 
  a.dispatchEvent(evt);      
}

CSS transition when class removed

Basically set up your css like:

element {
  border: 1px solid #fff;      
  transition: border .5s linear;
}

element.saved {
  border: 1px solid transparent;
}

Project vs Repository in GitHub

In general, on GitHub, 1 repository = 1 project. For example: https://github.com/spring-projects/spring-boot . But it isn't a hard rule.

1 repository = many projects. For example: https://github.com/donhuvy/java_examples

1 projects = many repositories. For example: https://github.com/zendframework/zendframework (1 project named Zend Framework 3 has 61 + 1 = 62 repositories, don't believe? let count Zend Frameworks' modules + main repository)

I totally agree with @Brandon Ibbotson's comment:

A GitHub repository is just a "directory" where folders and files can exist.

Consider marking event handler as 'passive' to make the page more responsive

For those stuck with legacy issues, find the line throwing the error and add {passive: true} - eg:

this.element.addEventListener(t, e, !1)

becomes

this.element.addEventListener(t, e, { passive: true} )