Programs & Examples On #Code caching

Passing Objects By Reference or Value in C#

Objects aren't passed at all. By default, the argument is evaluated and its value is passed, by value, as the initial value of the parameter of the method you're calling. Now the important point is that the value is a reference for reference types - a way of getting to an object (or null). Changes to that object will be visible from the caller. However, changing the value of the parameter to refer to a different object will not be visible when you're using pass by value, which is the default for all types.

If you want to use pass-by-reference, you must use out or ref, whether the parameter type is a value type or a reference type. In that case, effectively the variable itself is passed by reference, so the parameter uses the same storage location as the argument - and changes to the parameter itself are seen by the caller.

So:

public void Foo(Image image)
{
    // This change won't be seen by the caller: it's changing the value
    // of the parameter.
    image = Image.FromStream(...);
}

public void Foo(ref Image image)
{
    // This change *will* be seen by the caller: it's changing the value
    // of the parameter, but we're using pass by reference
    image = Image.FromStream(...);
}

public void Foo(Image image)
{
    // This change *will* be seen by the caller: it's changing the data
    // within the object that the parameter value refers to.
    image.RotateFlip(...);
}

I have an article which goes into a lot more detail in this. Basically, "pass by reference" doesn't mean what you think it means.

Save Javascript objects in sessionStorage

This is a dynamic solution which works with all value types including objects :

class Session extends Map {
  set(id, value) {
    if (typeof value === 'object') value = JSON.stringify(value);
    sessionStorage.setItem(id, value);
  }

  get(id) {
    const value = sessionStorage.getItem(id);
    try {
      return JSON.parse(value);
    } catch (e) {
      return value;
    }
  }
}

Then :

const session = new Session();

session.set('name', {first: 'Ahmed', last : 'Toumi'});
session.get('name');

How do you implement a re-try-catch?

You need to enclose your try-catch inside a while loop like this: -

int count = 0;
int maxTries = 3;
while(true) {
    try {
        // Some Code
        // break out of loop, or return, on success
    } catch (SomeException e) {
        // handle exception
        if (++count == maxTries) throw e;
    }
}

I have taken count and maxTries to avoid running into an infinite loop, in case the exception keeps on occurring in your try block.

How do I measure the execution time of JavaScript code with callbacks?

Surprised no one had mentioned yet the new built in libraries:

Available in Node >= 8.5, and should be in Modern Browers

https://developer.mozilla.org/en-US/docs/Web/API/Performance

https://nodejs.org/docs/latest-v8.x/api/perf_hooks.html#

Node 8.5 ~ 9.x (Firefox, Chrome)

_x000D_
_x000D_
// const { performance } = require('perf_hooks'); // enable for node
const delay = time => new Promise(res=>setTimeout(res,time))
async function doSomeLongRunningProcess(){
  await delay(1000);
}
performance.mark('A');
(async ()=>{
  await doSomeLongRunningProcess();
  performance.mark('B');
  performance.measure('A to B', 'A', 'B');
  const measure = performance.getEntriesByName('A to B')[0];
  // firefox appears to only show second precision.
  console.log(measure.duration);
  // apparently you should clean up...
  performance.clearMarks();
  performance.clearMeasures();         
  // Prints the number of milliseconds between Mark 'A' and Mark 'B'
})();
_x000D_
_x000D_
_x000D_

https://repl.it/@CodyGeisler/NodeJsPerformanceHooks

Node 12.x

https://nodejs.org/docs/latest-v12.x/api/perf_hooks.html

const { PerformanceObserver, performance } = require('perf_hooks');
const delay = time => new Promise(res => setTimeout(res, time))
async function doSomeLongRunningProcess() {
    await delay(1000);
}
const obs = new PerformanceObserver((items) => {
    console.log('PerformanceObserver A to B',items.getEntries()[0].duration);
      // apparently you should clean up...
      performance.clearMarks();
      // performance.clearMeasures(); // Not a function in Node.js 12
});
obs.observe({ entryTypes: ['measure'] });

performance.mark('A');

(async function main(){
    try{
        await performance.timerify(doSomeLongRunningProcess)();
        performance.mark('B');
        performance.measure('A to B', 'A', 'B');
    }catch(e){
        console.log('main() error',e);
    }
})();

How to get default gateway in Mac OSX

Using System Preferences:

Step 1: Click the Apple icon (at the top left of the screen) and select System Preferences.

Step 2: Click Network.

Step 3: Select your network connection and then click Advanced.

Step 4: Select the TCP/IP tab and find your gateway IP address listed next to Router.

AttributeError: 'tuple' object has no attribute

You return four variables s1,s2,s3,s4 and receive them using a single variable obj. This is what is called a tuple, obj is associated with 4 values, the values of s1,s2,s3,s4. So, use index as you use in a list to get the value you want, in order.

obj=list_benefits()
print obj[0] + " is a benefit of functions!"
print obj[1] + " is a benefit of functions!"
print obj[2] + " is a benefit of functions!"
print obj[3] + " is a benefit of functions!"

jQuery Mobile: document ready vs. page events

While you use .on(), it's basically a live query that you are using.

On the other hand, .ready (as in your case) is a static query. While using it, you can dynamically update data and do not have to wait for the page to load. You can simply pass on the values into your database (if required) when a particular value is entered.

The use of live queries is common in forms where we enter data (account or posts or even comments).

Given final block not properly padded

depending on the cryptography algorithm you are using, you may have to add some padding bytes at the end before encrypting a byte array so that the length of the byte array is multiple of the block size:

Specifically in your case the padding schema you chose is PKCS5 which is described here: http://www.rsa.com/products/bsafe/documentation/cryptoj35html/doc/dev_guide/group_CJ_SYM__PAD.html

(I assume you have the issue when you try to encrypt)

You can choose your padding schema when you instantiate the Cipher object. Supported values depend on the security provider you are using.

By the way are you sure you want to use a symmetric encryption mechanism to encrypt passwords? Wouldn't be a one way hash better? If you really need to be able to decrypt passwords, DES is quite a weak solution, you may be interested in using something stronger like AES if you need to stay with a symmetric algorithm.

Nginx fails to load css files

I had the same problem in Windows. I solved it adding: include mime.types; under http{ in my nginx.conf file. Then it still didn't work.. so I looked at the error.log file and I noticed it was trying to charge the .css and javascript files from the file path but with an /http folder between. Ex: my .css was in : "C:\Users\pc\Documents\nginx-server/player-web/css/index.css" and it was taking it from: "C:\Users\pc\Documents\nginx-server/html/player-web/css/index.css" So i changed my player-web folder inside an html folder and it worked ;)

Concatenating null strings in Java

This is behavior specified in the Java API's String.valueOf(Object) method. When you do concatenation, valueOf is used to get the String representation. There is a special case if the Object is null, in which case the string "null" is used.

public static String valueOf(Object obj)

Returns the string representation of the Object argument.

Parameters: obj - an Object.

Returns:

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

Onclick javascript to make browser go back to previous page?

You just need to call the following:

history.go(-1);

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

Just do the following:

build.gradle

(module:app)


android {
            ....
      defaultConfig {
              multiDexEnabled true // enable mun
      }
}

And add below dependency in your build.gradle app level file

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
} 

Rename a dictionary key

I came up with this function which does not mutate the original dictionary. This function also supports list of dictionaries too.

import functools
from typing import Union, Dict, List


def rename_dict_keys(
    data: Union[Dict, List[Dict]], old_key: str, new_key: str
):
    """
    This function renames dictionary keys

    :param data:
    :param old_key:
    :param new_key:
    :return: Union[Dict, List[Dict]]
    """
    if isinstance(data, dict):
        res = {k: v for k, v in data.items() if k != old_key}
        try:
            res[new_key] = data[old_key]
        except KeyError:
            raise KeyError(
                "cannot rename key as old key '%s' is not present in data"
                % old_key
            )
        return res
    elif isinstance(data, list):
        return list(
            map(
                functools.partial(
                    rename_dict_keys, old_key=old_key, new_key=new_key
                ),
                data,
            )
        )
    raise ValueError("expected type List[Dict] or Dict got '%s' for data" % type(data))

How to open a second activity on click of button in android app

Replace the below line code:

import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener{
   Button button;
    @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button1);
        button.setOnClickListener(this);
      }
       public void onClick(View v) {
        if(v.getId==R.id.button1){
      Intent i = new Intent(FromActivity.this, ToActivity.class);
               startActivity(i);
            }
        }
     }

Add the below lines in your manifest file:

   <activity android:name="com.packagename.FromActivity"></activity>
   <activity android:name="com.packagename.ToActivity"></activity>

Center/Set Zoom of Map to cover all visible Markers?

You need to use the fitBounds() method.

var markers = [];//some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
 bounds.extend(markers[i]);
}

map.fitBounds(bounds);

Documentation from developers.google.com/maps/documentation/javascript:

fitBounds(bounds[, padding])

Parameters:

`bounds`:  [`LatLngBounds`][1]|[`LatLngBoundsLiteral`][1]
`padding` (optional):  number|[`Padding`][1]

Return Value: None

Sets the viewport to contain the given bounds.
Note: When the map is set to display: none, the fitBounds function reads the map's size as 0x0, and therefore does not do anything. To change the viewport while the map is hidden, set the map to visibility: hidden, thereby ensuring the map div has an actual size.

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

When is the finalize() method called in Java?

protected void finalize() throws Throwable {}
  • every class inherits the finalize() method from java.lang.Object
  • the method is called by the garbage collector when it determines no more references to the object exist
  • the Object finalize method performs no actions but it may be overridden by any class
  • normally it should be overridden to clean-up non-Java resources ie closing a file
  • if overridding finalize() it is good programming practice to use a try-catch-finally statement and to always call super.finalize(). This is a safety measure to ensure you do not inadvertently miss closing a resource used by the objects calling class

    protected void finalize() throws Throwable {
         try {
             close();        // close open files
         } finally {
             super.finalize();
         }
     }
    
  • any exception thrown by finalize() during garbage collection halts the finalization but is otherwise ignored

  • finalize() is never run more than once on any object

quoted from: http://www.janeg.ca/scjp/gc/finalize.html

You could also check this article:

unable to remove file that really exists - fatal: pathspec ... did not match any files

In my instance, there was something completely odd that I'm not sure what the cause was. An entire folder was committed previously. I could see it in Git, Windows Explorer, and GitHub, but any changes I made to the folder itself and the files in it were ignored. Using git check-ignore to see what was ignoring it, and attempting to remove it using git rm --cached had no impact. The changes were not able to be staged.

I fixed it by:

  1. Making a copy of the folder and files in another location.
  2. I deleted the original that was getting ignored somehow.
  3. Commit and push this update.
  4. Finally, I added the files and folder back and git was seeing and reacting to it as expected again.
  5. Stage and commit this, and you're good to go! :)

Bootstrap trying to load map file. How to disable it? Do I need to do it?

Delete /*# sourceMappingURL=bootstrap.min.css.map */ in css/bootstrap.min.css

and delete /*# sourceMappingURL=bootstrap.css.map */ in css/bootstrap.css

What's the difference between display:inline-flex and display:flex?

flex and inline-flex both apply flex layout to children of the container. Container with display:flex behaves like a block-level element itself, while display:inline-flex makes the container behaves like an inline element.

Object not found! The requested URL was not found on this server. localhost

If the page you are visiting is index.php, then your url should look like

http://localhost/test/content/home/ OR http://localhost/test/content/home/index.php

not the way you specified - http://localhost/test/content/home

Specified cast is not valid.. how to resolve this

If you are expecting double, decimal, float, integer why not use the one which accomodates all namely decimal (128 bits are enough for most numbers you are looking at).

instead of (double)value use decimal.Parse(value.ToString()) or Convert.ToDecimal(value)

Setting up a git remote origin

You can include the branch to track when setting up remotes, to keep things working as you might expect:

git remote add --track master origin [email protected]:group/project.git   # git
git remote add --track master origin [email protected]:group/project.git   # git w/IP
git remote add --track master origin http://github.com/group/project.git   # http
git remote add --track master origin http://172.16.1.100/group/project.git # http w/IP
git remote add --track master origin /Volumes/Git/group/project/           # local
git remote add --track master origin G:/group/project/                     # local, Win

This keeps you from having to manually edit your git config or specify branch tracking manually.

Execute function after Ajax call is complete

Add .done() to your function

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({                                            
         url: 'api.php',                        
         data: 'id1='+q+'',                                                         
         dataType: 'json',
         async:false,                    
         success: function(data)          
         {   
            id = data[0];              
            vname = data[1];
         }
      }).done(function(){
           printWithAjax(); 
      });



 }//end of the for statement
}//end of ajax call function

insert password into database in md5 format?

Don't use MD5 as it is insecure. I would recommend using SHA or bcrypt with a salt:

SHA256('".$password."')

http://en.wikipedia.org/wiki/Salt_(cryptography)

Make a td fixed size (width,height) while rest of td's can expand

This will take care of the empty td:

<td style="min-width: 20px;"></td>

Reportviewer tool missing in visual studio 2017 RC

** Update**: 11/19/2019

Microsoft has released a new version of the control 150.1400.0 in their Nuget library. My short testing shows that it works again in the forms designer where 150.1357.0 and 150.1358.0 did not. This includes being able to resize and modify the ReportViewer Tasks on the control itself.

** Update**: 8/18/2019

Removing the latest version and rolling back to 150.900.148.0 seems to work on multiple computers I'm using with VS2017 and VS2019.

You can roll back to 150.900.148 in the Nuget solution package manager. It works similarly to the previous versions. Use the drop down box to select the older version.

enter image description here

It may be easier to manually delete references to post 150.900 versions of ReportViewer and readd them than it is to fix them.

Remember to restart Visual Studio after changing the toolbox entry.

Update: 8/7/2019

A newer version of the ReportViewer control has been released, probably coinciding with Visual Studio 2019. I was working with V150.1358.0.

Following the directions in this answer gets the control in the designer's toolbox. But once dropped on the form it doesn't display. The control shows up below the form as a non-visual component.

This is working as designed according to Microsoft SQL BI support. This is the group responsible for the control.

While you still cannot interact with the control directly, these additional steps give a workaround so the control can be sized on the form. While now visible, the designer treats the control as if it didn't exist.

I've created a feedback request at the suggestion of Microsoft SQL BI support. Please consider voting on it to get Microsoft's attention.

Microsoft Azure Feedback page - Restore Designtime features of the WinForms ReportViewer Control

Additional steps:

  • After adding the reportviewer to the WinForm
  • Add a Panel Control to the WinForm.
  • In the form's form.designer.cs file, add the Reportviewer control to the panel.

      // 
      // panel1
      // 
      this.panel1.Controls.Add(this.reportViewer1);
    
  • Return to the form's designer, you should see the reportViewer on the panel

  • In the Properties panel select the ReportViewer in the controls list dropdown
  • Set the reportViewer's Dock property to Fill

Now you can position the reportViewer by actually interacting with the panel.

Update: Microsoft released a document on April 18, 2017 describing how to configure and use the reporting tool in Visual Studio 2017.

Visual Studio 2017 does not have the ReportViewer tool installed by default in the ToolBox. Installing the extension Microsoft Rdlc Report Designer for Visual Studio and then adding that to the ToolBox results in a non-visual component that appears below the form.

Microsoft Support had told me this is a bug, but as of April 21, 2017 it is "working as designed".

The following steps need to be followed for each project that requires ReportViewer.

  • If you have ReportViewer in the Toolbox, remove it. Highlight, right-click and delete.
    • You will have to have a project with a form open to do this.

Edited 8/7/2019 - It looks like the current version of the RDLC Report Designer extension no longer interferes. You need this to actually edit the reports.

  • If you have the Microsoft Rdlc Report Designer for Visual Studio extension installed, uninstall it.

  • Close your solution and restart Visual Studio. This is a crucial step, errors will occur if VS is not restarted when switching between solutions.

  • Open your solution.
  • Open the NuGet Package Manager Console (Tools/NuGet Package Manager/Package Manager Console)
  • At the PM> prompt enter this command, case matters.

    Install-Package Microsoft.ReportingServices.ReportViewerControl.WinForms

    You should see text describing the installation of the package.

Now we can temporarily add the ReportViewer tool to the tool box.

  • Right-click in the toolbox and use Choose Items...

  • We need to browse to the proper DLL that is located in the solutions Packages folder, so hit the browse button.

  • In our example we can paste in the packages folder as shown in the text of Package Manager Console.

    C:\Users\jdoe\Documents\Projects\_Test\ReportViewerTest\WindowsFormsApp1\packages

  • Then double click on the folder named Microsoft.ReportingServices.ReportViewerControl.Winforms.140.340.80

    The version number will probably change in the future.

  • Then double-click on lib and again on net40.

  • Finally, double click on the file Microsoft.ReportViewer.WinForms.dll

    You should see ReportViewer checked in the dialog. Scroll to the right and you will see the version 14.0.0.0 associated to it.

  • Click OK.

ReportViewer is now located in the ToolBox.

  • Drag the tool to the desired form(s).

  • Once completed, delete the ReportViewer tool from the tool box. You can't use it with another project.

  • You may save the project and are good to go.

Remember to restart Visual Studio any time you need to open a project with ReportViewer so that the DLL is loaded from the correct location. If you try and open a solution with a form with ReportViewer without restarting you will see errors indicating that the “The variable 'reportViewer1' is either undeclared or was never assigned.“.

If you add a new project to the same solution you need to create the project, save the solution, restart Visual Studio and then you should be able to add the ReportViewer to the form. I have seen it not work the first time and show up as a non-visual component.

When that happens, removing the component from the form, deleting the Microsoft.ReportViewer.* references from the project, saving and restarting usually works.

Tomcat won't stop or restart

You can go to the location ${CATALINA_HOME}/logs/ open catalina.pid. Here we will get the pid. then terminate the process. kill -9 pid

Testing if a checkbox is checked with jQuery

Try this

$('input:checkbox:checked').click(function(){
    var val=(this).val(); // it will get value from checked checkbox;
})

Here flag is true if checked otherwise false

var flag=$('#ans').attr('checked');

Again this will make cheked

$('#ans').attr('checked',true);

Creating stored procedure and SQLite?

If you are still interested, Chris Wolf made a prototype implementation of SQLite with Stored Procedures. You can find the details at his blog post: Adding Stored Procedures to SQLite

Select option padding not working in chrome

You can use font-size property for option if you need.

How to get StackPanel's children to fill maximum space downward?

You can use SpicyTaco.AutoGrid - a modified version of StackPanel:

<st:StackPanel Orientation="Horizontal" MarginBetweenChildren="10" Margin="10">
   <Button Content="Info" HorizontalAlignment="Left" st:StackPanel.Fill="Fill"/>
   <Button Content="Cancel"/>
   <Button Content="Save"/>
</st:StackPanel>

First button will be fill.

You can install it via NuGet:

Install-Package SpicyTaco.AutoGrid

I recommend taking a look at SpicyTaco.AutoGrid. It's very useful for forms in WPF instead of DockPanel, StackPanel and Grid and solve problem with stretching very easy and gracefully. Just look at readme on GitHub.

<st:AutoGrid Columns="160,*" ChildMargin="3">
    <Label Content="Name:"/>
    <TextBox/>

    <Label Content="E-Mail:"/>
    <TextBox/>

    <Label Content="Comment:"/>
    <TextBox/>
</st:AutoGrid>

How to run a Command Prompt command with Visual Basic code?

Or, you could do it the really simple way.

Dim OpenCMD 
OpenCMD = CreateObject("wscript.shell")
OpenCMD.run("Command Goes Here")

Is it possible to remove inline styles with jQuery?

The Lazy way (which will cause future designers to curse your name and murder you in your sleep):

#myelement 
{
    display: none !important;
}

Disclaimer: I do not advocate this approach, but it certainly is the lazy way.

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

If you start a 64 bit virtual machine on a 32 bit host machine you will get this error.

Android center view in FrameLayout doesn't work

I'd suggest a RelativeLayout instead of a FrameLayout.

Assuming that you want to have the TextView always below the ImageView I'd use following layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true"
        android:src="@drawable/icon"
        android:visibility="visible"/>
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_below="@id/imageview"
        android:gravity="center"
        android:text="@string/hello"/>
</RelativeLayout>

Note that if you set the visibility of an element to gone then the space that element would consume is gone whereas when you use invisible instead the space it'd consume will be preserved.

If you want to have the TextView on top of the ImageView then simply leave out the android:layout_alignParentTop or set it to false and on the TextView leave out the android:layout_below="@id/imageview" attribute. Like this.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="false"
        android:layout_centerInParent="true"
        android:src="@drawable/icon"
        android:visibility="visible"/>
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="@string/hello"/>
</RelativeLayout>

I hope this is what you were looking for.

How to make Toolbar transparent?

All you need to is to define theme which hide action bar, define action bar style with transparent background and set this style to the toolbar widget. Please note that toolbar should be drawen as last view (over all view tree)

<style name="Theme.Custom" parent="@android:style/Theme.AppCompat">
    <item name="windowActionBar">false</item>
    <item name="windowActionBarOverlay">true</item>
    <item name="android:windowActionBarOverlay">true</item>
</style>

<style name="CustomActionBar" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:windowActionBarOverlay">true</item>
    <!-- Support library compatibility -->
    <item name="windowActionBarOverlay">true</item>
</style>

Layout:

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

    <!-- Toolbar should be above content-->
    <include layout="@layout/toolbar" />

</RelativeLayout>

Toolbar layout:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:theme="@style/CustomActionBar"/>

Android Emulator sdcard push error: Read-only file system

I had this problem on Android L developer preview, and, at least for this version, I solved it by creating an sdcard with a size that had square 2 size (e.g 128M, 256M etc)

VBA Subscript out of range - error 9

Suggest the following simplification: capture return value from Workbooks.Add instead of subscripting Windows() afterward, as follows:

Set wkb = Workbooks.Add
wkb.SaveAs ...

wkb.Activate ' instead of Windows(expression).Activate


General Philosophy Advice:

Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.

Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.

Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection

During and within macros do not rely on these built-in names, instead capture return values, e.g.

Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate

Also, try to use qualified expressions, e.g.

wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"

or

Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"

Use qualified expressions, e.g.

newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar" 

These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.

Also please note that you'll likely find that you don't need to .Activate nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate could simply be eliminated instead of even being replaced by wkb.Activate.

(Also note: I think the .Select statements you show are not contributing and can be omitted.)

(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

I was getting the same error message in VS 2012, but was not running as Administrator. When I ran the app as administrator, I got a different and slightly more helpful message (which I was able to figure out). HTH

How do I measure request and response times at once using cURL?

here is the string you can use with -w, contains all options that curl -w supports.

{"contentType":"%{content_type}","filenameEffective":"%{filename_effective}","ftpEntryPath":"%{ftp_entry_path}","httpCode":"%{http_code}","httpConnect":"%{http_connect}","httpVersion":"%{http_version}","localIp":"%{local_ip}","localPort":"%{local_port}","numConnects":"%{num_connects}","numRedirects":"%{num_redirects}","proxySslVerifyResult":"%{proxy_ssl_verify_result}","redirectUrl":"%{redirect_url}","remoteIp":"%{remote_ip}","remotePort":"%{remote_port}","scheme":"%{scheme}","size":{"download":"%{size_download}","header":"%{size_header}","request":"%{size_request}","upload":"%{size_upload}"},"speed":{"download":"%{speed_download}","upload":"%{speed_upload}"},"sslVerifyResult":"%{ssl_verify_result}","time":{"appconnect":"%{time_appconnect}","connect":"%{time_connect}","namelookup":"%{time_namelookup}","pretransfer":"%{time_pretransfer}","redirect":"%{time_redirect}","starttransfer":"%{time_starttransfer}","total":"%{time_total}"},"urlEffective":"%{url_effective}"}

outputs JSON.

White space at top of page

If nothing of the above helps, check if there is margin-top set on some of the (some levels below) nested DOM element(s).

It will be not recognizable when you inspect body element itself in the debugger. It will only be visible when you unfold several elements nested down in body element in Chrome Dev Tools elements debugger and check if there is one of them with margin-top set.

The below is the upper part of a site screen shot and the corresponding Chrome Dev Tools view when you inspect body tag.

No sign of top margin here and you have resetted all the browser-scpecific CSS properties as per answers above but that unwanted white space is still here.

The unwanted white space above the body element The corresponding debugger view

The following is a view when you inspect the right nested element. It is clearly seen the orange'ish top-margin is set on it. This is the one that causes the white space on top of body element.

Clearly visible top-margin enter image description here

On that found element replace margin-top with padding-top if you need space above it and yet not to leak it above the body tag.

Hope that helps :)

Reload parent window from child window

No jQuery is necessary in this situation.

window.opener.location.reload(false);

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

How to add double quotes to a string that is inside a variable?

If I understand your question properly, maybe you can try this:

string title = string.Format("<div>\"{0}\"</div>", "some text");

How do you check that a number is NaN in JavaScript?

It seems that isNaN() is not supported in Node.js out of the box.
I worked around with

var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);

The best way to remove duplicate values from NSMutableArray in Objective-C?

Available in OS X v10.7 and later.

If you are worried about the order,right way to do

NSArray *no = [[NSOrderedSet orderedSetWithArray:originalArray]allObjects];

Here is the code of removing duplicates values from NSArray in Order.

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

[Quick Answer]

There are a problem with Metro using some NPM and Node versions.

You can fix the problem changing some code in the file \node_modules\metro-config\src\defaults\blacklist.js .

Search this variable:

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

and change to this:

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

Please note that if you run an npm install or a yarn install you need to change the code again.

Extract number from string with Oracle function

This works for me, I only need first numbers in string:

TO_NUMBER(regexp_substr(h.HIST_OBSE, '\.*[[:digit:]]+\.*[[:digit:]]*'))

the field had the following string: "(43 Paginas) REGLAS DE PARTICIPACION".

result field: 43

Java check to see if a variable has been initialized

Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.

Now if you know that once assigned, the value will never reassigned a value of null, you can use:

if (box != null) {
    box.removeFromCanvas();
}

(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:

if (box != null) {
    box.removeFromCanvas();
    // Forget about the box - we don't want to try to remove it again
    box = null;
}

The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):

// Won't compile
String x;
System.out.println(x);

// Will compile, prints null
String y = null;
System.out.println(y);

Delete rows containing specific strings in R

You can use stri_detect_fixed function from stringi package

stri_detect_fixed(c("REVERSE223","GENJJS"),"REVERSE")
[1]  TRUE FALSE

How to add jQuery in JS file

var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

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

You need to add the package containing the executable pg_config.

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

How do you set EditText to only accept numeric values in Android?

using the below can solve your problem better;

in xml:

<EditText
      android:id="@+id/age"
      android:inputType="numberDecimal|numberSigned"        />

or //in activity inside etfield.addtextchangelistener

     private String blockCharacterSet="+(/)N,*;#";//declare globally
               try {
                for (int i = 0; i < s.length(); i++) {


                    if (blockCharacterSet.contains(s.charAt(i) + "")) {

                        String corrected_settempvalue = arrivalsettemp.substring(0, arrivalsettemp.length() - 1);
                        et_ArrivalSetTemp.setText(corrected_settempvalue);
                        if (corrected_settempvalue.length() != 0)
                            et_ArrivalSetTemp.setSelection(corrected_settempvalue.length());

                    }
                }
            } catch (Exception d) {
                d.printStackTrace();
            }

Printing all global variables/local variables?

Type info variables to list "All global and static variable names".

Type info locals to list "Local variables of current stack frame" (names and values), including static variables in that function.

Type info args to list "Arguments of the current stack frame" (names and values).

Nodejs send file in response

Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.

[Update] As mentioned by @Aftershock in the comments, util.pump is gone and was replaced with a method on the Stream prototype called pipe; the code below reflects this.

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, 'myfile.mp3');
    var stat = fileSystem.statSync(filePath);

    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stat.size
    });

    var readStream = fileSystem.createReadStream(filePath);
    // We replaced all the event handlers with a simple call to readStream.pipe()
    readStream.pipe(response);
})
.listen(2000);

Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/

Import XXX cannot be resolved for Java SE standard classes

This is an issue relating JRE.In my case (eclipse Luna with Maven plugin, JDK 7) I solved this by making following change in pom.xml and then Maven Update Project.

from:

 <configuration>
        <source>1.8</source>
        <target>1.8</target>
</configuration>

to:

 <configuration>
        <source>1.7</source>
        <target>1.7</target>
</configuration>

Screenshot showing problem in JRE: enter image description here

How to set up a PostgreSQL database in Django

This may seem a bit lengthy, but it worked for me without any error.

At first, Install phppgadmin from Ubuntu Software Center.

Then run these steps in terminal.

sudo apt-get install libpq-dev python-dev
pip install psycopg2
sudo apt-get install postgresql postgresql-contrib phppgadmin

Start the apache server

sudo service apache2 start

Now run this too in terminal, to edit the apache file.

sudo gedit /etc/apache2/apache2.conf

Add the following line to the opened file:

Include /etc/apache2/conf.d/phppgadmin

Now reload apache. Use terminal.

sudo /etc/init.d/apache2 reload

Now you will have to create a new database. Login as 'postgres' user. Continue in terminal.

sudo su - postgres

In case you have trouble with the password of 'postgres', you can change it using the answer here https://stackoverflow.com/a/12721020/1990793 and continue with the steps.

Now create a database

createdb <db_name>

Now create a new user to login to phppgadmin later, providing a new password.

createuser -P <new_user>

Now your postgressql has been setup, and you can go to:

http://localhost/phppgadmin/

and login using the new user you've created, in order to view the database.

How to iterate through a String

How about this

for (int i = 0; i < str.length(); i++) { 
    System.out.println(str.substring(i, i + 1)); 
} 

Converting bool to text in C++

This should be fine:


const char* bool_cast(const bool b) {
    return b ? "true" : "false";
}

But, if you want to do it more C++-ish:


#include <iostream>
#include <string>
#include <sstream>
using namespace std;

string bool_cast(const bool b) {
    ostringstream ss;
    ss << boolalpha << b;
    return ss.str();
}

int main() {
    cout << bool_cast(true) << "\n";
    cout << bool_cast(false) << "\n";
}

What does 'var that = this;' mean in JavaScript?

This is a hack to make inner functions (functions defined inside other functions) work more like they should. In javascript when you define one function inside another this automatically gets set to the global scope. This can be confusing because you expect this to have the same value as in the outer function.

var car = {};
car.starter = {};

car.start = function(){
    var that = this;

    // you can access car.starter inside this method with 'this'
    this.starter.active = false;

    var activateStarter = function(){
        // 'this' now points to the global scope
        // 'this.starter' is undefined, so we use 'that' instead.
        that.starter.active = true;

        // you could also use car.starter, but using 'that' gives
        // us more consistency and flexibility
    };

    activateStarter();

};

This is specifically a problem when you create a function as a method of an object (like car.start in the example) then create a function inside that method (like activateStarter). In the top level method this points to the object it is a method of (in this case, car) but in the inner function this now points to the global scope. This is a pain.

Creating a variable to use by convention in both scopes is a solution for this very general problem with javascript (though it's useful in jquery functions, too). This is why the very general sounding name that is used. It's an easily recognizable convention for overcoming a shortcoming in the language.

Like El Ronnoco hints at Douglas Crockford thinks this is a good idea.

Should I use PATCH or PUT in my REST API?

The PATCH method is the correct choice here as you're updating an existing resource - the group ID. PUT should only be used if you're replacing a resource in its entirety.

Further information on partial resource modification is available in RFC 5789. Specifically, the PUT method is described as follows:

Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

Failed to load AppCompat ActionBar with unknown error in android studio

Try this:

Just change:

compile 'com.android.support:appcompat-v7:26.0.0-beta2'

to:

compile 'com.android.support:appcompat-v7:26.0.0-beta1'

Reference

Comparing two dataframes and getting the differences

I tried this method, and it worked. I hope it can help too:

"""Identify differences between two pandas DataFrames"""
df1.sort_index(inplace=True)
df2.sort_index(inplace=True)
df_all = pd.concat([df1, df12], axis='columns', keys=['First', 'Second'])
df_final = df_all.swaplevel(axis='columns')[df1.columns[1:]]
df_final[df_final['change this to one of the columns'] != df_final['change this to one of the columns']]

Permutations between two lists of unequal length

Answering the question "given two lists, find all possible permutations of pairs of one item from each list" and using basic Python functionality (i.e., without itertools) and, hence, making it easy to replicate for other programming languages:

def rec(a, b, ll, size):
    ret = []
    for i,e in enumerate(a):
        for j,f in enumerate(b):
            l = [e+f]
            new_l = rec(a[i+1:], b[:j]+b[j+1:], ll, size)
            if not new_l:
                ret.append(l)
            for k in new_l:
                l_k = l + k
                ret.append(l_k)
                if len(l_k) == size:
                    ll.append(l_k)
    return ret

a = ['a','b','c']
b = ['1','2']
ll = []
rec(a,b,ll, min(len(a),len(b)))
print(ll)

Returns

[['a1', 'b2'], ['a1', 'c2'], ['a2', 'b1'], ['a2', 'c1'], ['b1', 'c2'], ['b2', 'c1']]

how to convert image to byte array in java?

I think the best way to do that is to first read the file into a byte array, then convert the array to an image with ImageIO.read()

ActiveXObject creation error " Automation server can't create object"

For this to work you have to really, really loosen your security settings (generally NOT recommended)

You will need to add the website to your "Trusted Zone", then go into the custom settings (scroll about 1/2 way down the page) and change:

ActiveX controls and plugins - Enable (or prompt)... any of the settings that apply to your code (I think the very last one is the one you are hitting) -- "script ActiveX controls marked safe for scripting*"

That all said, unless you have a really, really good reason for doing this - you are opening up a major "hole" in your browsers security... step very carefully... and do not expect that other end users will be willing to do the same.

Recursive Fibonacci

int fib(int x) 
{
    if (x == 0)
      return 0;
    else if (x == 1 || x == 2) 
      return 1;
    else 
      return (fib(x - 1) + fib(x - 2));
}

Appending to 2D lists in Python

Came here to see how to append an item to a 2D array, but the title of the thread is a bit misleading because it is exploring an issue with the appending.

The easiest way I found to append to a 2D list is like this:

list=[[]]

list.append((var_1,var_2))

This will result in an entry with the 2 variables var_1, var_2. Hope this helps!

How do I handle newlines in JSON?

You might want to look into this C# function to escape the string:

http://www.aspcode.net/C-encode-a-string-for-JSON-JavaScript.aspx

public static string Enquote(string s)  
{ 
    if (s == null || s.Length == 0)  
    { 
        return "\"\""; 
    } 
    char         c; 
    int          i; 
    int          len = s.Length; 
    StringBuilder sb = new StringBuilder(len + 4); 
    string       t; 

    sb.Append('"'); 
    for (i = 0; i < len; i += 1)  
    { 
        c = s[i]; 
        if ((c == '\\') || (c == '"') || (c == '>')) 
        { 
            sb.Append('\\'); 
            sb.Append(c); 
        } 
        else if (c == '\b') 
            sb.Append("\\b"); 
        else if (c == '\t') 
            sb.Append("\\t"); 
        else if (c == '\n') 
            sb.Append("\\n"); 
        else if (c == '\f') 
            sb.Append("\\f"); 
        else if (c == '\r') 
            sb.Append("\\r"); 
        else 
        { 
            if (c < ' ')  
            { 
                //t = "000" + Integer.toHexString(c); 
                string t = new string(c,1); 
                t = "000" + int.Parse(tmp,System.Globalization.NumberStyles.HexNumber); 
                sb.Append("\\u" + t.Substring(t.Length - 4)); 
            }  
            else  
            { 
                sb.Append(c); 
            } 
        } 
    } 
    sb.Append('"'); 
    return sb.ToString(); 
} 

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

The Function adds gaussian , salt-pepper , poisson and speckle noise in an image

Parameters
----------
image : ndarray
    Input image data. Will be converted to float.
mode : str
    One of the following strings, selecting the type of noise to add:

    'gauss'     Gaussian-distributed additive noise.
    'poisson'   Poisson-distributed noise generated from the data.
    's&p'       Replaces random pixels with 0 or 1.
    'speckle'   Multiplicative noise using out = image + n*image,where
                n is uniform noise with specified mean & variance.


import numpy as np
import os
import cv2
def noisy(noise_typ,image):
   if noise_typ == "gauss":
      row,col,ch= image.shape
      mean = 0
      var = 0.1
      sigma = var**0.5
      gauss = np.random.normal(mean,sigma,(row,col,ch))
      gauss = gauss.reshape(row,col,ch)
      noisy = image + gauss
      return noisy
   elif noise_typ == "s&p":
      row,col,ch = image.shape
      s_vs_p = 0.5
      amount = 0.004
      out = np.copy(image)
      # Salt mode
      num_salt = np.ceil(amount * image.size * s_vs_p)
      coords = [np.random.randint(0, i - 1, int(num_salt))
              for i in image.shape]
      out[coords] = 1

      # Pepper mode
      num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
      coords = [np.random.randint(0, i - 1, int(num_pepper))
              for i in image.shape]
      out[coords] = 0
      return out
  elif noise_typ == "poisson":
      vals = len(np.unique(image))
      vals = 2 ** np.ceil(np.log2(vals))
      noisy = np.random.poisson(image * vals) / float(vals)
      return noisy
  elif noise_typ =="speckle":
      row,col,ch = image.shape
      gauss = np.random.randn(row,col,ch)
      gauss = gauss.reshape(row,col,ch)        
      noisy = image + image * gauss
      return noisy

Process list on Linux via Python

The sanctioned way of creating and using child processes is through the subprocess module.

import subprocess
pl = subprocess.Popen(['ps', '-U', '0'], stdout=subprocess.PIPE).communicate()[0]
print pl

The command is broken down into a python list of arguments so that it does not need to be run in a shell (By default the subprocess.Popen does not use any kind of a shell environment it just execs it). Because of this we cant simply supply 'ps -U 0' to Popen.

Negative list index?

List indexes of -x mean the xth item from the end of the list, so n[-1] means the last item in the list n. Any good Python tutorial should have told you this.

It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1] to access the last item of a list.

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

On Chrome's latest update (38.0.2125.104 m at the moment), Google added the option to know whether the files loaded to the website were newly downloaded from the server - or read from the local cache.

When an error like yours "hits" the console - you know the files were just downloaded from the server and not read from the local cache. You can recreate this error by clicking Ctrl + F5 (refresh and erase cache).

It fits your description where Firebug (or equivalents) doesn't fire any errors to the console - whilst Chrome does.

So, the bottom line is - your're just fine and you can ignore this error - it's merely an indicator.

Java 8: Lambda-Streams, Filter by Method with Exception

To properly add IOException (to RuntimeException) handling code, your method will look like this:

Stream<Account> s =  accounts.values().stream();

s = s.filter(a -> { try { return a.isActive(); } 
  catch (IOException e) { throw new RuntimeException(e); }});

Stream<String> ss = s.map(a -> { try { return a.getNumber() }
  catch (IOException e) { throw new RuntimeException(e); }});

return ss.collect(Collectors.toSet());

The problem now is that the IOException will have to be captured as a RuntimeException and converted back to an IOException -- and that will add even more code to the above method.

Why use Stream when it can be done just like this -- and the method throws IOException so no extra code is needed for that too:

Set<String> set = new HashSet<>();
for(Account a: accounts.values()){
  if(a.isActive()){
     set.add(a.getNumber());
  } 
}
return set;

Search a text file and print related lines in Python?

with open('file.txt', 'r') as searchfile:
    for line in searchfile:
        if 'searchphrase' in line:
            print line

With apologies to senderle who I blatantly copied.

Redirecting Output from within Batch file

if you want both out and err streams redirected

dir >> a.txt 2>&1

How to convert data.frame column from Factor to numeric

As an alternative to $dollarsign notation, use a within block:

breast <- within(breast, {
  class <- as.numeric(as.character(class))
})

Note that you want to convert your vector to a character before converting it to a numeric. Simply calling as.numeric(class) will not the ids corresponding to each factor level (1, 2) rather than the levels themselves.

How to programmatically open the Permission Screen for a specific app on Android Marshmallow?

Xamarin Forms Android:

//---------------------------------------------------------
public void OpenSettings()
//---------------------------------------------------------
{
    var intent = new Intent(Android.Provider.Settings.ActionApplicationDetailsSettings,
        Android.Net.Uri.Parse("package:" + Forms.Context.PackageName));
    Forms.Context.StartActivity(intent);
}

Reflection generic get field value

 Integer typeValue = 0;
 try {
     Class<Types> types = Types.class;
     java.lang.reflect.Field field = types.getDeclaredField("Type");
     field.setAccessible(true);
     Object value = field.get(types);
     typeValue = (Integer) value;
 } catch (Exception e) {
     e.printStackTrace();
 }

C++ - unable to start correctly (0xc0150002)

It is because there is a DLL that your program is missing or can't find.

In your case I believe you are missing the openCV dlls. You can find these under the "build" directory that comes with open CV. If you are using VS2010 and building to an x86 program you can locate your dlls here under "opencv\build\x86\vc10\bin". Simply copy all these files to your Debug and Release folders and it should resolve your issues.

Generally you can resolve this issue using the following procedure:

  1. Download Dependency Walker from here: http://www.dependencywalker.com/
  2. Load your .exe file into Dependency Walker (under your projects Debug or Release folder), in your case this would be DisplayImage.exe
  3. Look for any DLL's that are missing, or are corrupt, or are for the wrong architecture (i.e. x64 instead of x86) these will be highlighted in red.
  4. For each DLL that you are missing either copy to your Debug or Release folders with your .exe, or install the required software, or add the path to the DLLs to your environment variables (Win+Pause -> Advanced System Settings -> Environment Variables)

Remember that you will need to have these DLLs in the same directory as your .exe. If you copy the .exe from the Release folder to somewhere else then you will need those DLLs copied with the .exe as well. For portability I tend to try and have a test Virtual Machine with a clean install of Windows (no updates or programs installed), and I walk through the Dependencies using the Dependency Walker one by one until the program is running happily.

This is a common problem. Also see these questions:

Can't run a vc++, error code 0xc0150002

The application was unable to start (0xc0150002) with libcurl C++ Windows 7 VS 2010

0xc0150002 Error when trying to run VC++ libcurl

The application was unable to start correctly 0xc150002

The application was unable to start correctly (0*0150002) - OpenCv

Good Luck!

How to increase the distance between table columns in HTML?

There isn't any need for fake <td>s. Make use of border-spacing instead. Apply it like this:

HTML:

<table>
  <tr>
    <td>First Column</td>
    <td>Second Column</td>
    <td>Third Column</td>
  </tr>
</table>

CSS:

table {
  border-collapse: separate;
  border-spacing: 50px 0;
}

td {
  padding: 10px 0;
}

See it in action.

Text that shows an underline on hover

<span class="txt">Some Text</span>

.txt:hover {
    text-decoration: underline;
}

How can I flush GPU memory using CUDA (physical reset is unavailable)

for the ones using python:

import torch, gc
gc.collect()
torch.cuda.empty_cache()

<SELECT multiple> - how to allow only one item selected?

I am coming here after searching google and change thing at my-end.

So I just change this sample and it will work with jquery at run-time.

$('select[name*="homepage_select"]').removeAttr('multiple')

http://jsfiddle.net/ajayendra2707/ejkxgy1p/5/

Delete files or folder recursively on Windows CMD

If you want to delete a specific extension recursively, use this:

For /R "C:\Users\Desktop\saleh" %G IN (*.ppt) do del "%G"

How do you programmatically set an attribute?

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don't work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

JUnit Eclipse Plugin?

You might want to try out Quick JUnit: https://marketplace.eclipse.org/content/quick-junit

The plugin is stable and it allows switching between production and test code. I am currently using Eclipse Mars 4.5 and the plugin is supported for this release as well as for the following:

Luna (4.4), Kepler (4.3), Juno (4.2, 3.8), Previous to Juno (<=4.1)

Understanding Apache's access log

And what does "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.5 Safari/535.19" means ?

This is the value of User-Agent, the browser identification string.

For this reason, most Web browsers use a User-Agent string value as follows:

Mozilla/[version] ([system and browser information]) [platform] ([platform details]) [extensions]. For example, Safari on the iPad has used the following:

Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405 The components of this string are as follows:

Mozilla/5.0: Previously used to indicate compatibility with the Mozilla rendering engine. (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us): Details of the system in which the browser is running. AppleWebKit/531.21.10: The platform the browser uses. (KHTML, like Gecko): Browser platform details. Mobile/7B405: This is used by the browser to indicate specific enhancements that are available directly in the browser or through third parties. An example of this is Microsoft Live Meeting which registers an extension so that the Live Meeting service knows if the software is already installed, which means it can provide a streamlined experience to joining meetings.

This value will be used to identify what browser is being used by end user.

Refer

Invert "if" statement to reduce nesting

This is of course subjective, but I think it strongly improves on two points:

  • It is now immediately obvious that your function has nothing left to do if condition holds.
  • It keeps the nesting level down. Nesting hurts readability more than you'd think.

'Framework not found' in Xcode

If you are using CocoaPods. Similar thing has happened to me. Although this question is old someone like me might still be struggling. So for to help: after pod install it warns you about project files. I didn't notice till now. it says:

[!] Please close any current Xcode sessions and use ProjectFile.xcworkspace for this project from now on.

So basically, do not continue working on .xcodeproj after installing Pods. If you do linker won't find files.

JUnit Testing Exceptions

If your constructor is similar to this one:

public Example(String example) {
    if (example == null) {
        throw new NullPointerException();
    }
    //do fun things with valid example here
}

Then, when you run this JUnit test you will get a green bar:

@Test(expected = NullPointerException.class)
public void constructorShouldThrowNullPointerException() {
    Example example = new Example(null);
}

Unable to load AWS credentials from the /AwsCredentials.properties file on the classpath

If you're wanting to use Environment variables using apache/tomcat, I found that the only way they could be found was setting them in tomcat/bin/setenv.sh (where catalina_opts are set - might be catalina.sh in your setup)

export AWS_ACCESS_KEY_ID=*********;

export AWS_SECRET_ACCESS_KEY=**************;

If you're using ubuntu, try logging in as ubuntu $printenv then log in as root $printenv, the environmental variables won't necessarily be the same....

If you only want to use environmental variables you can use: com.amazonaws.auth.EnvironmentVariableCredentialsProvider

instead of:

com.amazonaws.auth.DefaultAWSCredentialsProviderChain

(which by default checks all 4 possible locations)

anyway after hours of trying to figure out why my environmental variables weren't being found...this worked for me.

Execution sequence of Group By, Having and Where clause in SQL Server?

Here is the complete sequence for sql server :

1.  FROM
2.  ON
3.  JOIN
4.  WHERE
5.  GROUP BY
6.  WITH CUBE or WITH ROLLUP
7.  HAVING
8.  SELECT
9.  DISTINCT
10. ORDER BY
11. TOP

So from the above list, you can easily understand the execution sequence of GROUP BY, HAVING and WHERE which is :

1.  WHERE
2.  GROUP BY
3.  HAVING

Get more information about it from Microsoft

MySQL: can't access root account

This worked for me:

https://blog.dotkam.com/2007/04/10/mysql-reset-lost-root-password/

Step 1: Stop MySQL daemon if it is currently running

  ps -ef | grep mysql      - checks if mysql/mysqld is one of the running processes.

  pkill mysqld             - kills the daemon, if it is running.

Step 2: Run MySQL safe daemon with skipping grant tables

  mysqld_safe --skip-grant-tables &

  mysql -u root mysql

Step 3: Login to MySQL as root with no password

  mysql -u root mysql

Step 4: Run UPDATE query to reset the root password

  UPDATE user SET password=PASSWORD("value=42") WHERE user="root";
  FLUSH PRIVILEGES;

In MySQL 5.7, the 'password' field was removed, now the field name is 'authentication_string':

  UPDATE user SET authentication_string=PASSWORD("42") WHERE 
  user="root";
  FLUSH PRIVILEGES;

Step 5: Stop MySQL safe daemon

Step 6: Start MySQL daemon

How to get the file extension in PHP?

You could try with this for mime type

$image = getimagesize($_FILES['image']['tmp_name']);

$image['mime'] will return the mime type.

This function doesn't require GD library. You can find the documentation here.

This returns the mime type of the image.

Some people use the $_FILES["file"]["type"] but it's not reliable as been given by the browser and not by PHP.

You can use pathinfo() as ThiefMaster suggested to retrieve the image extension.

First make sure that the image is being uploaded successfully while in development before performing any operations with the image.

How to redirect 404 errors to a page in ExpressJS?

I found this example quite helpful:

https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js

So it is actually this part:

// "app.router" positions our routes
// above the middleware defined below,
// this means that Express will attempt
// to match & call routes _before_ continuing
// on, at which point we assume it's a 404 because
// no route has handled the request.

app.use(app.router);

// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.

// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"

app.use(function(req, res, next){
  res.status(404);

  // respond with html page
  if (req.accepts('html')) {
    res.render('404', { url: req.url });
    return;
  }

  // respond with json
  if (req.accepts('json')) {
    res.send({ error: 'Not found' });
    return;
  }

  // default to plain-text. send()
  res.type('txt').send('Not found');
});

JQuery datepicker not working

If jQuery UI datepicker isn't working but it used to work on similar DOM earlier, try removing all the classes and try binding it to just a simple input with its id. In my case a class was interfering with it and preventing the date picker to appear.

How to force the input date format to dd/mm/yyyy?

DEMO : http://jsfiddle.net/shfj70qp/

//dd/mm/yyyy 

var date = new Date();
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();

console.log(month+"/"+day+"/"+year);

Storing Python dictionaries

My use case was to save multiple JSON objects to a file and marty's answer helped me somewhat. But to serve my use case, the answer was not complete as it would overwrite the old data every time a new entry was saved.

To save multiple entries in a file, one must check for the old content (i.e., read before write). A typical file holding JSON data will either have a list or an object as root. So I considered that my JSON file always has a list of objects and every time I add data to it, I simply load the list first, append my new data in it, and dump it back to a writable-only instance of file (w):

def saveJson(url,sc): # This function writes the two values to the file
    newdata = {'url':url,'sc':sc}
    json_path = "db/file.json"

    old_list= []
    with open(json_path) as myfile:  # Read the contents first
        old_list = json.load(myfile)
    old_list.append(newdata)

    with open(json_path,"w") as myfile:  # Overwrite the whole content
        json.dump(old_list, myfile, sort_keys=True, indent=4)

    return "success"

The new JSON file will look something like this:

[
    {
        "sc": "a11",
        "url": "www.google.com"
    },
    {
        "sc": "a12",
        "url": "www.google.com"
    },
    {
        "sc": "a13",
        "url": "www.google.com"
    }
]

NOTE: It is essential to have a file named file.json with [] as initial data for this approach to work

PS: not related to original question, but this approach could also be further improved by first checking if our entry already exists (based on one or multiple keys) and only then append and save the data.

How does the keyword "use" work in PHP and can I import classes with it?

Don’t overthink what a Namespace is.

Namespace is basically just a Class prefix (like directory in Operating System) to ensure the Class path uniqueness.

Also just to make things clear, the use statement is not doing anything only aliasing your Namespaces so you can use shortcuts or include Classes with the same name but different Namespace in the same file.

E.g:

// You can do this at the top of your Class
use Symfony\Component\Debug\Debug;

if ($_SERVER['APP_DEBUG']) {
    // So you can utilize the Debug class it in an elegant way
    Debug::enable();
    // Instead of this ugly one
    // \Symfony\Component\Debug\Debug::enable();
}

If you want to know how PHP Namespaces and autoloading (the old way as well as the new way with Composer) works, you can read the blog post I just wrote on this topic: https://enterprise-level-php.com/2017/12/25/the-magic-behind-autoloading-php-files-using-composer.html

What is the difference between "px", "dip", "dp" and "sp"?

SDP - a scalable size unit - basically it is not a unit, but dimension resources for different screen size.

Try the sdp library from Intuit. It's very handy to solve unit problems, and you can quickly support multiple screens.

Usage

android:paddingBottom="@dimen/_15sdp" for positive and android:layout_marginTop="@dimen/_minus10sdp" for negative sdp sdp

It has equivalent value in dp for each size in values-sw<N>dp folders (sw = smallestWidth).

Attention

Use it carefully! In most cases you still need to design a different layout for tablets.

Example

<LinearLayout
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginTop="@dimen/_minus10sdp"
          android:paddingBottom="@dimen/_15sdp"
          android:orientation="horizontal" >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:includeFontPadding="false"
                    android:text="?"
                    android:textColor="#ED6C27"
                    android:textSize="@dimen/_70sdp"
                    android:textStyle="bold" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:includeFontPadding="false"
                    android:text="U"
                    android:textColor="@android:color/black"
                    android:textSize="@dimen/_70sdp" />
            </LinearLayout>

You can use db for text size, but I prefer ssp for text size.

For more details, check the library GitHub page.

How to take backup of a single table in a MySQL database?

try

for line in $(mysql -u... -p... -AN -e "show tables from NameDataBase");
do 
mysqldump -u... -p.... NameDataBase $line > $line.sql ; 
done
  • $line cotent names tables ;)

Execute another jar in a Java program

Hope this helps:

public class JarExecutor {

private BufferedReader error;
private BufferedReader op;
private int exitVal;

public void executeJar(String jarFilePath, List<String> args) throws JarExecutorException {
    // Create run arguments for the

    final List<String> actualArgs = new ArrayList<String>();
    actualArgs.add(0, "java");
    actualArgs.add(1, "-jar");
    actualArgs.add(2, jarFilePath);
    actualArgs.addAll(args);
    try {
        final Runtime re = Runtime.getRuntime();
        //final Process command = re.exec(cmdString, args.toArray(new String[0]));
        final Process command = re.exec(actualArgs.toArray(new String[0]));
        this.error = new BufferedReader(new InputStreamReader(command.getErrorStream()));
        this.op = new BufferedReader(new InputStreamReader(command.getInputStream()));
        // Wait for the application to Finish
        command.waitFor();
        this.exitVal = command.exitValue();
        if (this.exitVal != 0) {
            throw new IOException("Failed to execure jar, " + this.getExecutionLog());
        }

    } catch (final IOException | InterruptedException e) {
        throw new JarExecutorException(e);
    }
}

public String getExecutionLog() {
    String error = "";
    String line;
    try {
        while((line = this.error.readLine()) != null) {
            error = error + "\n" + line;
        }
    } catch (final IOException e) {
    }
    String output = "";
    try {
        while((line = this.op.readLine()) != null) {
            output = output + "\n" + line;
        }
    } catch (final IOException e) {
    }
    try {
        this.error.close();
        this.op.close();
    } catch (final IOException e) {
    }
    return "exitVal: " + this.exitVal + ", error: " + error + ", output: " + output;
}
}

How to iterate over the files of a certain directory, in Java?

Use java.io.File.listFiles
Or
If you want to filter the list prior to iteration (or any more complicated use case), use apache-commons FileUtils. FileUtils.listFiles

"/usr/bin/ld: cannot find -lz"

Another possible cause: You've passed --static to the linker, but you only have a dynamic version of libz (libz.so), but not a version that can be statically linked (libz.a).

Null & empty string comparison in Bash

fedorqui has a working solution but there is another way to do the same thing.

Chock if a variable is set

#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
    echo 'No, I am not!';
fi

Or to verify that a variable is empty

#!/bin/bash      
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
    echo 'Yes I am!';
fi

tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

How to include libraries in Visual Studio 2012?

Typically you need to do 5 things to include a library in your project:

1) Add #include statements necessary files with declarations/interfaces, e.g.:

#include "library.h"

2) Add an include directory for the compiler to look into

-> Configuration Properties/VC++ Directories/Include Directories (click and edit, add a new entry)

3) Add a library directory for *.lib files:

-> project(on top bar)/properties/Configuration Properties/VC++ Directories/Library Directories (click and edit, add a new entry)

4) Link the lib's *.lib files

-> Configuration Properties/Linker/Input/Additional Dependencies (e.g.: library.lib;

5) Place *.dll files either:

-> in the directory you'll be opening your final executable from or into Windows/system32

How to get the path of current worksheet in VBA?

The quickest way

path = ThisWorkbook.Path & "\"

System.drawing namespace not found under console application

For,Adding System.Drawing Follow some steps: Firstly, right click on the solution and click on add Reference. Secondly, Select the .NET Folder. And then double click on the Using.System.Drawing;

How to set a:link height/width with css?

add display: block;

a-tag is an inline element so your height and width are ignored.

#header div#snav div a{
    display:block;
    width:150px;
    height:77px;
}

Is there a way to iterate over a dictionary?

The block approach avoids running the lookup algorithm for every key:

[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
  NSLog(@"%@ => %@", key, value);
}];

Even though NSDictionary is implemented as a hashtable (which means that the cost of looking up an element is O(1)), lookups still slow down your iteration by a constant factor.

My measurements show that for a dictionary d of numbers ...

NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (int i = 0; i < 5000000; ++i) {
  NSNumber* value = @(i);
  dict[value.stringValue] = value;
}

... summing up the numbers with the block approach ...

__block int sum = 0;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* value, BOOL* stop) {
  sum += value.intValue;
}];

... rather than the loop approach ...

int sum = 0;
for (NSString* key in dict)
  sum += [dict[key] intValue];

... is about 40% faster.

EDIT: The new SDK (6.1+) appears to optimise loop iteration, so the loop approach is now about 20% faster than the block approach, at least for the simple case above.

Parsing query strings on Android

if (queryString != null)
{
    final String[] arrParameters = queryString.split("&");
    for (final String tempParameterString : arrParameters)
    {
        final String[] arrTempParameter = tempParameterString.split("=");
        if (arrTempParameter.length >= 2)
        {
            final String parameterKey = arrTempParameter[0];
            final String parameterValue = arrTempParameter[1];
            //do something with the parameters
        }
    }
}

Handling optional parameters in javascript

I think you want to use typeof() here:

function f(id, parameters, callback) {
  console.log(typeof(parameters)+" "+typeof(callback));
}

f("hi", {"a":"boo"}, f); //prints "object function"
f("hi", f, {"a":"boo"}); //prints "function object"

How to delete a workspace in Perforce (using p4v)?

If you have successfully deleted from workspace tab but still it is showing in drop down menu. Then also you can successfully remove that by following these steps:

  1. Go to C:/Users/user_name/.p4qt

user_name will be your username of your computer

  1. Inside 001Clients folder WorkspaceSettings.xml file will be there.

There will be two tag

  1. varName = "RecentlyUsedWorkspaces" remove the deleted workspace tag

  2. A propertyList tag will be there with varName=deleted_workspace_name delete that tag.

from drop down menu workspace name will be deleted

How display only years in input Bootstrap Datepicker?

always year for bootstrap 3 datetimepicker https://eonasdan.github.io/bootstrap-datetimepicker/

   $('#year').datetimepicker({
        format: 'YYYY',
        viewMode: "years",
    });

    $("#year").on("dp.hide", function (e) {
        $('#year').datetimepicker('destroy');
        $('#year').datetimepicker({
            format: 'YYYY',
            viewMode: "years",
        });
    });

How do I remove duplicate items from an array in Perl?

The variable @array is the list with duplicate elements

%seen=();
@unique = grep { ! $seen{$_} ++ } @array;

How to implement static class member functions in *.cpp file?

Try this:

header.hxx:

class CFoo
{
public: 
    static bool IsThisThingOn();
};

class.cxx:

#include "header.hxx"
bool CFoo::IsThisThingOn() // note: no static keyword here
{
    return true;
}

How to clean up R memory (without the need to restart my PC)?

An example under Linux (Fedora 16) shows that memory is freed when R is closed:

$ free -m                                                                                                                                                                                                                                    
             total       used       free     shared    buffers     cached                                                                                                                                                                    
Mem:          3829       2854        974          0        344       1440                                                                                                                                                                    
-/+ buffers/cache:       1069       2759                                                                                                                                                                                                     
Swap:         4095         85       4010     

2854 megabytes is used. Next I open an R session and create a large matrix of random numbers:

m = matrix(runif(10e7), 10000, 1000)

when the matrix is created, 3714 MB is used:

$ free -m                                                                                                                                                                                                                                    
             total       used       free     shared    buffers     cached                                                                                                                                                                    
Mem:          3829       3714        115          0        344       1442                                                                                                                                                                    
-/+ buffers/cache:       1927       1902                                                                                                                                                                                                     
Swap:         4095         85       4010     

After closing the R session, I nicely get back the memory I used (2856 MB free):

$ free -m                                                                                                                                                                                                                                    
             total       used       free     shared    buffers     cached                                                                                                                                                                    
Mem:          3829       2856        972          0        344       1442                                                                                                                                                                    
-/+ buffers/cache:       1069       2759                                                                                                                                                                                                     
Swap:         4095         85       4010   

Ofcourse you use Windows, but you could repeat this excercise in Windows and report how the available memory develops before and after you create this large dataset in R.

Apply CSS rules to a nested class inside a div

If you need to target multiple classes use:

#main_text .title, #main_text .title2 {
  /* Properties */
}

How to use callback with useState hook in react

You can use like below -

this.setState(() => ({  subChartType1: value   }), () => this.props.dispatch(setChartData(null)));

Javascript Src Path

Use an relative path to the root of your site, for example:

If clock.js is on http://domain.com/javascript/clock.js

Include :

<script language="JavaScript" src="/javascript/clock.js"></script>

If it's on your domain root directory:

<script language="JavaScript" src="/clock.js"></script>

Parse error: syntax error, unexpected [

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

How to clear PermGen space Error in tomcat

The PermGen space is what Tomcat uses to store class definitions (definitions only, no instantiations) and string pools that have been interned. From experience, the PermGen space issues tend to happen frequently in dev environments really since Tomcat has to load new classes every time it deploys a WAR or does a jspc (when you edit a jsp file). Personally, I tend to deploy and redeploy wars a lot when I’m in dev testing so I know I’m bound to run out sooner or later (primarily because Java’s GC cycles are still kinda crap so if you redeploy your wars quickly and frequently enough, the space fills up faster than they can manage).

This should theoretically be less of an issue in production environments since you (hopefully) don’t change the codebase on a 10 minute basis. If it still occurs, that just means your codebase (and corresponding library dependencies) are too large for the default memory allocation and you’ll just need to mess around with stack and heap allocation. I think the standards are stuff like:

-XX:MaxPermSize=SIZE

I’ve found however the best way to take care of that for good is to allow classes to be unloaded so your PermGen never runs out:

-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

Stuff like that worked magic for me in the past. One thing tho, there’s a significant performance tradeoff in using those, since permgen sweeps will make like an extra 2 requests for every request you make or something along those lines. You’ll need to balance your use with the tradeoffs.

NuGet auto package restore does not work with MSBuild

I had an issue with nuget packages not being included in a scripted nightly build that builds the sln file using devenv.exe.

I followed the advice from Microsoft, and the key step was updating the NuGet config in %AppData%/NuGet so that it contained:

<configuration>
    <packageRestore>
        <add key="automatic" value="True" />
    </packageRestore>
</configuration>

What is the best way to iterate over a dictionary?

Generally, asking for "the best way" without a specific context is like asking what is the best color?

One the one hand, there are many colors and there's no best color. It depends on the need and often on taste, too.

On the other hand, there are many ways to iterate over a Dictionary in C# and there's no best way. It depends on the need and often on taste, too.

Most straightforward way

foreach (var kvp in items)
{
    // key is kvp.Key
    doStuff(kvp.Value)
}

If you need only the value (allows to call it item, more readable than kvp.Value).

foreach (var item in items.Values)
{
    doStuff(item)
}

If you need a specific sort order

Generally, beginners are surprised about order of enumeration of a Dictionary.

LINQ provides a concise syntax that allows to specify order (and many other things), e.g.:

foreach (var kvp in items.OrderBy(kvp => kvp.Key))
{
    // key is kvp.Key
    doStuff(kvp.Value)
}

Again you might only need the value. LINQ also provides a concise solution to:

  • iterate directly on the value (allows to call it item, more readable than kvp.Value)
  • but sorted by the keys

Here it is:

foreach (var item in items.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
{
    doStuff(item)
}

There are many more real-world use case you can do from these examples. If you don't need a specific order, just stick to the "most straightforward way" (see above)!

What's a .sh file?

If you open your second link in a browser you'll see the source code:

#!/bin/bash
# Script to download individual .nc files from the ORNL
# Daymet server at: http://daymet.ornl.gov

[...]

# For ranges use {start..end}
# for individul vaules, use: 1 2 3 4 
for year in {2002..2003}
do
   for tile in {1159..1160}
        do wget --limit-rate=3m http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc -O ${tile}_${year}_vp.nc
        # An example using curl instead of wget
    #do curl --limit-rate 3M -o ${tile}_${year}_vp.nc http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc
     done
done

So it's a bash script. Got Linux?


In any case, the script is nothing but a series of HTTP retrievals. Both wget and curl are available for most operating systems and almost all language have HTTP libraries so it's fairly trivial to rewrite in any other technology. There're also some Windows ports of bash itself (git includes one). Last but not least, Windows 10 now has native support for Linux binaries.

How do I connect to a specific Wi-Fi network in Android programmatically?

Before connecting WIFI network you need to check security type of the WIFI network ScanResult class has a capabilities. This field gives you type of network

Refer: https://developer.android.com/reference/android/net/wifi/ScanResult.html#capabilities

There are three types of WIFI networks.

First, instantiate a WifiConfiguration object and fill in the network’s SSID (note that it has to be enclosed in double quotes), set the initial state to disabled, and specify the network’s priority (numbers around 40 seem to work well).

WifiConfiguration wfc = new WifiConfiguration();

wfc.SSID = "\"".concat(ssid).concat("\"");
wfc.status = WifiConfiguration.Status.DISABLED;
wfc.priority = 40;

Now for the more complicated part: we need to fill several members of WifiConfiguration to specify the network’s security mode. For open networks.

wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedAuthAlgorithms.clear();
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

For networks using WEP; note that the WEP key is also enclosed in double quotes.

wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

if (isHexString(password)) wfc.wepKeys[0] = password;
else wfc.wepKeys[0] = "\"".concat(password).concat("\"");
wfc.wepTxKeyIndex = 0;

For networks using WPA and WPA2, we can set the same values for either.

wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

wfc.preSharedKey = "\"".concat(password).concat("\"");

Finally, we can add the network to the WifiManager’s known list

WifiManager wfMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int networkId = wfMgr.addNetwork(wfc);
if (networkId != -1) {
 // success, can call wfMgr.enableNetwork(networkId, true) to connect
} 

SQL Server 2008- Get table constraints

Here's a script to get foreign keys:

    SELECT TOP(150)
       t.[name] AS [Table],
       cols.[name] AS [Column],
       t2.[name] AS [Referenced Table],
       c2.[name] AS [Referenced Column],
       constr.[name] AS [Constraint]
  FROM sys.tables t
 INNER JOIN sys.foreign_keys constr ON constr.parent_object_id = t.object_id
 INNER JOIN sys.tables t2 ON t2.object_id = constr.referenced_object_id
 INNER JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = constr.object_id
 INNER JOIN sys.columns cols ON cols.object_id = fkc.parent_object_id AND cols.column_id = fkc.parent_column_id
 INNER JOIN sys.columns c2 ON c2.object_id = fkc.referenced_object_id AND c2.column_id = fkc.referenced_column_id
 --WHERE t.[name] IN ('?', '?', ...)
 ORDER BY t.[Name], cols.[name]

XPath: How to select elements based on their value?

//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]

The reason why I add this answer is that I want to explain the relationship of . and text() .

The first thing is when using [], there are only two types of data:

  1. [number] to select a node from node-set
  2. [bool] to filter a node-set from node-set

In this case, the value is evaluated to boolean by function boolean(), and there is a rule:

Filters are always evaluated with respect to a context.

When you need to compare text() or . with a string "Data", it first uses string() function to transform those to string type, than gets a boolean result.

There are two important rule about string():

  1. The string() function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.

    text() is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]. When it is evaluated by string(["Data"]), it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.

  2. If you want the string() function to concatenate all child text, you must then pass a single node instead of a node-set.

    For example, we get a node-set ['a', 'b'], you can pass there parent node to string(parent), this will return 'ab', and of cause string(.) in you case will return an concatenated string "Data".

Both way will get same result only when there is a text node.

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

Convert Char to String in C

This is an old question, but I'd say none of the answers really fits the OP's question. All he wanted/needed to do is this:

char c = std::fgetc(fp);
std::strcpy(buffer, &c);

The relevant aspect here is the fact, that the second argument of strcpy() doesn't need to be a char array / c-string. In fact, none of the arguments is a char or char array at all. They are both char pointers:

strcpy(char* dest, const char* src);

dest : A non-const char pointer
Its value has to be the memory address of an element of a writable char array (with at least one more element after that).
src : A const char pointer
Its value can be the address of a single char, or of an element in a char array. That array must contain the special character \0 within its remaining elements (starting with src), to mark the end of the c-string that should be copied.

Quoting backslashes in Python string literals

You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)

>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

Incidentally, there's another string form which might be a bit clearer:

>>> print(r'baz "\"')
baz "\"

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

I have a pc with intel c2d without hardware accelaration i am having same problem in android studio. firstly i get bored with android studio and installed eclipse+sdk+adt then i have installed every thing and started emulator it worked then the same emulator worked in android studio for direct launching application in android studio and i have also runned the sample app that emulator so you can run android studio without virtualization technique even your processor does not sopport vt-x

How to detect DataGridView CheckBox event change?

What worked for me was CurrentCellDirtyStateChanged in combination with datagridView1.EndEdit()

private void dataGridView1_CurrentCellDirtyStateChanged( object sender, EventArgs e ) {
    if ( dataGridView1.CurrentCell is DataGridViewCheckBoxCell ) {
        DataGridViewCheckBoxCell cb = (DataGridViewCheckBoxCell)dataGridView1.CurrentCell;
        if ( (byte)cb.Value == 1 ) {
            dataGridView1.CurrentRow.Cells["time_loadedCol"].Value = DateTime.Now.ToString();
        }
    }
    dataGridView1.EndEdit();
}

How do I start a program with arguments when debugging?

I would suggest using the directives like the following:

        static void Main(string[] args)
        {
#if DEBUG
            args = new[] { "A" };
#endif

            Console.WriteLine(args[0]);
        }

Good luck!

How to get UTC time in Python?

Simple, standard library only. Gives timezone-aware datetime, unlike datetime.utcnow().

from datetime import datetime,timezone
now_utc = datetime.now(timezone.utc)

Touch move getting stuck Ignored attempt to cancel a touchmove

I had this problem and all I had to do is return true from touchend and the warning went away.

align textbox and text/labels in html?

you can do a multi div layout like this

<div class="fieldcontainer">
    <div class="label"></div>
    <div class="field"></div>
</div>

where .fieldcontainer { clear: both; } .label { float: left; width: ___ } .field { float: left; }

Or, I actually prefer tables for forms like this. This is very much tabular data and it comes out very clean. Both will work though.

Recursive search and replace in text files on Mac and Linux

If you are using a zsh terminal you're able to use wildcard magic:

sed -i "" "s/search/high-replace/g" *.txt

Php artisan make:auth command is not defined

Update for Laravel 6

Now that Laravel 6 is released you need to install laravel/ui.

composer require laravel/ui --dev
php artisan ui vue --auth

You can change vue with react if you use React in your project (see Using React).

And then you need to perform the migrations and compile the frontend

php artisan migrate
npm install && npm run dev

Source : Laravel Documentation for authentication

Want to get started fast? Install the laravel/ui Composer package and run php artisan ui vue --auth in a fresh Laravel application. After migrating your database, navigate your browser to http://your-app.test/register or any other URL that is assigned to your application. These commands will take care of scaffolding your entire authentication system!

Note: That's only if you want to use scaffolding, you can use the default User model and the Eloquent authentication driver.

escaping question mark in regex javascript

Whenever you have a known pattern (i.e. you do not use a variable to build a RegExp), use literal regex notation where you only need to use single backslashes to escape special regex metacharacters:

var re = /I like your Apartment\. Could we schedule a viewing\?/g;
                               ^^                            ^^

Whenever you need to build a RegExp dynamically, use RegExp constructor notation where you MUST double backslashes for them to denote a literal backslash:

var questionmark_block = "\\?"; // A literal ?
var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot
var re = new RegExp(initial_subpattern + questionmark_block, "g");

And if you use the String.raw string literal you may use \ as is (see an example of using a template string literal where you may put variables into the regex pattern):

_x000D_
_x000D_
const questionmark_block = String.raw`\?`; // A literal ?
const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g
_x000D_
_x000D_
_x000D_

A must-read: RegExp: Description at MDN.

Floating elements within a div, floats outside of div. Why?

In some cases, i.e. when (if) you're just using float to have elements flow on the same "line", you might use

display: inline-block;

instead of

float: left;

Otherwise, using a clear element at the end works, even if it may go against the grain to need an element to do what should be CSS work.

Get table names using SELECT statement in MySQL

MySQL INFORMATION_SCHEMA.TABLES table contains data about both tables (not temporary but permanent ones) and views. The column TABLE_TYPE defines whether this is record for table or view (for tables TABLE_TYPE='BASE TABLE' and for views TABLE_TYPE='VIEW'). So if you want to see from your schema (database) tables only there's the following query :

SELECT *
FROM information_schema.tables
WHERE table_type='BASE TABLE'
AND table_schema='myschema'

jQuery UI 1.10: dialog and zIndex option

moveToTop is the proper way.

z-Index is not correct. It works initially, but multiple dialogs will continue to float underneath the one you altered with z-index. No good.

SQL query, store result of SELECT in local variable

Here are some other approaches you can take.

1. CTE with union:

;WITH cte AS (SELECT a, b, c FROM table1)
SELECT a AS val FROM cte
UNION SELECT b AS val FROM cte
UNION SELECT c AS val FROM cte;

2. CTE with unpivot:

;WITH cte AS (SELECT a, b, c FROM table1)
SELECT DISTINCT val
FROM cte
UNPIVOT (val FOR col IN (a, b, c)) u;

Global Git ignore

You need to set up your global core.excludesfile configuration file to point to this global ignore file.

e.g.

*nix or Windows git bash:

git config --global core.excludesFile '~/.gitignore'

Windows cmd:

git config --global core.excludesFile "%USERPROFILE%\.gitignore"

Windows PowerShell:

git config --global core.excludesFile "$Env:USERPROFILE\.gitignore"

For Windows it set to the location C:\Users\{myusername}\.gitignore. You can verify that the config value is correct by doing:

git config --global core.excludesFile

The result should be the expanded path to your user profile's .gitignore. Ensure that the value does not contain the unexpanded %USERPROFILE% string.

Important: The above commands will only set the location of the ignore file that git will use. The file has to still be manually created in that location and populated with the ignore list. (from muruge's comment)

You can read about the command at https://help.github.com/articles/ignoring-files/#create-a-global-gitignore

Python send UDP packet

Here is a complete example that has been tested with Python 2.7.5 on CentOS 7.

#!/usr/bin/python

import sys, socket

def main(args):
    ip = args[1]
    port = int(args[2])
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    file = 'sample.csv'

    fp = open(file, 'r')
    for line in fp:
        sock.sendto(line.encode('utf-8'), (ip, port))
    fp.close()

main(sys.argv)

The program reads a file, sample.csv from the current directory and sends each line in a separate UDP packet. If the program it were saved in a file named send-udp then one could run it by doing something like:

$ python send-udp 192.168.1.2 30088

How do I access command line arguments in Python?

Python code:

import sys

# main
param_1= sys.argv[1] 
param_2= sys.argv[2] 
param_3= sys.argv[3]  
print 'Params=', param_1, param_2, param_3

Invocation:

$python myfile.py var1 var2 var3

Output:

Params= var1 var2 var3 

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

VirtualBox version has many uncompatibilities with Linux version, so it's hard to install by using "Guest Addition CD image". For linux distributions it's frequently have a good companion Guest Addition package(equivalent functions to the CD image) which can be installed by:

sudo apt-get install virtualbox-guest-dkms

After that, on the window menu of the Guest, go to Devices->Shared Folders Settings->Shared Folders and add a host window folder to Machine Folders(Mark Auto-mount option) then you can see the shared folder in the Files of Guest Linux.

What is Unicode, UTF-8, UTF-16?

Unicode is a fairly complex standard. Don’t be too afraid, but be prepared for some work! [2]

Because a credible resource is always needed, but the official report is massive, I suggest reading the following:

  1. The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) An introduction by Joel Spolsky, Stack Exchange CEO.
  2. To the BMP and beyond! A tutorial by Eric Muller, Technical Director then, Vice President later, at The Unicode Consortium. (first 20 slides and you are done)

A brief explanation:

Computers read bytes and people read characters, so we use encoding standards to map characters to bytes. ASCII was the first widely used standard, but covers only Latin (7 bits/character can represent 128 different characters). Unicode is a standard with the goal to cover all possible characters in the world (can hold up to 1,114,112 characters, meaning 21 bits/character max. Current Unicode 8.0 specifies 120,737 characters in total, and that's all).

The main difference is that an ASCII character can fit to a byte (8 bits), but most Unicode characters cannot. So encoding forms/schemes (like UTF-8 and UTF-16) are used, and the character model goes like this:

Every character holds an enumerated position from 0 to 1,114,111 (hex: 0-10FFFF) called code point.
An encoding form maps a code point to a code unit sequence. A code unit is the way you want characters to be organized in memory, 8-bit units, 16-bit units and so on. UTF-8 uses 1 to 4 units of 8 bits, and UTF-16 uses 1 or 2 units of 16 bits, to cover the entire Unicode of 21 bits max. Units use prefixes so that character boundaries can be spotted, and more units mean more prefixes that occupy bits. So, although UTF-8 uses 1 byte for the Latin script it needs 3 bytes for later scripts inside Basic Multilingual Plane, while UTF-16 uses 2 bytes for all these. And that's their main difference.
Lastly, an encoding scheme (like UTF-16BE or UTF-16LE) maps (serializes) a code unit sequence to a byte sequence.

character: p
code point: U+03C0
encoding forms (code units):
      UTF-8: CF 80
      UTF-16: 03C0
encoding schemes (bytes):
      UTF-8: CF 80
      UTF-16BE: 03 C0
      UTF-16LE: C0 03

Tip: a hex digit represents 4 bits, so a two-digit hex number represents a byte
Also take a look at Plane maps in Wikipedia to get a feeling of the character set layout

Pass Parameter to Gulp Task

Just load it into a new object on process .. process.gulp = {} and have the task look there.

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

You should set your RecyclerView LayoutManager to Gridlayout mode. Just change your code when you want to set your RecyclerView LayoutManager:

recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfColumns));

Remove Android App Title Bar

Simple way
getSupportActionBar().hide();

Kotlin: supportActionBar?.hide()

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

The way I build CMake projects cross platform is the following:

/project-root> mkdir build
/project-root> cd build
/project-root/build> cmake -G "<generator>" -DCMAKE_INSTALL_PREFIX=stage ..
/project-root/build> cmake --build . --target=install --config=Release
  • The first two lines create the out-of-source build directory
  • The third line generates the build system specifying where to put the installation result (which I always place in ./project-root/build/stage - the path is always considered relative to the current directory if it is not absolute)
  • The fourth line builds the project configured in . with the buildsystem configured in the line before. It will execute the install target which also builds all necessary dependent targets if they need to be built and then copies the files into the CMAKE_INSTALL_PREFIX (which in this case is ./project-root/build/stage. For multi-configuration builds, like in Visual Studio, you can also specify the configuration with the optional --config <config> flag.
  • The good part when using the cmake --build command is that it works for all generators (i.e. makefiles and Visual Studio) without needing different commands.

Afterwards I use the installed files to create packages or include them in other projects...

Auto refresh code in HTML using meta tags

The quotes you use are the issue:

<meta http-equiv=”refresh” content=”5" >

You should use the "

<meta http-equiv="refresh" content="5">

How to make html <select> element look like "disabled", but pass values?

You can keep it disabled as desired, and then remove the disabled attribute before the form is submitted.

$('#myForm').submit(function() {
    $('select').removeAttr('disabled');
});

Note that if you rely on this method, you'll want to disable it programmatically as well, because if JS is disabled or not supported, you'll be stuck with the disabled select.

$(document).ready(function() {
    $('select').attr('disabled', 'disabled');
});

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

Killing the vpn is not needed.

This other comment about using a new network comes pretty close to the solution for me, and was working for a while, but I found a better way thanks to some talk over in another question

Create a network with:

docker network create your-network --subnet 172.24.24.0/24

Then, at the bottom of docker-compose.yaml, put this:

networks:
  default:
    external: 
      name: your-network

Done. No need to add networks to all container definitions etc. and you can re-use the network with other docker-compose files as well if you'd like.

React JSX: selecting "selected" on selected <select> option

Posting a similar answer for MULTISELECT / optgroups:

render() {
  return(
    <div>
      <select defaultValue="1" onChange={(e) => this.props.changeHandler(e.target.value) }>
        <option disabled="disabled" value="1" hidden="hidden">-- Select --</option>
        <optgroup label="Group 1">
          {options1}
        </optgroup>
        <optgroup label="Group 2">
          {options2}
        </optgroup>
      </select>
    </div>
  )
}

NSArray + remove item from array

NSArray is not mutable, that is, you cannot modify it. You should take a look at NSMutableArray. Check out the "Removing Objects" section, you'll find there many functions that allow you to remove items:

[anArray removeObjectAtIndex: index];
[anArray removeObject: item];
[anArray removeLastObject];

CSS white space at bottom of page despite having both min-height and height tag

I had white space at the bottom of all my websites; this is how I solved the matter:

the first and best thing you can do when you are debugging css issues like this is to add:

*{ border: 1px solid red; }

this css line puts a red box around all your css elements.

I had white space at the bottom of my page due to a faulty chrome extension which was adding the div 'dp_swf_engine' to the bottom of my page:

without the red box, I would have never noticed a 1px div. I then got rid of the faulty extension, and put 'display:none' on #dp_swf_engine as a secondary measure. (who knows when it could come back to add random white space at the bottom of my page for all my pages and apps?!)

How to get a user's client IP address in ASP.NET?

use in ashx file

public string getIP(HttpContext c)
{
    string ips = c.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (!string.IsNullOrEmpty(ips))
    {
        return ips.Split(',')[0];
    }
    return c.Request.ServerVariables["REMOTE_ADDR"];
}

What are projection and selection?

Simply PROJECTION deals with elimination or selection of columns, while SELECTION deals with elimination or selection of rows.

How to select the comparison of two columns as one column in Oracle

If you want to consider null values equality too, try the following

select column1, column2, 
   case
      when column1 is NULL and column2 is NULL then 'true'  
      when column1=column2 then 'true' 
      else 'false' 
   end 
from table;

Fastest Convert from Collection to List<T>

managementObjects.Cast<ManagementBaseObject>().ToList(); is a good choice.

You could improve performance by pre-initialising the list capacity:


    public static class Helpers
    {
        public static List<T> CollectionToList<T>(this System.Collections.ICollection other)
        {
            var output = new List<T>(other.Count);

            output.AddRange(other.Cast<T>());

            return output;
        }
    }

How to get mouse position in jQuery without mouse-events?

use window.event - it contains last event and as any event contains pageX, pageY etc. Works for Chrome, Safari, IE but not FF.

How do I disable a Pylint warning?

To disable a warning locally in a block, add

# pylint: disable=C0321

to that block.

Targeting only Firefox with CSS

The following code tends to throw Style lint warnings:

@-moz-document url-prefix() {
    h1 {
        color: red;
    }
}

Instead using

@-moz-document url-prefix('') {
    h1 {
        color: red;
    }
}

Helped me out! Got the solution for style lint warning from here

Change location of log4j.properties

This is my class : Path is fine and properties is loaded.

package com.fiserv.dl.idp.logging;

import java.io.File;
import java.io.FileInputStream;
import java.util.MissingResourceException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class LoggingCapsule {

    private static Logger logger = Logger.getLogger(LoggingCapsule.class);

    public static void info(String message) {


        try {

            String configDir = System.getProperty("config.path");
            if (configDir == null) {
                throw new MissingResourceException("System property: config.path not set", "", "");
            }
            Properties properties = new Properties();
            properties.load(new FileInputStream(configDir + File.separator + "log4j" + ".properties"));
            PropertyConfigurator.configure(properties);
        } catch (Exception e) {
            e.printStackTrace();

        }
        logger.info(message);
    }
    public static void error(String message){
        System.out.println(message);
    }

}

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

Another answer relies on the third-to-last character being a space. This will work with (almost) any character in that position and does it "WITHOUT using sed, or perl, etc.":

while read -r line
do
    echo ${line:0:${#line}-3}
done

If your lines are fixed length change the echo to:

echo ${line:0:9}

or

printf "%.10s\n" "$line"

but each of these is definitely much slower than sed.

How to change proxy settings in Android (especially in Chrome)

Found one solution for WIFI (works for Android 4.3, 4.4):

  1. Connect to WIFI network (e.g. 'Alex')
  2. Settings->WIFI
  3. Long tap on connected network's name (e.g. on 'Alex')
  4. Modify network config-> Show advanced options
  5. Set proxy settings

What is the "Upgrade-Insecure-Requests" HTTP header?

Short answer: it's closely related to the Content-Security-Policy: upgrade-insecure-requests response header, indicating that the browser supports it (and in fact prefers it).

It took me 30mins of Googling, but I finally found it buried in the W3 spec.

The confusion comes because the header in the spec was HTTPS: 1, and this is how Chromium implemented it, but after this broke lots of websites that were poorly coded (particularly WordPress and WooCommerce) the Chromium team apologized:

"I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."
— Mike West, in Chrome Issue 501842

Their fix was to rename it to Upgrade-Insecure-Requests: 1, and the spec has since been updated to match.

Anyway, here is the explanation from the W3 spec (as it appeared at the time)...

The HTTPS HTTP request header field sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive in order to make that preference as seamless as possible to provide.

...

When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.

When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a Strict-Transport-Security header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].

How to set recurring schedule for xlsm file using Windows Task Scheduler

Three important steps - How to Task Schedule an excel.xls(m) file

simply:

  1. make sure the .vbs file is correct
  2. set the Action tab correctly in Task Scheduler
  3. don't turn on "Run whether user is logged on or not"

IN MORE DETAIL...

  1. Here is an example .vbs file:

`

'   a .vbs file is just a text file containing visual basic code that has the extension renamed from .txt  to .vbs

'Write Excel.xls  Sheet's full path here
strPath = "C:\RodsData.xlsm" 

'Write the macro name - could try including module name
strMacro = "Update" '    "Sheet1.Macro2" 

'Create an Excel instance and set visibility of the instance
Set objApp = CreateObject("Excel.Application") 
objApp.Visible = True   '   or False 

'Open workbook; Run Macro; Save Workbook with changes; Close; Quit Excel
Set wbToRun = objApp.Workbooks.Open(strPath) 
objApp.Run strMacro     '   wbToRun.Name & "!" & strMacro 
wbToRun.Save 
wbToRun.Close 
objApp.Quit 

'Leaves an onscreen message!
MsgBox strPath & " " & strMacro & " macro and .vbs successfully completed!",         vbInformation 
'

`

  1. In the Action tab (Task Scheduler):

set Program/script: = C:\Windows\System32\cscript.exe

set Add arguments (optional): = C:\MyVbsFile.vbs

  1. Finally, don't turn on "Run whether user is logged on or not".

That should work.

Let me know!

Rod Bowen

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

As everyone has mentioned http.server module is equivalent to python -m SimpleHTTPServer.
But as a warning from https://docs.python.org/3/library/http.server.html#module-http.server

Warning: http.server is not recommended for production. It only implements basic security checks.

Usage

http.server can also be invoked directly using the -m switch of the interpreter.

python -m http.server

The above command will run a server by default on port number 8000. You can also give the port number explicitly while running the server

python -m http.server 9000

The above command will run an HTTP server on port 9000 instead of 8000.

By default, server binds itself to all interfaces. The option -b/--bind specifies a specific address to which it should bind. Both IPv4 and IPv6 addresses are supported. For example, the following command causes the server to bind to localhost only:

python -m http.server 8000 --bind 127.0.0.1

or

python -m http.server 8000 -b 127.0.0.1

Python 3.8 version also supports IPv6 in the bind argument.

Directory Binding

By default, server uses the current directory. The option -d/--directory specifies a directory to which it should serve the files. For example, the following command uses a specific directory:

python -m http.server --directory /tmp/

Directory binding is introduced in python 3.7

Comparing object properties in c#

sometimes you don't want to compare all public properties and want to compare only the subset of them, so in this case you can just move logic to compare the desired list of properties to abstract class

public abstract class ValueObject<T> where T : ValueObject<T>
{
    protected abstract IEnumerable<object> GetAttributesToIncludeInEqualityCheck();

    public override bool Equals(object other)
    {
        return Equals(other as T);
    }

    public bool Equals(T other)
    {
        if (other == null)
        {
            return false;
        }

        return GetAttributesToIncludeInEqualityCheck()
            .SequenceEqual(other.GetAttributesToIncludeInEqualityCheck());
    }

    public static bool operator ==(ValueObject<T> left, ValueObject<T> right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(ValueObject<T> left, ValueObject<T> right)
    {
        return !(left == right);
    }

    public override int GetHashCode()
    {
        int hash = 17;
        foreach (var obj in this.GetAttributesToIncludeInEqualityCheck())
            hash = hash * 31 + (obj == null ? 0 : obj.GetHashCode());

        return hash;
    }
}

and use this abstract class later to compare the objects

public class Meters : ValueObject<Meters>
{
    ...

    protected decimal DistanceInMeters { get; private set; }

    ...

    protected override IEnumerable<object> GetAttributesToIncludeInEqualityCheck()
    {
        return new List<Object> { DistanceInMeters };
    }
}

How to check if a column exists in a SQL Server table?

For the people who are checking the column existence before dropping it.

From SQL Server 2016 you can use new DIE statements instead of big IF wrappers

ALTER TABLE Table_name DROP COLUMN IF EXISTS Column_name

How to start an Intent by passing some parameters to it?

In order to pass the parameters you create new intent and put a parameter map:

Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);

In order to get the parameters values inside the started activity, you must call the get[type]Extra() on the same intent:

// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"

If your parameters are ints you would use getIntExtra() instead etc. Now you can use your parameters like you normally would.

How to get images in Bootstrap's card to be the same height/width?

Each of the images need to be the exact dimensions before you put them up otherwise bootstrap 4 will try to place them in a funky shape. Bootstrap also has something like Masonry on their documents that you can use if need be, you can see that here, http://v4-alpha.getbootstrap.com/components/card/#columns.

EF Code First "Invalid column name 'Discriminator'" but no inheritance

Turns out that Entity Framework will assume that any class that inherits from a POCO class that is mapped to a table on the database requires a Discriminator column, even if the derived class will not be saved to the DB.

The solution is quite simple and you just need to add [NotMapped] as an attribute of the derived class.

Example:

class Person
{
    public string Name { get; set; }
}

[NotMapped]
class PersonViewModel : Person
{
    public bool UpdateProfile { get; set; }
}

Now, even if you map the Person class to the Person table on the database, a "Discriminator" column will not be created because the derived class has [NotMapped].

As an additional tip, you can use [NotMapped] to properties you don't want to map to a field on the DB.

How to declare Return Types for Functions in TypeScript

You are correct - here is a fully working example - you'll see that var result is implicitly a string because the return type is specified on the greet() function. Change the type to number and you'll get warnings.

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() : string {
        return "Hello, " + this.greeting;
    }
} 

var greeter = new Greeter("Hi");
var result = greeter.greet();

Here is the number example - you'll see red squiggles in the playground editor if you try this:

greet() : number {
    return "Hello, " + this.greeting;
}

Property 'map' does not exist on type 'Observable<Response>'

  import { Injectable } from '@angular/core';
  import { Http } from '@angular/http';
  import 'rxjs/add/operator/map';

  @Injectable({
  providedIn: 'root'
  })
  export class RestfulService {

  constructor(public http: Http) { }

 //access apis Get Request 
 getUsers() {
 return this.http.get('http://jsonplaceholder.typicode.com/users')
  .map(res => res.json());
  }

 }

run the command

 npm install rxjs-compat 

I just import

 import 'rxjs/add/operator/map';

restart the vs code, issue solved.

TLS 1.2 not working in cURL

You must use an integer value for the CURLOPT_SSLVERSION value, not a string as listed above

Try this:

curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 6); //Integer NOT string TLS v1.2

http://php.net/manual/en/function.curl-setopt.php

value should be an integer for the following values of the option parameter: CURLOPT_SSLVERSION

One of

CURL_SSLVERSION_DEFAULT (0)
CURL_SSLVERSION_TLSv1 (1)
CURL_SSLVERSION_SSLv2 (2)
CURL_SSLVERSION_SSLv3 (3)
CURL_SSLVERSION_TLSv1_0 (4)
CURL_SSLVERSION_TLSv1_1 (5)
CURL_SSLVERSION_TLSv1_2 (6).

Getting the encoding of a Postgres database

Because there's more than one way to skin a cat:

psql -l

Shows all the database names, encoding, and more.

How to exit in Node.js

It depends on the reason why you're willing to exit node.js process, but in any case process.exit() is the last option to consider. A quote from documentation:

It is important to note that calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to process.stdout and process.stderr.

In most situations, it is not actually necessary to call process.exit() explicitly. The Node.js process will exit on it's own if there is no additional work pending in the event loop. The process.exitCode property can be set to tell the process which exit code to use when the process exits gracefully.

Let’s cover possible reasons why you might be willing to exit node.js process and why you should avoid process.exit():

Case 1 - Execution complete (command line script)

If script has reached its end and node interpreter doesn't exit, it indicates that some async operations are still pending. It’s wrong to force process termination with process.exit() at this point. It’s better to try to understand what is holding your script from exiting in expected way. And when you settle this, you can use process.exitCode to return any result to calling process.

Case 2 - Termination because of external signal (SIGINT/SIGTERM/other)

For example, if you’re willing to gracefully shut down an express app. Unlike command line script, express app keeps running infinitely, waiting for new requests. process.exit() will be a bad option here because it’s going to interrupt all requests which are in pipeline. And some of them might be non-idempotent (UPDATE, DELETE). Client will never know if those requests are completed or not on server side and it might be the reason of data inconsistency between client and server. The only good solution is to tell http server to stop accepting new requests and wait for pending ones to finish with server.close():

var express = require('express');
var app = express();
var server = app.listen(80);

process.on( 'SIGTERM', function () {
   server.close(function () {
     console.log("Finished all requests");
   });
});

If it still doesn't exit - see Case 1.

Case 3 - Internal error

It's always better to throw an error, you’ll get a nicely formatted stack trace and error message. Upper levels of code can always decide if they can handle error (catch) or let it crash the process. On the other side, process.exit(1) will terminate process silently and there will be no chance to recover from this. It might be the only “benefit” of process.exit(), you can be sure that process will be terminated.

How to read integer values from text file

use FileInputStream's readLine() method to read and parse the returned String to int using Integer.parseInt() method.

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

In my case, the problem was I didn't had a Tomcat server separately installed in my eclipse. I assumed my Springboot will start the server automatically within itself.

Since my main class extends SpringBootServletInitializer and override configure method, I definitely need a Tomcat server installed in my IDE.

To install, first download Apachce Tomcat (version 9 in my case) and create server using Servers tab.

After installation, run the main class on server.

Run As -> Run on Server

Loop Through Each HTML Table Column and Get the Data using jQuery

You can try with textContent.

var productId = val[key].textContent;

In angular $http service, How can I catch the "status" of error?

Since $http.get returns a 'promise' with the extra convenience methods success and error (which just wrap the result of then) you should be able to use (regardless of your Angular version):

$http.get('/someUrl')
    .then(function success(response) {
        console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText
    }, function error(response) {
        console.log('failed', response); // supposed to have: data, status, headers, config, statusText
    })

Not strictly an answer to the question, but if you're getting bitten by the "my version of Angular is different than the docs" issue you can always dump all of the arguments, even if you don't know the appropriate method signature:

$http.get('/someUrl')
  .success(function(data, foo, bar) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  })
  .error(function(baz, foo, bar, idontknow) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  });

Then, based on whatever you find, you can 'fix' the function arguments to match.

How to set a JVM TimeZone Properly

The accepted answer above:

-Duser.timezone="Europe/Sofia" 

Didn't work for me exactly. I only was able to successfully change my timezone when I didn't have quotes around the parameters:

-Duser.timezone=Europe/Sofia

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

How to use a ViewBag to create a dropdownlist?

hope it will work

 @Html.DropDownList("accountid", (IEnumerable<SelectListItem>)ViewBag.Accounts, String.Empty, new { @class ="extra-class" })

Here String.Empty will be the empty as a default selector.

How to multiply duration by integer?

In Go, you can multiply variables of same type, so you need to have both parts of the expression the same type.

The simplest thing you can do is casting an integer to duration before multiplying, but that would violate unit semantics. What would be multiplication of duration by duration in term of units?

I'd rather convert time.Millisecond to an int64, and then multiply it by the number of milliseconds, then cast to time.Duration:

time.Duration(int64(time.Millisecond) * int64(rand.Int31n(1000)))

This way any part of the expression can be said to have a meaningful value according to its type. int64(time.Millisecond) part is just a dimensionless value - the number of smallest units of time in the original value.

If walk a slightly simpler path:

time.Duration(rand.Int31n(1000)) * time.Millisecond

The left part of multiplication is nonsense - a value of type "time.Duration", holding something irrelevant to its type:

numberOfMilliseconds := 100
// just can't come up with a name for following:
someLHS := time.Duration(numberOfMilliseconds)
fmt.Println(someLHS)
fmt.Println(someLHS*time.Millisecond)

And it's not just semantics, there is actual functionality associated with types. This code prints:

100ns
100ms

Interestingly, the code sample here uses the simplest code, with the same misleading semantics of Duration conversion: https://golang.org/pkg/time/#Duration

seconds := 10

fmt.Print(time.Duration(seconds)*time.Second) // prints 10s

Casting string to enum

.NET 4.0+ has a generic Enum.TryParse

ContentEnum content;
Enum.TryParse(fileContentMessage, out content);

wildcard * in CSS for classes

Yes you can do this.

*[id^='term-']{
    [css here]
}

This will select all ids that start with 'term-'.

As for the reason for not doing this, I see where it would be preferable to select this way; as for style, I wouldn't do it myself, but it's possible.

How to use pip on windows behind an authenticating proxy

I ran into the same issue on windows 7. I managed to get it working by creating a "pip" folder with a "pip.ini" file inside it. I put this folder inside "C:\Users\{my.username}\AppData\Roaming", because according to the Python documentation:

On Windows the configuration file is %APPDATA%\pip\pip.ini

In the pip.ini file I have only:

[global]
proxy = [proxy address]:[proxy port]

So no username:password. And it is working just fine.

xlsxwriter: is there a way to open an existing worksheet in my workbook?

After searching a bit about the method to open the existing sheet in xlxs, i discovered

existingWorksheet = wb.get_worksheet_by_name('Your Worksheet name goes here...')
existingWorksheet.write_row(0,0,'xyz')

You can now append/write any data to the open worksheet. I hope it helps. Thanks

How do I log a Python error with debug information?

This answer builds up from the above excellent ones.

In most applications, you won't be calling logging.exception(e) directly. Most likely you have defined a custom logger specific for your application or module like this:

# Set the name of the app or module
my_logger = logging.getLogger('NEM Sequencer')
# Set the log level
my_logger.setLevel(logging.INFO)

# Let's say we want to be fancy and log to a graylog2 log server
graylog_handler = graypy.GELFHandler('some_server_ip', 12201)
graylog_handler.setLevel(logging.INFO)
my_logger.addHandler(graylog_handler)

In this case, just use the logger to call the exception(e) like this:

try:
    1/0
except ZeroDivisionError, e:
    my_logger.exception(e)

javascript check for not null

Use !== as != will get you into a world of nontransitive JavaScript truth table weirdness.

Python - Module Not Found

I had same error. For those who run python scripts on different servers, please check if the python path is correctly specified in shebang. For me on each server it was located in different dirs.

Import Error: No module named numpy

For those using python 2.7, should try:

apt-get install -y python-numpy

Instead of pip install numpy