Programs & Examples On #Infrared

Why my regexp for hyphenated words doesn't work?

A couple of things:

  1. Your regexes need to be anchored by separators* or you'll match partial words, as is the case now
  2. You're not using the proper syntax for a non-capturing group. It's (?: not (:?

If you address the first problem, you won't need groups at all.

*That is, a blank or beginning/end of string.

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

You can use strcmp:

break x:20 if strcmp(y, "hello") == 0

20 is line number, x can be any filename and y can be any variable.

What is the default encoding of the JVM?

Note that you can change the default encoding of the JVM using the confusingly-named property file.encoding.

If your application is particularly sensitive to encodings (perhaps through usage of APIs implying default encodings), then you should explicitly set this on JVM startup to a consistent (known) value.

JDK was not found on the computer for NetBeans 6.5

You just simply needs to add JAVA_HOME environment variable and provide the complete path of the latest JDK folder on your computer.

Re launch the installer and it would work.

nginx- duplicate default server error

You likely have other files (such as the default configuration) located in /etc/nginx/sites-enabled that needs to be removed.

This issue is caused by a repeat of the default_server parameter supplied to one or more listen directives in your files. You'll likely find this conflicting directive reads something similar to:

listen 80 default_server;

As the nginx core module documentation for listen states:

The default_server parameter, if present, will cause the server to become the default server for the specified address:port pair. If none of the directives have the default_server parameter then the first server with the address:port pair will be the default server for this pair.

This means that there must be another file or server block defined in your configuration with default_server set for port 80. nginx is encountering that first before your mysite.com file so try removing or adjusting that other configuration.

If you are struggling to find where these directives and parameters are set, try a search like so:

grep -R default_server /etc/nginx

Meaning of @classmethod and @staticmethod for beginner?

Meaning of @classmethod and @staticmethod?

  • A method is a function in an object's namespace, accessible as an attribute.
  • A regular (i.e. instance) method gets the instance (we usually call it self) as the implicit first argument.
  • A class method gets the class (we usually call it cls) as the implicit first argument.
  • A static method gets no implicit first argument (like a regular function).

when should I use them, why should I use them, and how should I use them?

You don't need either decorator. But on the principle that you should minimize the number of arguments to functions (see Clean Coder), they are useful for doing just that.

class Example(object):

    def regular_instance_method(self):
        """A function of an instance has access to every attribute of that 
        instance, including its class (and its attributes.)
        Not accepting at least one argument is a TypeError.
        Not understanding the semantics of that argument is a user error.
        """
        return some_function_f(self)

    @classmethod
    def a_class_method(cls):
        """A function of a class has access to every attribute of the class.
        Not accepting at least one argument is a TypeError.
        Not understanding the semantics of that argument is a user error.
        """
        return some_function_g(cls)

    @staticmethod
    def a_static_method():
        """A static method has no information about instances or classes
        unless explicitly given. It just lives in the class (and thus its 
        instances') namespace.
        """
        return some_function_h()

For both instance methods and class methods, not accepting at least one argument is a TypeError, but not understanding the semantics of that argument is a user error.

(Define some_function's, e.g.:

some_function_h = some_function_g = some_function_f = lambda x=None: x

and this will work.)

dotted lookups on instances and classes:

A dotted lookup on an instance is performed in this order - we look for:

  1. a data descriptor in the class namespace (like a property)
  2. data in the instance __dict__
  3. a non-data descriptor in the class namespace (methods).

Note, a dotted lookup on an instance is invoked like this:

instance = Example()
instance.regular_instance_method 

and methods are callable attributes:

instance.regular_instance_method()

instance methods

The argument, self, is implicitly given via the dotted lookup.

You must access instance methods from instances of the class.

>>> instance = Example()
>>> instance.regular_instance_method()
<__main__.Example object at 0x00000000399524E0>

class methods

The argument, cls, is implicitly given via dotted lookup.

You can access this method via an instance or the class (or subclasses).

>>> instance.a_class_method()
<class '__main__.Example'>
>>> Example.a_class_method()
<class '__main__.Example'>

static methods

No arguments are implicitly given. This method works like any function defined (for example) on a modules' namespace, except it can be looked up

>>> print(instance.a_static_method())
None

Again, when should I use them, why should I use them?

Each of these are progressively more restrictive in the information they pass the method versus instance methods.

Use them when you don't need the information.

This makes your functions and methods easier to reason about and to unittest.

Which is easier to reason about?

def function(x, y, z): ...

or

def function(y, z): ...

or

def function(z): ...

The functions with fewer arguments are easier to reason about. They are also easier to unittest.

These are akin to instance, class, and static methods. Keeping in mind that when we have an instance, we also have its class, again, ask yourself, which is easier to reason about?:

def an_instance_method(self, arg, kwarg=None):
    cls = type(self)             # Also has the class of instance!
    ...

@classmethod
def a_class_method(cls, arg, kwarg=None):
    ...

@staticmethod
def a_static_method(arg, kwarg=None):
    ...

Builtin examples

Here are a couple of my favorite builtin examples:

The str.maketrans static method was a function in the string module, but it is much more convenient for it to be accessible from the str namespace.

>>> 'abc'.translate(str.maketrans({'a': 'b'}))
'bbc'

The dict.fromkeys class method returns a new dictionary instantiated from an iterable of keys:

>>> dict.fromkeys('abc')
{'a': None, 'c': None, 'b': None}

When subclassed, we see that it gets the class information as a class method, which is very useful:

>>> class MyDict(dict): pass
>>> type(MyDict.fromkeys('abc'))
<class '__main__.MyDict'> 

My advice - Conclusion

Use static methods when you don't need the class or instance arguments, but the function is related to the use of the object, and it is convenient for the function to be in the object's namespace.

Use class methods when you don't need instance information, but need the class information perhaps for its other class or static methods, or perhaps itself as a constructor. (You wouldn't hardcode the class so that subclasses could be used here.)

Delete the 'first' record from a table in SQL Server, without a WHERE condition

Similar to the selected answer, a table source can be used, in this case a derived query:

delete from dd
from (
    select top 1 *
    from my_table
) dd

Feel free to add orderbys and conditions.

For the next example, I'll assume that the restriction on 'where' is due to not wanting to select a row based on its values. So assuming that we want to delete a row based on position (in this case the first position):

delete from dd
from (
    select
        *,
        row = row_number() over (order by (select 1))
    from my_table
) dd
where row = 1

Note that the (select 1) makes it the sort order that the tables or indexes are in. You can replace that with a newid to get fairly random rows.

You can also add a partition by to delete the top row of each color, for example.

How to make a query with group_concat in sql server

Select
      A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname
    , STUFF((
          SELECT ',' + T.maskdetail
          FROM dbo.maskdetails T
          WHERE A.maskid = T.maskid
          FOR XML PATH('')), 1, 1, '') as maskdetail 
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid
Group by  A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

- Another Update -

Since Twitter Bootstrap version 2.0 - which saw the removal of the .container-fluid class - it has not been possible to implement a two column fixed-fluid layout using just the bootstrap classes - however I have updated my answer to include some small CSS changes that can be made in your own CSS code that will make this possible

It is possible to implement a fixed-fluid structure using the CSS found below and slightly modified HTML code taken from the Twitter Bootstrap Scaffolding : layouts documentation page:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="fixed">  <!-- we want this div to be fixed width -->
            ...
        </div>
        <div class="hero-unit filler">  <!-- we have removed spanX class -->
            ...
        </div>
    </div>
</div>

CSS

/* CSS for fixed-fluid layout */

.fixed {
    width: 150px;  /* the fixed width required */
    float: left;
}

.fixed + div {
     margin-left: 150px;  /* must match the fixed width in the .fixed class */
     overflow: hidden;
}


/* CSS to ensure sidebar and content are same height (optional) */

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
    position: relative;
}

.filler:after{
    background-color:inherit;
    bottom: 0;
    content: "";
    height: auto;
    min-height: 100%;
    left: 0;
    margin:inherit;
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

I have kept the answer below - even though the edit to support 2.0 made it a fluid-fluid solution - as it explains the concepts behind making the sidebar and content the same height (a significant part of the askers question as identified in the comments)


Important

Answer below is fluid-fluid

Update As pointed out by @JasonCapriotti in the comments, the original answer to this question (created for v1.0) did not work in Bootstrap 2.0. For this reason, I have updated the answer to support Bootstrap 2.0

To ensure that the main content fills at least 100% of the screen height, we need to set the height of the html and body to 100% and create a new css class called .fill which has a minimum-height of 100%:

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
}

We can then add the .fill class to any element that we need to take up 100% of the sceen height. In this case we add it to the first div:

<div class="container-fluid fill">
    ...
</div>

To ensure that the Sidebar and the Content columns have the same height is very difficult and unnecessary. Instead we can use the ::after pseudo selector to add a filler element that will give the illusion that the two columns have the same height:

.filler::after {
    background-color: inherit;
    bottom: 0;
    content: "";
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

To make sure that the .filler element is positioned relatively to the .fill element we need to add position: relative to .fill:

.fill { 
    min-height: 100%;
    position: relative;
}

And finally add the .filler style to the HTML:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="span3">
            ...
        </div>
        <div class="span9 hero-unit filler">
            ...
        </div>
    </div>
</div>

Notes

  • If you need the element on the left of the page to be the filler then you need to change right: 0 to left: 0.

How to find out which package version is loaded in R?

Based on the previous answers, here is a simple alternative way of printing the R-version, followed by the name and version of each package loaded in the namespace. It works in the Jupyter notebook, where I had troubles running sessionInfo() and R --version.

print(paste("R", getRversion()))
print("-------------")
for (package_name in sort(loadedNamespaces())) {
    print(paste(package_name, packageVersion(package_name)))
}

Out:

[1] "R 3.2.2"
[1] "-------------"
[1] "AnnotationDbi 1.32.2"
[1] "Biobase 2.30.0"
[1] "BiocGenerics 0.16.1"
[1] "BiocParallel 1.4.3"
[1] "DBI 0.3.1"
[1] "DESeq2 1.10.0"
[1] "Formula 1.2.1"
[1] "GenomeInfoDb 1.6.1"
[1] "GenomicRanges 1.22.3"
[1] "Hmisc 3.17.0"
[1] "IRanges 2.4.6"
[1] "IRdisplay 0.3"
[1] "IRkernel 0.5"

Set value for particular cell in pandas DataFrame with iloc

Another way is to get the row index and then use df.loc or df.at.

# get row index 'label' from row number 'irow'
label = df.index.values[irow] 
df.at[label, 'COL_NAME'] = x

How to pretty-print a numpy.array without scientific notation and with given precision?

I often want different columns to have different formats. Here is how I print a simple 2D array using some variety in the formatting by converting (slices of) my NumPy array to a tuple:

import numpy as np
dat = np.random.random((10,11))*100  # Array of random values between 0 and 100
print(dat)                           # Lines get truncated and are hard to read
for i in range(10):
    print((4*"%6.2f"+7*"%9.4f") % tuple(dat[i,:]))

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

This gist will do most of the work for you showing a menu when there are multiple devices connected:

$ adb $(android-select-device) shell
1) 02783201431feeee device 3) emulator-5554
2) 3832380FA5F30000 device 4) emulator-5556
Select the device to use, <Q> to quit:

To avoid typing you can just create an alias that included the device selection as explained here.

Adding external library into Qt Creator project

LIBS += C:\Program Files\OpenCV\lib

won't work because you're using white-spaces in Program Files. In this case you have to add quotes, so the result will look like this: LIBS += "C:\Program Files\OpenCV\lib". I recommend placing libraries in non white-space locations ;-)

How to use awk sort by column 3

You can choose a delimiter, in this case I chose a colon and printed the column number one, sorting by alphabetical order:

awk -F\: '{print $1|"sort -u"}' /etc/passwd

Multidimensional Array [][] vs [,]

double[][] are called jagged arrays , The inner dimensions aren’t specified in the declaration. Unlike a rectangular array, each inner array can be an arbitrary length. Each inner array is implicitly initialized to null rather than an empty array. Each inner array must be created manually: Reference [C# 4.0 in nutshell The definitive Reference]

for (int i = 0; i < matrix.Length; i++)
{
    matrix[i] = new int [3]; // Create inner array
    for (int j = 0; j < matrix[i].Length; j++)
        matrix[i][j] = i * 3 + j;
}

double[,] are called rectangular arrays, which are declared using commas to separate each dimension. The following piece of code declares a rectangular 3-by-3 two-dimensional array, initializing it with numbers from 0 to 8:

int [,] matrix = new int [3, 3];
for (int i = 0; i < matrix.GetLength(0); i++)
    for (int j = 0; j < matrix.GetLength(1); j++)
        matrix [i, j] = i * 3 + j;

internet explorer 10 - how to apply grayscale filter?

Inline SVG can be used in IE 10 and 11 and Edge 12.

I've created a project called gray which includes a polyfill for these browsers. The polyfill switches out <img> tags with inline SVG: https://github.com/karlhorky/gray

To implement, the short version is to download the jQuery plugin at the GitHub link above and add after jQuery at the end of your body:

<script src="/js/jquery.gray.min.js"></script>

Then every image with the class grayscale will appear as gray.

<img src="/img/color.jpg" class="grayscale">

You can see a demo too if you like.

Infinite Recursion with Jackson JSON and Hibernate JPA issue

I have faced same issue, add jsonbackref and jsonmanagedref and please make sure @override equals and hashCode methods , this definitely fix this issue.

What good are SQL Server schemas?

I don't see the benefit in aliasing out users tied to Schemas. Here is why....

Most people connect their user accounts to databases via roles initially, As soon as you assign a user to either the sysadmin, or the database role db_owner, in any form, that account is either aliased to the "dbo" user account, or has full permissions on a database. Once that occurs, no matter how you assign yourself to a scheme beyond your default schema (which has the same name as your user account), those dbo rights are assigned to those object you create under your user and schema. Its kinda pointless.....and just a namespace and confuses true ownership on those objects. Its poor design if you ask me....whomever designed it.

What they should have done is created "Groups", and thrown out schemas and role and just allow you to tier groups of groups in any combination you like, then at each tier tell the system if permissions are inherited, denied, or overwritten with custom ones. This would have been so much more intuitive and allowed DBA's to better control who the real owners are on those objects. Right now its implied in most cases the dbo default SQL Server user has those rights....not the user.

What is the optimal algorithm for the game 2048?

This algorithm is not optimal for winning the game, but it is fairly optimal in terms of performance and amount of code needed:

  if(can move neither right, up or down)
    direction = left
  else
  {
    do
    {
      direction = random from (right, down, up)
    }
    while(can not move in "direction")
  }

clear form values after submission ajax

You can do this inside your $.post calls success callback like this

$.post('mail.php',{name:$('#name').val(),
                              email:$('#e-mail').val(),
                              phone:$('#phone').val(),
                              message:$('#message').val()},

            //return the data
            function(data){

              //hide the graphic
              $('.bar').css({display:'none'});
              $('.loader').append(data);

              //clear fields
              $('input[type="text"],textarea').val('');

            });

What values can I pass to the event attribute of the f:ajax tag?

The event attribute of <f:ajax> can hold at least all supported DOM events of the HTML element which is been generated by the JSF component in question. An easy way to find them all out is to check all on* attribues of the JSF input component of interest in the JSF tag library documentation and then remove the "on" prefix. For example, the <h:inputText> component which renders <input type="text"> lists the following on* attributes (of which I've already removed the "on" prefix so that it ultimately becomes the DOM event type name):

  • blur
  • change
  • click
  • dblclick
  • focus
  • keydown
  • keypress
  • keyup
  • mousedown
  • mousemove
  • mouseout
  • mouseover
  • mouseup
  • select

Additionally, JSF has two more special event names for EditableValueHolder and ActionSource components, the real HTML DOM event being rendered depends on the component type:

  • valueChange (will render as change on text/select inputs and as click on radio/checkbox inputs)
  • action (will render as click on command links/buttons)

The above two are the default events for the components in question.

Some JSF component libraries have additional customized event names which are generally more specialized kinds of valueChange or action events, such as PrimeFaces <p:ajax> which supports among others tabChange, itemSelect, itemUnselect, dateSelect, page, sort, filter, close, etc depending on the parent <p:xxx> component. You can find them all in the "Ajax Behavior Events" subsection of each component's chapter in PrimeFaces Users Guide.

Generating random, unique values C#

You can use basic Random Functions of C#

Random ran = new Random();
int randomno = ran.Next(0,100);

you can now use the value in the randomno in anything you want but keep in mind that this will generate a random number between 0 and 100 Only and you can extend that to any figure.

Correct way to pause a Python program

By this method, you can resume your program just by pressing any specified key you've specified that:

import keyboard
while True:
    key = keyboard.read_key()
    if key == 'space':  # You can put any key you like instead of 'space'
        break

The same method, but in another way:

import keyboard
while True:
    if keyboard.is_pressed('space'):  # The same. you can put any key you like instead of 'space'
        break

Note: you can install the keyboard module simply by writing this in you shell or cmd:

pip install keyboard

Perform an action in every sub-directory using Bash

for D in `find . -type d`
do
    //Do whatever you need with D
done

rsync: how can I configure it to create target directory on server?

I don't think you can do it with one rsync command, but you can 'pre-create' the extra directory first like this:

rsync --recursive emptydir/ destination/newdir

where 'emptydir' is a local empty directory (which you might have to create as a temporary directory first).

It's a bit of a hack, but it works for me.

cheers

Chris

Open Sublime Text from Terminal in macOS

You can create a new alias in Terminal:

nano ~/.bash_profile

Copy this line and paste it into the editor:

alias subl='open -a "Sublime Text"'

Hit control + x, then y, then enter to save and close it.

Close all Terminal windows and open it up again.

That's it, you can now use subl filename or subl .

Delete duplicate records from a SQL table without a primary key

Having a database table without Primary Key is really and will say extremely BAD PRACTICE...so after you add one (ALTER TABLE)

Run this until you don't see any more duplicated records (that is the purpose of HAVING COUNT)

DELETE FROM [TABLE_NAME] WHERE [Id] IN 
(
    SELECT MAX([Id])
    FROM [TABLE_NAME]
    GROUP BY [TARGET_COLUMN]
    HAVING COUNT(*) > 1
)


SELECT MAX([Id]),[TABLE_NAME], COUNT(*) AS dupeCount
FROM [TABLE_NAME]
GROUP BY [TABLE_NAME]
HAVING COUNT(*) > 1

MAX([Id]) will cause to delete latest records (ones added after first created) in case you want the opposite meaning that in case of requiring deleting first records and leave the last record inserted please use MIN([Id])

How can I use getSystemService in a non-activity class (LocationManager)?

I don't know if this will help, but I did this:

LocationManager locationManager  = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);

How to display errors for my MySQLi query?

Just simply add or die(mysqli_error($db)); at the end of your query, this will print the mysqli error.

 mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));

As a side note I'd say you are at risk of mysql injection, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.

Fatal error: Call to a member function bind_param() on boolean

I noticed that the error was caused by me passing table field names as variables i.e. I sent:

$stmt = $this->con->prepare("INSERT INTO tester ($test1, $test2) VALUES (?, ?)");

instead of:

$stmt = $this->con->prepare("INSERT INTO tester (test1, test2) VALUES (?, ?)");

Please note the table field names contained $ before field names. They should not be there such that $field1 should be field1.

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Migrator cannot identify all the functions that need @objc Inferred Objective-C thunks marked as deprecated to help you find them
• Build warnings about deprecated methods
• Console messages when running deprecated thunks

enter image description here

Android Material: Status bar color won't change

This solution sets the statusbar color of Lollipop, Kitkat and some pre Lollipop devices (Samsung and Sony). The SystemBarTintManager is managing the Kitkat devices ;)

@Override
protected void onCreate( Bundle savedInstanceState ) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    hackStatusBarColor(this, R.color.primary_dark);
}

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public static View hackStatusBarColor( final Activity act, final int colorResID ) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        try {

            if (act.getWindow() != null) {

                final ViewGroup vg = (ViewGroup) act.getWindow().getDecorView();
                if (vg.getParent() == null && applyColoredStatusBar(act, colorResID)) {
                    final View statusBar = new View(act);

                    vg.post(new Runnable() {
                        @Override
                        public void run() {

                            int statusBarHeight = (int) Math.ceil(25 * vg.getContext().getResources().getDisplayMetrics().density);
                            statusBar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, statusBarHeight));
                            statusBar.setBackgroundColor(act.getResources().getColor(colorResID));
                            statusBar.setId(13371337);
                            vg.addView(statusBar, 0);
                        }
                    });
                    return statusBar;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    else if (act.getWindow() != null) {
        act.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        act.getWindow().setStatusBarColor(act.getResources().getColor(colorResID));
    }
    return null;
}

private static boolean applyColoredStatusBar( Activity act, int colorResID ) {
    final Window window = act.getWindow();
    final int flag;
    if (window != null) {
        View decor = window.getDecorView();
        if (decor != null) {
            flag = resolveTransparentStatusBarFlag(act);

            if (flag != 0) {
                decor.setSystemUiVisibility(flag);
                return true;
            }
            else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                act.findViewById(android.R.id.content).setFitsSystemWindows(false);
                setTranslucentStatus(window, true);
                final SystemBarTintManager tintManager = new SystemBarTintManager(act);
                tintManager.setStatusBarTintEnabled(true);
                tintManager.setStatusBarTintColor(colorResID);
            }
        }
    }
    return false;
}

public static int resolveTransparentStatusBarFlag( Context ctx ) {
    String[] libs = ctx.getPackageManager().getSystemSharedLibraryNames();
    String reflect = null;

    if (libs == null)
        return 0;

    final String SAMSUNG = "touchwiz";
    final String SONY = "com.sonyericsson.navigationbar";

    for (String lib : libs) {

        if (lib.equals(SAMSUNG)) {
            reflect = "SYSTEM_UI_FLAG_TRANSPARENT_BACKGROUND";
        }
        else if (lib.startsWith(SONY)) {
            reflect = "SYSTEM_UI_FLAG_TRANSPARENT";
        }
    }

    if (reflect == null)
        return 0;

    try {
        Field field = View.class.getField(reflect);
        if (field.getType() == Integer.TYPE) {
            return field.getInt(null);
        }
    } catch (Exception e) {
    }

    return 0;
}

@TargetApi(Build.VERSION_CODES.KITKAT)
public static void setTranslucentStatus( Window win, boolean on ) {
    WindowManager.LayoutParams winParams = win.getAttributes();
    final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
    if (on) {
        winParams.flags |= bits;
    }
    else {
        winParams.flags &= ~bits;
    }
    win.setAttributes(winParams);
}

How to use Oracle ORDER BY and ROWNUM correctly?

Use ROW_NUMBER() instead. ROWNUM is a pseudocolumn and ROW_NUMBER() is a function. You can read about difference between them and see the difference in output of below queries:

SELECT * FROM (SELECT rownum, deptno, ename
           FROM scott.emp
        ORDER BY deptno
       )
 WHERE rownum <= 3
 /

ROWNUM    DEPTNO    ENAME
---------------------------
 7        10    CLARK
 14       10    MILLER
 9        10    KING


 SELECT * FROM 
 (
  SELECT deptno, ename
       , ROW_NUMBER() OVER (ORDER BY deptno) rno
  FROM scott.emp
 ORDER BY deptno
 )
WHERE rno <= 3
/

DEPTNO    ENAME    RNO
-------------------------
10    CLARK        1
10    MILLER       2
10    KING         3

Contains method for a slice

I think map[x]bool is more useful than map[x]struct{}.

Indexing the map for an item that isn't present will return false so instead of _, ok := m[X], you can just say m[X].

This makes it easy to nest inclusion tests in expressions.

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

I got this error message in Xcode 8 while refactoring code in to a framework, it comes out that I forgot to declare the class in the framework as public

Convert string to List<string> in one line?

The List<T> has a constructor that accepts an IEnumerable<T>:

List<string> listOfNames = new List<string>(names.Split(','));

Read a file line by line with VB.NET

Replaced the reader declaration with this one and now it works!

Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)

Encoding.Default represents the ANSI code page that is set under Windows Control Panel.

Canvas width and height in HTML5

Thank you very much! Finally I solved the blurred pixels problem with this code:

<canvas id="graph" width=326 height=240 style='width:326px;height:240px'></canvas>

With the addition of the 'half-pixel' does the trick to unblur lines.

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

VBA subs are no macros. A VBA sub can be a macro, but it is not a must.

The term "macro" is only used for recorded user actions. from these actions a code is generated and stored in a sub. This code is simple and do not provide powerful structures like loops, for example Do .. until, for .. next, while.. do, and others.

The more elegant way is, to design and write your own VBA code without using the macro features!

VBA is a object based and event oriented language. Subs, or bette call it "sub routines", are started by dedicated events. The event can be the pressing of a button or the opening of a workbook and many many other very specific events.

If you focus to VB6 and not to VBA, then you can state, that there is always a main-window or main form. This form is started if you start the compiled executable "xxxx.exe".

In VBA you have nothing like this, but you have a XLSM file wich is started by Excel. You can attach some code to the Workbook_Open event. This event is generated, if you open your desired excel file which is called a workbook. Inside the workbook you have worksheets.

It is useful to get more familiar with the so called object model of excel. The workbook has several events and methods. Also the worksheet has several events and methods.

In the object based model you have objects, that have events and methods. methods are action you can do with a object. events are things that can happen to an object. An objects can contain another objects, and so on. You can create new objects, like sheets or charts.

How to instantiate a javascript class in another js file?

It is saying the value is undefined because it is a constructor function, not a class with a constructor. In order to use it, you would need to use Customer() or customer().

First, you need to load file1.js before file2.js, like slebetman said:

<script defer src="file1.js" type="module"></script>
<script defer src="file2.js" type="module"></script>

Then, you could change your file1.js as follows:

export default class Customer(){
    constructor(){
        this.name="Jhon";
        this.getName=function(){
            return this.name;
        };
    }
}

And the file2.js as follows:

import { Customer } from "./file1";
var customer=new Customer();

Please correct me if I am wrong.

Application Crashes With "Internal Error In The .NET Runtime"

After years of wrestling with this issue in a number of applications, it appears that Microsoft has finally accepted it as a bug in .NET 4 CLR that causes this to occur. http://support.microsoft.com/kb/2640103.

I had previously been "fixing" it by forcing the garbage collector to run in server mode (gcServer enabled="true" in app.config) as described in the Microsoft article linked to by Think Before Coding. This in essence forces all threads in the application to pause during the collection removing the possibility of other threads accessing the memory being manipulated by the GC. I am happy to find that my years of searching in vain for a "bug" in my code or other 3rd party unmanaged libraries were only fruitless because the bug lay in Microsoft's code, not mine.

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

Remove the class 'Carousal slide' on page load & add it dynamically when image gets loaded using jquery.This fixed for me

jQuery Validation using the class instead of the name value

Another way you can do it, is using addClassRules. It's specific for classes, while the option using selector and .rules is more a generic way.

Before calling

$(form).validate()

Use like this:

jQuery.validator.addClassRules('myClassName', {
        required: true /*,
        other rules */
    });

Ref: http://docs.jquery.com/Plugins/Validation/Validator/addClassRules#namerules

I prefer this syntax for a case like this.

Fast and simple String encrypt/decrypt in JAVA

If you are using Android then you can use android.util.Base64 class.

Encode:

passwd = Base64.encodeToString( passwd.getBytes(), Base64.DEFAULT );

Decode:

passwd = new String( Base64.decode( passwd, Base64.DEFAULT ) );

A simple and fast single line solution.

Selector on background color of TextView

An even simpler solution to the above:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <color android:color="@color/semitransparent_white" />
    </item>
    <item>
        <color android:color="@color/transparent" />
    </item>
</selector>

Save that in the drawable folder and you're good to go.

Check if a list contains an item in Ansible

Ansible has a version_compare filter since 1.6. You can do something like below in when conditional:

when: ansible_distribution_version | version_compare('12.04', '>=')

This will give you support for major & minor versions comparisons and you can compare versions using operators like:

<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne

You can find more information about this here: Ansible - Version comparison filters

Otherwise if you have really simple case you can use what @ProfHase85 suggested

Disable ScrollView Programmatically?

Disablend ScrollView

ScrollView sw = (ScrollView) findViewById(R.id.scrollView1);
sw.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;
    }
});

How to get the number of characters in a string

There are several ways to get a string length:

package main

import (
    "bytes"
    "fmt"
    "strings"
    "unicode/utf8"
)

func main() {
    b := "?????"
    len1 := len([]rune(b))
    len2 := bytes.Count([]byte(b), nil) -1
    len3 := strings.Count(b, "") - 1
    len4 := utf8.RuneCountInString(b)
    fmt.Println(len1)
    fmt.Println(len2)
    fmt.Println(len3)
    fmt.Println(len4)

}

How to modify a global variable within a function in bash?

It's because command substitution is performed in a subshell, so while the subshell inherits the variables, changes to them are lost when the subshell ends.

Reference:

Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment

Can I grep only the first n lines of a file?

head -10 log.txt | grep -A 2 -B 2 pattern_to_search

-A 2: print two lines before the pattern.

-B 2: print two lines after the pattern.

head -10 log.txt # read the first 10 lines of the file.

Get and Set Screen Resolution

If you want to collect screen resolution you can run the following code within a WPF window (the window is what the this would refer to):

System.Windows.Media.Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
Double dpiX = m.M11 * 96;
Double dpiY = m.M22 * 96;

How to include a child object's child object in Entity Framework 5

If you include the library System.Data.Entity you can use an overload of the Include() method which takes a lambda expression instead of a string. You can then Select() over children with Linq expressions rather than string paths.

return DatabaseContext.Applications
     .Include(a => a.Children.Select(c => c.ChildRelationshipType));

How do I link to a library with Code::Blocks?

The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)

To link with gdi32:

enter image description here

This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a has no advantage over gdi32 other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib for MSVC).

For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).

Angular 6: How to set response type as text while making http call

Use like below:

  yourFunc(input: any):Observable<string> {
var requestHeader = { headers: new HttpHeaders({ 'Content-Type': 'text/plain', 'No-Auth': 'False' })};
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.post<string>(this.yourBaseApi+ '/do-api', input, { headers, responseType: 'text' as 'json'  });

}

Restricting input to textbox: allowing only numbers and decimal point

Suppose your textbox field name is Income
Call this validate method when you need to validate your field:

function validate() {
    var currency = document.getElementById("Income").value;
      var pattern = /^[1-9]\d*(?:\.\d{0,2})?$/ ;
    if (pattern.test(currency)) {
        alert("Currency is in valid format");
        return true;
    } 
        alert("Currency is not in valid format!Enter in 00.00 format");
        return false;
}

Setting timezone in Python

You can use pytz as well..

import datetime
import pytz
def utcnow():
    return datetime.datetime.now(tz=pytz.utc)
utcnow()
   datetime.datetime(2020, 8, 15, 14, 45, 19, 182703, tzinfo=<UTC>)
utcnow().isoformat()

'

2020-08-15T14:45:21.982600+00:00'

Removing padding gutter from grid columns in Bootstrap 4

Bootstrap4: Comes with .no-gutters out of the box. source: https://github.com/twbs/bootstrap/pull/21211/files

Bootstrap3:

Requires custom CSS.

Stylesheet:

.row.no-gutters {
  margin-right: 0;
  margin-left: 0;

  & > [class^="col-"],
  & > [class*=" col-"] {
    padding-right: 0;
    padding-left: 0;
  }
}

Then to use:

<div class="row no-gutters">
  <div class="col-xs-4">...</div>
  <div class="col-xs-4">...</div>
  <div class="col-xs-4">...</div>
</div>

It will:

  • Remove margin from the row
  • Remove padding from all columns directly beneath the row

Set language for syntax highlighting in Visual Studio Code

Syntax Highlighting for custom file extension

Any custom file extension can be associated with standard syntax highlighting with custom files association in User Settings as follows.

Changing File Association settings for permanent Syntax Highlighting

Note that this will be a permanent setting. In order to set for the current session alone, type in the preferred language in Select Language Mode box (without changing file association settings)

Installing new Syntax Package

If the required syntax package is not available by default, you can add them via the Extension Marketplace (Ctrl+Shift+X) and search for the language package.

You can further reproduce the above steps to map the file extensions with the new syntax package.

how to view the contents of a .pem certificate

An alternative to using keytool, you can use the command

openssl x509 -in certificate.pem -text

This should work for any x509 .pem file provided you have openssl installed.

How to remove all white spaces in java

package com.infy.test;

import java.util.Scanner ;
import java.lang.String ;

public class Test1 {


    public static void main (String[]args)
    {

        String a  =null;


        Scanner scan = new Scanner(System.in);
        System.out.println("*********White Space Remover Program************\n");
        System.out.println("Enter your string\n");
    a = scan.nextLine();
        System.out.println("Input String is  :\n"+a);


        String b= a.replaceAll("\\s+","");

        System.out.println("\nOutput String is  :\n"+b);


    }
}

Convert image from PIL to openCV format

The code commented works as well, just choose which do you prefer

import numpy as np
from PIL import Image


def convert_from_cv2_to_image(img: np.ndarray) -> Image:
    # return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    return Image.fromarray(img)


def convert_from_image_to_cv2(img: Image) -> np.ndarray:
    # return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
    return np.asarray(img)

Color theme for VS Code integrated terminal

The best colors I've found --which aside from being so beautiful, are very easy to look at too and do not boil my eyes-- are the ones I've found listed in this GitHub repository: VSCode Snazzy

Very Easy Installation:

Copy the contents of snazzy.json into your VS Code "settings.json" file.

(In case you don't know how to open the "settings.json" file, first hit Ctrl+Shift+P and then write Preferences: open settings(JSON) and hit enter).


Notice: For those who have tried ColorTool and it works outside VSCode but not inside VSCode, you've made no mistakes in implementing it, that's just a decision of VSCode developers for the VSCode's terminal to be colored independently.

unsigned int vs. size_t

The size_t type is the type returned by the sizeof operator. It is an unsigned integer capable of expressing the size in bytes of any memory range supported on the host machine. It is (typically) related to ptrdiff_t in that ptrdiff_t is a signed integer value such that sizeof(ptrdiff_t) and sizeof(size_t) are equal.

When writing C code you should always use size_t whenever dealing with memory ranges.

The int type on the other hand is basically defined as the size of the (signed) integer value that the host machine can use to most efficiently perform integer arithmetic. For example, on many older PC type computers the value sizeof(size_t) would be 4 (bytes) but sizeof(int) would be 2 (byte). 16 bit arithmetic was faster than 32 bit arithmetic, though the CPU could handle a (logical) memory space of up to 4 GiB.

Use the int type only when you care about efficiency as its actual precision depends strongly on both compiler options and machine architecture. In particular the C standard specifies the following invariants: sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) placing no other limitations on the actual representation of the precision available to the programmer for each of these primitive types.

Note: This is NOT the same as in Java (which actually specifies the bit precision for each of the types 'char', 'byte', 'short', 'int' and 'long').

How to set textColor of UILabel in Swift

If you are using Xcode 8 and swift 3. Use the following way to get the UIColor

label1.textColor = UIColor.red
label2.textColor = UIColor.black

What is the difference between "screen" and "only screen" in media queries?

Let's break down your examples one by one.

@media (max-width:632px)

This one is saying for a window with a max-width of 632px that you want to apply these styles. At that size you would be talking about anything smaller than a desktop screen in most cases.

@media screen and (max-width:632px)

This one is saying for a device with a screen and a window with max-width of 632px apply the style. This is almost identical to the above except you are specifying screen as opposed to the other available media types the most common other one being print.

@media only screen and (max-width:632px)

Here is a quote straight from W3C to explain this one.

The keyword ‘only’ can also be used to hide style sheets from older user agents. User agents must process media queries starting with ‘only’ as if the ‘only’ keyword was not present.

As there is no such media type as "only", the style sheet should be ignored by older browsers.

Here's the link to that quote that is shown in example 9 on that page.

Hopefully this sheds some light on media queries.

EDIT:

Be sure to check out @hybrids excellent answer on how the only keyword is really handled.

Horizontal list items

You could also use inline blocks to avoid floating elements

<ul>
    <li>
        <a href="#">some item</a>
    </li>
    <li>
        <a href="#">another item</a>
   </li>
</ul>

and then style as:

li{
    /* with fix for IE */
    display:inline;
    display:inline-block;
    zoom:1;
    /*
    additional styles to make it look nice
    */
 }

that way you wont need to float anything, eliminating the need for clearfixes

Using Mockito's generic "any()" method

You can use Mockito.isA() for that:

import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;

verify(bar).doStuff(isA(Foo[].class));

http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)

Windows path in Python

Use PowerShell

In Windows, you can use / in your path just like Linux or macOS in all places as long as you use PowerShell as your command-line interface. It comes pre-installed on Windows and it supports many Linux commands like ls command.

If you use Windows Command Prompt (the one that appears when you type cmd in Windows Start Menu), you need to specify paths with \ just inside it. You can use / paths in all other places (code editor, Python interactive mode, etc.).

dynamically add and remove view to viewpager

I did a similar program. hope this would help you.In its first activity four grid data can be selected. On the next activity, there is a view pager which contains two mandatory pages.And 4 more pages will be there, which will be visible corresponding to the grid data selected.

Following is the mainactivty MainActivity

    package com.example.jeffy.viewpagerapp;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.os.Bundle;
    import android.os.Parcel;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.util.Log;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.AdapterView;
    import android.widget.Button;
    import android.widget.GridView;
    import java.lang.reflect.Array;
    import java.util.ArrayList;
    public class MainActivity extends AppCompatActivity {
    SharedPreferences pref;
    SharedPreferences.Editor editor;
    GridView gridView;
    Button button;
    private static final String DATABASE_NAME = "dbForTest.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "diary";
    private static final String TITLE = "id";
    private static final String BODY = "content";
    DBHelper  dbHelper = new DBHelper(this);
    ArrayList<String> frags = new ArrayList<String>();
    ArrayList<FragmentArray> fragmentArray = new ArrayList<FragmentArray>();
    String[] selectedData;
    Boolean port1=false,port2=false,port3=false,port4=false;
    int Iport1=1,Iport2=1,Iport3=1,Iport4=1,location;



    // This Data show in grid ( Used by adapter )
        CustomGridAdapter customGridAdapter = new           CustomGridAdapter(MainActivity.this,GRID_DATA);
    static final String[ ] GRID_DATA = new String[] {
            "1" ,
            "2",
            "3" ,
            "4"
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        frags.add("TabFragment3");
        frags.add("TabFragment4");
        frags.add("TabFragment5");
        frags.add("TabFragment6");
        dbHelper = new DBHelper(this);
        dbHelper.insertContact(1,0);
        dbHelper.insertContact(2,0);
        dbHelper.insertContact(3,0);
        dbHelper.insertContact(4,0);
        final Bundle selected = new Bundle();
        button = (Button) findViewById(R.id.button);
        pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
        editor = pref.edit();
        gridView = (GridView) findViewById(R.id.gridView1);

        gridView.setAdapter(customGridAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              //view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                location = position + 1;
                if (position == 0) {
                    Iport1++;
                    Iport1 = Iport1 % 2;
                    if (Iport1 % 2 == 1) {
                        //dbHelper.updateContact(1,1);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                        dbHelper.updateContact(1,1);
                    } else {
                        //dbHelper.updateContact(1,0);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);
                        dbHelper.updateContact(1, 0);
                    }
                }
                if (position == 1) {
                    Iport2++;
                    Iport1 = Iport1 % 2;
                    if (Iport2 % 2 == 1) {
                        //dbHelper.updateContact(2,1);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                        dbHelper.updateContact(2, 1);
                    } else {
                        //dbHelper.updateContact(2,0);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);
                        dbHelper.updateContact(2,0);
                    }
                }
                if (position == 2) {
                    Iport3++;
                    Iport3 = Iport3 % 2;
                    if (Iport3 % 2 == 1) {
                        //dbHelper.updateContact(3,1);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                        dbHelper.updateContact(3, 1);
                    } else {
                        //dbHelper.updateContact(3,0);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);
                        dbHelper.updateContact(3, 0);
                    }
                }
                if (position == 3) {
                    Iport4++;
                    Iport4 = Iport4 % 2;
                    if (Iport4 % 2 == 1) {
                        //dbHelper.updateContact(4,1);
                       view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                        dbHelper.updateContact(4, 1);
                    } else {
                        //dbHelper.updateContact(4,0);
                       view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);
                        dbHelper.updateContact(4,0);
                    }
                }
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor.putInt("port1", Iport1);
                editor.putInt("port2", Iport2);
                editor.putInt("port3", Iport3);
                editor.putInt("port4", Iport4);
                Intent i = new Intent(MainActivity.this,Main2Activity.class);
                if(Iport1==1)
                    i.putExtra("3","TabFragment3");
                else
                    i.putExtra("3", "");
                if(Iport2==1)
                    i.putExtra("4","TabFragment4");
                else
                    i.putExtra("4","");
                if(Iport3==1)
                    i.putExtra("5", "TabFragment5");
                else
                    i.putExtra("5","");
                if(Iport4==1)
                    i.putExtra("6", "TabFragment6");
                else
                    i.putExtra("6","");
                dbHelper.updateContact(0, Iport1);
                dbHelper.updateContact(1, Iport2);
                dbHelper.updateContact(2, Iport3);
                dbHelper.updateContact(3, Iport4);
                startActivity(i);
            }
        });
    }
}

Here TabFragment1,TabFragment2 etc are fragment to be displayed on the viewpager.And I am not showing the layouts since they are out of scope of this project.

MainActivity will intent to Main2Activity Main2Activity

    package com.example.jeffy.viewpagerapp;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;

import java.util.ArrayList;

public class Main2Activity extends AppCompatActivity {

    private ViewPager pager = null;
    private PagerAdapter pagerAdapter = null;
    DBHelper dbHelper;
    Cursor rs;
    int port1,port2,port3,port4;
    //-----------------------------------------------------------------------------
    @Override
    public void onCreate (Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.MyToolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapse_toolbar);


        NestedScrollView scrollView = (NestedScrollView) findViewById (R.id.nested);
        scrollView.setFillViewport (true);

        ArrayList<String > selectedPort = new ArrayList<String>();

        Intent intent = getIntent();
        String Tab3 = intent.getStringExtra("3");
        String Tab4 = intent.getStringExtra("4");
        String Tab5 = intent.getStringExtra("5");
        String Tab6 = intent.getStringExtra("6");

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("View"));
        tabLayout.addTab(tabLayout.newTab().setText("All"));

        selectedPort.add("TabFragment1");
        selectedPort.add("TabFragment2");
        if(Tab3!=null && !TextUtils.isEmpty(Tab3))
        selectedPort.add(Tab3);
        if(Tab4!=null && !TextUtils.isEmpty(Tab4))
        selectedPort.add(Tab4);
        if(Tab5!=null && !TextUtils.isEmpty(Tab5))
        selectedPort.add(Tab5);
        if(Tab6!=null && !TextUtils.isEmpty(Tab6))
        selectedPort.add(Tab6);



        dbHelper = new DBHelper(this);
//        rs=dbHelper.getData(1);
//        port1 = rs.getInt(rs.getColumnIndex("id"));
//
//        rs=dbHelper.getData(2);
//        port2 = rs.getInt(rs.getColumnIndex("id"));
//
//        rs=dbHelper.getData(3);
//        port3 = rs.getInt(rs.getColumnIndex("id"));
//
//        rs=dbHelper.getData(4);
//        port4 = rs.getInt(rs.getColumnIndex("id"));


        Log.i(">>>>>>>>>>>>>>", "port 1" + port1 + "port 2" + port2 + "port 3" + port3 + "port 4" + port4);

        if(Tab3!=null && !TextUtils.isEmpty(Tab3))
        tabLayout.addTab(tabLayout.newTab().setText("Tab 0"));
        if(Tab3!=null && !TextUtils.isEmpty(Tab4))
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        if(Tab3!=null && !TextUtils.isEmpty(Tab5))
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        if(Tab3!=null && !TextUtils.isEmpty(Tab6))
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
        final PagerAdapter adapter = new PagerAdapter
                (getSupportFragmentManager(), tabLayout.getTabCount(), selectedPort);
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
//        setContentView(R.layout.activity_main2);
//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);

//        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
//        tabLayout.addTab(tabLayout.newTab().setText("View"));
//        tabLayout.addTab(tabLayout.newTab().setText("All"));
//        tabLayout.addTab(tabLayout.newTab().setText("Tab 0"));
//        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
//        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
//        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
//        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);


}
    }

ViewPagerAdapter Viewpageradapter.class

package com.example.jeffy.viewpagerapp;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jeffy on 25-01-2016.
 */
public class PagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;

    List<String> values;

    public PagerAdapter(FragmentManager fm, int NumOfTabs, List<String> Port) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
        this.values= Port;
    }


    @Override
    public Fragment getItem(int position) {


        String fragmentName = values.get(position);
        Class<?> clazz = null;
        Object fragment = null;
        try {
            clazz = Class.forName("com.example.jeffy.viewpagerapp."+fragmentName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            fragment = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return (Fragment) fragment;
    }

    @Override
    public int getCount() {
        return values.size();
    }
}

Layout for main2activity acticity_main2.xml

    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/MyAppbar"
            android:layout_width="match_parent"
            android:layout_height="256dp"
            android:fitsSystemWindows="true">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapse_toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"
                android:background="@color/material_deep_teal_500"
                android:fitsSystemWindows="true">

                <ImageView
                    android:id="@+id/bgheader"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:scaleType="centerCrop"
                    android:fitsSystemWindows="true"
                    android:background="@drawable/screen"
                    app:layout_collapseMode="pin" />

                <android.support.v7.widget.Toolbar
                    android:id="@+id/MyToolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="parallax" />





            </android.support.design.widget.CollapsingToolbarLayout>

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:id="@+id/nested"
            android:layout_height="match_parent"
            android:layout_gravity="fill_vertical"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/MyToolbar"
            android:background="?attr/colorPrimary"
            android:elevation="6dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>


        <android.support.v4.view.ViewPager
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

        </android.support.v4.view.ViewPager>
    </LinearLayout>


        </android.support.v4.widget.NestedScrollView>

    </android.support.design.widget.CoordinatorLayout>

Mainactivity layout
activity_main.xml

        <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.jeffy.viewpagerapp.MainActivity"
    tools:showIn="@layout/activity_main">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <GridView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/gridView1"
        android:numColumns="2"
        android:gravity="center"
        android:columnWidth="100dp"
        android:stretchMode="columnWidth"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

    </GridView>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SAVE"
        android:id="@+id/button" />

</LinearLayout>




</RelativeLayout>

Hope this would help someone... Click up button please if this helped you

Java way to check if a string is palindrome

 public boolean isPalindrom(String text) {
    StringBuffer stringBuffer = new StringBuffer(text);
     return stringBuffer.reverse().toString().equals(text);
}

Convert iterator to pointer?

For example, my vector<int> foo contains (5,2,6,87,251). A function takes vector<int>* and I want to pass it a pointer to (2,6,87,251).

A pointer to a vector<int> is not at all the same thing as a pointer to the elements of the vector.

In order to do this you will need to create a new vector<int> with just the elements you want in it to pass a pointer to. Something like:

 vector<int> tempVector( foo.begin()+1, foo.end());

 // now you can pass &tempVector to your function

However, if your function takes a pointer to an array of int, then you can pass &foo[1].

Using sed, how do you print the first 'N' characters of a line?

don't have to use grep either

an example:

sed -n '/searchwords/{s/^\(.\{12\}\).*/\1/g;p}' file

How to remove carriage returns and new lines in Postgresql?

In the case you need to remove line breaks from the begin or end of the string, you may use this:

UPDATE table 
SET field = regexp_replace(field, E'(^[\\n\\r]+)|([\\n\\r]+$)', '', 'g' );

Have in mind that the hat ^ means the begin of the string and the dollar sign $ means the end of the string.

Hope it help someone.

Android – Listen For Incoming SMS Messages

If someone referring how to do the same feature (reading OTP using received SMS) on Xamarin Android like me :

  1. Add this code to your AndroidManifest.xml file :

    <receiver android:name=".listener.BroadcastReveiverOTP">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
    </receiver>
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.BROADCAST_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    
  2. Then create your BroadcastReveiver class in your Android Project.

    [BroadcastReceiver(Enabled = true)] [IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED" }, Priority = (int)IntentFilterPriority.HighPriority)] 
    public class BroadcastReveiverOTP : BroadcastReceiver {
            public static readonly string INTENT_ACTION = "android.provider.Telephony.SMS_RECEIVED";
    
            protected string message, address = string.Empty;
    
            public override void OnReceive(Context context, Intent intent)
            {
                if (intent.HasExtra("pdus"))
                {
                    var smsArray = (Java.Lang.Object[])intent.Extras.Get("pdus");
                    foreach (var item in smsArray)
                    {
                        var sms = SmsMessage.CreateFromPdu((byte[])item);
                        address = sms.OriginatingAddress;
                        if (address.Equals("NotifyDEMO"))
                        {
                            message = sms.MessageBody;
                            string[] pin = message.Split(' ');
                            if (!string.IsNullOrWhiteSpace(pin[0]))
                            { 
                                    // NOTE : Here I'm passing received OTP to Portable Project using MessagingCenter. So I can display the OTP in the relevant entry field.
                                    MessagingCenter.Send<object, string>(this,MessengerKeys.OnBroadcastReceived, pin[0]);
                            }
                            }
                    }
                }
            }
    }
    
  3. Register this BroadcastReceiver class in your MainActivity class on Android Project:

    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity {
    
            // Initialize your class
            private BroadcastReveiverOTP _receiver = new BroadcastReveiverOTP ();
    
            protected override void OnCreate(Bundle bundle) { 
                    base.OnCreate(bundle);
    
                    global::Xamarin.Forms.Forms.Init(this, bundle);
                    LoadApplication(new App());
    
                    // Register your receiver :  RegisterReceiver(_receiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
    
            }
    }
    

__init__ and arguments in Python

Every method needs to accept one argument: The instance itself (or the class if it is a static method).

Read more about classes in Python.

Capitalize the first letter of both words in a two word string

You could also use the snakecase package:

install.packages("snakecase")
library(snakecase)

name <- c("zip code", "state", "final count")
to_title_case(name)
#> [1] "Zip Code"    "State"       "Final Count"

# or 
to_upper_camel_case(name, sep_out = " ")
#> [1] "Zip Code"    "State"       "Final Count"

https://github.com/Tazinho/snakecase

IN Clause with NULL or IS NULL

I know that is late to answer but could be useful for someone else You can use sub-query and convert the null to 0

SELECT *
FROM (SELECT CASE WHEN id_field IS NULL 
                THEN 0 
                ELSE id_field 
            END AS id_field
      FROM tbl_name) AS tbl
WHERE tbl.id_field IN ('value1', 'value2', 'value3', 0)

grep for special characters in Unix

You could try removing any alphanumeric characters and space. And then use -n will give you the line number. Try following:

grep -vn "^[a-zA-Z0-9 ]*$" application.log

How do I best silence a warning about unused variables?

In C++11, this is the solution I'm using:

template<typename... Ts> inline void Unreferenced(Ts&&...) {}

int Foo(int bar) 
{
    Unreferenced(bar);
    return 0;
}

int Foo2(int bar1, int bar2) 
{
    Unreferenced(bar1, bar2);
    return 0;
}

Verified to be portable (at least on modern msvc, clang and gcc) and not producing extra code when optimizations are enabled. With no optimization, the extra function call is performed and references to the parameters are copied to the stack, but there are no macros involved.

If the extra code is an issue, you can use this declaration instead:

(decltype(Unreferenced(bar1, bar2)))0;

but at that point, a macro provides better readability:

#define UNREFERENCED(...) { (decltype(Unreferenced(__VA_ARGS__)))0; }

Track a new remote branch created on GitHub

If you don't have an existing local branch, it is truly as simple as:

git fetch
git checkout <remote-branch-name>

For instance if you fetch and there is a new remote tracking branch called origin/feature/Main_Page, just do this:

git checkout feature/Main_Page

This creates a local branch with the same name as the remote branch, tracking that remote branch. If you have multiple remotes with the same branch name, you can use the less ambiguous:

git checkout -t <remote>/<remote-branch-name>

If you already made the local branch and don't want to delete it, see How do you make an existing Git branch track a remote branch?.

Adding header for HttpURLConnection

I have used the following code in the past and it had worked with basic authentication enabled in TomCat:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();

String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));

myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);

You can try the above code. The code above is for POST, and you can modify it for GET

Set Culture in an ASP.Net MVC app

protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            if(Context.Session!= null)
            Thread.CurrentThread.CurrentCulture =
                    Thread.CurrentThread.CurrentUICulture = (Context.Session["culture"] ?? (Context.Session["culture"] = new CultureInfo("pt-BR"))) as CultureInfo;
        }

What is the proper declaration of main in C++?

Details on return values and their meaning

Per 3.6.1 ([basic.start.main]):

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing

return 0;

The behavior of std::exit is detailed in section 18.5 ([support.start.term]), and describes the status code:

Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

jQuery Mobile Page refresh mechanism

I found this thread looking to create an ajax page refresh button with jQuery Mobile.

@sgissinger had the closest answer to what I was looking for, but it was outdated.

I updated for jQuery Mobile 1.4

function refreshPage() {
  jQuery.mobile.pageContainer.pagecontainer('change', window.location.href, {
    allowSamePageTransition: true,
    transition: 'none',
    reloadPage: true 
    // 'reload' parameter not working yet: //github.com/jquery/jquery-mobile/issues/7406
  });
}

// Run it with .on
$(document).on( "click", '#refresh', function() {
  refreshPage();
});

Core dumped, but core file is not in the current directory?

I'm on Linux Mint 19 (Ubuntu 18 based). I wanted to have coredump files in current folder. I had to do two things:

  1. Change /proc/sys/kernel/core_pattern (by # echo "core.%p.%s.%c.%d.%P > /proc/sys/kernel/core_pattern or by # sysctl -w kernel.core_pattern=core.%p.%s.%c.%d.%P)
  2. Raising limit for core file size by $ ulimit -c unlimited

That was written already in the answers, but I wrote to summarize succinctly. Interestingly changing limit did not require root privileges (as per https://askubuntu.com/questions/162229/how-do-i-increase-the-open-files-limit-for-a-non-root-user non-root can only lower the limit, so that was unexpected - comments about it are welcome).

Not receiving Google OAuth refresh token

I'd like to add a bit more info on this subject for those frustrated souls who encounter this issue. The key to getting a refresh token for an offline app is to make sure you are presenting the consent screen. The refresh_token is only returned immediately after a user grants authorization by clicking "Allow".

enter image description here

The issue came up for me (and I suspect many others) after I'd been doing some testing in a development environment and therefore already authorized my application on a given account. I then moved to production and attempted to authenticate again using an account which was already authorized. In this case, the consent screen will not come up again and the api will not return a new refresh token. To make this work, you must force the consent screen to appear again by either:

prompt=consent

or

approval_prompt=force

Either one will work but you should not use both. As of 2021, I'd recommend using prompt=consent since it replaces the older parameter approval_prompt and in some api versions, the latter was actually broken (https://github.com/googleapis/oauth2client/issues/453). Also, prompt is a space delimited list so you can set it as prompt=select_account%20consent if you want both.

Of course you also need:

access_type=offline

Additional reading:

Why is the time complexity of both DFS and BFS O( V + E )

Very simplified without much formality: every edge is considered exactly twice, and every node is processed exactly once, so the complexity has to be a constant multiple of the number of edges as well as the number of vertices.

Run Executable from Powershell script with parameters

Try quoting the argument list:

Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"

You can also provide the argument list as an array (comma separated args) but using a string is usually easier.

Chrome - ERR_CACHE_MISS

Yes, this is a current issue in Chrome. There is an issue report here.

The fix will appear in 40.x.y.z versions.

Until then? I don't think you can resolve the issue yourself. But you can ignore it. The shown error is only related to the dev tools and does not influence the behavior of your website. If you have any other problems they are not related to this error.

android - setting LayoutParams programmatically

int dp1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
            context.getResources().getDisplayMetrics());

tv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
dp1 * 100)); // if you want to set layout height to 100dp

llview.addView(tv);

How to prevent scientific notation in R?

Try format function:

> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

How to change the display name for LabelFor in razor in mvc3?

Decorate the model property with the DisplayName attribute.

Check if pull needed in Git

I would do the way suggested by brool. The following one-line script takes the SHA1 of your last commited version and compares it to the one of the remote origin, and pull changes only if they differ. And it's even more light-weight of the solutions based on git pull or git fetch.

[ `git log --pretty=%H ...refs/heads/master^` != `git ls-remote origin
-h refs/heads/master |cut -f1` ] && git pull

Laravel Redirect Back with() Message

Just set the flash message and redirect to back from your controller functiion.

    session()->flash('msg', 'Successfully done the operation.');
    return redirect()->back();

And then you can get the message in the view blade file.

   {!! Session::has('msg') ? Session::get("msg") : '' !!}

method in class cannot be applied to given types

The generateNumbers(int[] numbers) function definition has arguments (int[] numbers)that expects an array of integers. However, in the main, generateNumbers(); doesn't have any arguments.

To resolve it, simply add an array of numbers to the arguments while calling thegenerateNumbers() function in the main.

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You may need to handle javax.persistence.RollbackException

How to install "ifconfig" command in my ubuntu docker image?

You could also consider:

RUN apt-get update && apt-get install -y iputils-ping

(as Contango comments: you must first run apt-get update, to avoid error with missing repository).

See "Replacing ifconfig with ip"

it is most often recommended to move forward with the command that has replaced ifconfig. That command is ip, and it does a great job of stepping in for the out-of-date ifconfig.

But as seen in "Getting a Docker container's IP address from the host", using docker inspect can be more useful depending on your use case.

How to check Oracle database for long running queries

select sq.PARSING_SCHEMA_NAME, sq.LAST_LOAD_TIME, sq.ELAPSED_TIME, sq.ROWS_PROCESSED, ltrim(sq.sql_text), sq.SQL_FULLTEXT
  from v$sql sq, v$session se
 order by sq.ELAPSED_TIME desc, sq.LAST_LOAD_TIME desc;

What is the difference between typeof and instanceof and when should one be used vs. the other?

I would recommend using prototype's callback.isFunction().

They've figured out the difference and you can count on their reason.

I guess other JS frameworks have such things, too.

instanceOf wouldn't work on functions defined in other windows, I believe. Their Function is different than your window.Function.

How to get the first day of the current week and month?

Get First date of next month:-

SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
String selectedDate="MM-dd-yyyy like 07-02-2018";
Date dt = df.parse(selectedDate);`enter code here`
calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH) + 1);

String firstDate = df.format(calendar.getTime());
System.out.println("firstDateof next month ==>" + firstDate);

Find object in list that has attribute equal to some value (that meets any condition)

A simple example: We have the following array

li = [{"id":1,"name":"ronaldo"},{"id":2,"name":"messi"}]

Now, we want to find the object in the array that has id equal to 1

  1. Use method next with list comprehension
next(x for x in li if x["id"] == 1 )
  1. Use list comprehension and return first item
[x for x in li if x["id"] == 1 ][0]
  1. Custom Function
def find(arr , id):
    for x in arr:
        if x["id"] == id:
            return x
find(li , 1)

Output all the above methods is {'id': 1, 'name': 'ronaldo'}

C#, Looping through dataset and show each record from a dataset column

I believe you intended it more this way:

foreach (DataTable table in ds.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
        TaskStart.ToString("dd-MMMM-yyyy");
        rpt.SetParameterValue("TaskStartDate", TaskStart);
    }
}

You always accessed your first row in your dataset.

How do I fix an "Invalid license data. Reinstall is required." error in Visual C# 2010 Express?

It appears that this has been reported as a bug, but has been closed as "Not Reproducible". One suggestiong from the Microsoft supporter is to redownload and reinstall:

Please try downloading the complete ISO from http://www.microsoft.com/express/Downloads/#2010-All, mount it as virtual drive. Then execute Visual C# setup from the ISO media and select an option to remove the product. Once the Visual C# has been uninstalled, please try installing it again from the ISO media.

It sounds a bit far fetched to me, but you might want to give it a try.

If that does not help you, I would suggest that you either post a new bug report to Microsoft or vote to reopen the existing one (I am not sure if/how this is possible).

PHP upload image

This code is very easy to upload file by php. In this code I am performing uploading task in same page that mean our html and php both code resides in the same file. This code generates new name of image name.

first of all see the html code

<form action="index.php" method="post" enctype="multipart/form-data">
 <input type="file" name="banner_image" >
 <input type="submit" value="submit">
 </form>

now see the php code

<?php
$image_name=$_FILES['banner_image']['name'];
       $temp = explode(".", $image_name);
        $newfilename = round(microtime(true)) . '.' . end($temp);
       $imagepath="uploads/".$newfilename;
       move_uploaded_file($_FILES["banner_image"]["tmp_name"],$imagepath);
?>

Terminal Commands: For loop with echo

jot would work too (in bash shell)

for i in `jot 1000 1`; do echo "http://example.com/$i.jpg"; done

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

Eclipse failed to connect to SVN https repositories (should also apply to any app using SSL/TLS).

svn: E175002: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

The issue was caused by latest Java 8 OpenJDK update that disabled MD5 related algorithms. As a workaround until new certificates are issued (if ever), change the following keys at java.security file

WARNING
Keep in mind that this could have security implications as disabled algorithms are considered weak. As an alternative, the workaround can be applied on a JVM basis by a command line option to use an external java.security file with this changes, e.g.:
java -Djava.security.properties=/etc/sysconfig/noMD5.java.security
For Eclipse, add a line on eclipse.ini below -vmargs
-Djava.security.properties=/etc/sysconfig/noMD5.java.security

original keys

jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768

change to

jdk.certpath.disabledAlgorithms=MD2, RSA keySize < 1024
jdk.tls.disabledAlgorithms=SSLv3, RC4, DH keySize < 768

java.security file is located in linux 64 at /usr/lib64/jvm/java/jre/lib/security/java.security

Convert Java Array to Iterable

just my 2 cents:

final int a[] = {1,2,3};

java.lang.Iterable<Integer> aIterable=new Iterable<Integer>() {

    public Iterator<Integer> iterator() {
       return new Iterator<Integer>() {
            private int pos=0;

            public boolean hasNext() {
               return a.length>pos;
            }

            public Integer next() {
               return a[pos++];
            }

            public void remove() {
                throw new UnsupportedOperationException("Cannot remove an element of an array.");
            }
        };
    }
};

How to get a path to a resource in a Java JAR file

You need to understand the path within the jar file.
Simply refer to it relative. So if you have a file (myfile.txt), located in foo.jar under the \src\main\resources directory (maven style). You would refer to it like:

src/main/resources/myfile.txt

If you dump your jar using jar -tvf myjar.jar you will see the output and the relative path within the jar file, and use the FORWARD SLASHES.

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

Return a FileResult or FileStreamResult from your action, depending on whether the file exists or you create it on the fly.

public ActionResult GetPdf(string filename)
{
    return File(filename, "application/pdf", Server.UrlEncode(filename));
}

How to position the Button exactly in CSS

So, the trick here is to use absolute positioning calc like this:

top: calc(50% - XYpx);
left: calc(50% - XYpx);

where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.

How can I convert radians to degrees with Python?

You can simply convert your radian result to degree by using

math.degrees and rounding appropriately to the required decimal places

for example

>>> round(math.degrees(math.asin(0.5)),2)
30.0
>>> 

RichTextBox (WPF) does not have string property "Text"

How about just doing the following:

_richTextBox.SelectAll();
string myText = _richTextBox.Selection.Text;

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

use keyof typeof

const cat = {
    name: 'tuntun'
}

const key: string = 'name' 

cat[key as keyof typeof cat]

How to load URL in UIWebView in Swift?

UIWebView loadRequest: Create NSURLRequest using NSURL object, then passing the request to uiwebview it will load the requested URL into the web view.

 override func viewDidLoad() {
     super.viewDidLoad()
     // Do any additional setup after loading the view, typically from a nib.
     let url = NSURL (string: "http://www.google.com");
     let requestObj = NSURLRequest(URL: url!);
     myWebView.loadRequest(requestObj);
     self.view.addSubview(myWebView)
  }

For more reference:

http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/

Get child node index

Use binary search algorithm to improve the performace when the node has large quantity siblings.

function getChildrenIndex(ele){
    //IE use Element.sourceIndex
    if(ele.sourceIndex){
        var eles = ele.parentNode.children;
        var low = 0, high = eles.length-1, mid = 0;
        var esi = ele.sourceIndex, nsi;
        //use binary search algorithm
        while (low <= high) {
            mid = (low + high) >> 1;
            nsi = eles[mid].sourceIndex;
            if (nsi > esi) {
                high = mid - 1;
            } else if (nsi < esi) {
                low = mid + 1;
            } else {
                return mid;
            }
        }
    }
    //other browsers
    var i=0;
    while(ele = ele.previousElementSibling){
        i++;
    }
    return i;
}

How can I upload fresh code at github?

If you haven't already created the project in Github, do so on that site. If memory serves, they display a page that tells you exactly how to get your existing code into your new repository. At the risk of oversimplification, though, you'd follow Veeti's instructions, then:

git remote add [name to use for remote] [private URI] # associate your local repository to the remote
git push [name of remote] master # push your repository to the remote

How to style the <option> with only CSS?

There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...

GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

I got this error until I realized that I hadn't intialized a Git repository in that folder, on a mounted vagrant machine.

So I typed git init and then git worked.

Oracle: If Table Exists

Another method is to define an exception and then only catch that exception letting all others propagate.

Declare
   eTableDoesNotExist Exception;
   PRAGMA EXCEPTION_INIT(eTableDoesNotExist, -942);
Begin
   EXECUTE IMMEDIATE ('DROP TABLE myschema.mytable');
Exception
   When eTableDoesNotExist Then
      DBMS_Output.Put_Line('Table already does not exist.');
End;

Accurate way to measure execution times of php scripts

You can use microtime(true) with following manners:

Put this at the start of your php file:

//place this before any script you want to calculate time
$time_start = microtime(true);

// your script code goes here

// do something

Put this at the end of your php file:

// Display Script End time
$time_end = microtime(true);

//dividing with 60 will give the execution time in minutes other wise seconds
$execution_time = ($time_end - $time_start)/60;

//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';

It will output you result in minutes.

Copying files from one directory to another in Java

you use renameTo() – not obvious, I know ... but it's the Java equivalent of move ...

C - split string into an array of strings

Here is an example of how to use strtok borrowed from MSDN.

And the relevant bits, you need to call it multiple times. The token char* is the part you would stuff into an array (you can figure that part out).

char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[]   = " ,\t\n";
char *token;

int main( void )
{
    printf( "Tokens:\n" );
    /* Establish string and get the first token: */
    token = strtok( string, seps );
    while( token != NULL )
    {
        /* While there are tokens in "string" */
        printf( " %s\n", token );
        /* Get next token: */
        token = strtok( NULL, seps );
    }
}

How to determine whether a year is a leap year?

The whole formula can be contained in a single expression:

def is_leap_year(year):
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

print n, " is a leap year" if is_leap_year(n) else " is not a leap year"

Streaming Audio from A URL in Android using MediaPlayer?

Looking my projects:

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

How can I make Flexbox children 100% height of their parent?

I suppose that Chrome's behavior is more consistent with the CSS specification (though it's less intuitive). According to Flexbox specification, the default stretch value of align-self property changes only the used value of the element's "cross size property" (height, in this case). And, as I understand the CSS 2.1 specification, the percentage heights are calculated from the specified value of the parent's height, not its used value. The specified value of the parent's height isn't affected by any flex properties and is still auto.

Setting an explicit height: 100% makes it formally possible to calculate the percentage height of the child, just like setting height: 100% to html makes it possible to calculate the percentage height of body in CSS 2.1.

Add items in array angular 4

Your empList is object type but you are trying to push strings

Try this

this.empList.push({this.name,this.empoloyeeID});

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

Something like

select *
  from foo
 where regexp_like( col1, '[^[:alpha:]]' ) ;

should work

SQL> create table foo( col1 varchar2(100) );

Table created.

SQL> insert into foo values( 'abc' );

1 row created.

SQL> insert into foo values( 'abc123' );

1 row created.

SQL> insert into foo values( 'def' );

1 row created.

SQL> select *
  2    from foo
  3   where regexp_like( col1, '[^[:alpha:]]' ) ;

COL1
--------------------------------------------------------------------------------
abc123

Create dynamic URLs in Flask with url_for()

url_for in Flask is used for creating a URL to prevent the overhead of having to change URLs throughout an application (including in templates). Without url_for, if there is a change in the root URL of your app then you have to change it in every page where the link is present.

Syntax: url_for('name of the function of the route','parameters (if required)')

It can be used as:

@app.route('/index')
@app.route('/')
def index():
    return 'you are in the index page'

Now if you have a link the index page:you can use this:

<a href={{ url_for('index') }}>Index</a>

You can do a lot o stuff with it, for example:

@app.route('/questions/<int:question_id>'):    #int has been used as a filter that only integer will be passed in the url otherwise it will give a 404 error
def find_question(question_id):  
    return ('you asked for question{0}'.format(question_id))

For the above we can use:

<a href = {{ url_for('find_question' ,question_id=1) }}>Question 1</a>

Like this you can simply pass the parameters!

Imported a csv-dataset to R but the values becomes factors

Both the data import function (here: read.csv()) as well as a global option offer you to say stringsAsFactors=FALSE which should fix this.

Updating to latest version of CocoaPods?

This is a really quick & detailed solution

Open the Terminal and execute the following to get the latest stable version:

sudo gem install cocoapods

Add --pre to get the latest pre release:

sudo gem install cocoapods --pre

Incase any error occured

Try uninstall and install again:

sudo gem uninstall cocoapods
sudo gem install cocoapods

Run after updating CocoaPods

sudo gem clean cocoapods

After updating CocoaPods, also need to update Podfile.lock file in your project.

Go to your project directory

pod install

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

Simply you can use:

on server side:

Registry <objectName1> =LocateRegisty.createRegistry(1099);
Registry <objectName2> =LocateRegisty.getRegistry();

on Client Side:

Registry <object name you want> =LocateRegisty.getRegistry();

Select multiple columns in data.table by their numeric indices

@Tom, thank you very much for pointing out this solution. It works great for me.

I was looking for a way to just exclude one column from printing and from the example above. To exclude the second column you can do something like this

library(data.table)
dt <- data.table(a=1:2, b=2:3, c=3:4)
dt[,.SD,.SDcols=-2]
dt[,.SD,.SDcols=c(1,3)]

Definition of "downstream" and "upstream"

In terms of source control, you're "downstream" when you copy (clone, checkout, etc) from a repository. Information flowed "downstream" to you.

When you make changes, you usually want to send them back "upstream" so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you're not tracking divergent lines of development.

Sometimes you'll read about package or release managers (the people, not the tool) talking about submitting changes to "upstream". That usually means they had to adjust the original sources so they could create a package for their system. They don't want to keep making those changes, so if they send them "upstream" to the original source, they shouldn't have to deal with the same issue in the next release.

ASP.NET jQuery Ajax Calling Code-Behind Method

This hasn't solved my problem too, so I changed the parameters slightly.
This code worked for me:

var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";

$.ajax({
    type: "POST",
    url: "Default.aspx/OnSubmit",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        alert("We returned: " + result.d);
    }
});

get all the elements of a particular form

If you only want form elements that have a name attribute, you can filter the form elements.

const form = document.querySelector("your-form")
Array.from(form.elements).filter(e => e.getAttribute("name"))

Microsoft.ACE.OLEDB.12.0 is not registered

The easiest fix for me was to change SQL Agent job to run in 32-bit runtime. Go to SQL Job > right click properties > step > edit(step) > Execution option tab > Use 32 bit runtime

screenshot

How to change the plot line color from blue to black?

If you get the object after creation (for instance after "seasonal_decompose"), you can always access and edit the properties of the plot; for instance, changing the color of the first subplot from blue to black:

plt.axes[0].get_lines()[0].set_color('black')

ORA-30926: unable to get a stable set of rows in the source tables

A further clarification to the use of DISTINCT to resolve error ORA-30926 in the general case:

You need to ensure that the set of data specified by the USING() clause has no duplicate values of the join columns, i.e. the columns in the ON() clause.

In OP's example where the USING clause only selects a key, it was sufficient to add DISTINCT to the USING clause. However, in the general case the USING clause may select a combination of key columns to match on and attribute columns to be used in the UPDATE ... SET clause. Therefore in the general case, adding DISTINCT to the USING clause will still allow different update rows for the same keys, in which case you will still get the ORA-30926 error.

This is an elaboration of DCookie's answer and point 3.1 in Tagar's answer, which from my experience may not be immediately obvious.

Convert an array to string

You probably want something like this overload of String.Join:

String.Join<T> Method (String, IEnumerable<T>)

Docs:

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

In your example, you'd use

String.Join("", Client);

VHDL - How should I create a clock in a testbench?

How to use a clock and do assertions

This example shows how to generate a clock, and give inputs and assert outputs for every cycle. A simple counter is tested here.

The key idea is that the process blocks run in parallel, so the clock is generated in parallel with the inputs and assertions.

library ieee;
use ieee.std_logic_1164.all;

entity counter_tb is
end counter_tb;

architecture behav of counter_tb is
    constant width : natural := 2;
    constant clk_period : time := 1 ns;

    signal clk : std_logic := '0';
    signal data : std_logic_vector(width-1 downto 0);
    signal count : std_logic_vector(width-1 downto 0);

    type io_t is record
        load : std_logic;
        data : std_logic_vector(width-1 downto 0);
        count : std_logic_vector(width-1 downto 0);
    end record;
    type ios_t is array (natural range <>) of io_t;
    constant ios : ios_t := (
        ('1', "00", "00"),
        ('0', "UU", "01"),
        ('0', "UU", "10"),
        ('0', "UU", "11"),

        ('1', "10", "10"),
        ('0', "UU", "11"),
        ('0', "UU", "00"),
        ('0', "UU", "01")
    );
begin
    counter_0: entity work.counter port map (clk, load, data, count);

    process
    begin
        for i in ios'range loop
            load <= ios(i).load;
            data <= ios(i).data;
            wait until falling_edge(clk);
            assert count = ios(i).count;
        end loop;
        wait;
    end process;

    process
    begin
        for i in 1 to 2 * ios'length loop
            wait for clk_period / 2;
            clk <= not clk;
        end loop;
        wait;
    end process;
end behav;

The counter would look like this:

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all; -- unsigned

entity counter is
    generic (
        width : in natural := 2
    );
    port (
        clk, load : in std_logic;
        data : in std_logic_vector(width-1 downto 0);
        count : out std_logic_vector(width-1 downto 0)
    );
end entity counter;

architecture rtl of counter is
    signal cnt : unsigned(width-1 downto 0);
begin
    process(clk) is
    begin
        if rising_edge(clk) then
            if load = '1' then
                cnt <= unsigned(data);
            else
                cnt <= cnt + 1;
            end if;
        end if;
    end process;
    count <= std_logic_vector(cnt);
end architecture rtl;

Related: https://electronics.stackexchange.com/questions/148320/proper-clock-generation-for-vhdl-testbenches

How can I add spaces between two <input> lines using CSS?

You can also wrap your text in label fields, so your form will be more self-explainable semantically.

Just remember to float labels and inputs to the left and to add a specific width to them, and the containing form. Then you can add margins to both of them, to adjust the spacing between the lines (you understand, of course, that this is a pretty minimal markup that expects content to be as big as to some limit).

That way you wont have to add any more elements, just the label-input pairs, all of them wrapped in a form element.

For example:

<form>
<label for="txtName">Name</label>
<input id"txtName" type="text">
<label for="txtEmail">Email</label>
<input id"txtEmail" type="text">
<label for="txtAddress">Address</label>
<input id"txtAddress" type="text">
...
<input type="submit" value="Submit The Form">
</form>

And the css will be:

form{
float:left; /*to clear the floats of inner elements,usefull if you wanna add a border or background image*/
width:300px;
}
label{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}
input{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}

'if' statement in jinja2 template

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

How can I set the initial value of Select2 when using AJAX?

One scenario that I haven't seen people really answer, is how to have a preselection when the options are AJAX sourced, and you can select multiple. Since this is the go-to page for AJAX preselection, I'll add my solution here.

$('#mySelect').select2({
    ajax: {
        url: endpoint,
        dataType: 'json',
        data: [
            { // Each of these gets processed by fnRenderResults.
                id: usersId,
                text: usersFullName,
                full_name: usersFullName,
                email: usersEmail,
                image_url: usersImageUrl,
                selected: true // Causes the selection to actually get selected.
            }
        ],
        processResults: function(data) {

            return {
                results: data.users,
                pagination: {
                    more: data.next !== null
                }
            };

        }
    },
    templateResult: fnRenderResults,
    templateSelection: fnRenderSelection, // Renders the result with my own style
    selectOnClose: true
}); 

How to make unicode string with python3

This how I solved my problem to convert chars like \uFE0F, \u000A, etc. And also emojis that encoded with 16 bytes.

example = 'raw vegan chocolate cocoa pie w chocolate &amp; vanilla cream\\uD83D\\uDE0D\\uD83D\\uDE0D\\u2764\\uFE0F Present Moment Caf\\u00E8 in St.Augustine\\u2764\\uFE0F\\u2764\\uFE0F '
import codecs
new_str = codecs.unicode_escape_decode(example)[0]
print(new_str)
>>> 'raw vegan chocolate cocoa pie w chocolate &amp; vanilla cream\ud83d\ude0d\ud83d\ude0d?? Present Moment Cafè in St.Augustine???? '
new_new_str = new_str.encode('utf-16', 'surrogatepass').decode('utf-16')
print(new_new_str)
>>> 'raw vegan chocolate cocoa pie w chocolate &amp; vanilla cream?? Present Moment Cafè in St.Augustine???? '

Colors in JavaScript console

I wrote a reallllllllllllllllly simple plugin for myself several years ago:

To add to your page all you need to do is put this in the head:

<script src="https://jackcrane.github.io/static/cdn/jconsole.js" type="text/javascript">

Then in JS:

jconsole.color.red.log('hellllooo world');

The framework has code for:

jconsole.color.red.log();
jconsole.color.orange.log();
jconsole.color.yellow.log();
jconsole.color.green.log();
jconsole.color.blue.log();
jconsole.color.purple.log();
jconsole.color.teal.log();

as well as:

jconsole.css.log("hello world","color:red;");

for any other css. The above is designed with the following syntax:

jconsole.css.log(message to log,css code to style the logged message)

BitBucket - download source as ZIP

In case you want to download the repo from your shell/terminal it should work like this:

wget https://user:[email protected]/user-name/repo-name/get/master.tar.bz2

or whatever download URL you might have.

Please make sure the user:password are both URL-encoded. So for instance if your username contains the @ symbol then replace it with %40.

Convert file path to a file URI?

The System.Uri constructor has the ability to parse full file paths and turn them into URI style paths. So you can just do the following:

var uri = new System.Uri("c:\\foo");
var converted = uri.AbsoluteUri;

How to fix syntax error, unexpected T_IF error in php?

Here is the issue

  $total_result = $result->num_rows;

try this

<?php
if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
{
    if ($result->num_rows > 0)
    {
        $total_result = $result->num_rows;
        $total_pages = ceil($total_result / $per_page);

        if(isset($_GET['page']) && is_numeric($_GET['page']))
        {
            $show_page = $_GET['page'];

            if ($show_page > 0 && $show_page <= $total_pages)
            {
                $start = ($show_page - 1) * $per_page;
                $end = $start + $per_page;
            }
            else
            {
                $start = 0;
                $end = $per_page;
            }               

        }
        else
        {
            $start = 0;
            $end = $per_page;
        }


        //display paginations
        echo "<p> View pages: ";
        for ($i=1; $i < $total_pages; $i++)
        { 
            if (isset($_GET['page']) && $_GET['page'] == $i)
            {
                echo  $i . " ";
            }
            else
            {
                echo "<a href='view-pag.php?$i'>" . $i . "</a> | ";
            }

        }
        echo "</p>";

    }
    else
    {
        echo "No result to display.";
    }

}
else
{
    echo "Error: " . $mysqli->error;
}


?>

Difference between [routerLink] and routerLink

ROUTER LINK DIRECTIVE:

[routerLink]="link"                  //when u pass URL value from COMPONENT file
[routerLink]="['link','parameter']" //when you want to pass some parameters along with route

 routerLink="link"                  //when you directly pass some URL 
[routerLink]="['link']"              //when you directly pass some URL

Font is not available to the JVM with Jasper Reports

I tried installing mscorefonts, but the package was installed and up-to-date.

sudo apt-get update
sudo apt-get install ttf-mscorefonts-installer

I tried searching for the font in the filesystem, with:

ls /usr/share/fonts/truetype/msttcorefonts/

This folder just had the README, with the correct instructions on how to install.

cat /usr/share/fonts/truetype/msttcorefonts/README

You need an internet connection for this:

sudo apt-get install --reinstall ttf-mscorefonts-installer

I re-installed ttf-mscorefonts-installer (as shown above, making sure to accept the EULA!) and the problem was solved.

How do ACID and database transactions work?

What is the relationship between ACID and database transaction?

In a relational database, every SQL statement must execute in the scope of a transaction.

Without defining the transaction boundaries explicitly, the database is going to use an implicit transaction which is wraps around every individual statement.

The implicit transaction begins before the statement is executed and end (commit or rollback) after the statement is executed. The implicit transaction mode is commonly known as auto-commit.

A transaction is a collection of read/write operations succeeding only if all contained operations succeed.

Atomicity

Inherently a transaction is characterized by four properties (commonly referred as ACID):

  • Atomicity
  • Consistency
  • Isolation
  • Durability

Does ACID give database transaction or is it the same thing?

For a relational database system, this is true because the SQL Standard specifies that a transaction should provide the ACID guarantees:

Atomicity

Atomicity takes individual operations and turns them into an all-or-nothing unit of work, succeeding if and only if all contained operations succeed.

A transaction might encapsulate a state change (unless it is a read-only one). A transaction must always leave the system in a consistent state, no matter how many concurrent transactions are interleaved at any given time.

Consistency

Consistency means that constraints are enforced for every committed transaction. That implies that all Keys, Data types, Checks and Trigger are successful and no constraint violation is triggered.

Isolation

Transactions require concurrency control mechanisms, and they guarantee correctness even when being interleaved. Isolation brings us the benefit of hiding uncommitted state changes from the outside world, as failing transactions shouldn’t ever corrupt the state of the system. Isolation is achieved through concurrency control using pessimistic or optimistic locking mechanisms.

Durability

A successful transaction must permanently change the state of a system, and before ending it, the state changes are recorded in a persisted transaction log. If our system is suddenly affected by a system crash or a power outage, then all unfinished committed transactions may be replayed.

How a RDBMS works

In STL maps, is it better to use map::insert than []?

One note is that you can also use Boost.Assign:

using namespace std;
using namespace boost::assign; // bring 'map_list_of()' into scope

void something()
{
    map<int,int> my_map = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);
}

CHECK constraint in MySQL is not working

MySQL 8.0.16 is the first version that supports CHECK constraints.

Read https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html

If you use MySQL 8.0.15 or earlier, the MySQL Reference Manual says:

The CHECK clause is parsed but ignored by all storage engines.

Try a trigger...

mysql> delimiter //
mysql> CREATE TRIGGER trig_sd_check BEFORE INSERT ON Customer 
    -> FOR EACH ROW 
    -> BEGIN 
    -> IF NEW.SD<0 THEN 
    -> SET NEW.SD=0; 
    -> END IF; 
    -> END
    -> //
mysql> delimiter ;

Hope that helps.

Change Orientation of Bluestack : portrait/landscape mode

Try This...

Go to your notification area in the taskbar.

Right click on Bluestacks Agent>Rotate Portrait Apps>Enabled.

There are several options available..

a. Automatic - Selected By Default - It will rotate the app player in portrait mode for portrait apps.

b. Disabled - It will force the portrait apps to work in landscape mode.

c. Enabled - It will force the portrait apps to work in portrait mode only.

This May help you..

How to iterate through range of Dates in Java?

You can try this:

OffsetDateTime currentDateTime = OffsetDateTime.now();
for (OffsetDateTime date = currentDateTime; date.isAfter(currentDateTime.minusYears(YEARS)); date = date.minusWeeks(1))
{
    ...
}

laravel select where and where condition

$this->where('email', $email)->where('password', $password) 

is returning a Builder object which you could use to append more where filters etc.

To get the result you need:

$userRecord = $this->where('email', $email)->where('password', $password)->first();

Clicking submit button of an HTML form by a Javascript code

You can do :

document.forms["loginForm"].submit()

But this won't call the onclick action of your button, so you will need to call it by hand.

Be aware that you must use the name of your form and not the id to access it.

Copying sets Java

Java 8+:

Set<String> copy = new HashSet<>(mySet); 

MySQL skip first 10 results

Use LIMIT with two parameters. For example, to return results 11-60 (where result 1 is the first row), use:

SELECT * FROM foo LIMIT 10, 50

For a solution to return all results, see Thomas' answer.

PHP Warning: Invalid argument supplied for foreach()

You should check that what you are passing to foreach is an array by using the is_array function

If you are not sure it's going to be an array you can always check using the following PHP example code:

if (is_array($variable)) {

  foreach ($variable as $item) {
   //do something
  }
}

Select elements by attribute in CSS

    [data-value] {
  /* Attribute exists */
}

[data-value="foo"] {
  /* Attribute has this exact value */
}

[data-value*="foo"] {
  /* Attribute value contains this value somewhere in it */
}

[data-value~="foo"] {
  /* Attribute has this value in a space-separated list somewhere */
}

[data-value^="foo"] {
  /* Attribute value starts with this */
}

[data-value|="foo"] {
  /* Attribute value starts with this in a dash-separated list */
}

[data-value$="foo"] {
  /* Attribute value ends with this */
}

Calling a javascript function in another js file

You could consider using the es6 import export syntax. In file 1;

export function f1() {...}

And then in file 2;

import { f1 } from "./file1.js";
f1();

Please note that this only works if you're using <script src="./file2.js" type="module">

You will not need two script tags if you do it this way. You simply need the main script, and you can import all your other stuff there.

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

Inline CSS styles in React: how to implement a:hover?

I'm in the same situation. Really like the pattern of keeping the styling in the components but the hover states seems like the last hurdle.

What I did was writing a mixin that you can add to your component that needs hover states. This mixin will add a new hovered property to the state of your component. It will be set to true if the user hovers over the main DOM node of the component and sets it back to false if the users leaves the element.

Now in your component render function you can do something like:

<button style={m(
     this.styles.container,
     this.state.hovered && this.styles.hover,
)}>{this.props.children}</button>

Now each time the state of the hovered state changes the component will rerender.

I've also create a sandbox repo for this that I use to test some of these patterns myself. Check it out if you want to see an example of my implementation.

https://github.com/Sitebase/cssinjs/tree/feature-interaction-mixin

Foreach loop in C++ equivalent of C#

In C++0x you have

for(string str: strarr) { ... }

But till then use ordinary for loop.

How to generate unique ID with node.js

Install NPM uuid package (sources: https://github.com/kelektiv/node-uuid):

npm install uuid

and use it in your code:

var uuid = require('uuid');

Then create some ids ...

// Generate a v1 (time-based) id
uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'

// Generate a v4 (random) id
uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'

** UPDATE 3.1.0
The above usage is deprecated, so use this package like this:

const uuidv1 = require('uuid/v1');
uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 

const uuidv4 = require('uuid/v4');
uuidv4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

** UPDATE 7.x
And now the above usage is deprecated as well, so use this package like this:

const { v1: uuidv1 } = require('uuid');
uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 

const { v4: uuidv4 } = require('uuid');
uuidv4(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 

C# naming convention for constants?

Leave Hungarian to the Hungarians.

In the example I'd even leave out the definitive article and just go with

private const int Answer = 42;

Is that answer or is that the answer?

*Made edit as Pascal strictly correct, however I was thinking the question was seeking more of an answer to life, the universe and everything.

IndexOf function in T-SQL

One very small nit to pick:

The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:

"john@work"@myemployer.com

This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:

SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1

More information:

http://en.wikipedia.org/wiki/Email_address

What is the functionality of setSoTimeout and how it works?

This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT time! if it does not get any signal it throw exception! It means that time expired!

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class SocketTest extends Thread {
  private ServerSocket serverSocket;

  public SocketTest() throws IOException {
    serverSocket = new ServerSocket(8008);
    serverSocket.setSoTimeout(10000);
  }

  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket client = serverSocket.accept();

        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        client.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }

  public static void main(String[] args) {
    try {
      Thread t = new SocketTest();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Running Facebook application on localhost

2013 August. Facebook doesn't allow to set domain with port for an App, as example "localhost:3000".

So you can use https://pagekite.net to tunnel your localhost:port to proper domain.

Rails developers can use http://progrium.com/localtunnel/ for free.

  • Facebook allows only one domain for App at the time. If you are trying to add another one, as localhost, it will show some kind of different error about domain. Be sure to use only one domain for callback and for app domain setting at the time.

Enable IIS7 gzip

Another easy way to test without installing anything, neither is it dependent on IIS version. Paste your url to this link - SEO Checkup

test gzip

To add to web.config: http://www.iis.net/configreference/system.webserver/httpcompression

Tar a directory, but don't store full absolute paths in the archive

Found tar -cvf site1-$seqNumber.tar -C /var/www/ site1 as more friendlier solution than tar -cvf site1-$seqNumber.tar -C /var/www/site1 . (notice the . in the second solution) for the following reasons

  • Tar file name can be insignificant as the original folder is now an archive entry
  • Tar file name being insignificant to the content can now be used for other purposes like sequence numbers, periodical backup etc.

Android: show soft keyboard automatically when focus is on an EditText

Take a look at this discussion which handles manually hiding and showing the IME. However, my feeling is that if a focused EditText is not bringing the IME up it is because you are calling AlertDialog.show() in your OnCreate() or some other method which is evoked before the screen is actually presented. Moving it to OnPostResume() should fix it in that case I believe.

DataTrigger where value is NOT null?

Compare with null (As Michael Noonan said):

<Style>
    <Style.Triggers>
       <DataTrigger Binding="{Binding SomeProperty}" Value="{x:Null}">
           <Setter Property="Visibility" Value="Collapsed" />
        </DataTrigger>
     </Style.Triggers>
</Style>

Compare with not null (without a converter):

<Style>
    <Setter Property="Visibility" Value="Collapsed" />
    <Style.Triggers>
       <DataTrigger Binding="{Binding SomeProperty}" Value="{x:Null}">
           <Setter Property="Visibility" Value="Visible" />
        </DataTrigger>
     </Style.Triggers>
</Style>

Vertical divider CSS

<div class="headerdivider"></div>

and

.headerdivider {
    border-left: 1px solid #38546d;
    background: #16222c;
    width: 1px;
    height: 80px;
    position: absolute;
    right: 250px;
    top: 10px;
}

Using SSIS BIDS with Visual Studio 2012 / 2013

First Off, I object to this other question regarding Visual Studio 2015 as a duplicate question. How do I open SSRS (.rptproj) and SSIS (.dtproj) files in Visual Studio 2015? [duplicate]

Basically this question has the title ...Visual Studio 2012 / 2013 What about ALL the improvements and changes to VS 2015 ??? SSDT has been updated and changed. The entire way of doing various additions and updates is different.

So having vented / rant - I did open a VS 2015 update 2 instance and proceeded to open an existing solution that include a .rptproj project. Now this computer does not yet have sql server installed on it yet.

Solution for ME : Tools --> Extension and Updates --> Updates --> sql server tooling updates

Click on Update button and wait a long time and SSDT then installs and close visual studio 2015 and re-open and it works for me.

In case it is NOT found in VS 2015 for some reason : scroll to the bottom, pick your language iso https://msdn.microsoft.com/en-us/mt186501.aspx?f=255&MSPPError=-2147217396

CSS root directory

For example your directory is like this:

Desktop >
        ProjectFolder >
                      index.html
                      css >
                          style.css
                      images >
                             img.png

You are at your style.css and you want to use img.png as a background-image, use this:

url("../images/img.png")

Works for me!

How to find length of dictionary values

Lets do some experimentation, to see how we could get/interpret the length of different dict/array values in a dict.

create our test dict, see list and dict comprehensions:

>>> my_dict = {x:[i for i in range(x)] for x in range(4)}
>>> my_dict
{0: [], 1: [0], 2: [0, 1], 3: [0, 1, 2]}

Get the length of the value of a specific key:

>>> my_dict[3]
[0, 1, 2]
>>> len(my_dict[3])
3

Get a dict of the lengths of the values of each key:

>>> key_to_value_lengths = {k:len(v) for k, v in my_dict.items()}
{0: 0, 1: 1, 2: 2, 3: 3}
>>> key_to_value_lengths[2]
2

Get the sum of the lengths of all values in the dict:

>>> [len(x) for x in my_dict.values()]
[0, 1, 2, 3]
>>> sum([len(x) for x in my_dict.values()])
6

Text in a flex container doesn't wrap in IE11

I had the same issue and the point is that the element was not adapting its width to the container.

Instead of using width:100%, be consistent (don't mix the floating model and the flex model) and use flex by adding this:

.child { align-self: stretch; }

Or:

.parent { align-items: stretch; }

This worked for me.

Twitter Bootstrap - how to center elements horizontally or vertically

With bootstrap 4 you can use flex

<div class="d-flex justify-content-center align-items-center">
    <button type="submit" class="btn btn-primary">Create</button>
</div>

source: bootstrap 4.1

How do I insert a JPEG image into a python Tkinter window?

import tkinter as tk
from tkinter import ttk
from PIL import Image,  ImageTk
win = tk. Tk()
image1 = Image. open("Aoran. jpg")
image2 =  ImageTk. PhotoImage(image1)
image_label = ttk. Label(win , image =.image2)
image_label.place(x = 0 , y = 0)
win.mainloop()

Newtonsoft JSON Deserialize

You can implement a class that holds the fields you have in your JSON

class MyData
{
    public string t;
    public bool a;
    public object[] data;
    public string[][] type;
}

and then use the generic version of DeserializeObject:

MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
    // Do something with typeStr
}

Documentation: Serializing and Deserializing JSON

bash: Bad Substitution

I have found that this issue is either caused by the marked answer or you have a line or space before the bash declaration

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

Write a file in external storage in Android

Even though above answers are correct, I wanna add a notice to distinguish types of storage:

  • Internal storage: It should say 'private storage' because it belongs to the app and cannot be shared. Where it's saved is based on where the app installed. If the app was installed on an SD card (I mean the external storage card you put more into a cell phone for more space to store images, videos, ...), your file will belong to the app means your file will be in an SD card. And if the app was installed on an Internal card (I mean the onboard storage card coming with your cell phone), your file will be in an Internal card.
  • External storage: It should say 'public storage' because it can be shared. And this mode divides into 2 groups: private external storage and public external storage. Basically, they are nearly the same, you can consult more from this site: https://developer.android.com/training/data-storage/files
  • A real SD card (I mean the external storage card you put more into a cell phone for more space to store images, videos, ...): this was not stated clearly on Android docs, so many people might be confused with how to save files in this card.

Here is the link to source code for cases I mentioned above: https://github.com/mttdat/utils/blob/master/utils/src/main/java/mttdat/utils/FileUtils.java

Where is SQL Server Management Studio 2012?

On the Official SQL Server 2012 ISO that's for download, just navigate to \x64\Setup\ (or \x86\Setup) and you will find "sql_ssms.msi". It's only about 60 MB, and since it's an .MSI you can probably provision it to be installed automatically (say for a large lab or classroom environment).

How to access global js variable in AngularJS directive

I have tried these methods and find that they dont work for my needs. In my case, I needed to inject json rendered server side into the main template of the page, so when it loads and angular inits, the data is already there and doesnt have to be retrieved (large dataset).

The easiest solution that I have found is to do the following:

In your angular code outside of the app, module and controller definitions add in a global javascript value - this definition MUST come before the angular stuff is defined.

Example:

'use strict';

//my data variable that I need access to.
var data = null;

angular.module('sample', [])

Then in your controller:

.controller('SampleApp', function ($scope, $location) {

$scope.availableList = [];

$scope.init = function () {
    $scope.availableList = data;
}

Finally, you have to init everything (order matters):

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="/path/to/your/angular/js/sample.js"></script>
  <script type="text/javascript">
      data = <?= json_encode($cproducts); ?>
  </script>

Finally initialize your controller and init function.

  <div ng-app="samplerrelations" ng-controller="SamplerApp" ng-init="init();">

By doing this you will now have access to whatever data you stuffed into the global variable.

file_put_contents: Failed to open stream, no such file or directory

I was also stuck on the same kind of problem and I followed the simple steps below.

Just get the exact url of the file to which you want to copy, for example:

http://www.test.com/test.txt (file to copy)

Then pass the exact absolute folder path with filename where you do want to write that file.

  1. If you are on a Windows machine then d:/xampp/htdocs/upload/test.txt

  2. If you are on a Linux machine then /var/www/html/upload/test.txt

You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT'].

Insert json file into mongodb

the following two ways work well:

C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs --file example2.json
C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs < example2.json

if the collections are under a specific user, you can use -u -p --authenticationDatabase

Set selected item in Android BottomNavigationView

This will probably be added in coming updates. But in the meantime, to accomplish this you can use reflection.

Create a custom view extending from BottomNavigationView and access some of its fields.

public class SelectableBottomNavigationView extends BottomNavigationView {

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

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

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

    public void setSelected(int index) {
        try {
            Field f = BottomNavigationView.class.getDeclaredField("mMenuView");
            f.setAccessible(true);
            BottomNavigationMenuView menuView = (BottomNavigationMenuView) f.get(this);

            try {
                Method method = menuView.getClass().getDeclaredMethod("activateNewButton", Integer.TYPE);
                method.setAccessible(true);
                method.invoke(menuView, index);
            } catch (SecurityException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

}

And then use it in your xml layout file.

<com.your.app.SelectableBottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemBackground="@color/primary"
        app:itemIconTint="@drawable/nav_item_color_state"
        app:itemTextColor="@drawable/nav_item_color_state"
        app:menu="@menu/bottom_navigation_menu"/>

How to link html pages in same or different folders?

Also, this will go up a directory and then back down to another subfolder.

<a href = "../subfolder/page.html">link</a>

To go up multiple directories you can do this.

<a href = "../../page.html">link</a>

To go the root, I use this

<a href = "~/page.html">link</a>

Can I add extension methods to an existing static class?

You CAN do this if you are willing to "frig" it a little by making a variable of the static class and assigning it to null. However, this method would not be available to static calls on the class, so not sure how much use it would be:

Console myConsole = null;
myConsole.WriteBlueLine("my blue line");

public static class Helpers {
    public static void WriteBlueLine(this Console c, string text)
    {
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.WriteLine(text);
        Console.ResetColor();
    }
}

'NoneType' object is not subscriptable?

The indexing e.g. [0] should occour inside of the print...

(Deep) copying an array using jQuery

I've come across this "deep object copy" function that I've found handy for duplicating objects by value. It doesn't use jQuery, but it certainly is deep.

http://www.overset.com/2007/07/11/javascript-recursive-object-copy-deep-object-copy-pass-by-value/

Php $_POST method to get textarea value

Use htmlspecialchars():

echo htmlspecialchars($_POST['contact_list']);

You can even improve your form processing by stripping all tags with strip_tags() and remove all white spaces with trim():

function processText($text) {
    $text = strip_tags($text);
    $text = trim($text);
    $text = htmlspecialchars($text);
    return $text;
}

echo processText($_POST['contact_list']);

How to open a folder in Windows Explorer from VBA?

Thanks to PhilHibbs comment (on VBwhatnow's answer) I was finally able to find a solution that both reuses existing windows and avoids flashing a CMD-window at the user:

Dim path As String
path = CurrentProject.path & "\"
Shell "cmd /C start """" /max """ & path & """", vbHide

where 'path' is the folder you want to open.

(In this example I open the folder where the current workbook is saved.)

Pros:

  • Avoids opening new explorer instances (only sets focus if window exists).
  • The cmd-window is never visible thanks to vbHide.
  • Relatively simple (does not need to reference win32 libraries).

Cons:

  • Window maximization (or minimization) is mandatory.

Explanation:

At first I tried using only vbHide. This works nicely... unless there is already such a folder opened, in which case the existing folder window becomes hidden and disappears! You now have a ghost window floating around in memory and any subsequent attempt to open the folder after that will reuse the hidden window - seemingly having no effect.

In other words when the 'start'-command finds an existing window the specified vbAppWinStyle gets applied to both the CMD-window and the reused explorer window. (So luckily we can use this to un-hide our ghost-window by calling the same command again with a different vbAppWinStyle argument.)

However by specifying the /max or /min flag when calling 'start' it prevents the vbAppWinStyle set on the CMD window from being applied recursively. (Or overrides it? I don't know what the technical details are and I'm curious to know exactly what the chain of events is here.)

How to change Angular CLI favicon

Press Ctrl+F5 in browser window

iterating through json object javascript

An improved version for recursive approach suggested by @schirrmacher to print key[value] for the entire object:

var jDepthLvl = 0;
function visit(object, objectAccessor=null) {
  jDepthLvl++;
  if (isIterable(object)) {
    if(objectAccessor === null) {
      console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- START ? ?", "background:yellow");
    } else
      console.log("%c"+spacesDepth(jDepthLvl)+objectAccessor+"%c:","color:purple;font-weight:bold", "color:black");
    forEachIn(object, function (accessor, child) {
      visit(child, accessor);
    });
  } else {
    var value = object;
    console.log("%c"
      + spacesDepth(jDepthLvl)
      + objectAccessor + "[%c" + value + "%c] "
      ,"color:blue","color:red","color:blue");
  }
  if(objectAccessor === null) {
    console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- END ? ?", "background:yellow");
  }
  jDepthLvl--;
}

function spacesDepth(jDepthLvl) {
  let jSpc="";
  for (let jIter=0; jIter<jDepthLvl-1; jIter++) {
    jSpc+="\u0020\u0020"
  }
  return jSpc;
}

function forEachIn(iterable, functionRef) {
  for (var accessor in iterable) {
    functionRef(accessor, iterable[accessor]);
  }
}

function isIterable(element) {
  return isArray(element) || isObject(element);
}

function isArray(element) {
  return element.constructor == Array;
}

function isObject(element) {
  return element.constructor == Object;
}


visit($OBJECT_OR_ARRAY$);

Console Output using JSON from @eric