Programs & Examples On #Mixing

All com.android.support libraries must use the exact same version specification

I had these dependencies in my project:

implementation 'com.android.support.constraint:constraint-layout:1.1.3'

implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:support-media-compat:28.0.0'

implementation 'com.google.android.gms:play-services-maps:16.1.0'

implementation 'com.google.firebase:firebase-database:17.0.0'
implementation 'com.google.firebase:firebase-storage:17.0.0'
implementation 'com.google.firebase:firebase-messaging:18.0.0'

implementation 'com.firebaseui:firebase-ui-storage:0.6.0'

So far nothing seemed wrong, but I got this message:

Found versions 28.0.0, 23.4.0. Examples include com.android.support:animated-vector-drawable:28.0.0 and com.android.support:palette-v7:23.4.

Then I did:

$ ./gradlew -q dependencies app:dependencies --configuration debugAndroidTestCompileClasspath >> dep.txt

In the file, I searched for the palette and found that it was used by firebase storage:

\--- com.firebaseui:firebase-ui-storage:0.6.0
     +--- com.android.support:appcompat-v7:23.4.0 -> 28.0.0 (*)
     +--- com.android.support:palette-v7:23.4.0

After adding:

implementation 'com.android.support:palette-v7:28.0.0'

Seems resolved, and no more error.

//Cheers

React.js: How to append a component on click?

As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.

In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field

class HealthConditions extends React.Component {
  constructor(props) {
    super(props);


    this.state = {
      inputLinkClicked: false
    }
  }

  handleAddSecondInput() {
    this.setState({
      inputLinkClicked: true
    })
  }


  render() {
    return(
      <main id="wrapper" className="" data-reset-cookie-tab>
        <div id="content" role="main">
          <div className="inner-block">

            <H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>

            <InputField label="Name of condition"
              InputType="text"
              InputId="id-condition"
              InputName="condition"
            />

            {
              this.state.inputLinkClicked?

              <InputField label=""
                InputType="text"
                InputId="id-condition2"
                InputName="condition2"
              />

              :

              <div></div>
            }

            <button
              type="button"
              className="make-button-link"
              data-add-button=""
              href="#"
              onClick={this.handleAddSecondInput}
            >
              Add a condition
            </button>

            <FormButton buttonLabel="Next"
              handleSubmit={this.handleSubmit}
              linkto={
                this.state.illnessOrDisability === 'true' ?
                "/404"
                :
                "/add-your-details"
              }
            />

            <BackLink backLink="/add-your-details" />

          </div>
         </div>
      </main>
    );
  }
}

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

Also please check your package name in Manifest and package name in google services json file. If both have package name differ from one another u will have this issue.

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

Yout can try this below.

<style name="MyToolbar" parent="Widget.AppCompat.Toolbar">
    <!-- your code here -->
</style>

And the detail elements you can find them in https://developer.android.com/reference/android/support/v7/appcompat/R.styleable.html#Toolbar

Here are some more:TextAppearance.Widget.AppCompat.Toolbar.Title, TextAppearance.Widget.AppCompat.Toolbar.Subtitle, Widget.AppCompat.Toolbar.Button.Navigation.

Hope this can help you.

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie results in another call to poruszanie, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.

Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

How to add a new audio (not mixing) into a video using ffmpeg?

Nothing quite worked for me (I think it was because my input .mp4 video didn't had any audio) so I found this worked for me:

ffmpeg -i input_video.mp4 -i balipraiavid.wav -map 0:v:0 -map 1:a:0 output.mp4

Mixing a PHP variable with a string literal

$bucket = '$node->' . $fieldname . "['und'][0]['value'] = " . '$form_state' . "['values']['" . $fieldname . "']";

print $bucket;

yields:

$node->mindd_2_study_status['und'][0]['value'] = $form_state['values']
['mindd_2_study_status']

Stop Visual Studio from mixing line endings in files

In Visual Studio 2015 (this still holds in 2019 for the same value), check the setting:

Tools > Options > Environment > Documents > Check for consistent line endings on load

VS2015 will now prompt you to convert line endings when you open a file where they are inconsistent, so all you need to do is open the files, select the desired option from the prompt and save them again.

Declaring and using MySQL varchar variables

Declare @variable type(size);

Set @variable = 'String' or Int ;

Example:

 Declare @id int;
 set @id = 10;

 Declare @str char(50);
 set @str='Hello' ; 

Combining C++ and C - how does #ifdef __cplusplus work?

A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code

Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.

The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.

The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.

One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.

Calling Java from Python

I've been integrating a lot of stuff into Python lately, including Java. The most robust method I've found is to use IKVM and a C# wrapper.

IKVM has a neat little application that allows you to take any Java JAR, and convert it directly to .Net DLL. It simply translates the JVM bytecode to CLR bytecode. See http://sourceforge.net/p/ikvm/wiki/Ikvmc/ for details.

The converted library behaves just like a native C# library, and you can use it without needing the JVM. You can then create a C# DLL wrapper project, and add a reference to the converted DLL.

You can now create some wrapper stubs that call the methods that you want to expose, and mark those methods as DllEport. See https://stackoverflow.com/a/29854281/1977538 for details.

The wrapper DLL acts just like a native C library, with the exported methods looking just like exported C methods. You can connect to them using ctype as usual.

I've tried it with Python 2.7, but it should work with 3.0 as well. Works on Windows and the Linuxes

If you happen to use C#, then this is probably the best approach to try when integrating almost anything into python.

Mixing C# & VB In The Same Project

No, you can't. An assembly/project (each project compiles to 1 assembly usually) has to be one language. However, you can use multiple assemblies, and each can be coded in a different language because they are all compiled to CIL.

It compiled fine and didn't complain because a VB.NET project will only actually compile the .vb files and a C# project will only actually compile the .cs files. It was ignoring the other ones, therefore you did not receive errors.

Edit: If you add a .vb file to a C# project, select the file in the Solution Explorer panel and then look at the Properties panel, you'll notice that the Build Action is 'Content', not 'Compile'. It is treated as a simple text file and doesn't even get embedded in the compiled assembly as a binary resource.

Edit: With asp.net websites you may add c# web user control to vb.net website

Why isn't Python very good for functional programming?

Guido has a good explanation of this here. Here's the most relevant part:

I have never considered Python to be heavily influenced by functional languages, no matter what people say or think. I was much more familiar with imperative languages such as C and Algol 68 and although I had made functions first-class objects, I didn't view Python as a functional programming language. However, earlier on, it was clear that users wanted to do much more with lists and functions.

...

It is also worth noting that even though I didn't envision Python as a functional language, the introduction of closures has been useful in the development of many other advanced programming features. For example, certain aspects of new-style classes, decorators, and other modern features rely upon this capability.

Lastly, even though a number of functional programming features have been introduced over the years, Python still lacks certain features found in “real” functional programming languages. For instance, Python does not perform certain kinds of optimizations (e.g., tail recursion). In general, because Python's extremely dynamic nature, it is impossible to do the kind of compile-time optimization known from functional languages like Haskell or ML. And that's fine.

I pull two things out of this:

  1. The language's creator doesn't really consider Python to be a functional language. Therefore, it's possible to see "functional-esque" features, but you're unlikely to see anything that is definitively functional.
  2. Python's dynamic nature inhibits some of the optimizations you see in other functional languages. Granted, Lisp is just as dynamic (if not more dynamic) as Python, so this is only a partial explanation.

Good MapReduce examples

From time to time I present MR concepts to people. I find processing tasks familiar to people and then map them to the MR paradigm.

Usually I take two things:

  1. Group By / Aggregations. Here the advantage of the shuffling stage is clear. An explanation that shuffling is also distributed sort + an explanation of distributed sort algorithm also helps.

  2. Join of two tables. People working with DB are familiar with the concept and its scalability problem. Show how it can be done in MR.

Inserting image into IPython notebook markdown

For those looking where to place the image file on the Jupyter machine so that it could be shown from the local file system.

I put my mypic.png into

/root/Images/mypic.png

(that is the Images folder that shows up in the Jupyter online file browser)

In that case I need to put the following line into the Markdown cell to make my pic showing in the notepad:

![My Title](Images/mypic.png)

How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

The simplest if you want to use only builtins is probably:

find `pwd` -name fileName

Only an extra two words to type, and this will work on all unix systems, as well as OSX.

Difference between using Makefile and CMake to compile the code

Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.

CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.

If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.

I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.

Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?

How to use the gecko executable with Selenium

You need to specify the system property with the path the .exe when starting the Selenium server node. See also the accepted anwser to Selenium grid with Chrome driver (WebDriverException: The path to the driver executable must be set by the webdriver.chrome.driver system property)

Datanode process not running in Hadoop

    mv /usr/local/hadoop_store/hdfs/datanode /usr/local/hadoop_store/hdfs/datanode.backup

    mkdir /usr/local/hadoop_store/hdfs/datanode

    hadoop datanode OR start-all.sh

    jps

How do I dump an object's fields to the console?

p object

Ruby doc for p.

p(*args) public

For each object, directly writes obj.inspect followed by a newline to the program’s standard output.

Using regular expression in css?

As complement of this answer you can use $ to get the end matches and * to get matches anywhere in the value name.

Matches anywhere: .col-md, .left-col, .col, .tricolor, etc.

[class*="col"]

Matches at the beginning: .col-md, .col-sm-6, etc.

[class^="col-"]

Matches at the ending: .left-col, .right-col, etc.

[class$="-col"]

How can I send and receive WebSocket messages on the server side?

C++ Implementation (not by me) here. Note that when your bytes are over 65535, you need to shift with a long value as shown here.

Python: converting a list of dictionaries to json

To convert it to a single dictionary with some decided keys value, you can use the code below.

data = ListOfDict.copy()
PrecedingText = "Obs_"
ListOfDictAsDict = {}
for i in range(len(data)):
    ListOfDictAsDict[PrecedingText + str(i)] = data[i]

What is the difference between '/' and '//' when used for division?

5.0//2 results in 2.0, and not 2 because the return type of the return value from // operator follows python coercion (type casting) rules.

Python promotes conversion of lower datatype (integer) to higher data type (float) to avoid data loss.

How to specify table's height such that a vertical scroll bar appears?

This CSS also shows a fixed height HTML table. It sets the height of the HTML tbody to 400 pixels and the HTML tbody scrolls when the it is larger, retaining the HTML thead as a non-scrolling element.

In addition, each th cell in the heading and each td cell the body should be styled for the desired fixed width.

#the-table {
  display: block;
  background: white; /* optional */
}

#the-table thead {
  text-align: left; /* optional */
}

#the-table tbody {
  display: block;
  max-height: 400px;
  overflow-y: scroll;
}

How to center horizontal table-cell

Short snippet for future visitors - how to center horizontal table-cell (+ vertically)

_x000D_
_x000D_
html, body {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.tab {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
  text-align: center; /* the key */_x000D_
  background-color: #EEEEEE;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  display: inline-block; /* important !! */_x000D_
  width: 100px;_x000D_
  background-color: #00FF00;_x000D_
}
_x000D_
<div class="tab">_x000D_
  <div class="cell">_x000D_
    <div class="content" id="a">_x000D_
      <p>Content</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make a Bootstrap accordion collapse when clicking the header div?

Here's a solution for Bootstrap4. You just need to put the card-header class in the a tag. This is a modified from an example in W3Schools.

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <div id="accordion">_x000D_
    <div class="card">_x000D_
      <a class="card-link card-header" data-toggle="collapse" href="#collapseOne" >_x000D_
        Collapsible Group Item #1_x000D_
      </a>_x000D_
      <div id="collapseOne" class="collapse" data-parent="#accordion">_x000D_
        <div class="card-body">_x000D_
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="card">_x000D_
      <a class="collapsed card-link card-header" data-toggle="collapse" href="#collapseTwo">_x000D_
        Collapsible Group Item #2_x000D_
      </a>_x000D_
      <div id="collapseTwo" class="collapse" data-parent="#accordion">_x000D_
        <div class="card-body">_x000D_
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="card">_x000D_
      <a class="card-link card-header" data-toggle="collapse" href="#collapseThree">_x000D_
        Collapsible Group Item #3_x000D_
      </a>_x000D_
      <div id="collapseThree" class="collapse" data-parent="#accordion">_x000D_
        <div class="card-body">_x000D_
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the difference between ( for... in ) and ( for... of ) statements?

For...in loop

The for...in loop improves upon the weaknesses of the for loop by eliminating the counting logic and exit condition.

Example:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in digits) {
  console.log(digits[index]);
}

But, you still have to deal with the issue of using an index to access the values of the array, and that stinks; it almost makes it more confusing than before.

Also, the for...in loop can get you into big trouble when you need to add an extra method to an array (or another object). Because for...in loops loop over all enumerable properties, this means if you add any additional properties to the array's prototype, then those properties will also appear in the loop.

Array.prototype.decimalfy = function() {
  for (let i = 0; i < this.length; i++) {
    this[i] = this[i].toFixed(2);
  }
};

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in digits) {
  console.log(digits[index]);
}

Prints:

0

1

2

3

4

5

6

7

8

9

function() { for (let i = 0; i < this.length; i++) { this[i] = this[i].toFixed(2); } }

This is why for...in loops are discouraged when looping over arrays.

NOTE: The forEach loop is another type of for loop in JavaScript. However, forEach() is actually an array method, so it can only be used exclusively with arrays. There is also no way to stop or break a forEach loop. If you need that type of behavior in your loop, you’ll have to use a basic for loop.

For...of loop

The for...of loop is used to loop over any type of data that is iterable.

Example:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const digit of digits) {
  console.log(digit);
}

Prints:

0

1

2

3

4

5

6

7

8

9

This makes the for...of loop the most concise version of all the for loops.

But wait, there’s more! The for...of loop also has some additional benefits that fix the weaknesses of the for and for...in loops.

You can stop or break a for...of loop at anytime.

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const digit of digits) {
  if (digit % 2 === 0) {
    continue;
  }
  console.log(digit);
}

Prints:

1

3

5

7

9

And you don’t have to worry about adding new properties to objects. The for...of loop will only loop over the values in the object.

Check if String / Record exists in DataTable

You can loop over each row of the DataTable and check the value.

I'm a big fan of using a foreach loop when using IEnumerables. Makes it very simple and clean to look at or process each row

DataTable dtPs = // ... initialize your DataTable
foreach (DataRow dr in dtPs.Rows)
{
    if (dr["item_manuf_id"].ToString() == "some value")
    {
        // do your deed
    }
}

Alternatively you can use a PrimaryKey for your DataTable. This helps in various ways, but you often need to define one before you can use it.

An example of using one if at http://msdn.microsoft.com/en-us/library/z24kefs8(v=vs.80).aspx

DataTable workTable = new DataTable("Customers");

// set constraints on the primary key
DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;

workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));

// set primary key
workTable.PrimaryKey = new DataColumn[] { workTable.Columns["CustID"] };

Once you have a primary key defined and data populated, you can use the Find(...) method to get the rows that match your primary key.

Take a look at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx

DataRow drFound = dtPs.Rows.Find("some value");
if (drFound["item_manuf_id"].ToString() == "some value")
{
    // do your deed
}

Finally, you can use the Select() method to find data within a DataTable also found at at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx.

String sExpression = "item_manuf_id == 'some value'";
DataRow[] drFound;
drFound = dtPs.Select(sExpression);

foreach (DataRow dr in drFound)
{
    // do you deed. Each record here was already found to match your criteria
}

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

Modifying list while iterating

Use a while loop that checks for the truthfulness of the array:

while array:
    value = array.pop(0)
    # do some calculation here

And it should do it without any errors or funny behaviour.

How do I open a URL from C++?

I was having the exact same problem in Windows.

I noticed that in OP's gist, he uses string("open ") in line 21, however, by using it one comes across this error:

'open' is not recognized as an internal or external command

After researching, I have found that open is MacOS the default command to open things. It is different on Windows or Linux.

Linux: xdg-open <URL>

Windows: start <URL>


For those of you that are using Windows, as I am, you can use the following:

std::string op = std::string("start ").append(url);
system(op.c_str());

In Java, how to append a string more efficiently?

- Each time you append or do any modification with it, it creates a new String object.

- So use append() method of StringBuilder(If thread safety is not important), else use StringBuffer(If thread safety is important.), that will be efficient way to do it.

How to read file binary in C#?

Quick and dirty version:

byte[] fileBytes = File.ReadAllBytes(inputFilename);
StringBuilder sb = new StringBuilder();

foreach(byte b in fileBytes)
{
    sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));  
}

File.WriteAllText(outputFilename, sb.ToString());

How to get the directory of the currently running file?

filepath.Abs("./")

Abs returns an absolute representation of path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path.

As stated in the comment, this returns the directory which is currently active.

Char array declaration and initialization in C

This is another C example of where the same syntax has different meanings (in different places). While one might be able to argue that the syntax should be different for these two cases, it is what it is. The idea is that not that it is "not allowed" but that the second thing means something different (it means "pointer assignment").

How to read a file and write into a text file?

    An example of reading a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for reading
Open "C:\Test.txt" For Input As #iFileNo
'change this filename to an existing file! (or run the example below first)

'read the file until we reach the end
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
'show the text (you will probably want to replace this line as appropriate to your program!)
MsgBox sFileText
Loop

'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo
(note: an alternative to Input # is Line Input # , which reads whole lines).


An example of writing a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for writing
Open "C:\Test.txt" For Output As #iFileNo
'please note, if this file already exists it will be overwritten!

'write some example text to the file
Print #iFileNo, "first line of text"
Print #iFileNo, " second line of text"
Print #iFileNo, "" 'blank line
Print #iFileNo, "some more text!"

'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo

From Here

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

It's possible that the modules are installed, but your PHP.ini still points to an old directory.

Check the contents of /usr/lib/php/extensions. In mine, there were two directories: no-debug-non-zts-20060613 and no-debug-non-zts-20060613. Around line 428 of your php.ini, change:

extension_dir = "/usr/local/lib/php/extensions/no-debug-non-zts-20060613"

to

extension_dir = "/usr/local/lib/php/extensions/no-debug-non-zts-20090626"

Then restart apache. This should resolve the issue.

Find OpenCV Version Installed on Ubuntu

1) Direct Answer: Try this:

   sudo updatedb
   locate OpenCVConfig.cmake

For me, I get:

   /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake

To see the version, you can try:

   cat /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake

giving

    ....
   SET(OpenCV_VERSION 2.3.1)
    ....

2) Better Answer:

"sudo make install" is your enemy, don't do that when you need to compile/update the library often and possibly debug step through it's internal functions. Notice how my config file is in a local build directory, not in /usr/something. You will avoid this confusion in the future, and can maintain several different versions even (debug and release, for example).

Edit: the reason this questions seems to arise often for OpenCV as opposed to other libraries is that it changes rather dramatically and fast between versions, and many of the operations are not so well-defined / well-constrained so you can't just rely on it to be a black-box like you do for something like libpng or libjpeg. Thus, better to not install it at all really, but just compile and link to the build folder.

htmlentities() vs. htmlspecialchars()

htmlentities — Convert all applicable characters to HTML entities.

htmlspecialchars — Convert special characters to HTML entities.

The translations performed translation characters on the below:

  • '&' (ampersand) becomes '&amp;'
  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
  • "'" (single quote) becomes '&#039;' (or ') only when ENT_QUOTES is set.
  • '<' (less than) becomes '&lt;'
  • '>' (greater than) becomes '&gt;'

You can check the following code for more information about what's htmlentities and htmlspecialchars:

https://gist.github.com/joko-wandiro/f5c935708d9c37d8940b

The difference in months between dates in MySQL

This depends on how you want the # of months to be defined. Answer this questions: 'What is difference in months: Feb 15, 2008 - Mar 12, 2009'. Is it defined by clear cut # of days which depends on leap years- what month it is, or same day of previous month = 1 month.

A calculation for Days:

Feb 15 -> 29 (leap year) = 14 Mar 1, 2008 + 365 = Mar 1, 2009. Mar 1 -> Mar 12 = 12 days. 14 + 365 + 12 = 391 days. Total = 391 days / (avg days in month = 30) = 13.03333

A calculation of months:

Feb 15 2008 - Feb 15 2009 = 12 Feb 15 -> Mar 12 = less than 1 month Total = 12 months, or 13 if feb 15 - mar 12 is considered 'the past month'

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

If you are using WAMP or XAMP server to install mysql database. Then you have to explicitly start mysql sever other wise it will show com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure while connecting with database

Event system in Python

You can try buslane module.

This library makes implementation of message-based system easier. It supports commands (single handler) and events (0 or multiple handlers) approach. Buslane uses Python type annotations to properly register handler.

Simple example:

from dataclasses import dataclass

from buslane.commands import Command, CommandHandler, CommandBus


@dataclass(frozen=True)
class RegisterUserCommand(Command):
    email: str
    password: str


class RegisterUserCommandHandler(CommandHandler[RegisterUserCommand]):

    def handle(self, command: RegisterUserCommand) -> None:
        assert command == RegisterUserCommand(
            email='[email protected]',
            password='secret',
        )


command_bus = CommandBus()
command_bus.register(handler=RegisterUserCommandHandler())
command_bus.execute(command=RegisterUserCommand(
    email='[email protected]',
    password='secret',
))

To install buslane, simply use pip:

$ pip install buslane

top nav bar blocking top content of the page

In my project derived from the MVC 5 tutorial I found that changing the body padding had no effect. The following worked for me:

@media screen and (min-width:768px) and (max-width:991px) {
    body {
        margin-top:100px;
    }
}
@media screen and (min-width:992px) and (max-width:1199px) {
    body {
        margin-top:50px;
    }
}

It resolves the cases where the navbar folds into 2 or 3 lines. This can be inserted into bootstrap.css anywhere after the lines body { margin: 0; }

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

Solution for per-app deployments

This is a listener I wrote to solve the problem: it autodetects if the driver has registered itself and acts accordingly.it

Important: it is meant to be used ONLY when the driver jar is deployed in WEB-INF/lib, not in the Tomcat /lib, as many suggest, so that each application can take care of its own driver and run on a untouched Tomcat. That is the way it should be IMHO.

Just configure the listener in your web.xml before any other and enjoy.

add near the top of web.xml:

<listener>
    <listener-class>utils.db.OjdbcDriverRegistrationListener</listener-class>    
</listener>

save as utils/db/OjdbcDriverRegistrationListener.java:

package utils.db;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import oracle.jdbc.OracleDriver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Registers and unregisters the Oracle JDBC driver.
 * 
 * Use only when the ojdbc jar is deployed inside the webapp (not as an
 * appserver lib)
 */
public class OjdbcDriverRegistrationListener implements ServletContextListener {

    private static final Logger LOG = LoggerFactory
            .getLogger(OjdbcDriverRegistrationListener.class);

    private Driver driver = null;

    /**
     * Registers the Oracle JDBC driver
     */
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        this.driver = new OracleDriver(); // load and instantiate the class
        boolean skipRegistration = false;
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
            if (driver instanceof OracleDriver) {
                OracleDriver alreadyRegistered = (OracleDriver) driver;
                if (alreadyRegistered.getClass() == this.driver.getClass()) {
                    // same class in the VM already registered itself
                    skipRegistration = true;
                    this.driver = alreadyRegistered;
                    break;
                }
            }
        }

        try {
            if (!skipRegistration) {
                DriverManager.registerDriver(driver);
            } else {
                LOG.debug("driver was registered automatically");
            }
            LOG.info(String.format("registered jdbc driver: %s v%d.%d", driver,
                    driver.getMajorVersion(), driver.getMinorVersion()));
        } catch (SQLException e) {
            LOG.error(
                    "Error registering oracle driver: " + 
                            "database connectivity might be unavailable!",
                    e);
            throw new RuntimeException(e);
        }
    }

    /**
     * Deregisters JDBC driver
     * 
     * Prevents Tomcat 7 from complaining about memory leaks.
     */
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        if (this.driver != null) {
            try {
                DriverManager.deregisterDriver(driver);
                LOG.info(String.format("deregistering jdbc driver: %s", driver));
            } catch (SQLException e) {
                LOG.warn(
                        String.format("Error deregistering driver %s", driver),
                        e);
            }
            this.driver = null;
        } else {
            LOG.warn("No driver to deregister");
        }

    }

}

How to test my servlet using JUnit

First off, in a real application, you would never get database connection info in a servlet; you would configure it in your app server.

There are ways, however, of testing Servlets without having a container running. One is to use mock objects. Spring provides a set of very useful mocks for things like HttpServletRequest, HttpServletResponse, HttpServletSession, etc:

http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/mock/web/package-summary.html

Using these mocks, you could test things like

What happens if username is not in the request?

What happens if username is in the request?

etc

You could then do stuff like:

import static org.junit.Assert.assertEquals;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

public class MyServletTest {
    private MyServlet servlet;
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;

    @Before
    public void setUp() {
        servlet = new MyServlet();
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
    }

    @Test
    public void correctUsernameInRequest() throws ServletException, IOException {
        request.addParameter("username", "scott");
        request.addParameter("password", "tiger");

        servlet.doPost(request, response);

        assertEquals("text/html", response.getContentType());

        // ... etc
    }
}

Importing CommonCrypto in a Swift framework

I'm not sure if something's changed with Xcode 9.2 but it's now much simpler to achieve this. The only things I had to do are create a folder called "CommonCrypto" in my framework project directory and create two files inside it, one called "cc.h" as follows:

#include <CommonCrypto/CommonCrypto.h>
#include <CommonCrypto/CommonRandom.h>

And another called module.modulemap:

module CommonCrypto {
    export *
    header "cc.h"
}

(I don't know why you can't reference header files from the SDKROOT area directly in a modulemap file but I couldn't get it to work)

The third thing is to find the "Import Paths" setting and set to $(SRCROOT). In fact you can set it to whatever folder you want the CommonCrypto folder to be under, if you don't want it at the root level.

After this you should be able to use

import CommonCrypto

In any swift file and all the types/functions/etc. are available.

A word of warning though - if your app uses libCommonCrypto (or libcoreCrypto) it's exceptionally easy for a not-too-sophisticated hacker to attach a debugger to your app and find out what keys are being passed to these functions.

Android fade in and fade out with ImageView

This is probably the best solution you'll get. Simple and Easy. I learned it on udemy. Suppose you have two images having image id's id1 and id2 respectively and currently the image view is set as id1 and you want to change it to the other image everytime someone clicks in. So this is the basic code in MainActivity.java File

int clickNum=0;
public void click(View view){
clickNum++;
ImageView a=(ImageView)findViewById(R.id.id1);
ImageView b=(ImageView)findViewById(R.id.id2);
if(clickNum%2==1){
  a.animate().alpha(0f).setDuration(2000); //alpha controls the transpiracy
}
else if(clickNum%2==0){
  b.animate().alpha(0f).setDuration(2000); //alpha controls the transpiracy
}

}

I hope this will surely help

no module named zlib

By default when you configuring Python source, zlib module is disabled, so you can enable it using option --with-zlib when you configure it. So it becomes

./configure --with-zlib

Convert JSON to Map

If you're using org.json, JSONObject has a method toMap(). You can easily do:

Map<String, Object> myMap = myJsonObject.toMap();

how to remove css property using javascript?

actually, if you already know the property, this will do it...

for example:

<a href="test.html" style="color:white;zoom:1.2" id="MyLink"></a>

    var txt = "";
    txt = getStyle(InterTabLink);
    setStyle(InterTabLink, txt.replace("zoom\:1\.2\;","");

    function setStyle(element, styleText){
        if(element.style.setAttribute)
            element.style.setAttribute("cssText", styleText );
        else
            element.setAttribute("style", styleText );
    }

    /* getStyle function */
    function getStyle(element){
        var styleText = element.getAttribute('style');
        if(styleText == null)
            return "";
        if (typeof styleText == 'string') // !IE
            return styleText;
        else  // IE
            return styleText.cssText;
    } 

Note that this only works for inline styles... not styles you've specified through a class or something like that...

Other note: you may have to escape some characters in that replace statement, but you get the idea.

How can I upload files asynchronously?

Look for Handling the upload process for a file, asynchronously in here: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

Sample from the link

<?php
if (isset($_FILES['myFile'])) {
    // Example:
    move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
    exit;
}
?><!DOCTYPE html>
<html>
<head>
    <title>dnd binary upload</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
        function sendFile(file) {
            var uri = "/index.php";
            var xhr = new XMLHttpRequest();
            var fd = new FormData();

            xhr.open("POST", uri, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // Handle response.
                    alert(xhr.responseText); // handle response.
                }
            };
            fd.append('myFile', file);
            // Initiate a multipart/form-data upload
            xhr.send(fd);
        }

        window.onload = function() {
            var dropzone = document.getElementById("dropzone");
            dropzone.ondragover = dropzone.ondragenter = function(event) {
                event.stopPropagation();
                event.preventDefault();
            }

            dropzone.ondrop = function(event) {
                event.stopPropagation();
                event.preventDefault();

                var filesArray = event.dataTransfer.files;
                for (var i=0; i<filesArray.length; i++) {
                    sendFile(filesArray[i]);
                }
            }
        }
    </script>
</head>
<body>
    <div>
        <div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>
    </div>
</body>
</html>

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

Check this:

// Define the border style of the form to a dialog box.
form1.FormBorderStyle = FormBorderStyle.FixedDialog;

// Set the MaximizeBox to false to remove the maximize box.
form1.MaximizeBox = false;

// Set the MinimizeBox to false to remove the minimize box.
form1.MinimizeBox = false;

// Set the start position of the form to the center of the screen.
form1.StartPosition = FormStartPosition.CenterScreen;

// Display the form as a modal dialog box.
form1.ShowDialog();

How to remove spaces from a string using JavaScript?

your_string = 'Hello world';
words_array = your_tring.split(' ');

string_without_space = '';

for(i=0; i<words_array.length; i++){
    new_text += words_array[i]; 
}

console.log("The new word:" new_text);

The output:

HelloWorld

Java for loop syntax: "for (T obj : objects)"

yes... This is for each loop in java.

Generally this loop is become useful when you are retrieving data or object from the database.

Syntex :

for(Object obj : Collection obj)
{
     //Code enter code here
}

Example :

for(User user : userList)
{
     System.out.println("USer NAme :" + user.name);
   // etc etc
}

This is for each loop.

it will incremental by automatically. one by one from collection to USer object data has been filled. and working.

How to display pie chart data values of each slice in chart.js

For Chart.js 2.0 and up, the Chart object data has changed. For those who are using Chart.js 2.0+, below is an example of using HTML5 Canvas fillText() method to display data value inside of the pie slice. The code works for doughnut chart, too, with the only difference being type: 'pie' versus type: 'doughnut' when creating the chart.

Script:

Javascript

var data = {
    datasets: [{
        data: [
            11,
            16,
            7,
            3,
            14
        ],
        backgroundColor: [
            "#FF6384",
            "#4BC0C0",
            "#FFCE56",
            "#E7E9ED",
            "#36A2EB"
        ],
        label: 'My dataset' // for legend
    }],
    labels: [
        "Red",
        "Green",
        "Yellow",
        "Grey",
        "Blue"
    ]
};

var pieOptions = {
  events: false,
  animation: {
    duration: 500,
    easing: "easeOutQuart",
    onComplete: function () {
      var ctx = this.chart.ctx;
      ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
      ctx.textAlign = 'center';
      ctx.textBaseline = 'bottom';

      this.data.datasets.forEach(function (dataset) {

        for (var i = 0; i < dataset.data.length; i++) {
          var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
              total = dataset._meta[Object.keys(dataset._meta)[0]].total,
              mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius)/2,
              start_angle = model.startAngle,
              end_angle = model.endAngle,
              mid_angle = start_angle + (end_angle - start_angle)/2;

          var x = mid_radius * Math.cos(mid_angle);
          var y = mid_radius * Math.sin(mid_angle);

          ctx.fillStyle = '#fff';
          if (i == 3){ // Darker text color for lighter background
            ctx.fillStyle = '#444';
          }
          var percent = String(Math.round(dataset.data[i]/total*100)) + "%";      
          //Don't Display If Legend is hide or value is 0
          if(dataset.data[i] != 0 && dataset._meta[0].data[i].hidden != true) {
            ctx.fillText(dataset.data[i], model.x + x, model.y + y);
            // Display percent in another line, line break doesn't work for fillText
            ctx.fillText(percent, model.x + x, model.y + y + 15);
          }
        }
      });               
    }
  }
};

var pieChartCanvas = $("#pieChart");
var pieChart = new Chart(pieChartCanvas, {
  type: 'pie', // or doughnut
  data: data,
  options: pieOptions
});

HTML

<canvas id="pieChart" width=200 height=200></canvas>

jsFiddle

An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server

Summary

SQL Server won't let you insert an explicit value in an identity column unless you use a column list. Thus, you have the following options:

  1. Make a column list (either manually or using tools, see below)

OR

  1. make the identity column in tbl_A_archive a regular, non-identity column: If your table is an archive table and you always specify an explicit value for the identity column, why do you even need an identity column? Just use a regular int instead.

Details on Solution 1

Instead of

SET IDENTITY_INSERT archive_table ON;

INSERT INTO archive_table
  SELECT *
  FROM source_table;

SET IDENTITY_INSERT archive_table OFF;

you need to write

SET IDENTITY_INSERT archive_table ON;

INSERT INTO archive_table (field1, field2, ...)
  SELECT field1, field2, ...
  FROM source_table;

SET IDENTITY_INSERT archive_table OFF;

with field1, field2, ... containing the names of all columns in your tables. If you want to auto-generate that list of columns, have a look at Dave's answer or Andomar's answer.


Details on Solution 2

Unfortunately, it is not possible to just "change the type" of an identity int column to a non-identity int column. Basically, you have the following options:

  • If the archive table does not contain data yet, drop the column and add a new one without identity.

OR

  • Use SQL Server Management Studio to set the Identity Specification/(Is Identity) property of the identity column in your archive table to No. Behind the scenes, this will create a script to re-create the table and copy existing data, so, to do that, you will also need to unset Tools/Options/Designers/Table and Database Designers/Prevent saving changes that require table re-creation.

OR

Perl: Use s/ (replace) and return new string

print "bla: ", $myvar =~ tr{a}{b},"\n";

iPhone: How to get current milliseconds?

[NSDate timeIntervalSinceReferenceDate] is another option, if you don't want to include the Quartz framework. It returns a double, representing seconds.

how to add json library

AFAIK the json module was added in version 2.6, see here. I'm guessing you can update your python installation to the latest stable 2.6 from this page.

Align two divs horizontally side by side center to the page using bootstrap css

Use the bootstrap classes col-xx-# and col-xx-offset-#

So what is happening here is your screen is getting divided into 12 columns. In col-xx-#, # is the number of columns you cover and offset is the number of columns you leave.

For xx, in a general website, md is preferred and if you want your layout to look the same in a mobile device, xs is preferred.

With what I can make of your requirement,

<div class="row">
  <div class="col-md-4">First Div</div>
  <div class="col-md-8">Second DIV </div>
</div>

Should do the trick.

How to generate unique IDs for form labels in React?

Hopefully this is helpful to anyone coming looking for a universal/isomorphic solution, since the checksum issue is what led me here in the first place.

As said above, I've created a simple utility to sequentially create a new id. Since the IDs keep incrementing on the server, and start over from 0 in the client, I decided to reset the increment each the SSR starts.

// utility to generate ids
let current = 0

export default function generateId (prefix) {
  return `${prefix || 'id'}-${current++}`
}

export function resetIdCounter () { current = 0 }

And then in the root component's constructor or componentWillMount, call the reset. This essentially resets the JS scope for the server in each server render. In the client it doesn't (and shouldn't) have any effect.

Access PHP variable in JavaScript

metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:

<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>

Python reshape list to ndim array

The answers above are good. Adding a case that I used. Just if you don't want to use numpy and keep it as list without changing the contents.

You can run a small loop and change the dimension from 1xN to Nx1.

    tmp=[]
    for b in bus:
        tmp.append([b])
    bus=tmp

It is maybe not efficient while in case of very large numbers. But it works for a small set of numbers. Thanks

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

A bit late to the game, but non of the above solutions pointed me in the direction of a pure and simple .NET, no json.net solution. So here it is, ended up being very simple. Below a full running example of how it is done with standard .NET Json serialization, the example has dictionary both in the root object and in the child objects.

The golden bullet is this cat, parse the settings as second parameter to the serializer:

DataContractJsonSerializerSettings settings =
                       new DataContractJsonSerializerSettings();
                    settings.UseSimpleDictionaryFormat = true;

Full code below:

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

    namespace Kipon.dk
    {
        public class JsonTest
        {
            public const string EXAMPLE = @"{
                ""id"": ""some id"",
                ""children"": {
                ""f1"": {
                    ""name"": ""name 1"",
                    ""subs"": {
                    ""1"": { ""name"": ""first sub"" },
                    ""2"": { ""name"": ""second sub"" }
                    }
                },
                ""f2"": {
                    ""name"": ""name 2"",
                    ""subs"": {
                    ""37"": { ""name"":  ""is 37 in key""}
                    }
                }
                }
            }
            ";

            [DataContract]
            public class Root
            {
                [DataMember(Name ="id")]
                public string Id { get; set; }

                [DataMember(Name = "children")]
                public Dictionary<string,Child> Children { get; set; }
            }

            [DataContract]
            public class Child
            {
                [DataMember(Name = "name")]
                public string Name { get; set; }

                [DataMember(Name = "subs")]
                public Dictionary<int, Sub> Subs { get; set; }
            }

            [DataContract]
            public class Sub
            {
                [DataMember(Name = "name")]
                public string Name { get; set; }
            }

            public static void Test()
            {
                var array = System.Text.Encoding.UTF8.GetBytes(EXAMPLE);
                using (var mem = new System.IO.MemoryStream(array))
                {
                    mem.Seek(0, System.IO.SeekOrigin.Begin);
                    DataContractJsonSerializerSettings settings =
                       new DataContractJsonSerializerSettings();
                    settings.UseSimpleDictionaryFormat = true;

                    var ser = new DataContractJsonSerializer(typeof(Root), settings);
                    var data = (Root)ser.ReadObject(mem);
                    Console.WriteLine(data.Id);
                    foreach (var childKey in data.Children.Keys)
                    {
                        var child = data.Children[childKey];
                        Console.WriteLine(" Child: " + childKey + " " + child.Name);
                        foreach (var subKey in child.Subs.Keys)
                        {
                            var sub = child.Subs[subKey];
                            Console.WriteLine("   Sub: " + subKey + " " + sub.Name);
                        }
                    }
                }
            }
        }
    }

Git merge reports "Already up-to-date" though there is a difference

The same happened to me. But the scenario was a little different, I had master branch, and I carved out release_1 (say) out of it. Made some changes in release_1 branch and merged it into origin. then I did ssh and on the remote server I again checkout out release_1 using the command git checkout -b release_1 - which actually carves out a new branch release_! from the master rather than checking out the already existing branch release_1 from origin. Solved the problem by removing "-b" switch

PostgreSQL column 'foo' does not exist

I also ran into this error when I was using Dapper and forgot to input a parameterized value.

To fix I had to ensure that the object passed in as a parameter had properties matching the parameterised values in the SQL string.

Detect and exclude outliers in Pandas data frame

Since I am in a very early stage of my data science journey, I am treating outliers with the code below.

#Outlier Treatment

def outlier_detect(df):
    for i in df.describe().columns:
        Q1=df.describe().at['25%',i]
        Q3=df.describe().at['75%',i]
        IQR=Q3 - Q1
        LTV=Q1 - 1.5 * IQR
        UTV=Q3 + 1.5 * IQR
        x=np.array(df[i])
        p=[]
        for j in x:
            if j < LTV or j>UTV:
                p.append(df[i].median())
            else:
                p.append(j)
        df[i]=p
    return df

How to get full file path from file name?

private const string BulkSetPriceFile = "test.txt";
...
var fullname = Path.GetFullPath(BulkSetPriceFile);

Using Java to find substring of a bigger string using Regular Expression

If you simply need to get whatever is between [], the you can use \[([^\]]*)\] like this:

Pattern regex = Pattern.compile("\\[([^\\]]*)\\]");
Matcher m = regex.matcher(str);
if (m.find()) {
    result = m.group();
}

If you need it to be of the form identifier + [ + content + ] then you can limit extracting the content only when the identifier is a alphanumerical:

[a-zA-Z][a-z-A-Z0-9_]*\s*\[([^\]]*)\]

This will validate things like Foo [Bar], or myDevice_123["input"] for instance.

Main issue

The main problem is when you want to extract the content of something like this:

FOO[BAR[CAT[123]]+DOG[FOO]]

The Regex won't work and will return BAR[CAT[123 and FOO.
If we change the Regex to \[(.*)\] then we're OK but then, if you're trying to extract the content from more complex things like:

FOO[BAR[CAT[123]]+DOG[FOO]] = myOtherFoo[BAR[5]]

None of the Regexes will work.

The most accurate Regex to extract the proper content in all cases would be a lot more complex as it would need to balance [] pairs and give you they content.

A simpler solution

If your problems is getting complex and the content of the [] arbitrary, you could instead balance the pairs of [] and extract the string using plain old code rathe than a Regex:

int i;
int brackets = 0;
string c;
result = "";
for (i = input.indexOf("["); i < str.length; i++) {
    c = str.substring(i, i + 1);
    if (c == '[') {
        brackets++;
    } else if (c == ']') {
        brackets--;
        if (brackets <= 0) 
            break;
    }
    result = result + c;
}   

This is more pseudo-code than real code, I'm not a Java coder so I don't know if the syntax is correct, but it should be easy enough to improve upon.
What count is that this code should work and allow you to extract the content of the [], however complex it is.

deleting folder from java

It will delete a folder recursively

public static void folderdel(String path){
    File f= new File(path);
    if(f.exists()){
        String[] list= f.list();
        if(list.length==0){
            if(f.delete()){
                System.out.println("folder deleted");
                return;
            }
        }
        else {
            for(int i=0; i<list.length ;i++){
                File f1= new File(path+"\\"+list[i]);
                if(f1.isFile()&& f1.exists()){
                    f1.delete();
                }
                if(f1.isDirectory()){
                    folderdel(""+f1);
                }
            }
            folderdel(path);
        }
    }
}

System.Net.Http: missing from namespace? (using .net 4.5)

HttpClient lives in the System.Net.Http namespace.

You'll need to add:

using System.Net.Http;

And make sure you are referencing System.Net.Http.dll in .NET 4.5.


The code posted doesn't appear to do anything with webClient. Is there something wrong with the code that is actually compiling using HttpWebRequest?


Update

To open the Add Reference dialog right-click on your project in Solution Explorer and select Add Reference.... It should look something like:

enter image description here

No module named pkg_resources

I experienced that error in my Google App Engine environment. And pip install -t lib setuptools fixed the issue.

Add new column with foreign key constraint in one command

For DB2, the syntax is:

ALTER TABLE one ADD two_id INTEGER FOREIGN KEY (two_id) REFERENCES two (id);

semaphore implementation

Your Fundamentals are wrong, the program won't work, so go through the basics and rewrite the program.

Some of the corrections you must make are:

1) You must make a variable of semaphore type

sem_t semvar;

2) The functions sem_wait(), sem_post() require the semaphore variable but you are passing the semaphore id, which makes no sense.

sem_wait(&semvar);
   //your critical section code
sem_post(&semvar);

3) You are passing the semaphore to sem_wait() and sem_post() without initializing it. You must initialize it to 1 (in your case) before using it, or you will have a deadlock.

ret = semctl( semid, 1, SETVAL, sem);
if (ret == 1)
     perror("Semaphore failed to initialize");

Study the semaphore API's from the man page and go through this example.

Update multiple columns in SQL

The "tiresome way" is standard SQL and how mainstream RDBMS do it.

With a 100+ columns, you mostly likely have a design problem... also, there are mitigating methods in client tools (eg generation UPDATE statements) or by using ORMs

How do I get PHP errors to display?

Create a file called php.ini in the folder where your PHP file resides.

Inside php.ini add the following code (I am giving an simple error showing code):

display_errors = on

display_startup_errors = on

How can I list (ls) the 5 last modified files in a directory?

ls -t list files by creation time not last modified time. Use ls -ltc if you want to list files by last modified time from last to first(top to bottom). Thus to list the last n: ls -ltc | head ${n}

SQL Server stored procedure parameters

CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50),
@Id INT
AS
BEGIN
-- SP Logic
END

Procedure Calling

DECLARE @return_value nvarchar(50)

EXEC  @return_value = GetTaskEvents
        @TaskName = 'TaskName',
        @Id =2  

SELECT  'Return Value' = @return_value

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

Here is a link to VeriSign's SSL Certificate Installation Checker: https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR1130

Enter your URL, click "Test this Web Server" and it will tell you if there are issues with your intermediate certificate authority.

Excel VBA to Export Selected Sheets to PDF

Once you have Selected a group of sheets, you can use Selection

Consider:

Sub luxation()
    ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
    Selection.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:="C:\TestFolder\temp.pdf", _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub

EDIT#1:

Further testing has reveled that this technique depends on the group of cells selected on each worksheet. To get a comprehensive output, use something like:

Sub Macro1()

   Sheets("Sheet1").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet2").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet3").Activate
   ActiveSheet.UsedRange.Select

   ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
   Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
      "C:\Users\James\Desktop\pdfmaker.pdf", Quality:=xlQualityStandard, _
      IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
      True
End Sub

Why does .json() return a promise?

In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:

function callApi(url) {
  return fetch(url)
    .then(response => {
      if (response.ok) {
        return response.json().then(response => ({ response }));
      }

      return response.json().then(error => ({ error }));
    })
  ;
}

let url = 'http://jsonplaceholder.typicode.com/posts/6';

const { response, error } = callApi(url);
if (response) {
  // handle json decoded response
} else {
  // handle json decoded 500 series response
}

How to loop over a Class attributes in Java?

Accessing the fields directly is not really good style in java. I would suggest creating getter and setter methods for the fields of your bean and then using then Introspector and BeanInfo classes from the java.beans package.

MyBean bean = new MyBean();
BeanInfo beanInfo = Introspector.getBeanInfo(MyBean.class);
for (PropertyDescriptor propertyDesc : beanInfo.getPropertyDescriptors()) {
    String propertyName = propertyDesc.getName();
    Object value = propertyDesc.getReadMethod().invoke(bean);
}

What is the difference between __dirname and ./ in node.js?

The gist

In Node.js, __dirname is always the directory in which the currently executing script resides (see this). So if you typed __dirname into /d1/d2/myscript.js, the value would be /d1/d2.

By contrast, . gives you the directory from which you ran the node command in your terminal window (i.e. your working directory) when you use libraries like path and fs. Technically, it starts out as your working directory but can be changed using process.chdir().

The exception is when you use . with require(). The path inside require is always relative to the file containing the call to require.

For example...

Let's say your directory structure is

/dir1
  /dir2
    pathtest.js

and pathtest.js contains

var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));

and you do

cd /dir1/dir2
node pathtest.js

you get

. = /dir1/dir2
__dirname = /dir1/dir2

Your working directory is /dir1/dir2 so that's what . resolves to. Since pathtest.js is located in /dir1/dir2 that's what __dirname resolves to as well.

However, if you run the script from /dir1

cd /dir1
node dir2/pathtest.js

you get

. = /dir1
__dirname = /dir1/dir2

In that case, your working directory was /dir1 so that's what . resolved to, but __dirname still resolves to /dir1/dir2.

Using . inside require...

If inside dir2/pathtest.js you have a require call into include a file inside dir1 you would always do

require('../thefile')

because the path inside require is always relative to the file in which you are calling it. It has nothing to do with your working directory.

Which Protocols are used for PING?

ICMP means Internet Control Message Protocol and is always coupled with the IP protocol (There's 2 ICMP variants one for IPv4 and one for IPv6.)

echo request and echo response are the two operation codes of ICMP used to implement ping.

Besides the original ping program, ping might simply mean the action of checking if a remote node is responding, this might be done on several layers in a protocol stack - e.g. ARP ping for testing hosts on a local network. The term ping might be used on higher protocol layers and APIs as well, e.g. the act of checking if a database is up, done at the database layer protocol.

ICMP sits on top of IP. What you have below depends on the network you're on, and are not in themselves relevant to the operation of ping.

Return content with IHttpActionResult for non-OK response

I ended up going with the following solution:

public class HttpActionResult : IHttpActionResult
{
    private readonly string _message;
    private readonly HttpStatusCode _statusCode;

    public HttpActionResult(HttpStatusCode statusCode, string message)
    {
        _statusCode = statusCode;
        _message = message;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage response = new HttpResponseMessage(_statusCode)
        {
            Content = new StringContent(_message)
        };
        return Task.FromResult(response);
    }
}

... which can be used like this:

public IHttpActionResult Get()
{
   return new HttpActionResult(HttpStatusCode.InternalServerError, "error message"); // can use any HTTP status code
}

I'm open to suggestions for improvement. :)

Rails 4: before_filter vs. before_action

As we can see in ActionController::Base, before_action is just a new syntax for before_filter.

However all before_filters syntax are deprecated in Rails 5.0 and will be removed in Rails 5.1

Writing Python lists to columns in csv

If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:

import pandas as pd

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')

df.to_csv('file.csv', index=False)

print(df)

   Col0  Col1  Col2
0     1     4     7
1     2     5     8
2     3     6     9

Get current date/time in seconds

 Date.now()

gives milliseconds since epoch. No need to use new.

Check out the reference here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

(Not supported in IE8.)

invalid new-expression of abstract class type

Another possible cause for future Googlers

I had this issue because a method I was trying to implement required a std::unique_ptr<Queue>(myQueue) as a parameter, but the Queue class is abstract. I solved that by using a QueuePtr(myQueue) constructor like so:

using QueuePtr = std::unique_ptr<Queue>;

and used that in the parameter list instead. This fixes it because the initializer tries to create a copy of Queue when you make a std::unique_ptr of its type, which can't happen.

Decompile an APK, modify it and then recompile it

This is a way:

  1. Using apktool to decode:

     $ apktool d -f {apkfile} -o {output folder}
    
  2. Next, using JADX (at github.com/skylot/jadx)

     $ jadx -d {output folder} {apkfile}
    

2 tools extract and decompiler to same output folder.

Easy way: Using Online APK Decompiler

How to join components of a path when you are constructing a URL in Python

I know this is a bit more than the OP asked for, However I had the pieces to the following url, and was looking for a simple way to join them:

>>> url = 'https://api.foo.com/orders/bartag?spamStatus=awaiting_spam&page=1&pageSize=250'

Doing some looking around:

>>> split = urlparse.urlsplit(url)
>>> split
SplitResult(scheme='https', netloc='api.foo.com', path='/orders/bartag', query='spamStatus=awaiting_spam&page=1&pageSize=250', fragment='')
>>> type(split)
<class 'urlparse.SplitResult'>
>>> dir(split)
['__add__', '__class__', '__contains__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_asdict', '_fields', '_make', '_replace', 'count', 'fragment', 'geturl', 'hostname', 'index', 'netloc', 'password', 'path', 'port', 'query', 'scheme', 'username']
>>> split[0]
'https'
>>> split = (split[:])
>>> type(split)
<type 'tuple'>

So in addition to the path joining which has already been answered in the other answers, To get what I was looking for I did the following:

>>> split
('https', 'api.foo.com', '/orders/bartag', 'spamStatus=awaiting_spam&page=1&pageSize=250', '')
>>> unsplit = urlparse.urlunsplit(split)
>>> unsplit
'https://api.foo.com/orders/bartag?spamStatus=awaiting_spam&page=1&pageSize=250'

According to the documentation it takes EXACTLY a 5 part tuple.

With the following tuple format:

scheme 0 URL scheme specifier empty string

netloc 1 Network location part empty string

path 2 Hierarchical path empty string

query 3 Query component empty string

fragment 4 Fragment identifier empty string

Resize jqGrid when browser is resized?

<script>
$(document).ready(function(){    
$(window).on('resize', function() {
    jQuery("#grid").setGridWidth($('#fill').width(), false); 
    jQuery("#grid").setGridHeight($('#fill').height(),true); 
}).trigger('resize');      
});
</script>

Compile Views in ASP.NET MVC

Next release of ASP.NET MVC (available in January or so) should have MSBuild task that compiles views, so you might want to wait.

See announcement

How do I update pip itself from inside my virtual environment?

Very Simple. Just download pip from https://bootstrap.pypa.io/get-pip.py . Save the file in some forlder or dekstop. I saved the file in my D drive.Then from your command prompt navigate to the folder where you have downloaded pip. Then type there

python -get-pip.py

Pip installation screenshot

How to read text file in JavaScript

my example

<html>

<head>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>

<body>
  <script>
    function PreviewText() {
      var oFReader = new FileReader();
      oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
      oFReader.onload = function(oFREvent) {
        document.getElementById("uploadTextValue").value = oFREvent.target.result;
        document.getElementById("obj").data = oFREvent.target.result;
      };
    };
    jQuery(document).ready(function() {
      $('#viewSource').click(function() {
        var text = $('#uploadTextValue').val();
        alert(text);
        //here ajax
      });
    });
  </script>
  <object width="100%" height="400" data="" id="obj"></object>
  <div>
    <input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
    <input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
  </div>
  <a href="#" id="viewSource">Source file</a>
</body>

</html>

How to do multiple conditions for single If statement

Use the 'And' keyword for a logical and. Like this:

If Not ((filename = testFileName) And (fileName <> "")) Then

How to destroy an object?

I would go with unset because it might give the garbage collector a better hint so that the memory can be available again sooner. Be careful that any things the object points to either have other references or get unset first or you really will have to wait on the garbage collector since there would then be no handles to them.

Laravel migration default value

Might be a little too late to the party, but hope this helps someone with similar issue.

The reason why your default value doesnt't work is because the migration file sets up the default value in your database (MySQL or PostgreSQL or whatever), and not in your Laravel application.

Let me illustrate with an example.

This line means Laravel is generating a new Book instance, as specified in your model. The new Book object will have properties according to the table associated with the model. Up until this point, nothing is written on the database.

$book = new Book();

Now the following lines are setting up the values of each property of the Book object. Same still, nothing is written on the database yet.

$book->author = 'Test'
$book->title = 'Test'

This line is the one writing to the database. After passing on the object to the database, then the empty fields will be filled by the database (may be default value, may be null, or whatever you specify on your migration file).

$book->save();

And thus, the default value will not pop up before you save it to the database.

But, that is not enough. If you try to access $book->price, it will still be null (or 0, i'm not sure). Saving it is only adding the defaults to the record in the database, and it won't affect the Object you are carrying around.

So, to get the instance with filled-in default values, you have to re-fetch the instance. You may use the

Book::find($book->id);

Or, a more sophisticated way by refreshing the instance

$book->refresh();

And then, the next time you try to access the object, it will be filled with the default values.

List comprehension vs. lambda + filter

Curiously on Python 3, I see filter performing faster than list comprehensions.

I always thought that the list comprehensions would be more performant. Something like: [name for name in brand_names_db if name is not None] The bytecode generated is a bit better.

>>> def f1(seq):
...     return list(filter(None, seq))
>>> def f2(seq):
...     return [i for i in seq if i is not None]
>>> disassemble(f1.__code__)
2         0 LOAD_GLOBAL              0 (list)
          2 LOAD_GLOBAL              1 (filter)
          4 LOAD_CONST               0 (None)
          6 LOAD_FAST                0 (seq)
          8 CALL_FUNCTION            2
         10 CALL_FUNCTION            1
         12 RETURN_VALUE
>>> disassemble(f2.__code__)
2           0 LOAD_CONST               1 (<code object <listcomp> at 0x10cfcaa50, file "<stdin>", line 2>)
          2 LOAD_CONST               2 ('f2.<locals>.<listcomp>')
          4 MAKE_FUNCTION            0
          6 LOAD_FAST                0 (seq)
          8 GET_ITER
         10 CALL_FUNCTION            1
         12 RETURN_VALUE

But they are actually slower:

   >>> timeit(stmt="f1(range(1000))", setup="from __main__ import f1,f2")
   21.177661532000116
   >>> timeit(stmt="f2(range(1000))", setup="from __main__ import f1,f2")
   42.233950221000214

What does the clearfix class do in css?

When an element, such as a div is floated, its parent container no longer considers its height, i.e.

<div id="main">
  <div id="child" style="float:left;height:40px;"> Hi</div>
</div>

The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.

So the clearfix class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.

Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.

Can read more here

http://www.webtoolkit.info/css-clearfix.html

How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

From RFC 2818 (Section 3.1):

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1.

EDIT:

You can request a SAN in OpenSSL by changing openssl.cnf (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF environment variable).

Set the following options (find the appropriate sections within brackets first):

[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

How to use JUnit to test asynchronous processes

You can try using the Awaitility library. It makes it easy to test the systems you're talking about.

Get class list for element with jQuery

You can use document.getElementById('divId').className.split(/\s+/); to get you an array of class names.

Then you can iterate and find the one you want.

var classList = document.getElementById('divId').className.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
    if (classList[i] === 'someClass') {
        //do something
    }
}

jQuery does not really help you here...

var classList = $('#divId').attr('class').split(/\s+/);
$.each(classList, function(index, item) {
    if (item === 'someClass') {
        //do something
    }
});

Where is JAVA_HOME on macOS Mojave (10.14) to Lion (10.7)?

I Had to explicitly set it to the exact path on my Macbook air .

Steps followed:

  1. try to echo $JAVA_HOME (if it's set it'll show the path), if not, try to search for it using sudo find /usr/ -name *jdk
  2. Edit the Bash p with - sudo nano ~/.bash_profile
  3. Add the exact path to JAVA Home (with the path from step 2 above) export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home
  4. Save and exit
  5. Check JAVA_Home using - echo $JAVA_HOME

I am running MACOS MOJAVE - 10.14.2 (18C54) on a Macbook Air with JAVA 8

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

IIS AppPoolIdentity and file system write access permissions

The ApplicationPoolIdentity is assigned membership of the Users group as well as the IIS_IUSRS group. On first glance this may look somewhat worrying, however the Users group has somewhat limited NTFS rights.

For example, if you try and create a folder in the C:\Windows folder then you'll find that you can't. The ApplicationPoolIdentity still needs to be able to read files from the windows system folders (otherwise how else would the worker process be able to dynamically load essential DLL's).

With regard to your observations about being able to write to your c:\dump folder. If you take a look at the permissions in the Advanced Security Settings, you'll see the following:

enter image description here

See that Special permission being inherited from c:\:

enter image description here

That's the reason your site's ApplicationPoolIdentity can read and write to that folder. That right is being inherited from the c:\ drive.

In a shared environment where you possibly have several hundred sites, each with their own application pool and Application Pool Identity, you would store the site folders in a folder or volume that has had the Users group removed and the permissions set such that only Administrators and the SYSTEM account have access (with inheritance).

You would then individually assign the requisite permissions each IIS AppPool\[name] requires on it's site root folder.

You should also ensure that any folders you create where you store potentially sensitive files or data have the Users group removed. You should also make sure that any applications that you install don't store sensitive data in their c:\program files\[app name] folders and that they use the user profile folders instead.

So yes, on first glance it looks like the ApplicationPoolIdentity has more rights than it should, but it actually has no more rights than it's group membership dictates.

An ApplicationPoolIdentity's group membership can be examined using the SysInternals Process Explorer tool. Find the worker process that is running with the Application Pool Identity you're interested in (you will have to add the User Name column to the list of columns to display:

enter image description here

For example, I have a pool here named 900300 which has an Application Pool Identity of IIS APPPOOL\900300. Right clicking on properties for the process and selecting the Security tab we see:

enter image description here

As we can see IIS APPPOOL\900300 is a member of the Users group.

Keyboard shortcuts in WPF

One way is to add your shortcut keys to the commands themselves them as InputGestures. Commands are implemented as RoutedCommands.

This enables the shortcut keys to work even if they're not hooked up to any controls. And since menu items understand keyboard gestures, they'll automatically display your shortcut key in the menu items text, if you hook that command up to your menu item.

  1. Create static attribute to hold a command (preferably as a property in a static class you create for commands - but for a simple example, just using a static attribute in window.cs):

     public static RoutedCommand MyCommand = new RoutedCommand();
    
  2. Add the shortcut key(s) that should invoke method:

     MyCommand.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Control));
    
  3. Create a command binding that points to your method to call on execute. Put these in the command bindings for the UI element under which it should work for (e.g., the window) and the method:

     <Window.CommandBindings>
         <CommandBinding Command="{x:Static local:MyWindow.MyCommand}" Executed="MyCommandExecuted"/>
     </Window.CommandBindings>
    
     private void MyCommandExecuted(object sender, ExecutedRoutedEventArgs e) { ... }
    

ConfigurationManager.AppSettings - How to modify and save?

I know I'm late :) But this how i do it:

public static void AddOrUpdateAppSettings(string key, string value)
{
    try
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}

For more information look at MSDN

Launch an app on OS X with command line

Simple, here replace the "APP" by name of the app you want to launch.

export APP_HOME=/Applications/APP.app/Contents/MacOS
export PATH=$PATH:$APP_HOME

Thanks me later.

Python: finding an element in a list

I use function for returning index for the matching element (Python 2.6):

def index(l, f):
     return next((i for i in xrange(len(l)) if f(l[i])), None)

Then use it via lambda function for retrieving needed element by any required equation e.g. by using element name.

element = mylist[index(mylist, lambda item: item["name"] == "my name")]

If i need to use it in several places in my code i just define specific find function e.g. for finding element by name:

def find_name(l, name):
     return l[index(l, lambda item: item["name"] == name)]

And then it is quite easy and readable:

element = find_name(mylist,"my name")

Make DateTimePicker work as TimePicker only in WinForms

A snippet out of the MSDN:

'The following code sample shows how to create a DateTimePicker that enables users to choose a time only.'

timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Time;
timePicker.ShowUpDown = true;

Converting Integers to Roman Numerals - Java

I think my solution is one of the more concise ones:

private static String convertToRoman(int mInt) {
    String[] rnChars = { "M",  "CM", "D", "C",  "XC", "L",  "X", "IX", "V", "I" };
    int[] rnVals = {  1000, 900, 500, 100, 90, 50, 10, 9, 5, 1 };
    String retVal = "";

    for (int i = 0; i < rnVals.length; i++) {
        int numberInPlace = mInt / rnVals[i];
        if (numberInPlace == 0) continue;
        retVal += numberInPlace == 4 && i > 0? rnChars[i] + rnChars[i - 1]:
            new String(new char[numberInPlace]).replace("\0",rnChars[i]);
        mInt = mInt % rnVals[i];
    }
    return retVal;
}

Pointer arithmetic for void pointer in C

Final conclusion: arithmetic on a void* is illegal in both C and C++.

GCC allows it as an extension, see Arithmetic on void- and Function-Pointers (note that this section is part of the "C Extensions" chapter of the manual). Clang and ICC likely allow void* arithmetic for the purposes of compatibility with GCC. Other compilers (such as MSVC) disallow arithmetic on void*, and GCC disallows it if the -pedantic-errors flag is specified, or if the -Werror-pointer-arith flag is specified (this flag is useful if your code base must also compile with MSVC).

The C Standard Speaks

Quotes are taken from the n1256 draft.

The standard's description of the addition operation states:

6.5.6-2: For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to an object type and the other shall have integer type.

So, the question here is whether void* is a pointer to an "object type", or equivalently, whether void is an "object type". The definition for "object type" is:

6.2.5.1: Types are partitioned into object types (types that fully describe objects) , function types (types that describe functions), and incomplete types (types that describe objects but lack information needed to determine their sizes).

And the standard defines void as:

6.2.5-19: The void type comprises an empty set of values; it is an incomplete type that cannot be completed.

Since void is an incomplete type, it is not an object type. Therefore it is not a valid operand to an addition operation.

Therefore you cannot perform pointer arithmetic on a void pointer.

Notes

Originally, it was thought that void* arithmetic was permitted, because of these sections of the C standard:

6.2.5-27: A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.

However,

The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.

So this means that printf("%s", x) has the same meaning whether x has type char* or void*, but it does not mean that you can do arithmetic on a void*.

Editor's note: This answer has been edited to reflect the final conclusion.

Sorting a list with stream.sorted() in Java

Use list.sort instead:

list.sort((o1, o2) -> o1.getItem().getValue().compareTo(o2.getItem().getValue()));

and make it more succinct using Comparator.comparing:

list.sort(Comparator.comparing(o -> o.getItem().getValue()));

After either of these, list itself will be sorted.

Your issue is that list.stream.sorted returns the sorted data, it doesn't sort in place as you're expecting.

equivalent of rm and mv in windows .cmd

move and del ARE certainly the equivalents, but from a functionality standpoint they are woefully NOT equivalent. For example, you can't move both files AND folders (in a wildcard scenario) with the move command. And the same thing applies with del.

The preferred solution in my view is to use Win32 ports of the Linux tools, the best collection of which I have found being here.

mv and rm are in the CoreUtils package and they work wonderfully!

How to send parameters with jquery $.get()

Try this:

$.ajax({
    type: 'get',
    url: 'manageproducts.do',
    data: 'option=1',
    success: function(data) {

        availableProductNames = data.split(",");

        alert(availableProductNames);

    }
});

Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.

extracting days from a numpy.timedelta64 value

Suppose you have a timedelta series:

import pandas as pd
from datetime import datetime
z = pd.DataFrame({'a':[datetime.strptime('20150101', '%Y%m%d')],'b':[datetime.strptime('20140601', '%Y%m%d')]})

td_series = (z['a'] - z['b'])

One way to convert this timedelta column or series is to cast it to a Timedelta object (pandas 0.15.0+) and then extract the days from the object:

td_series.astype(pd.Timedelta).apply(lambda l: l.days)

Another way is to cast the series as a timedelta64 in days, and then cast it as an int:

td_series.astype('timedelta64[D]').astype(int)

Android getActivity() is undefined

This is because you're using getActivity() inside an inner class. Try using:

SherlockFragmentActivity.this.getActivity()

instead, though there's really no need for the getActivity() part. In your case, SherlockFragmentActivity .this should suffice.

How to switch text case in visual studio code

Quoted from this post:

The question is about how to make CTRL+SHIFT+U work in Visual Studio Code. Here is how to do it. (Version 1.8.1 or above). You can also choose a different key combination.

File-> Preferences -> Keyboard Shortcuts.

An editor will appear with keybindings.json file. Place the following JSON in there and save.

[
 {
    "key": "ctrl+shift+u",
    "command": "editor.action.transformToUppercase",
    "when": "editorTextFocus"
 },
 {
    "key": "ctrl+shift+l",
    "command": "editor.action.transformToLowercase",
    "when": "editorTextFocus"
 }
]

Now CTRL+SHIFT+U will capitalise selected text, even if multi line. In the same way, CTRL+SHIFT+L will make selected text lowercase.

These commands are built into VS Code, and no extensions are required to make them work.

Dynamically add event listener

I will add a StackBlitz example and a comment to the answer from @tahiche.

The return value is a function to remove the event listener after you have added it. It is considered good practice to remove event listeners when you don't need them anymore. So you can store this return value and call it inside your ngOnDestroy method.

I admit that it might seem confusing at first, but it is actually a very useful feature. How else can you clean up after yourself?

export class MyComponent implements OnInit, OnDestroy {

  public removeEventListener: () => void;

  constructor(
    private renderer: Renderer2, 
    private elementRef: ElementRef
  ) {
  }

  public ngOnInit() {
    this.removeEventListener = this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
      if (event.target instanceof HTMLAnchorElement) {
        // Prevent opening anchors the default way
        event.preventDefault();
        // Your custom anchor click event handler
        this.handleAnchorClick(event);
      }
    });
  }

  public ngOnDestroy() {
    this.removeEventListener();
  }
}

You can find a StackBlitz here to show how this could work for catching clicking on anchor elements.

I added a body with an image as follows:
<img src="x" onerror="alert(1)"></div>
to show that the sanitizer is doing its job.

Here in this fiddle you find the same body attached to an innerHTML without sanitizing it and it will demonstrate the issue.

Console.log(); How to & Debugging javascript

Learn to use a javascript debugger. Venkman (for Firefox) or the Web Inspector (part of Chome & Safari) are excellent tools for debugging what's going on.

You can set breakpoints and interrogate the state of the machine as you're interacting with your script; step through parts of your code to make sure everything is working as planned, etc.

Here is an excellent write up from WebMonkey on JavaScript Debugging for Beginners. It's a great place to start.

Make cross-domain ajax JSONP request with jQuery

Try

alert(xml.Data[0].City)

Case sensitivly!

How to describe "object" arguments in jsdoc?

There's a new @config tag for these cases. They link to the preceding @param.

/** My function does X and Y.
    @params {object} parameters An object containing the parameters
    @config {integer} setting1 A required setting.
    @config {string} [setting2] An optional setting.
    @params {MyClass~FuncCallback} callback The callback function
*/
function(parameters, callback) {
    // ...
};

/**
 * This callback is displayed as part of the MyClass class.
 * @callback MyClass~FuncCallback
 * @param {number} responseCode
 * @param {string} responseMessage
 */

How to import existing Git repository into another?

git-subtree is a script designed for exactly this use case of merging multiple repositories into one while preserving history (and/or splitting history of subtrees, though that seems to be irrelevant to this question). It is distributed as part of the git tree since release 1.7.11.

To merge a repository <repo> at revision <rev> as subdirectory <prefix>, use git subtree add as follows:

git subtree add -P <prefix> <repo> <rev>

git-subtree implements the subtree merge strategy in a more user friendly manner.

For your case, inside repository YYY, you would run:

git subtree add -P ZZZ /path/to/XXX.git master

The downside is that in the merged history the files are unprefixed (not in a subdirectory). As a result git log ZZZ/a will show you all the changes (if any) except those in the merged history. You can do:

git log --follow -- a

but that won't show the changes other then in the merged history.

In other words, if you don't change ZZZ's files in repository XXX, then you need to specify --follow and an unprefixed path. If you change them in both repositories, then you have 2 commands, none of which shows all the changes.

More on it here.

In Excel, sum all values in one column in each row where another column is a specific value

You should be able to use the IF function for that. the syntax is =IF(condition, value_if_true, value_if_false). To add an extra column with only the non-reimbursed amounts, you would use something like:

=IF(B1="No", A1, 0)

and sum that. There's probably a way to include it in a single cell below the column as well, but off the top of my head I can't think of anything simple.

dereferencing pointer to incomplete type

What do you mean, the error only shows up when you assign? For example on GCC, with no assignment in sight:

int main() {
    struct blah *b = 0;
    *b; // this is line 6
}

incompletetype.c:6: error: dereferencing pointer to incomplete type.

The error is at line 6, that's where I used an incomplete type as if it were a complete type. I was fine up until then.

The mistake is that you should have included whatever header defines the type. But the compiler can't possibly guess what line that should have been included at: any line outside of a function would be fine, pretty much. Neither is it going to go trawling through every text file on your system, looking for a header that defines it, and suggest you should include that.

Alternatively (good point, potatoswatter), the error is at the line where b was defined, when you meant to specify some type which actually exists, but actually specified blah. Finding the definition of the variable b shouldn't be too difficult in most cases. IDEs can usually do it for you, compiler warnings maybe can't be bothered. It's some pretty heinous code, though, if you can't find the definitions of the things you're using.

Visual Studio: Relative Assembly References Paths

In VS 2017 it is automatic. So just Add Reference as usually.

Note that in Reference Properties absolute path is shown, but in .vbproj/.csproj relative is used.

<Reference Include="NETnetworkmanager">
      <HintPath>..\..\libs\NETnetworkmanager.dll</HintPath>
      <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>

How to open up a form from another form in VB.NET?

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
                          Handles Button3.Click

    Dim box = New AboutBox1()
    box.Show()

End Sub

What algorithms compute directions from point A to point B on a map?

The current state of the art in terms of query times for static road networks is the Hub labelling algorithm proposed by Abraham et al. http://link.springer.com/chapter/10.1007/978-3-642-20662-7_20 . A through and excellently written survey of the field was recently published as a Microsoft technical report http://research.microsoft.com/pubs/207102/MSR-TR-2014-4.pdf .

The short version is...

The Hub labelling algorithm provides the fastest queries for static road networks but requires a large amount of ram to run (18 GiB).

Transit node routing is slightly slower, although, it only requires around 2 GiB of memory and has a quicker preprocessing time.

Contraction Hierarchies provide a nice trade off between quick preprocessing times, low space requirements (0.4 GiB) and fast query times.

No one algorithm is completely dominate...

This Google tech talk by Peter Sanders may be of interest

https://www.youtube.com/watch?v=-0ErpE8tQbw

Also this talk by Andrew Goldberg

https://www.youtube.com/watch?v=WPrkc78XLhw

An open source implementation of contraction hierarchies is available from Peter Sanders research group website at KIT. http://algo2.iti.kit.edu/english/routeplanning.php

Also an easily accessible blog post written by Microsoft on there usage of the CRP algorithm... http://blogs.bing.com/maps/2012/01/05/bing-maps-new-routing-engine/

AngularJs ReferenceError: angular is not defined

If you've downloaded the angular.js file from Google, you need to make sure that Everyone has Read access to it, or it will not be loaded by your HTML file. By default, it seems to download with No access permissions, so you'll also be getting a message such as:

GET http://localhost/myApp/js/angular.js

This maddened me for about half an hour!

How can I pass a parameter to a setTimeout() callback?

This is a very old question with an already "correct" answer but I thought I'd mention another approach that nobody has mentioned here. This is copied and pasted from the excellent underscore library:

_.delay = function(func, wait) {
  var args = slice.call(arguments, 2);
  return setTimeout(function(){ return func.apply(null, args); }, wait);
};

You can pass as many arguments as you'd like to the function called by setTimeout and as an added bonus (well, usually a bonus) the value of the arguments passed to your function are frozen when you call setTimeout, so if they change value at some point between when setTimeout() is called and when it times out, well... that's not so hideously frustrating anymore :)

Here's a fiddle where you can see what I mean.

tmux status bar configuration

Do C-b, :show which will show you all your current settings. /green, nnn will find you which properties have been set to green, the default. Do C-b, :set window-status-bg cyan and the bottom bar should change colour.

List available colours for tmux

You can tell more easily by the titles and the colours as they're actually set in your live session :show, than by searching through the man page, in my opinion. It is a very well-written man page when you have the time though.

If you don't like one of your changes and you can't remember how it was originally set, you can open do a new tmux session. To change settings for good edit ~/.tmux.conf with a line like set window-status-bg -g cyan. Here's mine: https://gist.github.com/9083598

Producer/Consumer threads using a Queue

Java 5+ has all the tools you need for this kind of thing. You will want to:

  1. Put all your Producers in one ExecutorService;
  2. Put all your Consumers in another ExecutorService;
  3. If necessary, communicate between the two using a BlockingQueue.

I say "if necessary" for (3) because from my experience it's an unnecessary step. All you do is submit new tasks to the consumer executor service. So:

final ExecutorService producers = Executors.newFixedThreadPool(100);
final ExecutorService consumers = Executors.newFixedThreadPool(100);
while (/* has more work */) {
  producers.submit(...);
}
producers.shutdown();
producers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
consumers.shutdown();
consumers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

So the producers submit directly to consumers.

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

To call a sub inside another sub you only need to do:

Call Subname()

So where you have CalculateA(Nc,kij, xi, a1, a) you need to have call CalculateA(Nc,kij, xi, a1, a)

As the which runs first problem it's for you to decide, when you want to run a sub you can go to the macro list select the one you want to run and run it, you can also give it a key shortcut, therefore you will only have to press those keys to run it. Although, on secondary subs, I usually do it as Private sub CalculateA(...) cause this way it does not appear in the macro list and it's easier to work

Hope it helps, Bruno

PS: If you have any other question just ask, but this isn't a community where you ask for code, you come here with a question or a code that isn't running and ask for help, not like you did "It would be great if you could write it in the Excel VBA format."

How do I remove the passphrase for the SSH key without having to create a new key?

On the Mac you can store the passphrase for your private ssh key in your Keychain, which makes the use of it transparent. If you're logged in, it is available, when you are logged out your root user cannot use it. Removing the passphrase is a bad idea because anyone with the file can use it.

ssh-keygen -K

Add this to ~/.ssh/config

UseKeychain yes

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

Turns out all I needed to do was wrap the left-hand side of the expression in soft brackets:

<span class="gallery-date">{{(gallery.date | date:'mediumDate') || "Various"}}</span>

Spark - SELECT WHERE or filtering?

As Yaron mentioned, there isn't any difference between where and filter.

filter is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.

filter overloaded method

We can use explain() to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name and person_country columns. All of the following code snippets will return the same Physical Plan below:

df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()

These all return this Physical Plan:

== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
   +- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>

The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.

Type or namespace name does not exist

And if all else fails, such as ensuring that the target frameworks are the same, and you are dealing with a WPF class library in VS2010, simply restart Visual Studio. That did it for me.

Safely override C++ virtual functions

I would suggest a slight change in your logic. It may or may not work, depending on what you need to accomplish.

handle_event() can still do the "boring default code" but instead of being virtual, at the point where you want it to do the "new exciting code" have the base class call an abstract method (i.e. must-be-overridden) method that will be supplied by your descendant class.

EDIT: And if you later decide that some of your descendant classes do not need to provide "new exciting code" then you can change the abstract to virtual and supply an empty base class implementation of that "inserted" functionality.

How to show alert message in mvc 4 controller?

<a href="@Url.Action("DeleteBlog")" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');">

apache redirect from non www to www

-If you host multiple domain names (Optional)

-If all those domain names are using https (as they should)

-if you want all those domain names to use www dot domainName

This will avoid doble redirection (http://non www to http://www and then to https://www)

<VirtualHost *:80>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^(.*)$ https://www.%1$1 [R=301,L]
</VirtualHost>

And

<VirtualHost *:443>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}$1 [R=301,L]
</VirtualHost>

You should change the redirection code 301 to the most convenient one

javascript windows alert with redirect function

You could do this:

echo "<script>alert('Successfully Updated'); window.location = './edit.php';</script>";

Open youtube video in Fancybox jquery

$("a.more").click(function() {
                 $.fancybox({
                  'padding'             : 0,
                  'autoScale'   : false,
                  'transitionIn'        : 'none',
                  'transitionOut'       : 'none',
                  'title'               : this.title,
                  'width'               : 680,
                  'height'              : 495,
                  'href'                : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
                  'type'                : 'swf',    // <--add a comma here
                  'swf'                 : {'allowfullscreen':'true'} // <-- flashvars here
                  });
                 return false;

            }); 

Convert hex color value ( #ffffff ) to integer value

Answer is really simple guys, in android if you want to convert hex color in to int, just use android Color class, example shown as below

this is for light gray color

Color.parseColor("#a8a8a8");

Thats it and you will get your result.

ERROR 2006 (HY000): MySQL server has gone away

A couple things could be happening here;

  • Your INSERT is running long, and client is disconnecting. When it reconnects it's not selecting a database, hence the error. One option here is to run your batch file from the command line, and select the database in the arguments, like so;

$ mysql db_name < source.sql

  • Another is to run your command via php or some other language. After each long - running statement, you can close and re-open the connection, ensuring that you're connected at the start of each query.

Cannot ping AWS EC2 instance

I had the same problem truying to connect from linux server to EC2, you have two make sure about to things that "ALL ICMP" is added from EC2 as shown above and that alone won't work, you have to update Ansible to newest version 2.4, it did not work with my previous version 2.2.

How can I get a Dialog style activity window to fill the screen?

In your manifest file where our activity is defined

<activity
        android:name=".YourPopUpActivity"
        android:theme="@android:style/Theme.Holo.Dialog" >
    </activity>

without action bar

<activity android:name=".YourPopUpActivity"
            android:theme="@android:style/Theme.Holo.Dialog.NoActionBar"/>

How to remove all elements in String array in java?

example = new String[example.length];

If you need dynamic collection, you should consider using one of java.util.Collection implementations that fits your problem. E.g. java.util.List.

How to select first child with jQuery?

Use the :first-child selector.

In your example...

$('div.alldivs div:first-child')

This will also match any first child descendents that meet the selection criteria.

While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

For the first matched only, use the :first selector.

Alternatively, Felix Kling suggested using the direct descendent selector to get only direct children...

$('div.alldivs > div:first-child')

How do I save a String to a text file using Java?

Use Apache Commons IO api. Its simple

Use API as

 FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");

Maven Dependency

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

This expression will force the first letter to be alphabetic and the remaining characters to be alphanumeric or any of the following special characters: @,#,%,&,*

^[A-Za-z][A-Za-z0-9@#%&*]*$

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

Follow the steps below in Oracle VM VirtualBox Manager:

  1. Select the Virtual device and choose Settings
  2. Navigate to System and click the Processor tab
  3. Tick the check-box, Enable PAE/NX
  4. Click OK and you are done

To verify, start the Virtual device from Oracle VM VirtualBox. If all has gone well, the device boots up.

Close this device and open it from Genymotion.

Proper way to catch exception from JSON.parse

i post something into an iframe then read back the contents of the iframe with json parse...so sometimes it's not a json string

Try this:

if(response) {
    try {
        a = JSON.parse(response);
    } catch(e) {
        alert(e); // error in the above string (in this case, yes)!
    }
}

How to run a cron job on every Monday, Wednesday and Friday?

Have you tried the following expression ..?

0 19 * * 1,3,5

How to take screenshot of a div with JavaScript?

<script src="/assets/backend/js/html2canvas.min.js"></script>


<script>
    $("#download").on('click', function(){
        html2canvas($("#printform"), {
            onrendered: function (canvas) {
                var url = canvas.toDataURL();

                var triggerDownload = $("<a>").attr("href", url).attr("download", getNowFormatDate()+"????????.jpeg").appendTo("body");
                triggerDownload[0].click();
                triggerDownload.remove();
            }
        });
    })
</script>

quotation

File inside jar is not visible for spring

In the spring jar package, I use new ClassPathResource(filename).getFile(), which throws the exception:

cannot be resolved to absolute file path because it does not reside in the file system: jar

But using new ClassPathResource(filename).getInputStream() will solve this problem. The reason is that the configuration file in the jar does not exist in the operating system's file tree,so must use getInputStream().

Installing Git on Eclipse

It's Very Easy To Install By Following Below Steps In Eclipse JUNO version

Help-->Eclipse Marketplace-->Find: beside Textbox u can type "Egit"-->select Egit-git team provider intall button-->follow next steps and finally click finish

ADB.exe is obsolete and has serious performance problems

Had the same issue but in my case the fix was slightly different, as no updates were showing for the Android SDK Tools. I opened the Virtual Device Manager and realised my emulator was running API 27. Checked back in the SDK Manager and I didn't have API 27 SDK Tools installed at all. Installing v 27 resolved the issue for me.

How to send an object from one Android Activity to another using Intents?

If you have a singleton class (fx Service) acting as gateway to your model layer anyway, it can be solved by having a variable in that class with getters and setters for it.

In Activity 1:

Intent intent = new Intent(getApplicationContext(), Activity2.class);
service.setSavedOrder(order);
startActivity(intent);

In Activity 2:

private Service service;
private Order order;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quality);

    service = Service.getInstance();
    order = service.getSavedOrder();
    service.setSavedOrder(null) //If you don't want to save it for the entire session of the app.
}

In Service:

private static Service instance;

private Service()
{
    //Constructor content
}

public static Service getInstance()
{
    if(instance == null)
    {
        instance = new Service();
    }
    return instance;
}
private Order savedOrder;

public Order getSavedOrder()
{
    return savedOrder;
}

public void setSavedOrder(Order order)
{
    this.savedOrder = order;
}

This solution does not require any serialization or other "packaging" of the object in question. But it will only be beneficial if you are using this kind of architecture anyway.

How different is Scrum practice from Agile Practice?

Agile is the practice and Scrum is the process to following this practice same as eXtreme Programming (XP) and Kanban are the alternative process to following Agile development practice.

How to read a local text file?

Using Fetch and async function

const logFileText = async file => {
    const response = await fetch(file)
    const text = await response.text()
    console.log(text)
}

logFileText('file.txt')

TypeError: object of type 'int' has no len() error assistance needed

May be it is the problem of using len() for an integer value. does not posses the len attribute in Python.

Error as:I will give u an example:

number= 1
print(len(num))

Instead of use ths,

data = [1,2,3,4]
print(len(data))

How can I find last row that contains data in a specific column?

The first line moves the cursor to the last non-empty row in the column. The second line prints that columns row.

Selection.End(xlDown).Select
MsgBox(ActiveCell.Row)

Find first element by predicate

No, filter does not scan the whole stream. It's an intermediate operation, which returns a lazy stream (actually all intermediate operations return a lazy stream). To convince you, you can simply do the following test:

List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
int a = list.stream()
            .peek(num -> System.out.println("will filter " + num))
            .filter(x -> x > 5)
            .findFirst()
            .get();
System.out.println(a);

Which outputs:

will filter 1
will filter 10
10

You see that only the two first elements of the stream are actually processed.

So you can go with your approach which is perfectly fine.

Difference between null and empty ("") Java String

as a curiosity

    String s1 = null;
    String s2 = "hello";

     s1 = s1 + s2;
   

    System.out.println((s); // nullhello

Adding new line of data to TextBox

If you use WinForms:

Use the AppendText(myTxt) method on the TextBox instead (.net 3.5+):

    private void button1_Click(object sender, EventArgs e)
    {
        string sent = chatBox.Text;

        displayBox.AppendText(sent);
        displayBox.AppendText(Environment.NewLine);

    }

Text in itself has typically a low memory footprint (you can say a lot within f.ex. 10kb which is "nothing"). The TextBox does not render all text that is in the buffer, only the visible part so you don't need to worry too much about lag. The slower operations are inserting text. Appending text is relatively fast.

If you need a more complex handling of the content you can use StringBuilder combined with the textbox. This will give you a very efficient way of handling text.

How do you do natural logs (e.g. "ln()") with numpy in Python?

I usually do like this:

from numpy import log as ln

Perhaps this can make you more comfortable.

ES6 modules implementation, how to load a json file

Node v8.5.0+

You don't need JSON loader. Node provides ECMAScript Modules (ES6 Module support) with the --experimental-modules flag, you can use it like this

node --experimental-modules myfile.mjs

Then it's very simple

import myJSON from './myJsonFile.json';
console.log(myJSON);

Then you'll have it bound to the variable myJSON.

How to Disable landscape mode in Android?

If you want to disable Landscape mode for your android app ( or a single activity) all you need to do is add,

android:screenOrientation="portrait" to the activity tag in AndroidManifest.xml file.

Like:

<activity android:name="YourActivityName" 
    android:icon="@drawable/ic_launcher" 
    android:label="Your App Name" 
    android:screenOrientation="portrait">

Another Way , Programmatic Approach.

If you want to do this programatically ie. using Java code. You can do so by adding the below code in the Java class of the activity that you don't want to be displayed in landscape mode.

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

I hope it helps you .For more details you can visit here enter link description here

How to use graphics.h in codeblocks?

  1. First download WinBGIm from http://winbgim.codecutter.org/ Extract it.
  2. Copy graphics.h and winbgim.h files in include folder of your compiler directory
  3. Copy libbgi.a to lib folder of your compiler directory
  4. In code::blocks open Settings >> Compiler and debugger >>linker settings click Add button in link libraries part and browse and select libbgi.a file
  5. In right part (i.e. other linker options) paste commands -lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32
  6. Click OK

For detail information follow this link.

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Usually the problem is not closing brackets (}) or missing semicolon (;)

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Yes. You need to use Assembly.LoadFrom to load the assembly into memory, then you can use Activator.CreateInstance to create an instance of your preferred type. You'll need to look the type up first using reflection. Here is a simple example:

Assembly assembly = Assembly.LoadFrom("MyNice.dll");

Type type = assembly.GetType("MyType");

object instanceOfMyType = Activator.CreateInstance(type);

Update

When you have the assembly file name and the type name, you can use Activator.CreateInstance(assemblyName, typeName) to ask the .NET type resolution to resolve that into a type. You could wrap that with a try/catch so that if it fails, you can perform a search of directories where you may specifically store additional assemblies that otherwise might not be searched. This would use the preceding method at that point.

Why is my xlabel cut off in my matplotlib plot?

for some reason sharex was set to True so I turned it back to False and it worked fine.

df.plot(........,sharex=False)

How should I copy Strings in Java?

String str1="this is a string";
String str2=str1.clone();

How about copy like this? I think to get a new copy is better, so that the data of str1 won't be affected when str2 is reference and modified in futher action.

How to correctly use the extern keyword in C

In C, 'extern' is implied for function prototypes, as a prototype declares a function which is defined somewhere else. In other words, a function prototype has external linkage by default; using 'extern' is fine, but is redundant.

(If static linkage is required, the function must be declared as 'static' both in its prototype and function header, and these should normally both be in the same .c file).

log4j logging hierarchy order

Use the force, read the source (excerpt from the Priority and Level class compiled, TRACE level was introduced in version 1.2.12):

public final static int OFF_INT = Integer.MAX_VALUE;
public final static int FATAL_INT = 50000;
public final static int ERROR_INT = 40000;
public final static int WARN_INT  = 30000;
public final static int INFO_INT  = 20000;
public final static int DEBUG_INT = 10000;
public static final int TRACE_INT = 5000; 
public final static int ALL_INT = Integer.MIN_VALUE; 

or the log4j API for the Level class, which makes it quite clear.

When the library decides whether to print a certain statement or not, it computes the effective level of the responsible Logger object (based on configuration) and compares it with the LogEvent's level (depends on which method was used in the code – trace/debug/.../fatal). If LogEvent's level is greater or equal to the Logger's level, the LogEvent is sent to appender(s) – "printed". At the core, it all boils down to an integer comparison and this is where these constants come to action.

How to stop an animation (cancel() does not work)

Use the method setAnimation(null) to stop an animation, it exposed as public method in View.java, it is the base class for all widgets, which are used to create interactive UI components (buttons, text fields, etc.). /** * Sets the next animation to play for this view. * If you want the animation to play immediately, use * {@link #startAnimation(android.view.animation.Animation)} instead. * This method provides allows fine-grained * control over the start time and invalidation, but you * must make sure that 1) the animation has a start time set, and * 2) the view's parent (which controls animations on its children) * will be invalidated when the animation is supposed to * start. * * @param animation The next animation, or null. */ public void setAnimation(Animation animation)

How to retry image pull in a kubernetes Pods?

Usually in case of "ImagePullBackOff" it's retried after few seconds/minutes. In case you want to try again manually you can delete the old pod and recreate the pod. The one line command to delete and recreate the pod would be:

kubectl replace --force -f <yml_file_describing_pod>

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

Convert Rows to columns using 'Pivot' in SQL Server

Here is a revision of @Tayrn answer above that might help you understand pivoting a little easier:

This may not be the best way to do this, but this is what helped me wrap my head around how to pivot tables.

ID = rows you want to pivot

MY_KEY = the column you are selecting from your original table that contains the column names you want to pivot.

VAL = the value you want returning under each column.

MAX(VAL) => Can be replaced with other aggregiate functions. SUM(VAL), MIN(VAL), ETC...

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(MY_KEY) 
                from yt
                group by MY_KEY
                order by MY_KEY ASC
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')
set @query = 'SELECT ID,' + @cols + ' from 
         (
            select ID, MY_KEY, VAL 
            from yt
        ) x
        pivot 
        (
            sum(VAL)
            for MY_KEY in (' + @cols + ')
        ) p '

        execute(@query);

What is the maximum length of a Push Notification alert text?

The limit of the enhanced format notifications is documented here.

It explicitly states:

The payload must not exceed 256 bytes and must not be null-terminated.

ascandroli claims above that they were able to send messages with 1400 characters. My own testing with the new notification format showed that a message just 1 byte over the 256 byte limit was rejected. Given that the docs are very explicit on this point I suggest it is safer to use 256 regardless of what you may be able to achieve experimentally as there is no guarantee Apple won't change it to 256 in the future.

As for the alert text itself, if you can fit it in the 256 total payload size then it will be displayed by iOS. They truncate the message that shows up on the status bar, but if you open the notification center, the entire message is there. It even renders newline characters \n.

Convert file to byte array and vice versa

Otherwise Try this :

Converting File To Bytes

  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.IOException;


   public class Temp {

        public static void main(String[] args) {

         File file = new File("c:/EventItemBroker.java");

         byte[] b = new byte[(int) file.length()];
         try {
               FileInputStream fileInputStream = new FileInputStream(file);
               fileInputStream.read(b);
               for (int i = 0; i < b.length; i++) {
                           System.out.print((char)b[i]);
                }
          } catch (FileNotFoundException e) {
                      System.out.println("File Not Found.");
                      e.printStackTrace();
          }
          catch (IOException e1) {
                   System.out.println("Error Reading The File.");
                    e1.printStackTrace();
          }

       }
    }

Converting Bytes to File

      public class WriteByteArrayToFile {

         public static void main(String[] args) {

            String strFilePath = "Your path";
            try {
                 FileOutputStream fos = new FileOutputStream(strFilePath);
                 String strContent = "Write File using Java ";

                 fos.write(strContent.getBytes());
                 fos.close();
           }
          catch(FileNotFoundException ex)   {
                 System.out.println("FileNotFoundException : " + ex);
          }
         catch(IOException ioe)  {
                 System.out.println("IOException : " + ioe);
          }

       }
     }

Full width layout with twitter bootstrap

Just create another class and add along with the bootstrap container class. You can also use container-fluid though.

<div class="container full-width">
    <div class="row">
        ....
    </div>
</div>

The CSS part is pretty simple

* {
    margin: 0;
    padding: 0;
}
.full-width {
    width: 100%;
    min-width: 100%;
    max-width: 100%;
}

Hope this helps, Thanks!

How do I get the collection of Model State Errors in ASP.NET MVC?

To just get the errors from the ModelState, use this Linq:

var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);

How to add bootstrap in angular 6 project?

npm install --save bootstrap

afterwards, inside angular.json (previously .angular-cli.json) inside the project's root folder, find styles and add the bootstrap css file like this:

for angular 6

"styles": [
          "../node_modules/bootstrap/dist/css/bootstrap.min.css",
          "styles.css"
],

for angular 7

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
],

Is it possible to install both 32bit and 64bit Java on Windows 7?

You can install multiple Java runtimes under Windows (including Windows 7) as long as each is in their own directory.

For example, if you are running Win 7 64-bit, or Win Server 2008 R2, you may install 32-bit JRE in "C:\Program Files (x86)\Java\jre6" and 64-bit JRE in "C:\Program Files\Java\jre6", and perhaps IBM Java 6 in "C:\Program Files (x86)\IBM\Java60\jre".

The Java Control Panel app theoretically has the ability to manage multiple runtimes: Java tab >> View... button

There are tabs for User and System settings. You can add additional runtimes with Add or Find, but once you have finished adding runtimes and hit OK, you have to hit Apply in the main Java tab frame, which is not as obvious as it could be - otherwise your changes will be lost.

If you have multiple versions installed, only the main version will auto-update. I have not found a solution to this apart from the weak workaround of manually updating whenever I see an auto-update, so I'd love to know if anyone has a fix for that.

Most Java IDEs allow you to select any Java runtime on your machine to build against, but if not using an IDE, you can easily manage this using environment variables in a cmd window. Your PATH and the JAVA_HOME variable determine which runtime is used by tools run from the shell. Set the JAVA_HOME to the jre directory you want and put the bin directory into your path (and remove references to other runtimes) - with IBM you may need to add multiple bin directories. This is pretty much all the set up that the default system Java does. You can also set CLASSPATH, ANT_HOME, MAVEN_HOME, etc. to unique values to match your runtime.

How to remove a web site from google analytics

AS of 2018

Login to your analytics account
Select the account/property you want to delete
Click the  button. (left side bottom menu)
Click on property settings
To the right you will see Move To Trash Can Click on that
You will see the bellow screen. click on Delete Property button

or if you want to delete the account

follow the same steps, but this time click on the Accoutn Settings tab see below

Now Click on Move to Trash Can (button to the right)

when you see the next screen confirm to delete the account by clicking on the Trash Account button.

How to delete a website from google analytics

How to put Google Maps V2 on a Fragment using ViewPager

The following approach works for me.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

/**
 * A fragment that launches other parts of the demo application.
 */
public class MapFragment extends Fragment {

MapView mMapView;
private GoogleMap googleMap;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // inflat and return the layout
    View v = inflater.inflate(R.layout.fragment_location_info, container,
            false);
    mMapView = (MapView) v.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);

    mMapView.onResume();// needed to get the map to display immediately

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    googleMap = mMapView.getMap();
    // latitude and longitude
    double latitude = 17.385044;
    double longitude = 78.486671;

    // create marker
    MarkerOptions marker = new MarkerOptions().position(
            new LatLng(latitude, longitude)).title("Hello Maps");

    // Changing marker icon
    marker.icon(BitmapDescriptorFactory
            .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

    // adding marker
    googleMap.addMarker(marker);
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(17.385044, 78.486671)).zoom(12).build();
    googleMap.animateCamera(CameraUpdateFactory
            .newCameraPosition(cameraPosition));

    // Perform any camera updates here
    return v;
}

@Override
public void onResume() {
    super.onResume();
    mMapView.onResume();
}

@Override
public void onPause() {
    super.onPause();
    mMapView.onPause();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mMapView.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mMapView.onLowMemory();
}
}

fragment_location_info.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

In my case, there was no string on which i was calling appendChild, the object i was passing on appendChild argument was wrong, it was an array and i had pass an element object, so i used divel.appendChild(childel[0]) instead of divel.appendChild(childel) and it worked. Hope it help someone.

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

No, image/jpg is not the same as image/jpeg.

You should use image/jpeg. Only image/jpeg is recognised as the actual mime type for JPEG files.

See https://tools.ietf.org/html/rfc3745, https://www.w3.org/Graphics/JPEG/ .

Serving the incorrect Content-Type of image/jpg to IE can cause issues, see http://www.bennadel.com/blog/2609-internet-explorer-aborts-images-with-the-wrong-mime-type.htm.

Timing Delays in VBA

If you are in Excel VBA you can use the following.

Application.Wait(Now + TimeValue("0:00:01"))

(The time string should look like H:MM:SS.)

How to check if a value exists in a dictionary (python)

>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> 'one' in d.values()
True

Out of curiosity, some comparative timing:

>>> T(lambda : 'one' in d.itervalues()).repeat()
[0.28107285499572754, 0.29107213020324707, 0.27941107749938965]
>>> T(lambda : 'one' in d.values()).repeat()
[0.38303399085998535, 0.37257885932922363, 0.37096405029296875]
>>> T(lambda : 'one' in d.viewvalues()).repeat()
[0.32004380226135254, 0.31716084480285645, 0.3171098232269287]

EDIT: And in case you wonder why... the reason is that each of the above returns a different type of object, which may or may not be well suited for lookup operations:

>>> type(d.viewvalues())
<type 'dict_values'>
>>> type(d.values())
<type 'list'>
>>> type(d.itervalues())
<type 'dictionary-valueiterator'>

EDIT2: As per request in comments...

>>> T(lambda : 'four' in d.itervalues()).repeat()
[0.41178202629089355, 0.3959040641784668, 0.3970959186553955]
>>> T(lambda : 'four' in d.values()).repeat()
[0.4631338119506836, 0.43541407585144043, 0.4359898567199707]
>>> T(lambda : 'four' in d.viewvalues()).repeat()
[0.43414998054504395, 0.4213531017303467, 0.41684913635253906]

How to set component default props on React component

You can set the default props using the class name as shown below.

class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

// Specifies the default values for props:
Greeting.defaultProps = {
  name: 'Stranger'
};

You can use the React's recommended way from this link for more info

How to change column width in DataGridView?

Set the "AutoSizeColumnsMode" property to "Fill".. By default it is set to 'NONE'. Now columns will be filled across the DatagridView. Then you can set the width of other columns accordingly.

DataGridView1.Columns[0].Width=100;// The id column 
DataGridView1.Columns[1].Width=200;// The abbrevation columln
//Third Colulmns 'description' will automatically be resized to fill the remaining 
//space

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

Swift add icon/image in UITextField

Try adding emailField.leftViewMode = UITextFieldViewMode.Always

(Default leftViewMode is Never)

Updated Answer for Swift 4

emailField.leftViewMode = UITextFieldViewMode.always

emailField.leftViewMode = .always

Progress during large file copy (Copy-Item & Write-Progress?)

Alternativly this option uses the native windows progress bar...

$FOF_CREATEPROGRESSDLG = "&H0&"

$objShell = New-Object -ComObject "Shell.Application"

$objFolder = $objShell.NameSpace($DestLocation) 

$objFolder.CopyHere($srcFile, $FOF_CREATEPROGRESSDLG)

The Eclipse executable launcher was unable to locate its companion launcher jar windows

You might want to check that library

**org.eclipse.equinox.launcher_(version).dist.jar**
and 
**plugins/org.eclipse.equinox.launcher.gtk.linux.x86_(version).dist**
exists on your system. 

Make sure that the version of libraries mentioned in eclipse.ini and the version that exists on your system is same. Usually after upgrade this mismatch occurs and eclipse fails to locate the required jar. Please take a look at this blog post here

Bootstrap datepicker disabling past dates without current date

Use minDate

var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());

$('#date').datepicker({ 
    minDate: today
});

The representation of if-elseif-else in EL using JSF

You can use EL if you want to work as IF:

<h:outputLabel value="#{row==10? '10' : '15'}"/>

Changing styles or classes:

style="#{test eq testMB.test? 'font-weight:bold' : 'font-weight:normal'}"

class="#{test eq testMB.test? 'divRred' : 'divGreen'}"

how to realize countifs function (excel) in R

Easy peasy. Your data frame will look like this:

df <- data.frame(sex=c('M','F','M'),
                 occupation=c('Student','Analyst','Analyst'))

You can then do the equivalent of a COUNTIF by first specifying the IF part, like so:

df$sex == 'M'

This will give you a boolean vector, i.e. a vector of TRUE and FALSE. What you want is to count the observations for which the condition is TRUE. Since in R TRUE and FALSE double as 1 and 0 you can simply sum() over the boolean vector. The equivalent of COUNTIF(sex='M') is therefore

sum(df$sex == 'M')

Should there be rows in which the sex is not specified the above will give back NA. In that case, if you just want to ignore the missing observations use

sum(df$sex == 'M', na.rm=TRUE)

Printing an int list in a single line python3

For python 2.7 another trick is:

arr = [1,2,3]
for num in arr:
  print num,
# will print 1 2 3

Call a "local" function within module.exports from another function in module.exports?

To fix your issue, i have made few changes in bla.js and it is working,

var foo= function (req, res, next) {
  console.log('inside foo');
  return ("foo");
}

var  bar= function(req, res, next) {
  this.foo();
}
module.exports = {bar,foo};

and no modification in app.js

var bla = require('./bla.js');
console.log(bla.bar());

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

Add Variables to Tuple

As other answers have noted, you cannot change an existing tuple, but you can always create a new tuple (which may take some or all items from existing tuples and/or other sources).

For example, if all the items of interest are in scalar variables and you know the names of those variables:

def maketuple(variables, names):
  return tuple(variables[n] for n in names)

to be used, e.g, as in this example:

def example():
  x = 23
  y = 45
  z = 67
  return maketuple(vars(), 'x y z'.split())

of course this one case would be more simply expressed as (x, y, z) (or even foregoing the names altogether, (23, 45, 67)), but the maketuple approach might be useful in some more complicated cases (e.g. where the names to use are also determined dynamically and appended to a list during the computation).

Calculating time difference between 2 dates in minutes

Try this one:

select * from MyTab T where date_add(T.runTime, INTERVAL 20 MINUTE) < NOW()

NOTE: this should work if you're using MySQL DateTime format. If you're using Unix Timestamp (integer), then it would be even easier:

select * from MyTab T where UNIX_TIMESTAMP() - T.runTime > 20*60

UNIX_TIMESTAMP() function returns you current unix timestamp.

How can I create directories recursively?

os.makedirs is what you need. For chmod or chown you'll have to use os.walk and use it on every file/dir yourself.

C# LINQ find duplicates in List

Linq query:

var query = from s2 in (from s in someList group s by new { s.Column1, s.Column2 } into sg select sg) where s2.Count() > 1 select s2;