Programs & Examples On #Memory size

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

dmidecode -t 17 | grep  Size:

Adding all above values displayed after "Size: " will give exact total physical size of all RAM sticks in server.

Intent from Fragment to Activity

For Kotlin you can use

val myIntent = Intent(activity, your_destination_activity::class.java)
startActivity(myIntent)

Can't find AVD or SDK manager in Eclipse

Try to reinstall ADT plugin on Eclipse. Check out this: Installing the Eclipse Plugin

Is there a way to provide named parameters in a function call in JavaScript?

No - the object approach is JavaScript's answer to this. There is no problem with this provided your function expects an object rather than separate params.

Extension gd is missing from your system - laravel composer Update

It may not be enabled for php-cli, you can enable like this;

sudo phpenmod gd

UPDATE

I guess, you are using ppa:ondrej php package (5.6), which is confusing you with default ubuntu 14.04 php package (5.5.9).

To install php 5.6 gd library from ppa:ondrej, you should use:

sudo apt-get install php5.6-gd

Javascript equivalent of php's strtotime()?

There are few modules that provides similar behavior, but not exactly like PHP's strtotime. Among few alternatives I found date-util yields the best results.

Getting next element while cycling through a list

Use the zip method in Python. This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables

    while running:
        for thiselem,nextelem in zip(li, li[1 : ] + li[ : 1]):
            #Do whatever you want with thiselem and nextelem         

Vendor code 17002 to connect to SQLDeveloper

Listed are the steps that could rectify the error:

  1. Press Windows+R
  2. Type services.msc and strike Enter
  3. Find all services
  4. Starting with ora start these services and wait!!
  5. When your server specific service is initialized (in my case it was orcl)
  6. Now run mysql or whatever you are using and start coding.P

How do I wrap text in a pre tag?

I suggest forget the pre and just put it in a textarea.

Your indenting will remain and your code wont get word-wrapped in the middle of a path or something.

Easier to select text range in a text area too if you want to copy to clipboard.

The following is a php excerpt so if your not in php then the way you pack the html special chars will vary.

<textarea style="font-family:monospace;" onfocus="copyClipboard(this);"><?=htmlspecialchars($codeBlock);?></textarea>

For info on how to copy text to the clipboard in js see: How do I copy to the clipboard in JavaScript? .

However...

I just inspected the stackoverflow code blocks and they wrap in a <code> tag wrapped in <pre> tag with css ...

code {
  background-color: #EEEEEE;
  font-family: Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;
}
pre {
  background-color: #EEEEEE;
  font-family: Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;
  margin-bottom: 10px;
  max-height: 600px;
  overflow: auto;
  padding: 5px;
  width: auto;
}

Also the content of the stackoverflow code blocks is syntax highlighted using (I think) http://code.google.com/p/google-code-prettify/ .

Its a nice setup but Im just going with textareas for now.

How do I type a TAB character in PowerShell?

Test with [char]9, such as:

$Tab = [char]9
Write-Output "$Tab hello"

Output:

     hello

How to change Android usb connect mode to charge only?

The HTC devices have the PCSII.apk which allow them to select usb connect mode. For your device, you can set it manually:

Use SQLite Editor to open /data/data/com.android.providers.setting/databases/settings.db

open table secure

turn settings starting with mount_ums_ to 0, then restart devices.

UPDATE: If it still doesn't work, try turning on debug mode.

"The system cannot find the file specified"

I got this error when starting my ASP.NET application and in my case the problem was that the SQL Server service was not running. Starting that cleared it up.

Get hostname of current request in node.js Express

Here's an alternate

req.hostname

Read about it in the Express Docs.

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

What is <scope> under <dependency> in pom.xml for?

Scope tag is always use to limit the transitive dependencies and availability of the jar at class path level.If we don't provide any scope then the default scope will work i.e. Compile .

How to 'update' or 'overwrite' a python list

I'm learning to code and I found this same problem. I believe the easier way to solve this is literaly overwriting the list like @kerby82 said:

An item in a list in Python can be set to a value using the form

x[n] = v

Where x is the name of the list, n is the index in the array and v is the value you want to set.

In your exemple:

aList = [123, 'xyz', 'zara', 'abc']
aList[0] = 2014
print aList
>>[2014, 'xyz', 'zara', 'abc']

How to get child element by class name?

using querySelector

_x000D_
_x000D_
var doc=document.getElementById("test");
console.log(doc.querySelector('.two').innerHTML)
_x000D_
<div id="test">
 <span class="one"></span>
 <span class="two">two</span>
 <span class="three"></span>
 <span class="four"></span>
</div>
_x000D_
_x000D_
_x000D_ Using querySelectorAll

_x000D_
_x000D_
var doc=document.getElementById("test");
console.log(doc.querySelectorAll('*')[1].innerHTML)
_x000D_
<div id="test">
 <span class="one"></span>
 <span class="two">two</span>
 <span class="three"></span>
 <span class="four"></span>
</div>
_x000D_
_x000D_
_x000D_

using getElementsByTagNames

_x000D_
_x000D_
var doc=document.getElementById("test");
console.log(doc.getElementsByTagName("SPAN")[1].innerHTML);
_x000D_
<div id="test">
 <span class="one"></span>
 <span class="two">two</span>
 <span class="three"></span>
 <span class="four"></span>
</div>
<span>ss</span>
_x000D_
_x000D_
_x000D_

Using getElementsByClassName

_x000D_
_x000D_
var doc=document.getElementById("test");
console.log(doc.getElementsByClassName('two')[0].innerHTML)
_x000D_
<div id="test">
 <span class="one"></span>
 <span class="two">two</span>
 <span class="three"></span>
 <span class="four"></span>
</div>
_x000D_
_x000D_
_x000D_

How to add Android Support Repository to Android Studio?

Gradle can work with the 18.0.+ notation, it however now depends on the new support repository which is now bundled with the SDK.

Open the SDK manager and immediately under Extras the first option is "Android Support Repository" and install it

Check if the file exists using VBA

I'm not certain what's wrong with your code specifically, but I use this function I found online (URL in the comments) for checking if a file exists:

Private Function File_Exists(ByVal sPathName As String, Optional Directory As Boolean) As Boolean
    'Code from internet: http://vbadud.blogspot.com/2007/04/vba-function-to-check-file-existence.html
    'Returns True if the passed sPathName exist
    'Otherwise returns False
    On Error Resume Next
    If sPathName <> "" Then

        If IsMissing(Directory) Or Directory = False Then

            File_Exists = (Dir$(sPathName) <> "")
        Else

            File_Exists = (Dir$(sPathName, vbDirectory) <> "")
        End If

    End If
End Function

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

Following Andrii Karaivanskyi's answer here's the Maven POM declaration:

<properties>
    ...
    <junit-jupiter.version>5.2.0</junit-jupiter.version>
    <junit-platform.version>1.2.0</junit-platform.version>
    ...
</properties>

<dependencies>
    ...
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${junit-jupiter.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-launcher</artifactId>
        <version>${junit-platform.version}</version>
        <scope>test</scope>
    </dependency>
    ...
</dependencies>

UPDATE

As per comment by Alexander Wessel you can use org.junit:junit-bom as described in his answer to question Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory.

How can I change default dialog button text color in android 5

<style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:colorPrimary">#00397F</item>
    <item name="android:textColorPrimary">#22397F</item>
    <item name="android:colorAccent">#00397F</item>
    <item name="colorPrimaryDark">#22397F</item>
</style>

The color of the buttons and other text can also be changed using appcompat :

Jinja2 shorthand conditional

Alternative way (but it's not python style. It's JS style)

{{ files and 'Update' or 'Continue' }}

What is the cleanest way to ssh and run multiple commands in Bash?

I see two ways:

First you make a control socket like this:

 ssh -oControlMaster=yes -oControlPath=~/.ssh/ssh-%r-%h-%p <yourip>

and run your commands

 ssh -oControlMaster=no -oControlPath=~/.ssh/ssh-%r-%h-%p <yourip> -t <yourcommand>

This way you can write an ssh command without actually reconnecting to the server.

The second would be to dynamically generate the script, scping it and running.

Changing tab bar item image and text color iOS

From here.

Each tab bar item has a title, selected image, unselected image, and a badge value.

Use the Image Tint (selectedImageTintColor) field to specify the bar item’s tint color when that tab is selected. By default, that color is blue.

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

How to run a Maven project from Eclipse?

Well, you need to incorporate exec-maven-plugin, this plug-in performs the same thing that you do on command prompt when you type in java -cp .;jarpaths TestMain. You can pass argument and define which phase (test, package, integration, verify, or deploy), you want this plug-in to call your main class.

You need to add this plug-in under <build> tag and specify parameters. For example

   <project>
    ...
    ...
    <build>
     <plugins>
      <plugin>
       <groupId>org.codehaus.mojo</groupId>
       <artifactId>exec-maven-plugin</artifactId>
       <version>1.1.1</version>
       <executions>
        <execution>
         <phase>test</phase>
         <goals>
          <goal>java</goal>
         </goals>
         <configuration>
          <mainClass>my.company.name.packageName.TestMain</mainClass>
          <arguments>
           <argument>myArg1</argument>
           <argument>myArg2</argument>
          </arguments>
         </configuration>
        </execution>
       </executions>
      </plugin>
     </plugins>
    </build>
    ...
    ...
   </project>

Now, if you right-click on on the project folder and do Run As > Maven Test, or Run As > Maven Package or Run As > Maven Install, the test phase will execute and so your Main class.

How do I measure separate CPU core usage for a process?

htop gives a nice overview of individual core usage

How to enable/disable bluetooth programmatically in android

Add the following permissions into your manifest file:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Enable bluetooth use this

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (!mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.enable(); 
}else{Toast.makeText(getApplicationContext(), "Bluetooth Al-Ready Enable", Toast.LENGTH_LONG).show();}

Disable bluetooth use this

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.disable(); 
}

JQuery to load Javascript file dynamically

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});

How can I copy data from one column to another in the same table?

How about this

UPDATE table SET columnB = columnA;

This will update every row.

how to import csv data into django models

something like this:

f = open('data.txt', 'r')  
for line in f:  
   line =  line.split(';')  
   product = Product()  
   product.name = line[2] + '(' + line[1] + ')'  
   product.description = line[4]  
   product.price = '' #data is missing from file  
   product.save()  

f.close()  

ComboBox.SelectedText doesn't give me the SelectedText

I think you dont need SelectedText but you may need

String status = "The status of my combobox is " + comboBoxTest.Text;

Handling urllib2's timeout? - Python

There are very few cases where you want to use except:. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt, which can make your program annoying to use..

At the very simplest, you would catch urllib2.URLError:

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

The following should capture the specific error raised when the connection times out:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
    else:
        # reraise the original error
        raise
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

1. See information about the SQL server

tsql -LH SERVER_IP_ADDRESS

locale is "C"
locale charset is "646"
ServerName TITAN
InstanceName MSSQLSERVER
IsClustered No
Version 8.00.194
tcp 1433
np \\TITAN\pipe\sql\query

2. Set your freetds.conf

tsql -C    
freetds.conf directory: /usr/local/etc

[TITAN]
host = SERVER_IP_ADDRESS
port = 1433
tds version = 7.2

3 Try

tsql -S TITAN -U user -P password

OR

 'dsn' => 'dblib:host=TITAN:1433;dbname=YOURDBNAME',

See also http://www.freetds.org/userguide/confirminstall.htm (Example 3-5.)

If you get message 20009, remember you haven't connected to the machine. It's a configuration or network issue, not a protocol failure. Verify the server is up, has the name and IP address FreeTDS is using, and is listening to the configured port.

Java 8 Lambda function that throws exception?

I will do something generic:

public interface Lambda {

    @FunctionalInterface
    public interface CheckedFunction<T> {

        T get() throws Exception;
    }

    public static <T> T handle(CheckedFunction<T> supplier) {
        try {
            return supplier.get();
        } catch (Exception exception) {
            throw new RuntimeException(exception);

        }
    }
}

usage:

 Lambda.handle(() -> method());

How can you use optional parameters in C#?

From this site:

http://www.tek-tips.com/viewthread.cfm?qid=1500861&page=1

C# does allow the use of the [Optional] attribute (from VB, though not functional in C#). So you can have a method like this:

using System.Runtime.InteropServices;
public void Foo(int a, int b, [Optional] int c)
{
  ...
}

In our API wrapper, we detect optional parameters (ParameterInfo p.IsOptional) and set a default value. The goal is to mark parameters as optional without resorting to kludges like having "optional" in the parameter name.

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

detect back button click in browser

So as far as AJAX is concerned...

Pressing back while using most web-apps that use AJAX to navigate specific parts of a page is a HUGE issue. I don't accept that 'having to disable the button means you're doing something wrong' and in fact developers in different facets have long run into this problem. Here's my solution:

window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle the back (or forward) buttons here
            // Will NOT handle refresh, use onbeforeunload for this.
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Detect and redirect change here
                // Works in older FF and IE9
                // * it does mess with your hash symbol (anchor?) pound sign
                // delimiter on the end of the URL
            }
            else {
                ignoreHashChange = false;   
            }
        };
    }
}

As far as Ive been able to tell this works across chrome, firefox, haven't tested IE yet.

Label on the left side instead above an input field

<div class="control-group">
   <label class="control-label" for="firstname">First Name</label>
   <div class="controls">
    <input type="text" id="firstname" name="firstname"/>
   </div>
</div>

Also we can use it Simply as

<label>First name:
    <input type="text" id="firstname" name="firstname"/>
</label>

Sending email from Command-line via outlook without having to click send

Send SMS/Text Messages from Command Line with VBScript!

If VBA meets the rules for VB Script then it can be called from command line by simply placing it into a text file - in this case there's no need to specifically open Outlook.

I had a need to send automated text messages to myself from the command line, so I used the code below, which is just a compressed version of @Geoff's answer above.

Most mobile phone carriers worldwide provide an email address "version" of your mobile phone number. For example in Canada with Rogers or Chatr Wireless, an email sent to <YourPhoneNumber> @pcs.rogers.com will be immediately delivered to your Rogers/Chatr phone as a text message.

* You may need to "authorize" the first message on your phone, and some carriers may charge an additional fee for theses message although as far as I know, all Canadian carriers provide this little-known service for free. Check your carrier's website for details.

There are further instructions and various compiled lists of worldwide carrier's Email-to-Text addresses available online such as this and this and this.


Code & Instructions

  1. Copy the code below and paste into a new file in your favorite text editor.
  2. Save the file with any name with a .VBS extension, such as TextMyself.vbs.

That's all!
Just double-click the file to send a test message, or else run it from a batch file using START.

Sub SendMessage()
    Const EmailToSMSAddy = "[email protected]"
    Dim objOutlookRecip
    With CreateObject("Outlook.Application").CreateItem(0)
        Set objOutlookRecip = .Recipients.Add(EmailToSMSAddy)
        objOutlookRecip.Type = 1
        .Subject = "The computer needs your attention!"
        .Body = "Go see why Windows Command Line is texting you!"
        .Save
        .Send
    End With
End Sub

Example Batch File Usage:

START x:\mypath\TextMyself.vbs

Of course there are endless possible ways this could be adapted and customized to suit various practical or creative needs.

How can we draw a vertical line in the webpage?

You can use <hr> for a vertical line as well.
Set the width to 1 and the size(height) as long as you want.
I used 500 in my example(demo):

With <hr width="1" size="500">

DEMO

What's the "Content-Length" field in HTTP header?

According to the spec:

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

Content-Length    = "Content-Length" ":" 1*DIGIT

An example is

Content-Length: 3495

Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4.

Any Content-Length greater than or equal to zero is a valid value. Section 4.4 describes how to determine the length of a message-body if a Content-Length is not given.

Note that the meaning of this field is significantly different from the corresponding definition in MIME, where it is an optional field used within the "message/external-body" content-type. In HTTP, it SHOULD be sent whenever the message's length can be determined prior to being transferred, unless this is prohibited by the rules in section 4.4.

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

The best and tested solution is to put the following small snippet which will collapse the accordion tab which is already open when you load. In my case the last sixth tab was open so I made it collapsed on page load.

 $(document).ready(){
      $('#collapseSix').collapse("hide");
 }

How to iterate through a list of objects in C++

if you add an #include <algorithm> then you can use the for_each function and a lambda function like so:

for_each(data.begin(), data.end(), [](Student *it) 
{
    std::cout<<it->name;
});

you can read more about the algorithm library at https://en.cppreference.com/w/cpp/algorithm

and about lambda functions in cpp at https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=vs-2019

Setting network adapter metric priority in Windows 7

I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.

Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.

After this, Windows started prioritize Ethernet adapter.

Printing long int value in C

You must use %ld to print a long int, and %lld to print a long long int.

Note that only long long int is guaranteed to be large enough to store the result of that calculation (or, indeed, the input values you're using).

You will also need to ensure that you use your compiler in a C99-compatible mode (for example, using the -std=gnu99 option to gcc). This is because the long long int type was not introduced until C99; and although many compilers implement long long int in C90 mode as an extension, the constant 2147483648 may have a type of unsigned int or unsigned long in C90. If this is the case in your implementation, then the value of -2147483648 will also have unsigned type and will therefore be positive, and the overall result will be not what you expect.

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

React - uncaught TypeError: Cannot read property 'setState' of undefined

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>

    <script src="https://unpkg.com/[email protected]/dist/react.min.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/react-dom.min.js"></script>
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>

  </head>
  <body>
  <div id="root"></div>
    <script type="text/babel">

        class App extends React.Component{

            constructor(props){
                super(props);
                this.state = {
                    counter : 0,
                    isToggle: false
                }
            this.onEventHandler = this.onEventHandler.bind(this);   
            }

            increment = ()=>{
                this.setState({counter:this.state.counter + 1});
            }

            decrement= ()=>{
                if(this.state.counter > 0 ){
                this.setState({counter:this.state.counter - 1});    
                }else{
                this.setState({counter:0});             
                }
            }
            // Either do it as onEventHandler = () => {} with binding with this  // object. 
            onEventHandler(){
                this.setState({isToggle:!this.state.isToggle})
                alert('Hello');
            }


            render(){
                return(
                    <div>
                        <button onClick={this.increment}> Increment </button>
                        <button onClick={this.decrement}> Decrement </button>
                        {this.state.counter}
                        <button onClick={this.onEventHandler}> {this.state.isToggle ? 'Hi':'Ajay'} </button>

                    </div>
                    )
            }
        }
        ReactDOM.render(
        <App/>,
        document.getElementById('root'),
      );
    </script>
  </body>
  </html>

Sending private messages to user

In order for a bot to send a message, you need <client>.send() , the client is where the bot will send a message to(A channel, everywhere in the server, or a PM). Since you want the bot to PM a certain user, you can use message.author as your client. (you can replace author as mentioned user in a message or something, etc)

Hence, the answer is: message.author.send("Your message here.")

I recommend looking up the Discord.js documentation about a certain object's properties whenever you get stuck, you might find a particular function that may serve as your solution.

PHP Warning Permission denied (13) on session_start()

do a phpinfo(), and look for session.save_path. the directory there needs to have the correct permissions for the user and/or group that your webserver runs as

How to use radio buttons in ReactJS?

import React, { Component } from "react";

class RadionButtons extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // gender : "" , // use this one if you don't wanna any default value for gender
      gender: "male" // we are using this state to store the value of the radio button and also use to display the active radio button
    };

    this.handleRadioChange = this.handleRadioChange.bind(this);  // we require access to the state of component so we have to bind our function 
  }

  // this function is called whenever you change the radion button 
  handleRadioChange(event) {
      // set the new value of checked radion button to state using setState function which is async funtion
    this.setState({
      gender: event.target.value
    });
  }


  render() {
    return (
      <div>
        <div check>
          <input
            type="radio"
            value="male" // this is te value which will be picked up after radio button change
            checked={this.state.gender === "male"} // when this is true it show the male radio button in checked 
            onChange={this.handleRadioChange} // whenever it changes from checked to uncheck or via-versa it goes to the handleRadioChange function
          />
          <span
           style={{ marginLeft: "5px" }} // inline style in reactjs 
          >Male</span>
        </div>
        <div check>
          <input
            type="radio"
            value="female"
            checked={this.state.gender === "female"}
            onChange={this.handleRadioChange}
          />
          <span style={{ marginLeft: "5px" }}>Female</span>
        </div>
      </div>
    );
  }
}
export default RadionButtons;

Unique constraint on multiple columns

By using the constraint definition on table creation, you can specify one or multiple constraints that span multiple columns. The syntax, simplified from technet's documentation, is in the form of:

CONSTRAINT constraint_name UNIQUE [ CLUSTERED | NONCLUSTERED ] 
(
    column [ ASC | DESC ] [ ,...n ]
)

Therefore, the resuting table definition would be:

CREATE TABLE [dbo].[user](
    [userID] [int] IDENTITY(1,1) NOT NULL,
    [fcode] [int] NULL,
    [scode] [int] NULL,
    [dcode] [int] NULL,
    [name] [nvarchar](50) NULL,
    [address] [nvarchar](50) NULL,
    CONSTRAINT [PK_user_1] PRIMARY KEY CLUSTERED 
    (
        [userID] ASC
    ),
    CONSTRAINT [UQ_codes] UNIQUE NONCLUSTERED
    (
        [fcode], [scode], [dcode]
    )
) ON [PRIMARY]

HTML5 textarea placeholder not appearing

I had the same issue, only using a .pug file (similar to .jade). I realized that it was also a space issue, following the end of my closing parentheses. In my example, you need to highlight the text after (placeholder="YOUR MESSAGE") to see:

BEFORE:

form.form-horizontal(method='POST')
  .form-group
    textarea.form-control(placeholder="YOUR MESSAGE") 
  .form-group  
    button.btn.btn-primary(type='submit') SUBMIT

AFTER:

form.form-horizontal(method='POST')
  .form-group
    textarea.form-control(placeholder="YOUR MESSAGE")
  .form-group  
    button.btn.btn-primary(type='submit') SUBMIT

ReactJS - Call One Component Method From Another Component

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

How to make a progress bar

Here is my approach, i've tried to keep it slim:

HTML:

<div class="noload">
    <span class="loadtext" id="loadspan">50%</span>
    <div class="load" id="loaddiv">
    </div>
</div>

CSS:

.load{    
    width: 50%;
    height: 12px;
    background: url( data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAALCAYAAAC+jufvAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwAAADsABataJCQAAABp0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuMTAw9HKhAAAAPklEQVQYV2M48Gvvf4ZDv/b9Z9j7Fcha827Df4alr1b9Z1j4YsV/BuML3v8ZTC/7/GcwuwokrG4DCceH/v8Bs2Ef1StO/o0AAAAASUVORK5CYII=);  
    -moz-border-radius: 4px;
    border-radius: 4px;
}

.noload{
    width: 100px;    
    background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAALCAYAAAC+jufvAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwAAADsABataJCQAAABp0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuMTAw9HKhAAAANUlEQVQYVy3EIQ4AQQgEwfn/zwghCMwGh8Tj+8yVKN0d2l00M6i70XsPmdmfu6OIQJmJqooPOu8mqi//WKcAAAAASUVORK5CYII=);     
    -moz-border-radius: 4px;
    border-radius: 4px;
    border: 1px solid #999999;    
    position: relative;
}

.loadtext {
    font-family: Consolas;    
    font-size: 11px;
    color: #000000;
    position: absolute;
    bottom: -1px;
}

Fiddle: here

enter image description here

Why is Visual Studio 2013 very slow?

I had a Visual Studio 2013 installed, and it was running smoothly. At some point it started to get sluggish and decided to install Visual Studio 2015. After install, nothing changed and both versions were building the solution very slow (around 10 minutes for 18 projects in solution).

Then I have started thinking of recently installed extensions - the most recent installed was PHP tools for Visual Studio (had it on Visual Studio 2013 only). I am not sure how can an extension affect other versions of Visual Studio, but uninstalling it helped me to solve the problem.

I hope this will help others to realize that it is not always Visual Studio's fault.

How to get client IP address using jQuery


<html lang="en">
<head>
    <title>Jquery - get ip address</title>
    <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
</head>
<body>


<h1>Your Ip Address : <span class="ip"></span></h1>


<script type="text/javascript">
    $.getJSON("http://jsonip.com?callback=?", function (data) {
        $(".ip").text(data.ip);
    });
</script>


</body>
</html>

How do I trim whitespace from a string?

strip is not limited to whitespace characters either:

# remove all leading/trailing commas, periods and hyphens
title = title.strip(',.-')

MVC 4 Data Annotations "Display" Attribute

In addition to the other answers, there is a big benefit to using the DisplayAttribute when you want to localize the fields. You can lookup the name in a localization database using the DisplayAttribute and it will use whatever translation you wish.

Also, you can let MVC generate the templates for you by using Html.EditorForModel() and it will generate the correct label for you.

Ultimately, it's up to you. But the MVC is very "Model-centric", which is why data attributes are applied to models, so that metadata exists in a single place. It's not like it's a huge amount of extra typing you have to do.

Select unique or distinct values from a list in UNIX shell script

With AWK you can do, I find it faster than sort

 ./yourscript.ksh | awk '!a[$0]++'

IntelliJ shortcut to show a popup of methods in a class that can be searched

If you are running on Linux (I tested in Ubuntu 10.04), the shortcut is Ctrl + F12 (same of Windows)

Streaming via RTSP or RTP in HTML5

This is an old qustion, but I had to do it myself recently and I achieved something working so (besides response like mine would save me some time): Basically use ffmpeg to change the container to HLS, most of the IPCams stream h264 and some basic type of PCM, so use something like that:

ffmpeg -v info -i rtsp://ip:port/h264.sdp -c:v copy -c:a copy -bufsize 1835k -pix_fmt yuv420p -flags -global_header -hls_time 10 -hls_list_size 6 -hls_wrap 10 -start_number 1 /var/www/html/test.m3u8

Then use video.js with HLS plugin This will play Live stream nicely There is also a jsfiddle example under second link).

Note: although this is not a native support it doesn't require anything extra on user frontend.

Failed to instantiate module error in Angular js

I got this error due to not pointing the script to the correct path. So make absolutely sure that you are pointing to the correct path in you html file.

What are .tpl files? PHP, web design

In this specific case it is Smarty, but it could also be Jinja2 templates. They usually also have a .tpl extension.

Download a file by jQuery.Ajax

Ok, based on ndpu's code heres an improved (I think) version of ajax_download;-

function ajax_download(url, data) {
    var $iframe,
        iframe_doc,
        iframe_html;

    if (($iframe = $('#download_iframe')).length === 0) {
        $iframe = $("<iframe id='download_iframe'" +
                    " style='display: none' src='about:blank'></iframe>"
                   ).appendTo("body");
    }

    iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;
    if (iframe_doc.document) {
        iframe_doc = iframe_doc.document;
    }

    iframe_html = "<html><head></head><body><form method='POST' action='" +
                  url +"'>" 

    Object.keys(data).forEach(function(key){
        iframe_html += "<input type='hidden' name='"+key+"' value='"+data[key]+"'>";

    });

        iframe_html +="</form></body></html>";

    iframe_doc.open();
    iframe_doc.write(iframe_html);
    $(iframe_doc).find('form').submit();
}

Use this like this;-

$('#someid').on('click', function() {
    ajax_download('/download.action', {'para1': 1, 'para2': 2});
});

The params are sent as proper post params as if coming from an input rather than as a json encoded string as per the previous example.

CAVEAT: Be wary about the potential for variable injection on those forms. There might be a safer way to encode those variables. Alternatively contemplate escaping them.

How can I print a quotation mark in C?

You have to escape the quotationmark:

printf("\"");

Quotation marks inside a string

You can add escaped double quotes like this: String name = "\"john\"";

How to get selected value of a dropdown menu in ReactJS

Just use onChange event of the <select> object. Selected value is in e.target.value then.

By the way, it's a bad practice to use id="...". It's better to use ref=">.." http://facebook.github.io/react/docs/more-about-refs.html

bash "if [ false ];" returns true instead of false -- why?

I found that I can do some basic logic by running something like:

A=true
B=true
if ($A && $B); then
    C=true
else
    C=false
fi
echo $C

Default nginx client_max_body_size

You can increase body size in nginx configuration file as

sudo nano /etc/nginx/nginx.conf

client_max_body_size 100M;

Restart nginx to apply the changes.

sudo service nginx restart

How do I check when a UITextField changes?

Swift 4.2

write this in viewDidLoad

// to detect if TextField changed
TextField.addTarget(self, action: #selector(textFieldDidChange(_:)),
                                   for: UIControl.Event.editingChanged)

write this outside viewDidLoad

@objc func textFieldDidChange(_ textField: UITextField) {
    // do something
}

You could change the event by UIControl.Event.editingDidBegin or what ever you want to detect.

app-release-unsigned.apk is not signed

I was successfully able to debug signed APK , Follow this procedure:-

  1. Choose "release" version in "Build Variant" ToolBar
  2. In the Build.gradle for the module set debuggable true for release build type
  3. Go to File->Project Structure->under signing tab fill all info->Under Flavours tab->Choose signing Config You just created
  4. Set the breakpoints
  5. Run the application in the debug mode

Java "user.dir" property - what exactly does it mean?

It's the directory where java was run from, where you started the JVM. Does not have to be within the user's home directory. It can be anywhere where the user has permission to run java.

So if you cd into /somedir, then run your program, user.dir will be /somedir.

A different property, user.home, refers to the user directory. As in /Users/myuser or /home/myuser or C:\Users\myuser.

See here for a list of system properties and their descriptions.

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

Well there's the Network Connections preference page; you can add proxies there. I don't know much about it; I don't know if the Maven integration plugins will use the proxies defined there.

You can find it at Window...Preferences, then General...Network Connections.

Add custom message to thrown exception while maintaining stack trace in Java

you can use super while extending Exception

if (pass.length() < minPassLength)
    throw new InvalidPassException("The password provided is too short");
 } catch (NullPointerException e) {
    throw new InvalidPassException("No password provided", e);
 }


// A custom business exception
class InvalidPassException extends Exception {

InvalidPassException() {

}

InvalidPassException(String message) {
    super(message);
}
InvalidPassException(String message, Throwable cause) {
   super(message, cause);
}

}

}

source

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

adb -d shell (or adb -e shell).

This command will help you in most of the cases, if you are too lazy to type the full ID.

From http://developer.android.com/tools/help/adb.html#commandsummary:

-d - Direct an adb command to the only attached USB device. Returns an error when more than one USB device is attached.

-e - Direct an adb command to the only running emulator. Returns an error when more than one emulator is running.

How to join multiple collections with $lookup in mongodb

You can actually chain multiple $lookup stages. Based on the names of the collections shared by profesor79, you can do this :

db.sivaUserInfo.aggregate([
    {
        $lookup: {
           from: "sivaUserRole",
           localField: "userId",
           foreignField: "userId",
           as: "userRole"
        }
    },
    {
        $unwind: "$userRole"
    },
    {
        $lookup: {
            from: "sivaUserInfo",
            localField: "userId",
            foreignField: "userId",
            as: "userInfo"
        }
    },
    {
        $unwind: "$userInfo"
    }
])

This will return the following structure :

{
    "_id" : ObjectId("56d82612b63f1c31cf906003"),
    "userId" : "AD",
    "phone" : "0000000000",
    "userRole" : {
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "role" : "admin"
    },
    "userInfo" : {
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "phone" : "0000000000"
    }
}

Maybe this could be considered an anti-pattern because MongoDB wasn't meant to be relational but it is useful.

What is the difference between syntax and semantics in programming languages?

Understanding how the compiler sees the code

Usually, syntax and semantics analysis of the code is done in the 'frontend' part of the compiler.

  • Syntax: Compiler generates tokens for each keyword and symbols: the token contains the information- type of keyword and its location in the code. Using these tokens, an AST(short for Abstract Syntax Tree) is created and analysed. What compiler actually checks here is whether the code is lexically meaningful i.e. does the 'sequence of keywords' comply with the language rules? As suggested in previous answers, you can see it as the grammar of the language(not the sense/meaning of the code). Side note: Syntax errors are reported in this phase.(returns tokens with the error type to the system)

  • Semantics: Now, the compiler will check whether your code operations 'makes sense'. e.g. If the language supports Type Inference, sematic error will be reported if you're trying to assign a string to a float. OR declaring the same variable twice. These are errors that are 'grammatically'/ syntaxially correct, but makes no sense during the operation. Side note: For checking whether the same variable is declared twice, compiler manages a symbol table

So, the output of these 2 frontend phases is an annotated AST(with data types) and symbol table.

Understanding it in a less technical way

Considering the normal language we use; here, English:

e.g. He go to the school. - Incorrect grammar/syntax, though he wanted to convey a correct sense/semantic.

e.g. He goes to the cold. - cold is an adjective. In English, we might say this doesn't comply with grammar, but it actually is the closest example to incorrect semantic with correct syntax I could think of.

Android overlay a view ontop of everything?

The best way is ViewOverlay , You can add any drawable as overlay to any view as its overlay since Android JellyBeanMR2(Api 18).

Add mMyDrawable to mMyView as its overlay:

mMyDrawable.setBounds(0, 0, mMyView.getMeasuredWidth(), mMyView.getMeasuredHeight())
mMyView.getOverlay().add(mMyDrawable)

Which Architecture patterns are used on Android?

Binder uses "Observer Pattern" for Death Recipient notifications.

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

var datatable_jquery_script = document.createElement("script");
datatable_jquery_script.src = "vendor/datatables/jquery.dataTables.min.js";
document.body.appendChild(datatable_jquery_script);
setTimeout(function(){
    var datatable_bootstrap_script = document.createElement("script");
    datatable_bootstrap_script.src = "vendor/datatables/dataTables.bootstrap4.min.js";
    document.body.appendChild(datatable_bootstrap_script);
},100);

I used setTimeOut to make sure datatables.min.js loads first. I inspected the waterfall loading of each, bootstrap4.min.js always loads first.

relative path to CSS file

You have to move the css folder into your web folder. It seems that your web folder on the hard drive equals the /ServletApp folder as seen from the www. Other content than inside your web folder cannot be accessed from the browsers.

The url of the CSS link is then

 <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>

Entity Framework Refresh context?

EF 6

In my scenario, Entity Framework was not picking up the newly updated data. The reason might be the data was updated outside of its scope. Refreshing data after fetching resolved my issue.

private void RefreshData(DBEntity entity)
{
    if (entity == null) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entity);
}

private void RefreshData(List<DBEntity> entities)
{
    if (entities == null || entities.Count == 0) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entities);
}

How can I obtain the element-wise logical NOT of a pandas Series?

NumPy is slower because it casts the input to boolean values (so None and 0 becomes False and everything else becomes True).

import pandas as pd
import numpy as np
s = pd.Series([True, None, False, True])
np.logical_not(s)

gives you

0    False
1     True
2     True
3    False
dtype: object

whereas ~s would crash. In most cases tilde would be a safer choice than NumPy.

Pandas 0.25, NumPy 1.17

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

Ok, I faced the problem before. Since push notification requires serverside implementation, for me recreating profile was not an option. So I found this solution WITHOUT creating new provisioning profile.

Xcode is not properly selecting the correct provisioning profile although we are selecting it correctly.

First go to organizer. On the Devices tab, Provisioning profile from Library list, select the intended profile we are trying to use. Right click on it and then "Reveal Profile in Finder".

enter image description here

The correct profile will be selected in the opened Finder window. Note the name.

enter image description here

Now go to Xcode > Log Navigator. Select filter for "All" and "All Messages". Now in the last phase(Build Target) look for the step called "ProcessProductPackaging" expand it. Note the provisioning profile name. They should NOT match if you are having the error. enter image description here

Now in the Opened Finder window delete the rogue provisioning profile which Xcode is using. Now build again. The error should be resolved. If not repeat the process to find another rogue profile to remove it.

Hope this helps.

mysql -> insert into tbl (select from another table) and some default values

If you you want to copy a sub-set of the source table you can do:

INSERT INTO def (field_1, field_2, field3)

SELECT other_field_1, other_field_2, other_field_3 from `abc`

or to copy ALL fields from the source table to destination table you can do more simply:

INSERT INTO def 
SELECT * from `abc`

Delete default value of an input text on click

Using jQuery, you can do:

$("input:text").each(function ()
{
    // store default value
    var v = this.value;

    $(this).blur(function ()
    {
        // if input is empty, reset value to default 
        if (this.value.length == 0) this.value = v;
    }).focus(function ()
    {
        // when input is focused, clear its contents
        this.value = "";
    }); 
});

And you could stuff all this into a custom plug-in, like so:

jQuery.fn.hideObtrusiveText = function ()
{
    return this.each(function ()
    {
        var v = this.value;

        $(this).blur(function ()
        {
            if (this.value.length == 0) this.value = v;
        }).focus(function ()
        {
            this.value = "";
        }); 
    });
};

Here's how you would use the plug-in:

$("input:text").hideObtrusiveText();

Advantages to using this code is:

  • Its unobtrusive and doesn't pollute the DOM
  • Code re-use: it works on multiple fields
  • It figures out the default value of inputs by itself



Non-jQuery approach:

function hideObtrusiveText(id)
{
    var e = document.getElementById(id);

    var v = e.value;

    e.onfocus = function ()
    {
        e.value = "";
    };

    e.onblur = function ()
    {
        if (e.value.length == 0) e.value = v;
    };
}

Razor/CSHTML - Any Benefit over what we have?

Ex Microsoft Developer's Opinion

I worked on a core team for the MSDN website. Now, I use c# razor for ecommerce sites with my programming team and we focus heavy on jQuery front end with back end c# razor pages and LINQ-Entity memory database so the pages are 1-2 millisecond response times even on nested for loops with queries and no page caching. We don't use MVC, just plain ASP.NET with razor pages being mapped with URL Rewrite module for IIS 7, no ASPX pages or ViewState or server-side event programming at all. It doesn't have the extra (unnecessary) layers MVC puts in code constructs for the regex challenged. Less is more for us. Its all lean and mean but I give props to MVC for its testability but that's all.

Razor pages have no event life cycle like ASPX pages. Its just rendering as one requested page. C# is such a great language and Razor gets out of its way nicely to let it do its job. The anonymous typing with generics and linq make life so easy with c# and razor pages. Using Razor pages will help you think and code lighter.

One of the drawback of Razor and MVC is there is no ViewState-like persistence. I needed to implement a solution for that so I ended up writing a jQuery plugin for that here -> http://www.jasonsebring.com/dumbFormState which is an HTML 5 offline storage supported plugin for form state that is working in all major browsers now. It is just for form state currently but you can use window.sessionStorage or window.localStorage very simply to store any kind of state across postbacks or even page requests, I just bothered to make it autosave and namespace it based on URL and form index so you don't have to think about it.

Are static class variables possible in Python?

The best way I found is to use another class. You can create an object and then use it on other objects.

class staticFlag:
    def __init__(self):
        self.__success = False
    def isSuccess(self):
        return self.__success
    def succeed(self):
        self.__success = True

class tryIt:
    def __init__(self, staticFlag):
        self.isSuccess = staticFlag.isSuccess
        self.succeed = staticFlag.succeed

tryArr = []
flag = staticFlag()
for i in range(10):
    tryArr.append(tryIt(flag))
    if i == 5:
        tryArr[i].succeed()
    print tryArr[i].isSuccess()

With the example above, I made a class named staticFlag.

This class should present the static var __success (Private Static Var).

tryIt class represented the regular class we need to use.

Now I made an object for one flag (staticFlag). This flag will be sent as reference to all the regular objects.

All these objects are being added to the list tryArr.


This Script Results:

False
False
False
False
False
True
True
True
True
True

Python Sets vs Lists

I would recommend a Set implementation where the use case is limit to referencing or search for existence and Tuple implementation where the use case requires you to perform iteration. A list is a low-level implementation and requires significant memory overhead.

CMake does not find Visual C++ compiler

Those stumbling with this on Visual Studio 2017: there is a feature related to CMake that needs to be selected and installed together with the relevant compiler toolsets. See the screenshot below.

Visaul C++ tools for CMake must be installed

Why does git say "Pull is not possible because you have unmerged files"?

Theres a simple solution to it. But for that you will first need to learn the following

vimdiff

To remove conficts, you can use

git mergetool

The above command basically opens local file, mixed file, remote file (3 files in total), for each conflicted file. The local & remote files are just for your reference, and using them you can choose what to include (or not) in the mixed file. And just save and quit the file.

What is the difference between . (dot) and $ (dollar sign)?

The short and sweet version:

  • ($) calls the function which is its left-hand argument on the value which is its right-hand argument.
  • (.) composes the function which is its left-hand argument on the function which is its right-hand argument.

How to convert a string to ASCII

I think this code may be help you:

string str = char.ConvertFromUtf32(65)

Basic calculator in Java

Java program example for making a simple Calculator:

import java.util.Scanner;

public class Calculator
{
public static void main(String args[])
{
    float a, b, res;
    char select, ch;
    Scanner scan = new Scanner(System.in);

    do
    {
        System.out.print("(1) Addition\n");
        System.out.print("(2) Subtraction\n");
        System.out.print("(3) Multiplication\n");
        System.out.print("(4) Division\n");
        System.out.print("(5) Exit\n\n");
        System.out.print("Enter Your Choice : ");
        choice = scan.next().charAt(0);

        switch(select)
        {
            case '1' : System.out.print("Enter Two Number : ");
                a = scan.nextFloat();
                b = scan.nextFloat();
                res = a + b;
                System.out.print("Result = " + res);
                break;
            case '2' : System.out.print("Enter Two Number : ");
                a = scan.nextFloat();
                b = scan.nextFloat();
                res = a - b;
                System.out.print("Result = " + res);
                break;
            case '3' : System.out.print("Enter Two Number : ");
                a = scan.nextFloat();
                b = scan.nextFloat();
                res = a * b;
                System.out.print("Result = " + res);
                break;
            case '4' : System.out.print("Enter Two Number : ");
                a = scan.nextFloat();
                b = scan.nextFloat();
                res = a / b;
                System.out.print("Result = " + res);
                break;
            case '5' : System.exit(0);
                break;
            default : System.out.print("Wrong Choice!!!");
        }
    }while(choice != 5);       
}
}

Which to use <div class="name"> or <div id="name">?

The object itself will not change. The main difference between these 2 keyword is the use:

  • The ID is usually single in the page
  • The class can have one or many occurences

In the CSS or Javascript files:

  • The ID will be accessed by the character #
  • The class will be accessed by the character .

How do I make a JAR from a .java file?

Although it is not recommended method but still it works
[7-Zip Software is needed]
Procedure to get jar from java files:

  • place all java files in one folder

  • right click on the folder enter image description here

  • now click on Add to archive you will get something like shown below enter image description here

  • now just change zip to jar and click on ok

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

If you use Python 3.6 (possibly 3.5 or later), it doesn't give that error to me anymore. I had a similar issue, because I was using v3.4, but it went away after I uninstalled and reinstalled.

How to call a method after a delay in Android

If you use RxAndroid then thread and error handling becomes much easier. Following code executes after a delay

   Observable.timer(delay, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(aLong -> {
           // Execute code here
        }, Throwable::printStackTrace);

Spring JPA selecting specific columns

You can use the answer suggested by @jombie, and:

  • place the interface in a separate file, outside the entity class;
  • use native query or not (the choice depended on your needs);
  • don't override findAll() method for this purpose but use name of your choice;
  • remember to return a List parametrized with your new interface (e.g. List<SmallProject>).

How to wait until an element is present in Selenium?

FluentWait throws a NoSuchElementException is case of the confusion

org.openqa.selenium.NoSuchElementException;     

with

java.util.NoSuchElementException

in

.ignoring(NoSuchElementException.class)

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21

webViewClient = object : WebViewClient() {
.
.
        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            parseUri(request?.url)
            return true
        }

        @SuppressWarnings("deprecation")
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            parseUri(Uri.parse(url))
            return true
        }
}

Check orientation on Android phone

It's also worth noting that nowadays, there's less good reason to check for explicit orientation with getResources().getConfiguration().orientation if you're doing so for layout reasons, as Multi-Window Support introduced in Android 7 / API 24+ could mess with your layouts quite a bit in either orientation. Better to consider using <ConstraintLayout>, and alternative layouts dependent on available width or height, along with other tricks for determining which layout is being used, e.g. the presence or not of certain Fragments being attached to your Activity.

How is AngularJS different from jQuery

Jquery :-

jQuery is a lightweight and feature-rich JavaScript Library that helps web developers
by simplifying the usage of client-side scripting for web applications using JavaScript.
It extensively simplifies using JavaScript on a website and it’s lightweight as well as fast.

So, using jQuery, we can:

easily manipulate the contents of a webpage
apply styles to make UI more attractive
easy DOM traversal
effects and animation
simple to make AJAX calls and
utilities and much more… 

AngularJS :-

AngularJS is a product by none other the Search Engine Giant Google and it’s an open source
MVC-based framework(considered to be the best and only next generation framework). AngularJS
is a great tool for building highly rich client-side web applications.

As being a framework, it dictates us to follow some rules and a structured approach. It’s
not just a JavaScript library but a framework that is perfectly designed (framework tools
are designed to work together in a truly interconnected way).

In comparison of features jQuery Vs AngularJS, AngularJS simply offers more features:

Two-Way data binding
REST friendly
MVC-based Pattern
Deep Linking
Template
Form Validation
Dependency Injection
Localization
Full Testing Environment
Server Communication

Run all SQL files in a directory

You could use ApexSQL Propagate. It is a free tool which executes multiple scripts on multiple databases. You can select as many scripts as you need and execute them against one or multiple databases (even multiple servers). You can create scripts list and save it, then just select that list each time you want to execute those same scripts in the created order (multiple script lists can be added also):

Select scripts

When scripts and databases are selected, they will be shown in the main window and all you have to do is to click the “Execute” button and all scripts will be executed on selected databases in the given order:

Scripts execution

Load and execute external js file in node.js with access to local variables?

You need to understand CommonJS, which is a pattern to define modules. You shouldn't abuse GLOBAL scope that's always a bad thing to do, instead you can use the 'exports' token, like this:

// circle.js

var PI = 3.14; // PI will not be accessible from outside this module

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

And the client code that will use our module:

// client.js

var circle = require('./circle');
console.log( 'The area of a circle of radius 4 is '
           + circle.area(4));

This code was extracted from node.js documentation API:

http://nodejs.org/docs/v0.3.2/api/modules.html

Also, if you want to use something like Rails or Sinatra, I recommend Express (I couldn't post the URL, shame on Stack Overflow!)

How to merge every two lines into one from the command line?

If Perl is an option, you can try:

perl -0pe 's/(.*)\n(.*)\n/$1 $2\n/g' file.txt

How to check the multiple permission at single request in Android M?

I am late, but i want tell the library which i have ended with.

RxPermission is best library with reactive code, which makes permission code unexpected just 1 line.

RxPermissions rxPermissions = new RxPermissions(this);
rxPermissions
.request(Manifest.permission.CAMERA,
         Manifest.permission.READ_PHONE_STATE)
.subscribe(granted -> {
    if (granted) {
       // All requested permissions are granted
    } else {
       // At least one permission is denied
    }
});

add in your build.gradle

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    implementation 'com.github.tbruyelle:rxpermissions:0.10.1'
    implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'
}

Update a column value, replacing part of a string

Try this...

update [table_name] set [field_name] = 
replace([field_name],'[string_to_find]','[string_to_replace]');

Which is a better way to check if an array has more than one element?

I assume $arr is an array then this is what you are looking for

if ( sizeof($arr) > 1) ...

Pure Javascript listen to input value change

Actually, the ticked answer is exactly right, but the answer can be in ES6 shape:

HTMLInputElementObject.oninput = () => {
  console.log('run'); // Do something
}

Or can be written like below:

HTMLInputElementObject.addEventListener('input', (evt) => {
  console.log('run'); // Do something
});

jQuery see if any or no checkboxes are selected

You can do a simple return of the .length here:

function areAnyChecked(formID) {
  return !!$('#'+formID+' input[type=checkbox]:checked').length;
}

This look for checkboxes in the given form, sees if any are :checked and returns true if they are (since the length would be 0 otherwise). To make it a bit clearer, here's the non boolean converted version:

function howManyAreChecked(formID) {
  return $('#'+formID+' input[type=checkbox]:checked').length;
}

This would return a count of how many were checked.

React navigation goBack() and update parent state

I would also use navigation.navigate. If someone has the same problem and also uses nested navigators, this is how it would work:

onPress={() =>
        navigation.navigate('MyStackScreen', {
          // Passing params to NESTED navigator screen:
          screen: 'goToScreenA',
          params: { Data: data.item },
        })
      }

What's your most controversial programming opinion?

QA can be done well, over the long haul, without exploring all forms of testing

Lots of places seem to have an "approach", how "we do it". This seems to implicitly exclude other approaches.

This is a serious problem over the long term, because the primary function of QA is to file bugs -and- get them fixed.

You cannot do this well if you are not finding as many bugs as possible. When you exclude methodologies, for example, by being too black-box dependent, you start to ignore entire classes of discoverable coding errors. That means, by implication, you are making entire classes of coding errors unfixable, except when someone else stumbles on it.

The underlying problem often seems to be management + staff. Managers with this problem seem to have narrow thinking about the computer science and/or the value proposition of their team. They tend to create teams that reflect their approach, and a whitelist of testing methods.

I am not saying you can or should do everything all the time. Lets face it, some test methods are simply going to be a waste of time for a given product. And some methodologies are more useful at certain levels of product maturity. But what I think is missing is the ability of testing organizations to challenge themselves to learn new things, and apply that to their overall performance.

Here's a hypothetical conversation that would sum it up:

Me: You tested that startup script for 10 years, and you managed to learn NOTHING about shell scripts and how they work?!

Tester: Yes.

Me: Permissions?

Tester: The installer does that

Me: Platform, release-specific dependencies?

Tester: We file bugs for that

Me: Error handling?

Tester: when errors happen to customer support sends us some info.

Me: Okay...(starts thinking about writing post in stackoverflow...)

How to play only the audio of a Youtube video using HTML 5?

Embed the video player and use CSS to hide the video. If you do it properly you may even be able to hide only the video and not the controls below it.

However, I'd recommend against it, because it will be a violation of YouTube TOS. Use your own server instead if you really want to play only audio.

Git: How to remove remote origin from Git repo

You can rename (changing URL of a remote repository) using :

git remote set-url origin new_URL

new_URL can be like https://github.com/abcdefgh/abcd.git

Too permanently delete the remote repository use :

git remote remove origin

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

No, that's not true. The session-timeout configures a per session timeout in case of inactivity.

Are these methods equivalent? Should I favour the web.xml config?

The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.

How to get the current TimeStamp?

Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch() to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.

Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.

npm not working after clearing cache

Try npm cache clean --force if it doesn't work then manually delete %appdata%\npm-cache folder.

It worked for me.

Return HTML from ASP.NET Web API

ASP.NET Core. Approach 1

If your Controller extends ControllerBase or Controller you can use Content(...) method:

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}

ASP.NET Core. Approach 2

If you choose not to extend from Controller classes, you can create new ContentResult:

[HttpGet]
public ContentResult Index() 
{
    return new ContentResult 
    {
        ContentType = "text/html",
        Content = "<div>Hello World</div>"
    };
}

Legacy ASP.NET MVC Web API

Return string content with media type text/html:

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("<div>Hello World</div>");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

When to use "ON UPDATE CASCADE"

  1. Yes, it means that for example if you do UPDATE parent SET id = 20 WHERE id = 10 all children parent_id's of 10 will also be updated to 20

  2. If you don't update the field the foreign key refers to, this setting is not needed

  3. Can't think of any other use.

  4. You can't do that as the foreign key constraint would fail.

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

Not the same, but idea that works anyway.

#!/bin/bash  
i='y'  
while [ ${i:0:1} != n ]  
do  
    # Command(s)  
    read -p " Again? Y/n " i  
    [[ ${#i} -eq 0 ]] && i='y'  
done  

Output:
Again? Y/n N
Again? Y/n Anything
Again? Y/n 7
Again? Y/n &
Again? Y/n nsijf
$

Now only checks 1st character of $i read.

sass :first-child not working

I think that it is better (for my expirience) to use: :first-of-type, :nth-of-type(), :last-of-type. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type, than *-child selectors.

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

How to send HTML email using linux command line

I was struggling with similar problem (with mail) in one of my git's post_receive hooks and finally I found out, that sendmail actually works better for that kind of things, especially if you know a bit of how e-mails are constructed (and it seems like you know). I know this answer comes very late, but maybe it will be of some use to others too. I made use of heredoc operator and use of the feature, that it expands variables, so it can also run inlined scripts. Just check this out (bash script):

#!/bin/bash
recipients=(
    '[email protected]'
    '[email protected]'
#   '[email protected]'
);
sender='[email protected]';
subject='Oh, who really cares, seriously...';
sendmail -t <<-MAIL
    From: ${sender}
    `for r in "${recipients[@]}"; do echo "To: ${r}"; done;`
    Subject: ${subject}
    Content-Type: text/html; charset=UTF-8

    <html><head><meta charset="UTF-8"/></head>
    <body><p>Ladies and gents, here comes the report!</p>
    <pre>`mysql -u ***** -p***** -H -e "SELECT * FROM users LIMIT 20"`</pre>
    </body></html>
MAIL

Note of backticks in the MAIL part to generate some output and remember, that <<- operator strips only tabs (not spaces) from the beginning of lines, so in that case copy-paste will not work (you need to replace indentation with proper tabs). Or use << operator and make no indentation at all. Hope this will help someone. Of course you can use backticks outside o MAIL part and save the output into some variable, that you can later use in the MAIL part — matter of taste and readability. And I know, #!/bin/bash does not always work on every system.

CSS: How to align vertically a "label" and "input" inside a "div"?

Wrap the label and input in another div with a defined height. This may not work in IE versions lower than 8.

position:absolute; 
top:0; bottom:0; left:0; right:0;
margin:auto;

Header set Access-Control-Allow-Origin in .htaccess doesn't work

I +1'd Miro's answer for the link to the header-checker site http://www.webconfs.com/http-header-check.php. It pops up an obnoxious ad every time you use it, but it is, nevertheless, very useful for verifying the presence of the Access-Control-Allow-Origin header.

I'm reading a .json file from the javascript on my web page. I found that adding the following to my .htaccess file fixed the problem when viewing my web page in IE 11 (version 11.447.14393.0):

<FilesMatch "\.(json)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

I also added the following to /etc/httpd.conf (Apache's configuration file):

AllowOverride All

The header-checker site verified that the Access-Control-Allow-Origin header is now being sent (thanks, Miro!).

However, Firefox 50.0.2, Opera 41.0.2353.69, and Edge 38.14393.0.0 all fetch the file anyhow, even without the Access-Control-Allow-Origin header. (Note: they might be checking IP addresses, since the two domains I was using are both hosted on the same server, at the same IPv4 address.)

However, Chrome 54.0.2840.99 m (64-bit) ignores the Access-Control-Allow-Origin header and fails anyhow, erroneously reporting:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '{mydomain}' is therefore not allowed access.

I think this has got to be some sort of "first." IE is working correctly; Chrome, Firefox, Opera and Edge are all buggy; and Chrome is the worst. Isn't that the exact opposite of the usual case?

Get column index from label in a data frame

Use t function:

t(colnames(df))

     [,1]   [,2]   [,3]   [,4]   [,5]   [,6]  
[1,] "var1" "var2" "var3" "var4" "var5" "var6"

100% width in React Native Flexbox

Simply add alignSelf: "stretch" to your item's stylesheet.

line1: {
    backgroundColor: '#FDD7E4',
    alignSelf: 'stretch',
    textAlign: 'center',
},

Excel column number from column name

Based on Anastasiya's answer. I think this is the shortest vba command:

Option Explicit

Sub Sample()
    Dim sColumnLetter as String
    Dim iColumnNumber as Integer

    sColumnLetter = "C"
    iColumnNumber = Columns(sColumnLetter).Column

    MsgBox "The column number is " & iColumnNumber
End Sub

Caveat: The only condition for this code to work is that a worksheet is active, because Columns is equivalent to ActiveSheet.Columns. ;)

Why is my toFixed() function not working?

document.getElementById("EDTVALOR").addEventListener("change", function() {
  this.value = this.value.replace(",", ".");
  this.value = parseFloat(this.value).toFixed(2);
  if (this.value < 0) {
    this.value = 0;
  }
  this.value = this.value.replace(".", ",");
  this.value = this.value.replace("NaN", "0");
});

Java Inheritance - calling superclass method

You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:

solution 1: call alpha's alphaMethod1() from beta's alphaMethod1()

class Beta extends Alpha
{
  public void alphaMethod1()
  {
    super.alphaMethod1();
  }
}

or from any other method of Beta like:

class Beta extends Alpha
{
  public void foo()
  {
     super.alphaMethod1();
  }
}

class Test extends Beta 
{
   public static void main(String[] args)
   {
      Beta beta = new Beta();
      beta.foo();
   }
}

solution 2: create alpha's object and call alpha's alphaMethod1()

class Test extends Beta
{
   public static void main(String[] args)
   {
      Alpha alpha = new Alpha();
      alpha.alphaMethod1();
   }
}

Print execution time of a shell command

time is a built-in command in most shells that writes execution time information to the tty.

You could also try something like

start_time=`date +%s`
<command-to-execute>
end_time=`date +%s`
echo execution time was `expr $end_time - $start_time` s.

Or in bash:

start_time=`date +%s`
<command-to-execute> && echo run time is $(expr `date +%s` - $start_time) s

Setting onSubmit in React.js

You can pass the event as argument to the function and then prevent the default behaviour.

var OnSubmitTest = React.createClass({
        render: function() {
        doSomething = function(event){
           event.preventDefault();
           alert('it works!');
        }

        return <form onSubmit={this.doSomething}>
        <button>Click me</button>
        </form>;
    }
});

Find unused npm packages in package.json

As other answer mentioned depcheck is good for check unused dependecies in your porject. Use npm outdated command to check the outdated library.

enter image description here

ORDER BY using Criteria API

You can add join type as well:

Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

I know this is a very old question, but this worked for me:

UPDATE TABLE SET FIELD1 =
CASE 
WHEN FIELD1 = Condition1 THEN 'Result1'
WHEN FIELD1 = Condition2 THEN 'Result2'
WHEN FIELD1 = Condition3 THEN 'Result3'
END;

Regards

Format in kotlin string templates

As a workaround, There is a Kotlin stdlib function that can be used in a nice way and fully compatible with Java's String format (it's only a wrapper around Java's String.format())

See Kotlin's documentation

Your code would be:

val pi = 3.14159265358979323
val s = "pi = %.2f".format(pi)

LDAP root query syntax to search more than one specific OU

The answer is NO you can't. Why?

Because the LDAP standard describes a LDAP-SEARCH as kind of function with 4 parameters:

  1. The node where the search should begin, which is a Distinguish Name (DN)
  2. The attributes you want to be brought back
  3. The depth of the search (base, one-level, subtree)
  4. The filter

You are interested in the filter. You've got a summary here (it's provided by Microsoft for Active Directory, it's from a standard). The filter is composed, in a boolean way, by expression of the type Attribute Operator Value.

So the filter you give does not mean anything.

On the theoretical point of view there is ExtensibleMatch that allows buildind filters on the DN path, but it's not supported by Active Directory.

As far as I know, you have to use an attribute in AD to make the distinction for users in the two OUs.

It can be any existing discriminator attribute, or, for example the attribute called OU which is inherited from organizationalPerson class. you can set it (it's not automatic, and will not be maintained if you move the users) with "staff" for some users and "vendors" for others and them use the filter:

(&(objectCategory=person)(|(ou=staff)(ou=vendors)))

Breaking out of a nested loop

I've seen a lot of examples that use "break" but none that use "continue".

It still would require a flag of some sort in the inner loop:

while( some_condition )
{
    // outer loop stuff
    ...

    bool get_out = false;
    for(...)
    {
        // inner loop stuff
        ...

        get_out = true;
        break;
    }

    if( get_out )
    {
        some_condition=false;
        continue;
    }

    // more out loop stuff
    ...

}

includes() not working in all browsers

import 'core-js/es7/array' 

into polyfill.ts worked for me.

How do I change the font-size of an <option> element within <select>?

Like most form controls in HTML, the results of applying CSS to <select> and <option> elements vary a lot between browsers. Chrome, as you've found, won't let you apply and font styles to an <option> element directly --- if you do Inspect Element on it, you'll see the font-size: 14px declaration is crossed through as if it's been overridden by the cascade, but it's actually because Chrome is ignoring it.

However, Chrome will let you apply font styles to the <optgroup> element, so to achieve the result you want you can wrap all the <option>s in an <optgroup> and then apply your font styles to a .styled-select optgroup selector. If you want the optgroup sans-label, you may have to do some clever CSS with positioning or something to hide the white area at the top where the label would be shown, but that should be possible.

Forked to a new JSFiddle to show you what I mean:

http://jsfiddle.net/zRtbZ/

how to change text in Android TextView

per your advice, i am using handle and runnables to switch/change the content of the TextView using a "timer". for some reason, when running, the app always skips the second step ("Step Two: fry egg"), and only show the last (third) step ("Step three: serve egg").

TextView t; 
private String sText;

private Handler mHandler = new Handler();

private Runnable mWaitRunnable = new Runnable() {
    public void run() {
        t.setText(sText);
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    mMonster = BitmapFactory.decodeResource(getResources(),
            R.drawable.monster1);

    t=new TextView(this); 
    t=(TextView)findViewById(R.id.TextView01); 

    sText = "Step One: unpack egg";
    t.setText(sText);

    sText = "Step Two: fry egg";        
    mHandler.postDelayed(mWaitRunnable, 3000);

    sText = "Step three: serve egg";
    mHandler.postDelayed(mWaitRunnable, 4000);      
    ...
}

CSS: stretching background image to 100% width and height of screen?

The VH unit can be used to fill the background of the viewport, aka the browser window.

(height:100vh;)

html{
    height:100%;
    }
.body {
     background: url(image.jpg) no-repeat center top; 
     background-size: cover; 
     height:100vh;     
}

How to print out more than 20 items (documents) in MongoDB's shell?

I suggest you to have a ~/.mongorc.js file so you do not have to set the default size everytime.

 # execute in your terminal
 touch ~/.mongorc.js
 echo 'DBQuery.shellBatchSize = 100;' > ~/.mongorc.js
 # add one more line to always prettyprint the ouput
 echo 'DBQuery.prototype._prettyShell = true; ' >> ~/.mongorc.js

To know more about what else you can do, I suggest you to look at this article: http://mo.github.io/2017/01/22/mongo-db-tips-and-tricks.html

Get JSON Data from URL Using Android?

Easy way to get JSON especially for Android SDK 23:

public class MainActivity extends AppCompatActivity {

Button btnHit;
TextView txtJson;
ProgressDialog pd;

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

    btnHit = (Button) findViewById(R.id.btnHit);
    txtJson = (TextView) findViewById(R.id.tvJsonItem);

    btnHit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new JsonTask().execute("Url address here");
        }
    });


}


private class JsonTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog(MainActivity.this);
        pd.setMessage("Please wait");
        pd.setCancelable(false);
        pd.show();
    }

    protected String doInBackground(String... params) {


        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line+"\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-) 

            }

            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pd.isShowing()){
            pd.dismiss();
        }
        txtJson.setText(result);
    }
}
}

How can I specify my .keystore file with Spring Boot and Tomcat?

It turns out that there is a way to do this, although I'm not sure I've found the 'proper' way since this required hours of reading source code from multiple projects. In other words, this might be a lot of dumb work (but it works).

First, there is no way to get at the server.xml in the embedded Tomcat, either to augment it or replace it. This must be done programmatically.

Second, the 'require_https' setting doesn't help since you can't set cert info that way. It does set up forwarding from http to https, but it doesn't give you a way to make https work so the forwarding isnt helpful. However, use it with the stuff below, which does make https work.

To begin, you need to provide an EmbeddedServletContainerFactory as explained in the Embedded Servlet Container Support docs. The docs are for Java but the Groovy would look pretty much the same. Note that I haven't been able to get it to recognize the @Value annotation used in their example but its not needed. For groovy, simply put this in a new .groovy file and include that file on the command line when you launch spring boot.

Now, the instructions say that you can customize the TomcatEmbeddedServletContainerFactory class that you created in that code so that you can alter web.xml behavior, and this is true, but for our purposes its important to know that you can also use it to tailor server.xml behavior. Indeed, reading the source for the class and comparing it with the Embedded Tomcat docs, you see that this is the only place to do that. The interesting function is TomcatEmbeddedServletContainerFactory.addConnectorCustomizers(), which may not look like much from the Javadocs but actually gives you the Embedded Tomcat object to customize yourself. Simply pass your own implementation of TomcatConnectorCustomizer and set the things you want on the given Connector in the void customize(Connector con) function. Now, there are about a billion things you can do with the Connector and I couldn't find useful docs for it but the createConnector() function in this this guys personal Spring-embedded-Tomcat project is a very practical guide. My implementation ended up looking like this:

package com.deepdownstudios.server

import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.boot.*
import org.springframework.stereotype.*

@Configuration
class MyConfiguration {

@Bean
public EmbeddedServletContainerFactory servletContainer() {
final int port = 8443;
final String keystoreFile = "/path/to/keystore"
final String keystorePass = "keystore-password"
final String keystoreType = "pkcs12"
final String keystoreProvider = "SunJSSE"
final String keystoreAlias = "tomcat"

TomcatEmbeddedServletContainerFactory factory = 
        new TomcatEmbeddedServletContainerFactory(this.port);
factory.addConnectorCustomizers( new TomcatConnectorCustomizer() {
    void    customize(Connector con) {
        Http11NioProtocol proto = (Http11NioProtocol) con.getProtocolHandler();
            proto.setSSLEnabled(true);
        con.setScheme("https");
        con.setSecure(true);
        proto.setKeystoreFile(keystoreFile);
        proto.setKeystorePass(keystorePass);
        proto.setKeystoreType(keystoreType);
        proto.setProperty("keystoreProvider", keystoreProvider);
        proto.setKeyAlias(keystoreAlias);
    }
});
return factory;
}
}

The Autowiring will pick up this implementation an run with it. Once I fixed my busted keystore file (make sure you call keytool with -storetype pkcs12, not -storepass pkcs12 as reported elsewhere), this worked. Also, it would be far better to provide the parameters (port, password, etc) as configuration settings for testing and such... I'm sure its possible if you can get the @Value annotation to work with Groovy.

How to find whether MySQL is installed in Red Hat?

yum list installed | grep mysql

Then if it's not installed you can do (as root)

yum install mysql -y

Vertical Align text in a Label

Use css on your label.

For example:

label {line-height:1em; margin:2px 5px 3px 5px; padding:2px 5px 3px 5px;}

Notice that the line-height will adjust the height of the line itself, whereas margin will dictate how far out other elements will be outside the lable and padding will dictate any inner space from the outside edge of the label. The margin and padding work like this (clockwise: Top Right Bottom Left), so 2px 5px 3px 5px is:

2px Top 5px Right 3px Bottom 5px Left

pip install failing with: OSError: [Errno 13] Permission denied on directory

We should really stop advising the use of sudo with pip install. It's better to first try pip install --user. If this fails then take a look at the top post here.

The reason you shouldn't use sudo is as follows:

When you run pip with sudo, you are running arbitrary Python code from the Internet as a root user, which is quite a big security risk. If someone puts up a malicious project on PyPI and you install it, you give an attacker root access to your machine.

How to calculate the inverse of the normal cumulative distribution function in python?

NORMSINV (mentioned in a comment) is the inverse of the CDF of the standard normal distribution. Using scipy, you can compute this with the ppf method of the scipy.stats.norm object. The acronym ppf stands for percent point function, which is another name for the quantile function.

In [20]: from scipy.stats import norm

In [21]: norm.ppf(0.95)
Out[21]: 1.6448536269514722

Check that it is the inverse of the CDF:

In [34]: norm.cdf(norm.ppf(0.95))
Out[34]: 0.94999999999999996

By default, norm.ppf uses mean=0 and stddev=1, which is the "standard" normal distribution. You can use a different mean and standard deviation by specifying the loc and scale arguments, respectively.

In [35]: norm.ppf(0.95, loc=10, scale=2)
Out[35]: 13.289707253902945

If you look at the source code for scipy.stats.norm, you'll find that the ppf method ultimately calls scipy.special.ndtri. So to compute the inverse of the CDF of the standard normal distribution, you could use that function directly:

In [43]: from scipy.special import ndtri

In [44]: ndtri(0.95)
Out[44]: 1.6448536269514722

Node.js https pem error: routines:PEM_read_bio:no start line

I faced with the problem like this.

The problem was that I added the public key without '-----BEGIN PUBLIC KEY-----' at the beginning and without '-----END PUBLIC KEY-----'.

So it causes the error.

Initially, my public key was like this:

-----BEGIN PUBLIC KEY-----
WnsbGUXbb0GbJSCwCBAhrzT0s2KMRyqqS7QBiIG7t3H2Qtmde6UoUIcTTPJgv71
......
oNLcaK2wKKyRdcROK7ZTSCSMsJpAFOY
-----END PUBLIC KEY-----

But I used just this part:

WnsbGUXb+b0GbJSCwCBAhrzT0s2KMRyqqS7QBiIG7t3H2Qtmde6UoUIcTTPJgv71
......
oNLcaK2w+KKyRdcROK7ZTSCSMsJpAFOY

how can I debug a jar at runtime?

With IntelliJ IDEA you can create a Jar Application runtime configuration, select the JAR, the sources, the JRE to run the Jar with and start debugging. Here is the documentation.

What's default HTML/CSS link color?

The best way to get a browser's default styling on something is to not style the element at all in the first place.

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

Expand/collapse section in UITableView in iOS

I've used a NSDictionary as datasource, this looks like a lot of code, but it's really simple and works very well! how looks here

I created a enum for the sections

typedef NS_ENUM(NSUInteger, TableViewSection) {

    TableViewSection0 = 0,
    TableViewSection1,
    TableViewSection2,
    TableViewSectionCount
};

sections property:

@property (nonatomic, strong) NSMutableDictionary * sectionsDisctionary;

A method returning my sections:

-(NSArray <NSNumber *> * )sections{

    return @[@(TableViewSection0), @(TableViewSection1), @(TableViewSection2)];
}

And then setup my data soruce:

-(void)loadAndSetupData{

    self.sectionsDisctionary = [NSMutableDictionary dictionary];

    NSArray * sections = [self sections];

    for (NSNumber * section in sections) {

    NSArray * sectionObjects = [self objectsForSection:section.integerValue];

    [self.sectionsDisctionary setObject:[NSMutableDictionary dictionaryWithDictionary:@{@"visible" : @YES, @"objects" : sectionObjects}] forKey:section];
    }
}

-(NSArray *)objectsForSection:(NSInteger)section{

    NSArray * objects;

    switch (section) {

        case TableViewSection0:

            objects = @[] // objects for section 0;
            break;

        case TableViewSection1:

            objects = @[] // objects for section 1;
            break;

        case TableViewSection2:

            objects = @[] // objects for section 2;
            break;

        default:
            break;
    }

    return objects;
}

The next methods, will help you to know when a section is opened, and how to respond to tableview datasource:

Respond the section to datasource:

/**
 *  Asks the delegate for a view object to display in the header of the specified section of the table view.
 *
 *  @param tableView The table-view object asking for the view object.
 *  @param section   An index number identifying a section of tableView .
 *
 *  @return A view object to be displayed in the header of section .
 */
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    NSString * headerName = [self titleForSection:section];

    YourCustomSectionHeaderClass * header = (YourCustomSectionHeaderClass *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:YourCustomSectionHeaderClassIdentifier];

    [header setTag:section];
    [header addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)]];
    header.title = headerName;
    header.collapsed = [self sectionIsOpened:section];


    return header;
}

/**
 * Asks the data source to return the number of sections in the table view
 *
 * @param An object representing the table view requesting this information.
 * @return The number of sections in tableView.
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    // Return the number of sections.

    return self.sectionsDisctionary.count;
}

/**
 * Tells the data source to return the number of rows in a given section of a table view
 *
 * @param tableView: The table-view object requesting this information.
 * @param section: An index number identifying a section in tableView.
 * @return The number of rows in section.
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    BOOL sectionOpened = [self sectionIsOpened:section];
    return sectionOpened ? [[self objectsForSection:section] count] : 0;
}

Tools:

/**
 Return the section at the given index

 @param index the index

 @return The section in the given index
 */
-(NSMutableDictionary *)sectionAtIndex:(NSInteger)index{

    NSString * asectionKey = [self.sectionsDisctionary.allKeys objectAtIndex:index];

    return [self.sectionsDisctionary objectForKey:asectionKey];
}

/**
 Check if a section is currently opened

 @param section the section to check

 @return YES if is opened
 */
-(BOOL)sectionIsOpened:(NSInteger)section{

    NSDictionary * asection = [self sectionAtIndex:section];
    BOOL sectionOpened = [[asection objectForKey:@"visible"] boolValue];

    return sectionOpened;
}


/**
 Handle the section tap

 @param tap the UITapGestureRecognizer
 */
- (void)handleTapGesture:(UITapGestureRecognizer*)tap{

    NSInteger index = tap.view.tag;

    [self toggleSection:index];
}

Toggle section visibility

/**
 Switch the state of the section at the given section number

 @param section the section number
 */
-(void)toggleSection:(NSInteger)section{

    if (index >= 0){

        NSMutableDictionary * asection = [self sectionAtIndex:section];

        [asection setObject:@(![self sectionIsOpened:section]) forKey:@"visible"];

        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
    }
}

In plain English, what does "git reset" do?

When you commit something to git you first have to stage (add to the index) your changes. This means you have to git add all the files you want to have included in this commit before git considers them part of the commit. Let's first have a look over the image of a git repo: enter image description here

so, its simple now. We have to work in working directory, creating files, directories and all. These changes are untracked changes. To make them tracked, we need to add them to git index by using git add command. Once they are added to git index. We can now commit these changes, if we want to push it to git repository.

But suddenly we came to know while commiting that we have one extra file which we added in index is not required to push in git repository. It means we don't want that file in index. Now the question is how to remove that file from git index, Since we used git add to put them in the index it would be logical to use git rm? Wrong! git rm will simply delete the file and add the deletion to the index. So what to do now:

Use:-

git reset

It Clears your index, leaves your working directory untouched. (simply unstaging everything).

It can be used with number of options with it. There are three main options to use with git reset: --hard, --soft and --mixed. These affect what get’s reset in addition to the HEAD pointer when you reset.

First, --hard resets everything. Your current directory would be exactly as it would if you had been following that branch all along. The working directory and the index are changed to that commit. This is the version that I use most often. git reset --hard is something like svn revert .

Next, the complete opposite, —soft, does not reset the working tree nor the index. It only moves the HEAD pointer. This leaves your current state with any changes different than the commit you are switching to in place in your directory, and “staged” for committing. If you make a commit locally but haven’t pushed the commit to the git server, you can reset to the previous commit, and recommit with a good commit message.

Finally, --mixed resets the index, but not the working tree. So the changes are all still there, but are “unstaged” and would need to be git add’ed or git commit -a. we use this sometimes if we committed more than we meant to with git commit -a, we can back out the commit with git reset --mixed, add the things that we want to commit and just commit those.

Difference between git revert and git reset :-


In simple words, git reset is a command to "fix-uncommited mistakes" and git revert is a command to "fix-commited mistake".

It means if we have made some error in some change and commited and pushed the same to git repo, then git revert is the solution. And if in case we have identified the same error before pushing/commiting, we can use git reset to fix the issue.

I hope it will help you to get rid of your confusion.

Getting the screen resolution using PHP

The only way is to use javascript, then get the javascript to post to it to your php(if you really need there res server side). This will however completly fall flat on its face, if they turn javascript off.

Loop through checkboxes and count each one checked or unchecked

I don't think enough time was paid attention to the schema considerations brought up in the original post. So, here is something to consider for any newbies.

Let's say you went ahead and built this solution. All of your menial values are conctenated into a single value and stored in the database. You are indeed saving [a little] space in your database and some time coding.

Now let's consider that you must perform the frequent and easy task of adding a new checkbox between the current checkboxes 3 & 4. Your development manager, customer, whatever expects this to be a simple change.

So you add the checkbox to the UI (the easy part). Your looping code would already concatenate the values no matter how many checkboxes. You also figure your database field is just a varchar or other string type so it should be fine as well.

What happens when customers or you try to view the data from before the change? You're essentially serializing from left to right. However, now the values after 3 are all off by 1 character. What are you going to do with all of your existing data? Are you going write an application, pull it all back out of the database, process it to add in a default value for the new question position and then store it all back in the database? What happens when you have several new values a week or month apart? What if you move the locations and jQuery processes them in a different order? All your data is hosed and has to be reprocessed again to rearrange it.

The whole concept of NOT providing a tight key-value relationship is ludacris and will wind up getting you into trouble sooner rather than later. For those of you considering this, please don't. The other suggestions for schema changes are fine. Use a child table, more fields in the main table, a question-answer table, etc. Just don't store non-labeled data when the structure of that data is subject to change.

Why Java Calendar set(int year, int month, int date) not returning correct date?

Selected date at the example is interesting. Example code block is:

Calendar c1 = GregorianCalendar.getInstance();
c1.set(2000, 1, 30);  //January 30th 2000
Date sDate = c1.getTime();

System.out.println(sDate);

and output Wed Mar 01 19:32:21 JST 2000.

When I first read the example i think that output is wrong but it is true:)

  • Calendar.Month is starting from 0 so 1 means February.
  • February last day is 28 so output should be 2 March.
  • But selected year is important, it is 2000 which means February 29 so result should be 1 March.

Media Player called in state 0, error (-38,0)

This is my code,tested and working fine:

package com.example.com.mak.mediaplayer;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final MediaPlayer mpp = MediaPlayer.create(this, R.raw.red); //mp3 file in res/raw folder

    Button btnplay = (Button) findViewById(R.id.btnplay); //Play
    btnplay.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View vone) {
        mpp.start();
      }
    });

    Button btnpause = (Button) findViewById(R.id.btnpause); //Pause
    btnpause.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View vtwo) {
        if (mpp.isPlaying()) {
          mpp.pause();
          mpp.seekTo(0);
        }
      }
    });
  }
}

I am getting Failed to load resource: net::ERR_BLOCKED_BY_CLIENT with Google chrome

There are two steps here: troubleshooting and then fixing the issue:

  • To troubleshoot, check to see if it is a browser and/or extension problem. Chrome, Firefox and others have incognito or private mode which does not load extensions or the basic database of passwords and cookies.

  • In the case of ERR_BLOCKED_BY_CLIENT that is usually some kind of blocking software, such as Adblock, Ghostery, or some other kind of privacy/anti-spyware tool.

How to decrypt the password generated by wordpress

This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.

  1. In the DB table wp_users, add a key, like abc123 to the user_activation column.
  2. Visit yoursite.com/wp-login.php?action=rp&key=abc123&login=yourusername
  3. You will be prompted to enter a new password.

How to check if user input is not an int value

Try this one:

    for (;;) {
        if (!sc.hasNextInt()) {
            System.out.println(" enter only integers!: ");
            sc.next(); // discard
            continue;
        }
        choose = sc.nextInt();
        if (choose >= 0) {
            System.out.print("no problem with input");

        } else {
            System.out.print("invalid inputs");

        }
    break;
  }

How do I use JDK 7 on Mac OSX?

It's possible that you still need to add the JDK into Eclipse (STS). Just because the JDK is on the system doesn't mean Eclipse knows where to find it.

Go to Preferences > Java > Installed JREs

If there is not an entry for the 1.7 JDK, add it. You'll have to point Eclipse to where you installed your 1.7 JDK.

If Eclipse can't find a JRE that is 1.7 compatible, I'm guessing that it just uses your default JRE, and that's probably still pointing at Java 1.6, which would be causing your red squiggly lines.

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

You could try Conditional Formatting available in the tool menu "Format -> Conditional Formatting".

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

Might want to try

keytool -import -trustcacerts -noprompt -keystore <full path to cacerts> -storepass changeit -alias $REMHOST -file $REMHOST.pem

i honestly have no idea where it puts your certificate if you just write cacerts just give it a full path

Add padding on view programmatically

Write Following Code to set padding, it may help you.

TextView ApplyPaddingTextView = (TextView)findViewById(R.id.textView1);
final LayoutParams layoutparams = (RelativeLayout.LayoutParams) ApplyPaddingTextView.getLayoutParams();

layoutparams.setPadding(50,50,50,50);

ApplyPaddingTextView.setLayoutParams(layoutparams);

Use LinearLayout.LayoutParams or RelativeLayout.LayoutParams according to parent layout of the child view

How to remove leading and trailing whitespace in a MySQL field?

Please understand the use case before using this solution:

trim does not work while doing select query

This works

select replace(name , ' ','') from test;

While this doesn't

select trim(name) from test;

Removing special characters VBA Excel

Here is how removed special characters.

I simply applied regex

Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object    
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters

' Configure the regex object
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
End With

' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)

What's the best UI for entering date of birth?

I would prefer a datepicker (and a input box with documented format as a fall-back) for an international site.

Date formats vary and are sometimes hard to read if you are now used to them. Too bad many people aren't comfortable with ISO 8601. :-(

How to create a List with a dynamic object type

It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.

Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.

DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj

...

The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.

var DyObjectsList = new List<dynamic>; 
if (condition1) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = true; 
    DyObj.Message = "Message 1"; 
    DyObjectsList .Add(DyObj); 
} 
if (condition2) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = false; 
    DyObj.Message = "Message 2"; 
    DyObjectsList .Add(DyObj); 
} 

your resulting List essentially looks like this

DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj

Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.

However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

The problem with the other answers is, that some characters like numbers or punctuation also return true when checked for lowercase/uppercase.

I found this to work very well for it:

function isLowerCase(str)
{
    return str == str.toLowerCase() && str != str.toUpperCase();
}

This will work for punctuation, numbers and letters:

assert(isLowerCase("a"))
assert(!isLowerCase("Ü"))
assert(!isLowerCase("4"))
assert(!isLowerCase("_"))

To check one letter just call it using isLowerCase(str[charIndex])

How to combine results of two queries into a single dataset

How about,

select
        col1, 
        col2, 
        null col3, 
        null col4 
    from Table1
union all
select 
        null col1, 
        null col2,
        col4 col3, 
        col5 col4 
    from Table2;

How can I wait for set of asynchronous callback functions?

Use an control flow library like after

after.map(array, function (value, done) {
    // do something async
    setTimeout(function () {
        // do something with the value
        done(null, value * 2)
    }, 10)
}, function (err, mappedArray) {
    // all done, continue here
    console.log(mappedArray)
})

Change GridView row color based on condition

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    e.Row.Attributes.Add("style", "cursor:help;");
    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Alternate)
    { 
        if (e.Row.RowType == DataControlRowType.DataRow)
        {                
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='orange'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#E56E94'");
            e.Row.BackColor = Color.FromName("#E56E94");                
        }           
    }
    else
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='orange'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='gray'");
            e.Row.BackColor = Color.FromName("gray");                
        }           
    }
}

How to get elements with multiple classes

html

<h2 class="example example2">A heading with class="example"</h2>

javascritp code

var element = document.querySelectorAll(".example.example2");
element.style.backgroundColor = "green";

The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

also learn more about https://www.w3schools.com/jsref/met_document_queryselectorall.asp

== Thank You ==

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

How to clear Facebook Sharer cache?

I thing these two links have a wide discussion on your problem related stuff. fb:ref clear cashes by calling

fbml.refreshRefUrl

like this

<tt>fbml.refreshRefUrl("http://www.mysite.com/someurl.php")

You can study the related stuff from here fb:ref. I hope it will work for you

EXEC sp_executesql with multiple parameters

maybe this help :

declare 
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'

set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + ''' 
'
exec sp_executesql @statement;

this is same as below :

select @text1 + ' beautifull ' + @text2

PUT vs. POST in REST

At the risk of restating what has already been said, it seems important to remember that PUT implies that the client controls what the URL is going to end up being, when creating a resource. So part of the choice between PUT and POST is going to be about how much you can trust the client to provide correct, normalized URL that are coherent with whatever your URL scheme is.

When you can't fully trust the client to do the right thing, it would be more appropriate to use POST to create a new item and then send the URL back to the client in the response.

Batch Extract path and filename from a variable

@ECHO OFF
SETLOCAL
set file=C:\Users\l72rugschiri\Desktop\fs.cfg
FOR %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)

Not really sure what you mean by no "function"

Obviously, change ECHO to SET to set the variables rather thon ECHOing them...

See for documentation for a full list.


ceztko's test case (for reference)

@ECHO OFF
SETLOCAL
set file="C:\Users\ l72rugschiri\Desktop\fs.cfg"
FOR /F "delims=" %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)

Comment : please see comments.

How do I use a char as the case in a switch-case?

Here's an example:

public class Main {

    public static void main(String[] args) {

        double val1 = 100;
        double val2 = 10;
        char operation = 'd';
        double result = 0;

        switch (operation) {

            case 'a':
                result = val1 + val2; break;

            case 's':
                result = val1 - val2; break;
            case 'd':
                if (val2 != 0)
                    result = val1 / val2; break;
            case 'm':
                result = val1 * val2; break;

            default: System.out.println("Not a defined operation");


        }

        System.out.println(result);
    }
}

Rendering React Components from Array of Objects

this.data presumably contains all the data, so you would need to do something like this:

var stations = [];
var stationData = this.data.stations;

for (var i = 0; i < stationData.length; i++) {
    stations.push(
        <div key={stationData[i].call} className="station">
            Call: {stationData[i].call}, Freq: {stationData[i].frequency}
        </div>
    )
}

render() {
  return (
    <div className="stations">{stations}</div>
  )
}

Or you can use map and arrow functions if you're using ES6:

const stations = this.data.stations.map(station =>
    <div key={station.call} className="station">
      Call: {station.call}, Freq: {station.frequency}
    </div>
);

Arrays.fill with multidimensional array in Java

Using Java 8, you can declare and initialize a two-dimensional array without using a (explicit) loop as follows:

int x = 20; // first dimension
int y = 4; // second dimension

double[][] a = IntStream.range(0, x)
                        .mapToObj(i -> new double[y])
                        .toArray(i -> new double[x][]);

This will initialize the arrays with default values (0.0 in the case of double).

In case you want to explicitly define the fill value to be used, You can add in a DoubleStream:

int x = 20; // first dimension
int y = 4; // second dimension
double v = 5.0; // fill value

double[][] a = IntStream
        .range(0, x)
        .mapToObj(i -> DoubleStream.generate(() -> v).limit(y).toArray())
        .toArray(i -> new double[x][]);

Can a website detect when you are using Selenium with chromedriver?

It works for some websites, remove property webdriver from navigator

from selenium import webdriver
driver = webdriver.Chrome()
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source":
        "const newProto = navigator.__proto__;"
        "delete newProto.webdriver;"
        "navigator.__proto__ = newProto;"
    })

Merge r brings error "'by' must specify uniquely valid columns"

Rather give names of the column on which you want to merge:

exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)

docker entrypoint running bash script gets "permission denied"

I faced same issue & it resolved by

ENTRYPOINT ["sh", "/docker-entrypoint.sh"]

For the Dockerfile in the original question it should be like:

ENTRYPOINT ["sh", "/usr/src/app/docker-entrypoint.sh"]

Circular dependency in Spring

Say A depends on B, then Spring will first instantiate A, then B, then set properties for B, then set B into A.

But what if B also depends on A?

My understanding is: Spring just found that A has been constructed (constructor executed), but not fully initialized (not all injections done), well, it thought, it's OK, it's tolerable that A is not fully initialized, just set this not-fully-initialized A instances into B for now. After B is fully initialized, it was set into A, and finally, A was fully initiated now.

In other words, it just expose A to B in advance.

For dependencies via constructor, Sprint just throw BeanCurrentlyInCreationException, to resolve this exception, set lazy-init to true for the bean which depends on others via constructor-arg way.

Transfer data between iOS and Android via Bluetooth?

This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.

Some possible alternatives:

  1. Bonjour over WiFi, as you mentioned. However, I couldn't find a comprehensive tutorial for it.
  2. Some internet based sync service, like Dropbox, Google Drive, Amazon S3. These usually have libraries for several platforms.
  3. Direct TCP/IP communication over sockets. (How to write a small (socket) server in iOS)
  4. Bluetooth Low Energy will be possible once the issues on the Android side are solved (Communicating between iOS and Android with Bluetooth LE)

Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.

Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.

Writing new lines to a text file in PowerShell

`n is a line feed character. Notepad (prior to Windows 10) expects linebreaks to be encoded as `r`n (carriage return + line feed, CR-LF). Open the file in some useful editor (SciTE, Notepad++, UltraEdit-32, Vim, ...) and convert the linebreaks to CR-LF. Or use PowerShell:

(Get-Content $logpath | Out-String) -replace "`n", "`r`n" | Out-File $logpath

Create a folder and sub folder in Excel VBA

Private Sub CommandButton1_Click()
    Dim fso As Object
    Dim fldrname As String
    Dim fldrpath As String

    Set fso = CreateObject("scripting.filesystemobject")
    fldrname = Format(Now(), "dd-mm-yyyy")
    fldrpath = "C:\Temp\" & fldrname
    If Not fso.FolderExists(fldrpath) Then
        fso.createfolder (fldrpath)
    End If
End Sub

MySQL Error #1133 - Can't find any matching row in the user table

grant all on newdb.* to newuser@localhost identified by 'password';

CSS display:table-row does not expand when width is set to 100%

give on .view-type class float:left; or delete the float:right; of .view-name

edit: Wrap your div <div class="view-row"> with another div for example <div class="table">

and set the following css :

.table {
    display:table;
    width:100%;}

You have to use the table structure for correct results.

C# binary literals

Only integer and hex directly, I'm afraid (ECMA 334v4):

9.4.4.2 Integer literals Integer literals are used to write values of types int, uint, long, and ulong. Integer literals have two possible forms: decimal and hexadecimal.

To parse, you can use:

int i = Convert.ToInt32("01101101", 2);

Angular2 get clicked element id

If you want to have access to the id attribute of the button in angular 6 follow this code

`@Component({
  selector: 'my-app',
  template: `
    <button (click)="clicked($event)" id="myId">Click Me</button>
  `
})
export class AppComponent {
  clicked(event) {
    const target = event.target || event.srcElement || event.currentTarget;
    const idAttr = target.attributes.id;
    const value = idAttr.nodeValue;
  }
}`

your id in the value,

the value of value is myId.