Programs & Examples On #Umn mapserver

How to generate UL Li list from string array using jquery?

var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist')
$.each(countries, function(i)
{
    var li = $('<li/>')
        .addClass('ui-menu-item')
        .attr('role', 'menuitem')
        .appendTo(cList);
    var aaa = $('<a/>')
        .addClass('ui-all')
        .text(countries[i])
        .appendTo(li);
});

Iterating through all the cells in Excel VBA or VSTO 2005

Sub CheckValues1()
    Dim rwIndex As Integer
    Dim colIndex As Integer
    For rwIndex = 1 To 10
            For colIndex = 1 To 5
                If Cells(rwIndex, colIndex).Value <> 0 Then _
                    Cells(rwIndex, colIndex).Value = 0
            Next colIndex
    Next rwIndex
End Sub

Found this snippet on http://www.java2s.com/Code/VBA-Excel-Access-Word/Excel/Checksvaluesinarange10rowsby5columns.htm It seems to be quite useful as a function to illustrate the means to check values in cells in an ordered fashion.

Just imagine it as being a 2d Array of sorts and apply the same logic to loop through cells.

How to dismiss the dialog with click on outside of the dialog?

You can use dialog.setCanceledOnTouchOutside(true); which will close the dialog if you touch outside of the dialog.

Something like,

  Dialog dialog = new Dialog(context)
  dialog.setCanceledOnTouchOutside(true);

Or if your Dialog in non-model then,

1 - Set the flag-FLAG_NOT_TOUCH_MODAL for your dialog's window attribute

Window window = this.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);

2 - Add another flag to windows properties,, FLAG_WATCH_OUTSIDE_TOUCH - this one is for dialog to receive touch event outside its visible region.

3 - Override onTouchEvent() of dialog and check for action type. if the action type is 'MotionEvent.ACTION_OUTSIDE' means, user is interacting outside the dialog region. So in this case, you can dimiss your dialog or decide what you wanted to perform. view plainprint?

public boolean onTouchEvent(MotionEvent event)  
{  

       if(event.getAction() == MotionEvent.ACTION_OUTSIDE){  
        System.out.println("TOuch outside the dialog ******************** ");  
               this.dismiss();  
       }  
       return false;  
}  

For more info look at How to dismiss a custom dialog based on touch points? and How to dismiss your non-modal dialog, when touched outside dialog region

Redefine tab as 4 spaces

Add line
set ts=4
in
~/.vimrc file for per user
or
/etc/vimrc file for system wide

Is a Java hashmap search really O(1)?

A particular feature of a HashMap is that unlike, say, balanced trees, its behavior is probabilistic. In these cases its usually most helpful to talk about complexity in terms of the probability of a worst-case event occurring would be. For a hash map, that of course is the case of a collision with respect to how full the map happens to be. A collision is pretty easy to estimate.

pcollision = n / capacity

So a hash map with even a modest number of elements is pretty likely to experience at least one collision. Big O notation allows us to do something more compelling. Observe that for any arbitrary, fixed constant k.

O(n) = O(k * n)

We can use this feature to improve the performance of the hash map. We could instead think about the probability of at most 2 collisions.

pcollision x 2 = (n / capacity)2

This is much lower. Since the cost of handling one extra collision is irrelevant to Big O performance, we've found a way to improve performance without actually changing the algorithm! We can generalzie this to

pcollision x k = (n / capacity)k

And now we can disregard some arbitrary number of collisions and end up with vanishingly tiny likelihood of more collisions than we are accounting for. You could get the probability to an arbitrarily tiny level by choosing the correct k, all without altering the actual implementation of the algorithm.

We talk about this by saying that the hash-map has O(1) access with high probability

No server in Eclipse; trying to install Tomcat

You have probably installed Eclipse for Java Developers instead of Eclipse IDE for Enterprise Java Developers, server tab and some other are not available.

You don't have to uninstall. Just rerun eclipse-inst-win64.exe and choose Java EE IDE

JAVA EE IDE Installation

JSON Post with Customized HTTPHeader Field

if one wants to use .post() then this will set headers for all future request made with jquery

$.ajaxSetup({
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
});

then make your .post() calls as normal.

How to write an async method with out parameter?

I had the same problem as I like using the Try-method-pattern which basically seems to be incompatible to the async-await-paradigm...

Important to me is that I can call the Try-method within a single if-clause and do not have to pre-define the out-variables before, but can do it in-line like in the following example:

if (TryReceive(out string msg))
{
    // use msg
}

So I came up with the following solution:

  1. Define a helper struct:

     public struct AsyncOut<T, OUT>
     {
         private readonly T returnValue;
         private readonly OUT result;
    
         public AsyncOut(T returnValue, OUT result)
         {
             this.returnValue = returnValue;
             this.result = result;
         }
    
         public T Out(out OUT result)
         {
             result = this.result;
             return returnValue;
         }
    
         public T ReturnValue => returnValue;
    
         public static implicit operator AsyncOut<T, OUT>((T returnValue ,OUT result) tuple) => 
             new AsyncOut<T, OUT>(tuple.returnValue, tuple.result);
     }
    
  2. Define async Try-method like this:

     public async Task<AsyncOut<bool, string>> TryReceiveAsync()
     {
         string message;
         bool success;
         // ...
         return (success, message);
     }
    
  3. Call the async Try-method like this:

     if ((await TryReceiveAsync()).Out(out string msg))
     {
         // use msg
     }
    

For multiple out parameters you can define additional structs (e.g. AsyncOut<T,OUT1, OUT2>) or you can return a tuple.

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

Since 2.0.0.rc6:

forms: deprecated provideForms() and disableDeprecatedForms() functions have been removed. Please import the FormsModule or the ReactiveFormsModule from @angular/forms instead.

In short:

So, add to your app.module.ts or equivalent:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; // <== add the imports!
 
import { AppComponent }  from './app.component';
 
@NgModule({
  imports: [
    BrowserModule,
    FormsModule,                               // <========== Add this line!
    ReactiveFormsModule                        // <========== Add this line!
  ],
  declarations: [
    AppComponent
    // other components of yours
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

Failing to have one of these modules can lead to errors, including the one you face:

Can't bind to 'ngModel' since it isn't a known property of 'input'.

Can't bind to 'formGroup' since it isn't a known property of 'form'

There is no directive with "exportAs" set to "ngForm"

If you're in doubt, you can provide both the FormsModule and the ReactiveFormsModule together, but they are fully-functional separately. When you provide one of these modules, the default forms directives and providers from that module will be available to you app-wide.


Old Forms using ngControl?

If you do have those modules at your @NgModule, perhaps you are using old directives, such as ngControl, which is a problem, because there's no ngControl in the new forms. It was replaced more or less* by ngModel.

For instance, the equivalent to <input ngControl="actionType"> is <input ngModel name="actionType">, so change that in your template.

Similarly, the export in controls is not ngForm anymore, it is now ngModel. So, in your case, replace #actionType="ngForm" with #actionType="ngModel".

So the resulting template should be (===>s where changed):

<div class="form-group">
    <label for="actionType">Action Type</label>
    <select
  ===>  ngModel
  ===>  name="actionType" 
  ===>  #actionType="ngModel" 
        id="actionType" 
        class="form-control" 
        required>
        <option value=""></option>
        <option *ngFor="let actionType of actionTypes" value="{{ actionType.label }}">
            {{ actionType.label }}
        </option>
    </select> 
</div>

* More or less because not all functionality of ngControl was moved to ngModel. Some just were removed or are different now. An example is the name attribute, the very case you are having right now.

Display Image On Text Link Hover CSS Only

I did something like that:

HTML:

<p class='parent'>text text text</p>
<img class='child' src='idk.png'>

CSS:

.child {
    visibility: hidden;
}

.parent:hover .child {
    visibility: visible;
}

How to find row number of a value in R code

Instead of 1:nrow(mydata_2) you can simply use the which() function: which(mydata_2[,4] == 1578)

Although as it was pointed out above, the 3rd column contains 1578, not the fourth: which(mydata_2[,3] == 1578)

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

I don't know if this is accurate, but I have found that python/ruby works much better for scripts that have a lot of mathematical computations. Otherwise you have to use dc or some other "arbitrary precision calculator". It just becomes a very big pain. With python you have much more control over floats vs ints and it is much easier to perform a lot of computations and sometimes.

In particular, I would never work with a bash script to handle binary information or bytes. Instead I would use something like python (maybe) or C++ or even Node.JS.

Why are #ifndef and #define used in C++ header files?

This prevent from the multiple inclusion of same header file multiple time.

#ifndef __COMMON_H__
#define __COMMON_H__
//header file content
#endif

Suppose you have included this header file in multiple files. So first time __COMMON_H__ is not defined, it will get defined and header file included.

Next time __COMMON_H__ is defined, so it will not include again.

Checking whether a string starts with XXXX

Can also be done this way..

regex=re.compile('^hello')

## THIS WAY YOU CAN CHECK FOR MULTIPLE STRINGS
## LIKE
## regex=re.compile('^hello|^john|^world')

if re.match(regex, somestring):
    print("Yes")

Execute SQLite script

If you are using the windows CMD you can use this command to create a database using sqlite3

C:\sqlite3.exe DBNAME.db ".read DBSCRIPT.sql"

If you haven't a database with that name sqlite3 will create one, and if you already have one, it will run it anyways but with the "TABLENAME already exists" error, I think you can also use this command to change an already existing database (but im not sure)

How to find serial number of Android device?

For a simple number that is unique to the device and constant for its lifetime (barring a factory reset or hacking), use Settings.Secure.ANDROID_ID.

String id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);

To use the device serial number (the one shown in "System Settings / About / Status") if available and fall back to Android ID:

String serialNumber = Build.SERIAL != Build.UNKNOWN ? Build.SERIAL : Secure.getString(getContentResolver(), Secure.ANDROID_ID);

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

I just think of Rebuild as performing the Clean first followed by the Build. Perhaps I am wrong ... comments?

React-Native Button style not work

Try This one

<TouchableOpacity onPress={() => this._onPressAppoimentButton()} style={styles.Btn}>
    <Button title="Order Online" style={styles.Btn} > </Button>
</TouchableOpacity>

Each for object?

_x000D_
_x000D_
var object = { "a": 1, "b": 2};_x000D_
$.each(object, function(key, value){_x000D_
  console.log(key + ": " + object[key]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

//output
a: 1
b: 2

file path Windows format to java format

String path = "C:\\Documents and Settings\\Manoj\\Desktop";
String javaPath = path.replace("\\", "/"); // Create a new variable

or

path = path.replace("\\", "/"); // Just use the existing variable

Strings are immutable. Once they are created, you can't change them. This means replace returns a new String where the target("\\") is replaced by the replacement("/"). Simply calling replace will not change path.

The difference between replaceAll and replace is that replaceAll will search for a regex, replace doesn't.

Tab separated values in awk

Make sure they're really tabs! In bash, you can insert a tab using C-v TAB

$ echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk -F$'\t' '{print $1}'
LOAD_SETTLED

Writing a dictionary to a csv file with one line for every 'key: value'

#code to insert and read dictionary element from csv file
import csv
n=input("Enter I to insert or S to read : ")
if n=="I":
    m=int(input("Enter the number of data you want to insert: "))
    mydict={}
    list=[]
    for i in range(m):
        keys=int(input("Enter id :"))
        list.append(keys)
        values=input("Enter Name :")
        mydict[keys]=values

    with open('File1.csv',"w") as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=list)
        writer.writeheader()
        writer.writerow(mydict)
        print("Data Inserted")
else:
    keys=input("Enter Id to Search :")
    Id=str(keys)
    with open('File1.csv',"r") as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            print(row[Id]) #print(row) to display all data

Generate C# class from XML

Yes, by using xsd.exe

D:\temp>xsd test.xml
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'D:\temp\test.xsd'.

D:\temp>xsd test.xsd /classes
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'D:\temp\test.cs'.

Notes

Answer how to change directory in Developer Command Prompt to d:\temp may be useful.

If you generate classes for multi-dimensional array, there is a bug in XSD.exe generator, but there are workarounds.

Case insensitive string compare in LINQ-to-SQL

I used System.Data.Linq.SqlClient.SqlMethods.Like(row.Name, "test") in my query.

This performs a case-insensitive comparison.

Adding and removing extensionattribute to AD object

You could try using the -Clear parameter

Example:-Clear Attribute1LDAPDisplayName, Attribute2LDAPDisplayName

http://technet.microsoft.com/en-us/library/ee617215.aspx

What's NSLocalizedString equivalent in Swift?

Created a small helper method for cases, where "comment" is always ignored. Less code is easier to read:

public func NSLocalizedString(key: String) -> String {
    return NSLocalizedString(key, comment: "")
}

Just put it anywhere (outside a class) and Xcode will find this global method.

Create a file if it doesn't exist

If you don't need atomicity you can use os module:

import os

if not os.path.exists('/tmp/test'):
    os.mknod('/tmp/test')

UPDATE:

As Cory Klein mentioned, on Mac OS for using os.mknod() you need a root permissions, so if you are Mac OS user, you may use open() instead of os.mknod()

import os

if not os.path.exists('/tmp/test'):
    with open('/tmp/test', 'w'): pass

How to use XPath contains() here?

Paste my contains example here:

//table[contains(@class, "EC_result")]/tbody

How to download a file over HTTP?

If speed matters to you, I made a small performance test for the modules urllib and wget, and regarding wget I tried once with status bar and once without. I took three different 500MB files to test with (different files- to eliminate the chance that there is some caching going on under the hood). Tested on debian machine, with python2.

First, these are the results (they are similar in different runs):

$ python wget_test.py 
urlretrive_test : starting
urlretrive_test : 6.56
==============
wget_no_bar_test : starting
wget_no_bar_test : 7.20
==============
wget_with_bar_test : starting
100% [......................................................................] 541335552 / 541335552
wget_with_bar_test : 50.49
==============

The way I performed the test is using "profile" decorator. This is the full code:

import wget
import urllib
import time
from functools import wraps

def profile(func):
    @wraps(func)
    def inner(*args):
        print func.__name__, ": starting"
        start = time.time()
        ret = func(*args)
        end = time.time()
        print func.__name__, ": {:.2f}".format(end - start)
        return ret
    return inner

url1 = 'http://host.com/500a.iso'
url2 = 'http://host.com/500b.iso'
url3 = 'http://host.com/500c.iso'

def do_nothing(*args):
    pass

@profile
def urlretrive_test(url):
    return urllib.urlretrieve(url)

@profile
def wget_no_bar_test(url):
    return wget.download(url, out='/tmp/', bar=do_nothing)

@profile
def wget_with_bar_test(url):
    return wget.download(url, out='/tmp/')

urlretrive_test(url1)
print '=============='
time.sleep(1)

wget_no_bar_test(url2)
print '=============='
time.sleep(1)

wget_with_bar_test(url3)
print '=============='
time.sleep(1)

urllib seems to be the fastest

Regular Expression to match valid dates

if you didn't get those above suggestions working, I use this, as it gets any date I ran this expression through 50 links, and it got all the dates on each page.

^20\d\d-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(0[1-9]|[1-2][0-9]|3[01])$ 

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Check your system clock,

$ date

If it's not correct the certificate check will fail. To correct the system clock,

$ apt-get install ntp

The clock should synchronise itself.

Finally enter the clone command again.

Why does z-index not work?

The z-index property only works on elements with a position value other than static (e.g. position: absolute;, position: relative;, or position: fixed).

There is also position: sticky; that is supported in Firefox, is prefixed in Safari, worked for a time in older versions of Chrome under a custom flag, and is under consideration by Microsoft to add to their Edge browser.

Important
For regular positioning, be sure to include position: relative on the elements where you also set the z-index. Otherwise, it won't take effect.

Finding elements not in a list

No, z is undefined. item contains a list of integers.

I think what you're trying to do is this:

#z defined elsewhere
item = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for i in item:
  if i not in z: print i

As has been stated in other answers, you may want to try using sets.

Check if a class `active` exist on element with jquery

    if($('selector').hasClass('active')){ }

i think this will check if the selector hasClass active ...

Installation failed with message Invalid File

Try this in gradle project dependencies { classpath 'com.android.tools.build:gradle:2.2.3' }

Calculate the number of business days between two dates?

Check this 1. https://github.com/yatishbalaji/moment-working-days#readme 2. https://www.npmjs.com/package/moment-working-days

It allows you to calculate working days, considering sequence of date(s). You can customize the week off days, and also declare custom dates for holidays (eg: public holidays) to exclude them from being counted as working day(s)

How to convert string to long

Use parseLong(), e.g.:

long lg = lg.parseLong("123456789123456789");

Onclick function based on element id

you can try these:

document.getElementById("RootNode").onclick = function(){/*do something*/};

or

$('#RootNode').click(function(){/*do something*/});

or

$(document).on("click", "#RootNode", function(){/*do something*/});

There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload or DOMReady event, like:

//in Vanilla JavaScript
window.addEventListener("load", function(){
     document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
    $('#RootNode').click(function(){/*do something*/});
});

Including non-Python files with setup.py

This works in 2020!

As others said create "MANIFEST.in" where your setup.py is located.

Next in manifest include/exclude all the necessary things. Be careful here regarding the syntax. Ex: lets say we have template folder to be included in the source package.

in manifest file do this :

recursive-include template *

Make sure you leave space between dir-name and pattern for files/dirs like above. Dont do like this like we do in .gitignore

recursive-include template/* [this won't work]

Other option is to use include. There are bunch of options. Look up here at their docs for Manifest.in

And the final important step, include this param in your setup.py and you are good to go!

   setup(
    ...
    include_package_data=True,
    ......
)

Hope that helps! Happy Coding!

Iterating through a list to render multiple widgets in Flutter?

All you need to do is put it in a list and then add it as the children of the widget.

you can do something like this:

Widget listOfWidgets(List<String> item) {
  List<Widget> list = List<Widget>();
  for (var i = 0; i < item.length; i++) {
    list.add(Container(
        child: FittedBox(
          fit: BoxFit.fitWidth,
          child: Text(
            item[i],
          ),
        )));
  }
  return Wrap(
      spacing: 5.0, // gap between adjacent chips
      runSpacing: 2.0, // gap between lines
      children: list);
}

After that call like this

child: Row(children: <Widget>[
   listOfWidgets(itemList),
])

enter image description here

How can I do a BEFORE UPDATED trigger with sql server?

Can't be sure if this applied to SQL Server Express, but you can still access the "before" data even if your trigger is happening AFTER the update. You need to read the data from either the deleted or inserted table that is created on the fly when the table is changed. This is essentially what @Stamen says, but I still needed to explore further to understand that (helpful!) answer.

The deleted table stores copies of the affected rows during DELETE and UPDATE statements. During the execution of a DELETE or UPDATE statement, rows are deleted from the trigger table and transferred to the deleted table...

The inserted table stores copies of the affected rows during INSERT and UPDATE statements. During an insert or update transaction, new rows are added to both the inserted table and the trigger table...

https://msdn.microsoft.com/en-us/library/ms191300.aspx

So you can create your trigger to read data from one of those tables, e.g.

CREATE TRIGGER <TriggerName> ON <TableName>
AFTER UPDATE
AS
  BEGIN
    INSERT INTO <HistoryTable> ( <columns...>, DateChanged )
    SELECT <columns...>, getdate()
    FROM deleted;
  END;

My example is based on the one here:

http://www.seemoredata.com/en/showthread.php?134-Example-of-BEFORE-UPDATE-trigger-in-Sql-Server-good-for-Type-2-dimension-table-updates

Regular expression negative lookahead

If you revise your regular expression like this:

drupal-6.14/(?=sites(?!/all|/default)).*
             ^^

...then it will match all inputs that contain drupal-6.14/ followed by sites followed by anything other than /all or /default. For example:

drupal-6.14/sites/foo
drupal-6.14/sites/bar
drupal-6.14/sitesfoo42
drupal-6.14/sitesall

Changing ?= to ?! to match your original regex simply negates those matches:

drupal-6.14/(?!sites(?!/all|/default)).*
             ^^

So, this simply means that drupal-6.14/ now cannot be followed by sites followed by anything other than /all or /default. So now, these inputs will satisfy the regex:

drupal-6.14/sites/all
drupal-6.14/sites/default
drupal-6.14/sites/all42

But, what may not be obvious from some of the other answers (and possibly your question) is that your regex will also permit other inputs where drupal-6.14/ is followed by anything other than sites as well. For example:

drupal-6.14/foo
drupal-6.14/xsites

Conclusion: So, your regex basically says to include all subdirectories of drupal-6.14 except those subdirectories of sites whose name begins with anything other than all or default.

What is Dispatcher Servlet in Spring?

The job of the DispatcherServlet is to take an incoming URI and find the right combination of handlers (generally methods on Controller classes) and views (generally JSPs) that combine to form the page or resource that's supposed to be found at that location.

I might have

  • a file /WEB-INF/jsp/pages/Home.jsp
  • and a method on a class

    @RequestMapping(value="/pages/Home.html")
    private ModelMap buildHome() {
        return somestuff;
    }
    

The Dispatcher servlet is the bit that "knows" to call that method when a browser requests the page, and to combine its results with the matching JSP file to make an html document.

How it accomplishes this varies widely with configuration and Spring version.

There's also no reason the end result has to be web pages. It can do the same thing to locate RMI end points, handle SOAP requests, anything that can come into a servlet.

Conditionally Remove Dataframe Rows with R

Use the which function:

A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)

r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]

How to implement DrawerArrowToggle from Android appcompat v7 21 library

I want to correct little bit the above code

    public class MainActivity extends ActionBarActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
            this,  mDrawerLayout, mToolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close
        );
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

and all the other things will remain same...

For those who are having problem Drawerlayout overlaying toolbar

add android:layout_marginTop="?attr/actionBarSize" to root layout of drawer content

How to export table data in MySql Workbench to csv?

You can select the rows from the table you want to export in the MySQL Workbench SQL Editor. You will find an Export button in the resultset that will allow you to export the records to a CSV file, as shown in the following image:

MySQL Workbench Export Resultset Button

Please also keep in mind that by default MySQL Workbench limits the size of the resultset to 1000 records. You can easily change that in the Preferences dialog:

MySQL Workbench Preferences Dialog

Hope this helps.

How to dynamically change the color of the selected menu item of a web page?

I use PHP to find the URL and match the page name (without the extension of .php, also I can add multiple pages that all have the same word in common like contact, contactform, etc. All will have that class added) and add a class with PHP to change the color, etc. For that you would have to save your pages with file extension .php.

Here is a demo. Change your links and pages as required. The CSS class for all the links is .tab and for the active link there is also another class of .currentpage (as is the PHP function) so that is where you will overwrite your CSS rules. You could name them whatever you like.

<?php # Using REQUEST_URI
    $currentpage = $_SERVER['REQUEST_URI'];?>
    <div class="nav">
        <div class="tab
             <?php
                 if(preg_match("/index/i", $currentpage)||($currentpage=="/"))
                     echo " currentpage";
             ?>"><a href="index.php">Home</a>
         </div>
         <div class="tab
             <?php
                 if(preg_match("/services/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="services.php">Services</a>
         </div>
         <div class="tab
             <?php
                 if(preg_match("/about/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="about.php">About</a>
         </div>
         <div class="tab
             <?php
                 if(preg_match("/contact/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="contact.php">Contact</a>
         </div>
     </div> <!--nav-->

Indent List in HTML and CSS

You can use [Adjacent sibling combinators] as described in the W3 CSS Selectors Recommendation1 So you can use a + sign (or even a ~ tilde) apply a padding to the nested ul tag, as you described in your question and you'll get the result you need. I also think what you want it to override the main css, locally. You can do this:

<style>
    li+ul {padding-left: 20px;}
</style>

This way the inner ul will be nested including the bullets of the li elements. I wish this was helpful! =)

if, elif, else statement issues in Bash

I would recommend you having a look at the basics of conditioning in bash.

The symbol "[" is a command and must have a whitespace prior to it. If you don't give whitespace after your elif, the system interprets elif[ as a a particular command which is definitely not what you'd want at this time.

Usage:

elif(A COMPULSORY WHITESPACE WITHOUT PARENTHESIS)[(A WHITE SPACE WITHOUT PARENTHESIS)conditions(A WHITESPACE WITHOUT PARENTHESIS)]

In short, edit your code segment to:

elif [ "$seconds" -gt 0 ]

You'd be fine with no compilation errors. Your final code segment should look like this:

#!/bin/sh    
if [ "$seconds" -eq 0 ];then
       $timezone_string="Z"
    elif [ "$seconds" -gt 0 ]
    then
       $timezone_string=`printf "%02d:%02d" $seconds/3600 ($seconds/60)%60`
    else
       echo "Unknown parameter"
    fi

Import a file from a subdirectory?

I am writing this down because everyone seems to suggest that you have to create a lib directory.

You don't need to name your sub-directory lib. You can name it anything provided you put an __init__.py into it.

You can do that by entering the following command in a linux shell:

$ touch anything/__init__.py 

So now you have this structure:

$ ls anything/
__init__.py
mylib.py

$ ls
main.py

Then you can import mylib into main.py like this:

from anything import mylib 

mylib.myfun()

You can also import functions and classes like this:

from anything.mylib import MyClass
from anything.mylib import myfun

instance = MyClass()
result = myfun()

Any variable function or class you place inside __init__.py can also be accessed:

import anything

print(anything.myvar)

Or like this:

from anything import myvar

print(myvar)

Use 'class' or 'typename' for template parameters?

It doesn't matter at all, but class makes it look like T can only be a class, while it can of course be any type. So typename is more accurate. On the other hand, most people use class, so that is probably easier to read generally.

What would be the Unicode character for big bullet in the middle of the character?

If you are on Windows (Any Version)

Go to start -> then search character map

that's where you will find 1000s of characters with their Unicode in the advance view you can get more options that you can use for different encoding symbols.

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I was facing the similar type of issue: Code Snippet :

<c:forEach items="${orderList}" var="xx"> ${xx.id} <br>
</c:forEach>

There was a space after orderlist like this : "${orderList} " because of which the xx variable was getting coverted into String and was not able to call xx.id.

So make sure about space. They play crucial role sometimes. :p

HTML5 live streaming

It is not possible to use the RTMP protocol in HTML 5, because the RTMP protocol is only used between the server and the flash player. So you can use the other streaming protocols for viewing the streaming videos in HTML 5.

Django: OperationalError No Such Table

I got through the same error when I went on to the admin panel. You ought to run this instead-: python manage.py migrate --run-syncdb. Don't forget to include migrate, I ran:

python manage.py make migrations and then python manage.py migrate

Still when the error persisted I tried it with the above suggested command.

How to get the scroll bar with CSS overflow on iOS

If you are trying to achieve horizontal div scrolling with touch on mobile, the updated CSS fix does not work (tested on Android Chrome and iOS Safari multiple versions), eg:

-webkit-overflow-scrolling: touch

I found a solution and modified it for horizontal scrolling from before the CSS trick. I've tested it on Android Chrome and iOS Safari and the listener touch events have been around a long time, so it has good support: http://caniuse.com/#feat=touch.

Usage:

touchHorizScroll('divIDtoScroll');

Functions:

function touchHorizScroll(id){
    if(isTouchDevice()){ //if touch events exist...
        var el=document.getElementById(id);
        var scrollStartPos=0;

        document.getElementById(id).addEventListener("touchstart", function(event) {
            scrollStartPos=this.scrollLeft+event.touches[0].pageX;              
        },false);

        document.getElementById(id).addEventListener("touchmove", function(event) {
            this.scrollLeft=scrollStartPos-event.touches[0].pageX;              
        },false);
    }
}
function isTouchDevice(){
    try{
        document.createEvent("TouchEvent");
        return true;
    }catch(e){
        return false;
    }
}  

Modified from vertical solution (pre CSS trick):

http://chris-barr.com/2010/05/scrolling_a_overflowauto_element_on_a_touch_screen_device/

std::vector versus std::array in C++

std::vector is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed. It provides all the hooks (begin(), end(), iterators, etc) that make it work fine with the rest of the STL. It also has several useful methods that let you perform operations that on a normal array would be cumbersome, like e.g. inserting elements in the middle of a vector (it handles all the work of moving the following elements behind the scenes).

Since it stores the elements in memory allocated on the heap, it has some overhead in respect to static arrays.

std::array is a template class that encapsulate a statically-sized array, stored inside the object itself, which means that, if you instantiate the class on the stack, the array itself will be on the stack. Its size has to be known at compile time (it's passed as a template parameter), and it cannot grow or shrink.

It's more limited than std::vector, but it's often more efficient, especially for small sizes, because in practice it's mostly a lightweight wrapper around a C-style array. However, it's more secure, since the implicit conversion to pointer is disabled, and it provides much of the STL-related functionality of std::vector and of the other containers, so you can use it easily with STL algorithms & co. Anyhow, for the very limitation of fixed size it's much less flexible than std::vector.

For an introduction to std::array, have a look at this article; for a quick introduction to std::vector and to the the operations that are possible on it, you may want to look at its documentation.


  1. Actually, I think that in the standard they are described in terms of maximum complexity of the different operations (e.g. random access in constant time, iteration over all the elements in linear time, add and removal of elements at the end in constant amortized time, etc), but AFAIK there's no other method of fulfilling such requirements other than using a dynamic array. As stated by @Lucretiel, the standard actually requires that the elements are stored contiguously, so it is a dynamic array, stored where the associated allocator puts it.

Javascript can't find element by id?

The script is performed before the DOM of the body is built. Put it all into a function and call it from the onload of the body-element.

Spring MVC: how to create a default controller for index page?

Just put one more entry in your spring xml file i.e.mvc-dispatcher-servlet.xml

<mvc:view-controller path="/" view-name="index"/>

After putting this to your xml put your default view or jsp file in your custom JSP folder as you have mentioned in mvc-dispatcher-servlet.xml file.

change index with your jsp name.

How to stop default link click behavior with jQuery

You want e.preventDefault() to prevent the default functionality from occurring.

Or have return false from your method.

preventDefault prevents the default functionality and stopPropagation prevents the event from bubbling up to container elements.

ldap query for group members

The query should be:

(&(objectCategory=user)(memberOf=CN=Distribution Groups,OU=Mybusiness,DC=mydomain.local,DC=com))

You missed & and ()

How can I right-align text in a DataGridView column?

you can edit all the columns at once by using this simple code via Foreach loop

        foreach (DataGridViewColumn item in datagridview1.Columns)
        {
            item.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
        }

Illegal mix of collations error in MySql

You need to set 'utf8' for all parameters in each Function. It's my case:

enter image description here

Converting a pointer into an integer

I came across this question while studying the source code of SQLite.

In the sqliteInt.h, there is a paragraph of code defined a macro convert between integer and pointer. The author made a very good statement first pointing out it should be a compiler dependent problem and then implemented the solution to account for most of the popular compilers out there.

#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
#else                          /* Generates a warning - but it always works     */
# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(X))
#endif

And here is a quote of the comment for more details:

/*
** The following macros are used to cast pointers to integers and
** integers to pointers.  The way you do this varies from one compiler
** to the next, so we have developed the following set of #if statements
** to generate appropriate macros for a wide range of compilers.
**
** The correct "ANSI" way to do this is to use the intptr_t type.
** Unfortunately, that typedef is not available on all compilers, or
** if it is available, it requires an #include of specific headers
** that vary from one machine to the next.
**
** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
** So we have to define the macros in different ways depending on the
** compiler.
*/

Credit goes to the committers.

A function to convert null to string

You can just use the null coalesce operator.

string result = value ?? "";

How to convert date to string and to date again?

try this function

public static Date StringToDate(String strDate) throws ModuleException {
    Date dtReturn = null;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
    try {
        dtReturn = simpleDateFormat.parse(strDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dtReturn;
}

How to run single test method with phpunit?

for run phpunit test in laravel by many way ..

vendor/bin/phpunit --filter methodName className pathTofile.php

vendor/bin/phpunit --filter 'namespace\\directoryName\\className::methodName'

for test single class :

vendor/bin/phpunit --filter  tests/Feature/UserTest.php
vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest'
vendor/bin/phpunit --filter 'UserTest' 

for test single method :

 vendor/bin/phpunit --filter testExample 
 vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest::testExample'
 vendor/bin/phpunit --filter testExample UserTest tests/Feature/UserTest.php

for run tests from all class within namespace :

vendor/bin/phpunit --filter 'Tests\\Feature'

for more way run test see more

How to return a file (FileContentResult) in ASP.NET WebAPI

If you want to return IHttpActionResult you can do it like this:

[HttpGet]
public IHttpActionResult Test()
{
    var stream = new MemoryStream();

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.GetBuffer())
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "test.pdf"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    var response = ResponseMessage(result);

    return response;
}

Proxy setting for R

This post pertains to R proxy issues on *nix. You should know that R has many libraries/methods to fetch data over internet.

For 'curl', 'libcurl', 'wget' etc, just do the following:

  1. Open a terminal. Type the following command:

    sudo gedit /etc/R/Renviron.site
    
  2. Enter the following lines:

    http_proxy='http://username:[email protected]:port/'
    https_proxy='https://username:[email protected]:port/'
    

    Replace username, password, abc.com, xyz.com and port with these settings specific to your network.

  3. Quit R and launch again.

This should solve your problem with 'libcurl' and 'curl' method. However, I have not tried it with 'httr'. One way to do that with 'httr' only for that session is as follows:

library(httr)
set_config(use_proxy(url="abc.com",port=8080, username="username", password="password"))

You need to substitute settings specific to your n/w in relevant fields.

Button button = findViewById(R.id.button) always resolves to null in Android Studio

This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.

Move that piece of code in the onCreateView() method of the fragment:

//...

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        onButtonClick((Button) view);
    }
});

Notice that now you access it through rootView view:

Button buttonClick = (Button)rootView.findViewById(R.id.button);

otherwise you would get again NullPointerException.

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

To fix it, set the scope to provided. This tells Maven use code servlet-api.jar for compiling and testing only, but NOT include it in the WAR file. The deployed container will ā€œprovideā€ the servlet-api.jar at runtime.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>

Install Application programmatically on Android

I just want to share the fact that my apk file was saved to my app "Data" directory and that I needed to change the permissions on the apk file to be world readable in order to allow it to be installed that way, otherwise the system was throwing "Parse error: There is a Problem Parsing the Package"; so using solution from @Horaceman that makes:

File file = new File(dir, "App.apk");
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(intent);

Remove a cookie

Most of you are forgetting that this will only work on a local machine. On a domain you will need a pattern like this example.

setcookie("example_cookie", 'password', time()-3600, "/", $_SERVER['SERVER_NAME']);

Returning anonymous type in C#

You can use the Tuple class as a substitute for an anonymous types when returning is necessary:

Note: Tuple can have up to 8 parameters.

return Tuple.Create(variable1, variable2);

Or, for the example from the original post:

public List<Tuple<SomeType, AnotherType>> TheMethod(SomeParameter)
{
  using (MyDC TheDC = new MyDC())
  {
     var TheQueryFromDB = (....
                           select Tuple.Create(..., ...)
                           ).ToList();

      return TheQueryFromDB.ToList();
    }
}

http://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx

How to get the current time in milliseconds from C in Linux?

C11 timespec_get

It returns up to nanoseconds, rounded to the resolution of the implementation.

It is already implemented in Ubuntu 15.10. API looks the same as the POSIX clock_gettime.

#include <time.h>
struct timespec ts;
timespec_get(&ts, TIME_UTC);
struct timespec {
    time_t   tv_sec;        /* seconds */
    long     tv_nsec;       /* nanoseconds */
};

More details here: https://stackoverflow.com/a/36095407/895245

ActiveX component can't create object

I know this is an old thread, but has anyone checked if their Antivirus is blocking Win32API and Scripting on their systems? I have CylanceProtect installed on my office system and i found the same issues occurring as listed by others. This can be confirmed if you check the Windows Logs in Event Viewer.

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

A bit similar to @bpile answer, my case was a my.cnf entry setting collation-server = utf8_general_ci. After I realized that (and after trying everything above), I forcefully switched my database to utf8_general_ci instead of utf8_unicode_ci and that was it:

ALTER DATABASE `db` CHARACTER SET utf8 COLLATE utf8_general_ci;

How do you list volumes in docker containers?

Useful variation for docker-compose users:

docker-compose ps -q | xargs docker container inspect  \
   -f '{{ range .Mounts }}{{ .Name }}:{{ .Destination }} {{ end }}' 

This will very neatly output parseable volume info. Example from my wordpress docker-compose:

ubuntu@core $ docker-compose ps -q | xargs docker container inspect  -f '{{ range .Mounts }}{{ .Name }}:{{ .Destination }} {{ end }}' 
core_wpdb:/var/lib/mysql 
core_wpcode:/code core_wphtml:/var/www/html 

The output contains one line for each container, listing the volumes (and mount points) used. Alter the {{ .Name }}:{{ .Destination }} portion to output the info you would like.

If you just want a simple list of volumes, one per line

$ docker-compose ps -q | xargs docker container inspect  \
   -f '{{ range .Mounts }}{{ .Name }} {{ end }}' \
   | xargs -n 1 echo
core_wpdb
core_wpcode
core_wphtml

Great to generate a list of volumes to backup. I use this technique along with Blacklabelops Volumerize to backup all volumes used by all containers within a docker-compose. The docs for Volumerize don't call it out, but you don't need to use it in a persistent container or to use the built-in facilities for starting and stopping services. I prefer to leave critical operations such as backup and service control to the actual user (outside docker). My backups are triggered by the actual (non-docker) user account, and use docker-compose stop to stop services, backup all volumes in use, and finally docker-compose start to restart.

decompiling DEX into Java sourcecode

You might try JADX (https://bitbucket.org/mstrobel/procyon/wiki/Java%20Decompiler), this is a perfect tool for DEX decompilation.

And yes, it is also available online on (my :0)) new site: http://www.javadecompilers.com/apk/

How to check if an element of a list is a list (in Python)?

Use isinstance:

if isinstance(e, list):

If you want to check that an object is a list or a tuple, pass several classes to isinstance:

if isinstance(e, (list, tuple)):

Function overloading in Python: Missing

You don't need function overloading, as you have the *args and **kwargs arguments.

The fact is that function overloading is based on the idea that passing different types you will execute different code. If you have a dynamically typed language like Python, you should not distinguish by type, but you should deal with interfaces and their compliance with the code you write.

For example, if you have code that can handle either an integer, or a list of integers, you can try iterating on it and if you are not able to, then you assume it's an integer and go forward. Of course it could be a float, but as far as the behavior is concerned, if a float and an int appear to be the same, then they can be interchanged.

How to calculate growth with a positive and negative number?

Simplest solution is the following:

=(NEW/OLD-1)*SIGN(OLD)

The SIGN() function will result in -1 if the value is negative and 1 if the value is positive. So multiplying by that will conditionally invert the result if the previous value is negative.

How to create an array from a CSV file using PHP and the fgetcsv function

$arrayFromCSV =  array_map('str_getcsv', file('/path/to/file.csv'));

Environment variable substitution in sed

Another easy alternative:

Since $PWD will usually contain a slash /, use | instead of / for the sed statement:

sed -e "s|xxx|$PWD|"

Oracle 11g Express Edition for Windows 64bit?

It's not available yet. See this thread on the official forum.

How can I wrap or break long text/word in a fixed width span?

Try this

span {
    display: block;
    width: 150px;
}

ASP.NET MVC ActionLink and post method

This is taken from the MVC sample project

@if (ViewBag.ShowRemoveButton)
      {
         using (Html.BeginForm("RemoveLogin", "Manage"))
           {
              @Html.AntiForgeryToken()
                  <div>
                     @Html.Hidden("company_name", account)
                     @Html.Hidden("returnUrl", Model.returnUrl)
                     <input type="submit" class="btn btn-default" value="Remove" title="Remove your email address from @account" />
                  </div>
            }
        }

Why do python lists have pop() but not push()

Push is a defined stack behaviour; if you pushed A on to stack (B,C,D) you would get (A,B,C,D).

If you used python append, the resulting dataset would look like (B,C,D,A)

Edit: Wow, holy pedantry.

I would assume that it would be clear from my example which part of the list is the top, and which part is the bottom. Assuming that most of us here read from left to right, the first element of any list is always going to be on the left.

Fine control over the font size in Seaborn plots for academic papers

You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:

import seaborn as sns
tips = sns.load_dataset("tips")

b = sns.boxplot(x=tips["total_bill"])
b.axes.set_title("Title",fontsize=50)
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)
b.tick_params(labelsize=5)
sns.plt.show()

, which results in this:

Different font sizes for different labels

To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.

NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.

Convert alphabet letters to number in Python

If you are looking the opposite like 1 = A , 2 = B etc, you can use the following code. Please note that I have gone only up to 2 levels as I had to convert divisions in a class to A, B, C etc.

loopvariable = 0 
    numberofdivisions = 53
    while (loopvariable <numberofdivisions):
        if(loopvariable<26):
            print(chr(65+loopvariable))
        loopvariable +=1
        if(loopvariable > 26 and loopvariable <53):
            print(chr(65)+chr(65+(loopvariable-27)))

How to reset a timer in C#?

For System.Timers.Timer, according to MSDN documentation, http://msdn.microsoft.com/en-us/library/system.timers.timer.enabled.aspx:

If the interval is set after the Timer has started, the count is reset. For example, if you set the interval to 5 seconds and then set the Enabled property to true, the count starts at the time Enabled is set. If you reset the interval to 10 seconds when count is 3 seconds, the Elapsed event is raised for the first time 13 seconds after Enabled was set to true.

So,

    const double TIMEOUT = 5000; // milliseconds

    aTimer = new System.Timers.Timer(TIMEOUT);
    aTimer.Start();     // timer start running

    :
    :

    aTimer.Interval = TIMEOUT;  // restart the timer

How can I reverse a list in Python?

>>> l = [1, 2, 3, 4, 5]
>>> print(reduce(lambda acc, x: [x] + acc, l, []))
[5, 4, 3, 2, 1]

How to remove leading and trailing spaces from a string

 static void Main()
    {
        // A.
        // Example strings with multiple whitespaces.
        string s1 = "He saw   a cute\tdog.";
        string s2 = "There\n\twas another sentence.";

        // B.
        // Create the Regex.
        Regex r = new Regex(@"\s+");

        // C.
        // Strip multiple spaces.
        string s3 = r.Replace(s1, @" ");
        Console.WriteLine(s3);

        // D.
        // Strip multiple spaces.
        string s4 = r.Replace(s2, @" ");
        Console.WriteLine(s4);
        Console.ReadLine();
    }

OUTPUT:

He saw a cute dog. There was another sentence. He saw a cute dog.

Remove Duplicate objects from JSON Array

Javascript solution for your case:

console.log(unique(standardsList));

function unique(obj){
    var uniques=[];
    var stringify={};
    for(var i=0;i<obj.length;i++){
       var keys=Object.keys(obj[i]);
       keys.sort(function(a,b) {return a-b});
       var str='';
        for(var j=0;j<keys.length;j++){
           str+= JSON.stringify(keys[j]);
           str+= JSON.stringify(obj[i][keys[j]]);
        }
        if(!stringify.hasOwnProperty(str)){
            uniques.push(obj[i]);
            stringify[str]=true;
        }
    }
    return uniques;
}

Java function for arrays like PHP's join()?

Not in core, no. A search for "java array join string glue" will give you some code snippets on how to achieve this though.

e.g.

public static String join(Collection s, String delimiter) {
    StringBuffer buffer = new StringBuffer();
    Iterator iter = s.iterator();
    while (iter.hasNext()) {
        buffer.append(iter.next());
        if (iter.hasNext()) {
            buffer.append(delimiter);
        }
    }
    return buffer.toString();
}

How can I import data into mysql database via mysql workbench?

For MySQL Workbench 8.0 navigate to:

Server > Data Import

A new tab called Administration - Data Import/Restore appears. There you can choose to import a Dump Project Folder or use a specific SQL file according to your needs. Then you must select a schema where the data will be imported to, or you have to click the New... button to type a name for the new schema.

Then you can select the database objects to be imported or just click the Start Import button in the lower right part of the tab area.

Having done that and if the import was successful, you'll need to update the Schema Navigator by clicking the arrow circle icon.

That's it!

For more detailed info, check the MySQL Workbench Manual: 6.5.2 SQL Data Export and Import Wizard

JavaScript get clipboard data on paste event (Cross browser)

$('#dom').on('paste',function (e){
    setTimeout(function(){
        console.log(e.currentTarget.value);
    },0);
});

C#: how to get first char of a string?

You can use LINQ

char c = mystring.FirstOrDefault()

It will be equal to '\0' if the string is empty.

How get all values in a column using PHP?

Since mysql_* are deprecated, so here is the solution using mysqli.

$mysqli = new mysqli('host', 'username', 'password', 'database');
if($mysqli->connect_errno>0)
{
  die("Connection to MySQL-server failed!"); 
}
$resultArr = array();//to store results
//to execute query
$executingFetchQuery = $mysqli->query("SELECT `name` FROM customers WHERE 1");
if($executingFetchQuery)
{
   while($arr = $executingFetchQuery->fetch_assoc())
   {
        $resultArr[] = $arr['name'];//storing values into an array
   }
}
print_r($resultArr);//print the rows returned by query, containing specified columns

There is another way to do this using PDO

  $db = new PDO('mysql:host=host_name;dbname=db_name', 'username', 'password'); //to establish a connection
  //to fetch records
  $fetchD = $db->prepare("SELECT `name` FROM customers WHERE 1");
  $fetchD->execute();//executing the query
  $resultArr = array();//to store results
  while($row = $fetchD->fetch())
  {
     $resultArr[] = $row['name'];
  }
  print_r($resultArr);

How to get the correct range to set the value to a cell?

Solution : SpreadsheetApp.getActiveSheet().getRange('F2').setValue('hello')

Explanation :

Setting value in a cell in spreadsheet to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in sheet which is open currently and to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet name known)

SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet position known)

SpreadsheetApp.openById(SHEET_ID).getSheets()[POSITION].getRange(RANGE).setValue(VALUE);

These are constants, you must define them yourself

SHEET_ID

SHEET_NAME

POSITION

VALUE

RANGE

By script attached to a sheet I mean that script is residing in the script editor of that sheet. Not attached means not residing in the script editor of that sheet. It can be in any other place.

Copying text outside of Vim with set mouse=a enabled

If you are using, Putty session, then it automatically copies selection. If we have used "set mouse=a" option in vim, selecting using Shift+Mouse drag selects the text automatically. Need to check in X-term.

nginx missing sites-available directory

I tried sudo apt install nginx-full. You will get all the required packages.

RegEx: Grabbing values between quotation marks

I've been using the following with great success:

(["'])(?:(?=(\\?))\2.)*?\1

It supports nested quotes as well.

For those who want a deeper explanation of how this works, here's an explanation from user ephemient:

([""']) match a quote; ((?=(\\?))\2.) if backslash exists, gobble it, and whether or not that happens, match a character; *? match many times (non-greedily, as to not eat the closing quote); \1 match the same quote that was use for opening.

How to block users from closing a window in Javascript?

What will you do when a user hits ALT + F4 or closes it from Task Manager

Why don't you keep track if they did not complete it in a cookie or the DB and when they visit next time just bring the same screen back...:BTW..you haven't finished filling this form out..."

Of course if you were around before the dotcom bust you would remember porn storms, where if you closed 1 window 15 others would open..so yes there is code that will detect a window closing but if you hit ALT + F4 twice it will close the child and the parent (if it was a popup)

MySQL join with where clause

Try this

  SELECT *
    FROM categories
    LEFT JOIN user_category_subscriptions 
         ON user_category_subscriptions.category_id = categories.category_id 
   WHERE user_category_subscriptions.user_id = 1 
          or user_category_subscriptions.user_id is null

if condition in sql server update query

Something like this should work:

UPDATE
    table_Name
SET 
  column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
  column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
    ID = @ID

Refresh image with a new one at the same url

I improved the script from AlexMA for showing my webcam on a web page wich periodically uploads a new image with the same name. I had issues that sometimes the image was flickering because of a broken image or not complete (up)loaded image. To prevent flickering I check the natural height of the image because the size of my webcam image did not change. Only if the loaded image height fits the original image height the full image will be shown on page.

  <h3>Webcam</h3>
  <p align="center">
    <img id="webcam" title="Webcam" onload="updateImage();" src="https://www.your-domain.com/webcam/current.jpg" alt="webcam image" width="900" border="0" />

    <script type="text/javascript" language="JavaScript">

    // off-screen image to preload next image
    var newImage = new Image();
    newImage.src = "https://www.your-domain.com/webcam/current.jpg";

    // remember the image height to prevent showing broken images
    var height = newImage.naturalHeight;

    function updateImage()
    {
        // for sure if the first image was a broken image
        if(newImage.naturalHeight > height)
        {
          height = newImage.naturalHeight;
        }

        // off-screen image loaded and the image was not broken
        if(newImage.complete && newImage.naturalHeight == height) 
        {
          // show the preloaded image on page
          document.getElementById("webcam").src = newImage.src;
        }

        // preload next image with cachebreaker
        newImage.src = "https://www.your-domain.com/webcam/current.jpg?time=" + new Date().getTime();

        // refresh image (set the refresh interval to half of webcam refresh, 
        // in my case the webcam refreshes every 5 seconds)
        setTimeout(updateImage, 2500);
    }

    </script>
</p>

How do I get the find command to print out the file size with the file name?

Using gnu find, I think this is what you want. It finds all real files and not directories (-type f), and for each one prints the filename (%p), a tab (\t), the size in kilobytes (%k), the suffix " KB", and then a newline (\n).

find . -type f -printf '%p\t%k KB\n'

If the printf command doesn't format things the way you want, you can use exec, followed by the command you want to execute on each file. Use {} for the filename, and terminate the command with a semicolon (;). On most shells, all three of those characters should be escaped with a backslash.

Here's a simple solution that finds and prints them out using "ls -lh", which will show you the size in human-readable form (k for kilobytes, M for megabytes):

find . -type f -exec ls -lh \{\} \;

As yet another alternative, "wc -c" will print the number of characters (bytes) in the file:

find . -type f -exec wc -c \{\} \;

How do you find the current user in a Windows environment?

You can use the username variable: %USERNAME%

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

How can we redirect a Java program console output to multiple files?

To solve the problem I use ${string_prompt} variable. It shows a input dialog when application runs. I can set the date/time manually at that dialog.

  1. Move cursor at the end of file path. enter image description here

  2. Click variables and select string_prompt enter image description here

  3. Select Apply and Run enter image description here enter image description here

jQuery - Appending a div to body, the body is the object?

$('</div>').attr('id', 'holdy').appendTo('body');

Best Way to read rss feed in .net Using C#

Use this :

private string GetAlbumRSS(SyndicationItem album)
    {

        string url = "";
        foreach (SyndicationElementExtension ext in album.ElementExtensions)
            if (ext.OuterName == "itemRSS") url = ext.GetObject<string>();
        return (url);

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string albumRSS;
        string url = "http://www.SomeSite.com/rss?";
        XmlReader r = XmlReader.Create(url);
        SyndicationFeed albums = SyndicationFeed.Load(r);
        r.Close();
        foreach (SyndicationItem album in albums.Items)
        {

            cell.InnerHtml = cell.InnerHtml +string.Format("<br \'><a href='{0}'>{1}</a>", album.Links[0].Uri, album.Title.Text);
            albumRSS = GetAlbumRSS(album);

        }



    }

What is the best way to auto-generate INSERT statements for a SQL Server table?

If you'd rather use Google Sheets, use SeekWell to Send the table to a Sheet, then insert rows on a schedule, as they're added to the Sheet.

See here for the step by step process , or watch a video demo of the feature here.

Custom alert and confirm box in jquery

Try using SweetAlert its just simply the best . You will get a lot of customization and flexibility.

Confirm Example

sweetAlert(
  {
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",   
    showCancelButton: true,   
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, delete it!"
  }, 
  deleteIt()
);

Sample Alert

Warning: comparison with string literals results in unspecified behaviour

This an old question, but I have had to explain it to someone recently and I thought recording the answer here would be helpful at least in understanding how C works.

String literals like

"a"

or

"This is a string"

are put in the text or data segments of your program.

A string in C is actually a pointer to a char, and the string is understood to be the subsequent chars in memory up until a NUL char is encountered. That is, C doesn't really know about strings.

So if I have

char *s1 = "This is a string";

then s1 is a pointer to the first byte of the string.

Now, if I have

char *s2 = "This is a string";

this is also a pointer to the same first byte of that string in the text or data segment of the program.

But if I have

char *s3 = malloc( 17 );
strcpy(s3, "This is a string");

then s3 is a pointer to another place in memory into which I copy all the bytes of the other strings.

Illustrative examples:

Although, as your compiler rightly points out, you shouldn't do this, the following will evaluate to true:

s1 == s2 // True: we are comparing two pointers that contain the same address

but the following will evaluate to false

s1 == s3 // False: Comparing two pointers that don't hold the same address.

And although it might be tempting to have something like this:

struct Vehicle{
    char *type;
    // other stuff
}

if( type == "Car" )
   //blah1
else if( type == "Motorcycle )
   //blah2

You shouldn't do it because it's not something that is guarantied to work. Even if you know that type will always be set using a string literal.

I have tested it and it works. If I do

A.type = "Car";

then blah1 gets executed and similarly for "Motorcycle". And you'd be able to do things like

if( A.type == B.type )

but this is just terrible. I'm writing about it because I think it's interesting to know why it works, and it helps understand why you shouldn't do it.

Solutions:

In your case, what you want to do is use strcmp(a,b) == 0 to replace a == b

In the case of my example, you should use an enum.

enum type {CAR = 0, MOTORCYCLE = 1}

The preceding thing with string was useful because you could print the type, so you might have an array like this

char *types[] = {"Car", "Motorcycle"};

And now that I think about it, this is error prone since one must be careful to maintain the same order in the types array.

Therefore it might be better to do

char *getTypeString(int type)
{
    switch(type)
    case CAR: return "Car";
    case MOTORCYCLE: return "Motorcycle"
    default: return NULL;
}

Export to CSV using jQuery and html

From what I understand, you have your data on a table and you want to create the CSV from that data. However, you have problem creating the CSV.

My thoughts would be to iterate and parse the contents of the table and generate a string from the parsed data. You can check How to convert JSON to CSV format and store in a variable for an example. You are using jQuery in your example so that would not count as an external plugin. Then, you just have to serve the resulting string using window.open and use application/octetstream as suggested.

How to assign an exec result to a sql variable?

I had the same question. While there are good answers here I decided to create a table-valued function. With a table (or scalar) valued function you don't have to change your stored proc. I simply did a select from the table-valued function. Note that the parameter (MyParameter is optional).

CREATE FUNCTION [dbo].[MyDateFunction] 
(@MyParameter varchar(max))
RETURNS TABLE 
AS
RETURN 
(
    --- Query your table or view or whatever and select the results.
    SELECT DateValue FROM MyTable WHERE ID = @MyParameter;
)

To assign to your variable you simply can do something like:

Declare @MyDate datetime;
SET @MyDate = (SELECT DateValue FROM MyDateFunction(@MyParameter));

You can also use a scalar valued function:

CREATE FUNCTION TestDateFunction()  
RETURNS datetime  
BEGIN  
    RETURN (SELECT GetDate());
END

Then you can simply do

Declare @MyDate datetime;
SET @MyDate = (Select dbo.TestDateFunction());
SELECT @MyDate;

In C - check if a char exists in a char array

The less well-known but extremely useful (and standard since C89 — meaning 'forever') functions in the C library provide the information in a single call. Actually, there are multiple functions — an embarrassment of riches. The relevant ones for this are:

7.21.5.3 The strcspn function

Synopsis

#include <string.h>
size_t strcspn(const char *s1, const char *s2);

Description

The strcspn function computes the length of the maximum initial segment of the string pointed to by s1 which consists entirely of characters not from the string pointed to by s2.

Returns

The strcspn function returns the length of the segment.

7.21.5.4 The strpbrk function

Synopsis

#include <string.h>
char *strpbrk(const char *s1, const char *s2);

Description

The strpbrk function locates the first occurrence in the string pointed to by s1 of any character from the string pointed to by s2.

Returns

The strpbrk function returns a pointer to the character, or a null pointer if no character from s2 occurs in s1.

The question asks about 'for each char in string ... if it is in list of invalid chars'.

With these functions, you can write:

size_t len = strlen(test);
size_t spn = strcspn(test, "invald");

if (spn != len) { ...there's a problem... }

Or:

if (strpbrk(test, "invald") != 0) { ...there's a problem... }

Which is better depends on what else you want to do. There is also the related strspn() function which is sometimes useful (whitelist instead of blacklist).

What is the difference between Set and List?

List

  1. Is an Ordered grouping of elements.
  2. List is used to collection of elements with duplicates.
  3. New methods are defined inside List interface.

Set

  1. Is an Unordered grouping of elements.
  2. Set is used to collection of elements without duplicates.
  3. No new methods are defined inside Set interface, so we have to use Collection interface methods only with Set subclasses.

Convert string to JSON array

Using json lib:-

String data="[{"A":"a","B":"b","C":"c","D":"d","E":"e","F":"f","G":"g"}]";
Object object=null;
JSONArray arrayObj=null;
JSONParser jsonParser=new JSONParser();
object=jsonParser.parse(data);
arrayObj=(JSONArray) object;
System.out.println("Json object :: "+arrayObj);

Using GSON lib:-

Gson gson = new Gson();
String data="[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":\"d\",\"E\":\"e\",\"F\":\"f\",\"G\":\"g\"}]";
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(data);

How to ignore a particular directory or file for tslint?

add the section in your code example

"linterOptions": {
"exclude": [
  "node_modules/**/*.",
  "db/**/*.",
  "integrations/**/*."
]

},

How do I view executed queries within SQL Server Management Studio?

More clear query, targeting Studio sql queries is :

SELECT text  FROM sys.dm_exec_sessions es
  INNER JOIN sys.dm_exec_connections ec
      ON es.session_id = ec.session_id
  CROSS APPLY sys.dm_exec_sql_text(ec.most_recent_sql_handle) 
  where program_name like '%Query'

HTML Input - already filled in text

You seem to look for the input attribute value, "the initial value of the control"?

<input type="text" value="Morlodenhof 7" />

https://developer.mozilla.org/de/docs/Web/HTML/Element/Input#attr-value

Multiple Java versions running concurrently under Windows

Invoking Java with "java -version:1.5", etc. should run with the correct version of Java. (Obviously replace 1.5 with the version you want.)

If Java is properly installed on Windows there are paths to the vm for each version stored in the registry which it uses so you don't need to mess about with environment versions on Windows.

How to display images from a folder using php - PHP

Here is a possible solution the solution #3 on my comments to blubill's answer:

yourscript.php
========================
<?php
    $dir = '/home/user/Pictures';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if (file_exists($dir) == false) 
    {
        echo 'Directory "', $dir, '" not found!';
    } 
    else 
    {
        $dir_contents = scandir($dir);

        foreach ($dir_contents as $file) 
        {
            $file_type = strtolower(end(explode('.', $file)));
            if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true)     
            {
                $name = basename($file);
                echo "<img src='img.php?name={$name}' />";
            }
        }
    }
?>


img.php
========================
<?php
    $name = $_GET['name'];
    $mimes = array
    (
        'jpg' => 'image/jpg',
        'jpeg' => 'image/jpg',
        'gif' => 'image/gif',
        'png' => 'image/png'
    );

    $ext = strtolower(end(explode('.', $name)));

    $file = '/home/users/Pictures/'.$name;
    header('content-type: '. $mimes[$ext]);
    header('content-disposition: inline; filename="'.$name.'";');
    readfile($file);
?>

What exactly is Apache Camel?

My take to describe this in a more accessible way...

In order to understand what Apache Camel is, you need to understand what Enterprise Integration Patterns are.

Let's start with what we presumably already know: The Singleton pattern, the Factory pattern, etc; They are merely ways of organizing your solution to the problem, but they are not solutions themselves. These patterns were analyzed and extracted for the rest of us by the Gang of Four, when they published their book: Design Patterns. They saved some of us tremendous effort in thinking of how to best structure our code.

Much like the Gang of Four, Gregor Hohpe and Bobby Woolf authored the book Enterprise Integration Patterns (EIP) in which they propose and document a set of new patterns and blueprints for how we could best design large component-based systems, where components can be running on the same process or in a different machine.

They basically propose that we structure our system to be message oriented -- where components communicate with each others using messages as inputs and outputs and absolutely nothing else. They show us a complete set of patterns that we may choose from and implement in our different components that will together form the whole system.

So what is Apache Camel?

Apache Camel offers you the interfaces for the EIPs, the base objects, commonly needed implementations, debugging tools, a configuration system, and many other helpers which will save you a ton of time when you want to implement your solution to follow the EIPs.

Take MVC. MVC is pretty simple in theory and we could implement it without any framework help. But good MVC frameworks provide us with the structure ready-to-use and have gone the extra mile and thought out all the other "side" things you need when you create a large MVC project and that's why we use them most of the time.

That's exactly what Apache Camel is for EIPs. It's a complete production-ready framework for people who want to implement their solution to follow the EIPs.

Open page in new window without popup blocking

function openLinkNewTab (url){
    $('body').append('<a id="openLinkNewTab" href="' + url + '" target="_blank"><span></span></a>').find('#openLinkNewTab span').click().remove();
}

Java ArrayList clear() function

Your assumptions don't seem to be right. After a clear(), the newly added data start from index 0.

XPath selecting a node with some attribute value equals to some other node's attribute value

I think this is what you want:

/grand/parent/child[@id="#grand"]

CodeIgniter: "Unable to load the requested class"

I had a similar issue when deploying from OSx on my local to my Linux live site.

It ran fine on OSx, but on Linux I was getting:

An Error Was Encountered

Unable to load the requested class: Ckeditor

The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".

I also changed my load call to match the capitalization:

$this->load->library('CKEditor');

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:

src("'js/**/!(*.min).js")

Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

How should I remove all the leading spaces from a string? - swift

Swift 4, 4.2 and 5

Remove space from front and end only

let str = "  Akbar Code  "
let trimmedString = str.trimmingCharacters(in: .whitespacesAndNewlines)

Remove spaces from every where in the string

let stringWithSpaces = " The Akbar khan code "
let stringWithoutSpaces = stringWithSpaces.replacingOccurrences(of: " ", with: "")

How to Define Callbacks in Android?

In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the OnClickListener.

Just as a random example:

// The callback interface
interface MyCallback {
    void callbackCall();
}

// The class that takes the callback
class Worker {
   MyCallback callback;

   void onEvent() {
      callback.callbackCall();
   }
}

// Option 1:

class Callback implements MyCallback {
   void callbackCall() {
      // callback code goes here
   }
}

worker.callback = new Callback();

// Option 2:

worker.callback = new MyCallback() {

   void callbackCall() {
      // callback code goes here
   }
};

I probably messed up the syntax in option 2. It's early.

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

Can an Android NFC phone act as an NFC tag?

Its possible to make Android device behave as an NFC Tag. Such a behaviour is called Card Emulation.

  • Card emulation can be host-based(HCE) or secure-element based(CE).
  • In HCE, an application running on the Android main processor responds to the reader. So, the phone needs to be ON.
  • In CE, an applet residing in the Secure element responds to the reader. Here, its sufficient to have the NFC controller powered, with rest of the device suspended.
  • One of these or both approaches can be active simultaneously.
    A routing table instructs the NFC controller where route the Reader's commands to.

How can I copy columns from one sheet to another with VBA in Excel?

Selecting is often unnecessary. Try this

Sub OneCell()
    Sheets("Sheet2").range("B1:B3").value = Sheets("Sheet1").range("A1:A3").value
End Sub

Fast query runs slow in SSRS

I had the same problem, here is my description of the problem

"I created a store procedure which would generate 2200 Rows and would get executed in almost 2 seconds however after calling the store procedure from SSRS 2008 and run the report it actually never ran and ultimately I have to kill the BIDS (Business Intelligence development Studio) from task manager".

What I Tried: I tried running the SP from reportuser Login but SP was running normal for that user as well, I checked Profiler but nothing worked out.

Solution:

Actually the problem is that even though SP is generating the result but SSRS engine is taking time to read these many rows and render it back. So I added WITH RECOMPILE option in SP and ran the report .. this is when miracle happened and my problem got resolve.

Mocking a class: Mock() or patch()?

I've got a YouTube video on this.

Short answer: Use mock when you're passing in the thing that you want mocked, and patch if you're not. Of the two, mock is strongly preferred because it means you're writing code with proper dependency injection.

Silly example:

# Use a mock to test this.
my_custom_tweeter(twitter_api, sentence):
    sentence.replace('cks','x')   # We're cool and hip.
    twitter_api.send(sentence)

# Use a patch to mock out twitter_api. You have to patch the Twitter() module/class 
# and have it return a mock. Much uglier, but sometimes necessary.
my_badly_written_tweeter(sentence):
    twitter_api = Twitter(user="XXX", password="YYY")
    sentence.replace('cks','x') 
    twitter_api.send(sentence)

How do I select a sibling element using jQuery?

jQuery provides a method called "siblings()" which helps us to return all sibling elements of the selected element. For example, if you want to apply CSS to the sibling selectors, you can use this method. Below is an example which illustrates this. You can try this example and play with it to learn how it works.

$("p").siblings("h4").css({"color": "red", "border": "2px solid red"});

How to send JSON instead of a query string with $.ajax?

If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"

Original post here

Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

Getting the absolute path of the executable, using C#?

"Gets the path or UNC location of the loaded file that contains the manifest."

See: http://msdn.microsoft.com/en-us/library/system.reflection.assembly.location.aspx

Application.ResourceAssembly.Location

Unstage a deleted file in git

Both questions are answered in git status.

To unstage adding a new file use git rm --cached filename.ext

# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#   new file:   test

To unstage deleting a file use git reset HEAD filename.ext

# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   deleted:    test

In the other hand, git checkout -- never unstage, it just discards non-staged changes.

How can I find script's directory?

Try sys.path[0].

To quote from the Python docs:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

Source: https://docs.python.org/library/sys.html#sys.path

align right in a table cell with CSS

How to position block elements in a td cell

The answers provided do a great job to right-align text in a td cell.

This might not be the solution when you're looking to align a block element as commented in the accepted answer. To achieve such with a block element, I have found it useful to make use of margins;

general syntax

selector {
  margin: top right bottom left;
}

justify right

td {
  /* there is a shorthand, TODO!  */
  margin: auto 0 auto auto;
}

justify center

td {
  margin: auto auto auto auto;
}

/* or the short-hand */
margin: auto;

align center

td {
  margin: auto;
}

JS Fiddle example

Alternatively, you could make you td content display inline-block if that's an option, but that may distort the position of its child elements.

How to rename uploaded file before saving it into a directory?

You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file.

Instead of

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);

Use

$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

Changed to reflect your question, will product a random number based on the current time and append the extension from the originally uploaded file.

AFNetworking Post Request

for login screen;

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary 

dictionaryWithObjectsAndKeys:_usernametf.text, @"username",_passwordtf.text, @"password", nil];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];

[manager POST:@"enter your url" parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"%@", responseObject);

}
      failure:^(NSURLSessionTask *operation, NSError *error) {
          NSLog(@"Error: %@", error);
      }];

}

Filter Linq EXCEPT on properties

MoreLinq has something useful for this MoreLinq.Source.MoreEnumerable.ExceptBy

https://github.com/gsscoder/morelinq/blob/master/MoreLinq/ExceptBy.cs

namespace MoreLinq
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    static partial class MoreEnumerable
    {
        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector)
        {
            return ExceptBy(first, second, keySelector, null);
        }

        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <param name="keyComparer">The equality comparer to use to determine whether or not keys are equal.
        /// If null, the default equality comparer for <c>TSource</c> is used.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            if (first == null) throw new ArgumentNullException("first");
            if (second == null) throw new ArgumentNullException("second");
            if (keySelector == null) throw new ArgumentNullException("keySelector");
            return ExceptByImpl(first, second, keySelector, keyComparer);
        }

        private static IEnumerable<TSource> ExceptByImpl<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            var keys = new HashSet<TKey>(second.Select(keySelector), keyComparer);
            foreach (var element in first)
            {
                var key = keySelector(element);
                if (keys.Contains(key))
                {
                    continue;
                }
                yield return element;
                keys.Add(key);
            }
        }
    }
}

How to set date format in HTML date input tag?

Here is the solution:

  <input type="text" id="end_dt"/>

$(document).ready(function () {
    $("#end_dt").datepicker({ dateFormat: "MM/dd/yyyy" });
});

hopefully this will resolve the issue :)

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

Git: add vs push vs commit

add tells git to start tracking a file.

commit commits your current changes on your local repository

push pushes you local repo upstream.

How do you run CMD.exe under the Local System Account?

Using task scheduler, schedule a run of CMDKEY running under SYSTEM with the appropriate arguments of /add: /user: and /pass:

No need to install anything.

The maximum value for an int type in Go

From math lib: https://github.com/golang/go/blob/master/src/math/const.go#L39

package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Printf("max int64: %d\n", math.MaxInt64)
}

How can I get a list of all values in select box?

As per the DOM structure you can use below code:

var x = document.getElementById('mySelect');
     var txt = "";
     var val = "";
     for (var i = 0; i < x.length; i++) {
         txt +=x[i].text + ",";
         val +=x[i].value + ",";
      }

How to fully delete a git repository created with init?

Alternative to killing TortoiseGit:

  • Open the TortoiseGit-Settings (right click to any folder, TortoiseGit → Settings)
  • Go to the Icon Overlays option.
  • Change the Status Cache from Default to None
  • Now you can delete the directory (either with Windows Explorer or rmdir /S /Q)
  • Set back the Status Cache from None to Default and you should be fine again...

CSS - How to Style a Selected Radio Buttons Label?

As there is currently no CSS solution to style a parent, I use a simple jQuery one here to add a class to a label with checked input inside it.

$(document).on("change","input", function(){
 $("label").removeClass("checkedlabel");
 if($(this).is(":checked")) $(this).closest("label").addClass("checkedlabel");
});

Don't forget to give the pre-checked input's label the class checkedlabel too

T-SQL get SELECTed value of stored procedure

There is also a combination, you can use a return value with a recordset:

--Stored Procedure--

CREATE PROCEDURE [TestProc]

AS
BEGIN

    DECLARE @Temp TABLE
    (
        [Name] VARCHAR(50)
    )

    INSERT INTO @Temp VALUES ('Mark') 
    INSERT INTO @Temp VALUES ('John') 
    INSERT INTO @Temp VALUES ('Jane') 
    INSERT INTO @Temp VALUES ('Mary') 

    -- Get recordset
    SELECT * FROM @Temp

    DECLARE @ReturnValue INT
    SELECT @ReturnValue = COUNT([Name]) FROM @Temp

    -- Return count
    RETURN @ReturnValue

END

--Calling Code--

DECLARE @SelectedValue int
EXEC @SelectedValue = [TestProc] 

SELECT @SelectedValue

--Results--

enter image description here

Can't update data-attribute value

If we wanted to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:

JavaScript

<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'

// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>

Through jQuery

// Fetching data
var fruitCount = $(this).data('fruit');

// Above does not work in firefox. So use below to get attribute value.
var fruitCount = $(this).attr('data-fruit');

// Assigning data
$(this).data('fruit','7');

// But when you get the value again, it will return old value. 
// You have to set it as below to update value. Then you will get updated value.
$(this).attr('data-fruit','7'); 

Read this documentation for vanilla js or this documentation for jquery

Get and Set a Single Cookie with Node.js HTTP Server

Cookies are transfered through HTTP-Headers
You'll only have to parse the request-headers and put response-headers.

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

I tried a few things in this scenario.

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

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

Hopefully you can try the same and get some resolution?

SignalR Console app example

To build on @dyslexicanaboko's answer for dotnet core, here is a client console application:

Create a helper class:

using System;
using Microsoft.AspNetCore.SignalR.Client;

namespace com.stackoverflow.SignalRClientConsoleApp
{
    public class SignalRConnection
    {
        public async void Start()
        {
            var url = "http://signalr-server-url/hubname";

            var connection = new HubConnectionBuilder()
                .WithUrl(url)
                .WithAutomaticReconnect()
                .Build();

            // receive a message from the hub
            connection.On<string, string>("ReceiveMessage", (user, message) => OnReceiveMessage(user, message));

            var t = connection.StartAsync();

            t.Wait();

            // send a message to the hub
            await connection.InvokeAsync("SendMessage", "ConsoleApp", "Message from the console app");
        }

        private void OnReceiveMessage(string user, string message)
        {
            Console.WriteLine($"{user}: {message}");
        }

    }
}

Then implement in your console app's entry point:

using System;

namespace com.stackoverflow.SignalRClientConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var signalRConnection = new SignalRConnection();
            signalRConnection.Start();

            Console.Read();
        }
    }
}

Where do I find some good examples for DDD?

Not source projects per say but I stumbled upon Parleys.com which has a few good videos that cover DDD quite well (requires flash):

I found these much more helpful than the almost non-existent DDD examples that are currently available.

What are the differences between the different saving methods in Hibernate?

None of the following answers are right. All these methods just seem to be alike, but in practice do absolutely different things. It is hard to give short comments. Better to give a link to full documentation about these methods: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html

YAML Multi-Line Arrays

If what you are needing is an array of arrays, you can do this way:

key:
  - [ 'value11', 'value12', 'value13' ]
  - [ 'value21', 'value22', 'value23' ]

How to install a specific version of package using Composer?

As @alucic mentioned, use:

composer require vendor/package:version

or you can use:

composer update vendor/package:version

You should probably review this StackOverflow post about differences between composer install and composer update.

Related to question about version numbers, you can review Composer documentation on versions, but here in short:

  • Tilde Version Range (~) - ~1.2.3 is equivalent to >=1.2.3 <1.3.0
  • Caret Version Range (^) - ^1.2.3 is equivalent to >=1.2.3 <2.0.0

So, with Tilde you will get automatic updates of patches but minor and major versions will not be updated. However, if you use Caret you will get patches and minor versions, but you will not get major (breaking changes) versions.

Tilde Version is considered a "safer" approach, but if you are using reliable dependencies (well-maintained libraries) you should not have any problems with Caret Version (because minor changes should not be breaking changes.

How to set password for Redis?

using redis-cli:

root@server:~# redis-cli 
127.0.0.1:6379> CONFIG SET requirepass secret_password
OK

this will set password temporarily (until redis or server restart)

test password:

root@server:~# redis-cli 
127.0.0.1:6379> AUTH secret_password
OK

Pass Javascript variable to PHP via ajax

Alternatively, try removing "data" and making the URL "logtime.php?userID="+userId

I like Brian's answer better, this answer is just because you're trying to use URL parameter syntax in "data" and I wanted to demonstrate where you can use that syntax correctly.

printf format specifiers for uint32_t and size_t

If you don't want to use the PRI* macros, another approach for printing ANY integer type is to cast to intmax_t or uintmax_t and use "%jd" or %ju, respectively. This is especially useful for POSIX (or other OS) types that don't have PRI* macros defined, for instance off_t.

Conversion failed when converting the varchar value to data type int in sql

Your problem seams to be located here:

SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,LEN(Voucher_No)- LEN(@Prefix)) AS INT)) AS varchar(100)) FROM dbo.Journal_Entry;
SET @sCode=CAST(@maxCode AS INT)

As the error says, you're casting a string that contains a letter 'J' to an INT which for obvious reasons is not possible.

Either fix SUBSTRING or don't store the letter 'J' in the database and only prepend it when reading.

Jackson with JSON: Unrecognized field, not marked as ignorable

This works better than All please refer to this property.

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    projectVO = objectMapper.readValue(yourjsonstring, Test.class);

Error: "Could Not Find Installable ISAM"

Use this connection string

string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
      "Data Source=" + strFileName + ";" + "Extended Properties=" + "\"" + "Excel 12.0;HDR=YES;" + "\"";

How to enable CORS on Firefox?

Very often you have no option to setup the sending server so what I did I changed the XMLHttpRequest.open call in my javascript to a local get-file.php file where I have the following code in it:

_x000D_
_x000D_
<?php_x000D_
  $file = file($_GET['url']);_x000D_
  echo implode('', $file);_x000D_
?>
_x000D_
_x000D_
_x000D_

javascript is doing this:

_x000D_
_x000D_
var xhttp = new XMLHttpRequest();_x000D_
xhttp.onreadystatechange = function() {_x000D_
  if (this.readyState == 4 && this.status == 200) {_x000D_
    // File content is now in the this.responseText_x000D_
  }_x000D_
};_x000D_
xhttp.open("GET", "get-file.php?url=http://site/file", true);_x000D_
xhttp.send();
_x000D_
_x000D_
_x000D_

In my case this solved the restriction/situation just perfectly. No need to hack Firefox or servers. Just load your javascript/html file with that small php file into the server and you're done.

How to use Java property files?

You can pass an InputStream to the Property, so your file can pretty much be anywhere, and called anything.

Properties properties = new Properties();
try {
  properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
  ...
}

Iterate as:

for(String key : properties.stringPropertyNames()) {
  String value = properties.getProperty(key);
  System.out.println(key + " => " + value);
}

How to use a parameter in ExecStart command line?

To attempt command line arguments directly is not possible.

One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).

This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html

so sudo systemctl restart myprog -v -- systemctl will think you're trying to set one of its flags, not myprog's flag.

sudo systemctl restart myprog someotheroption -- systemctl will restart myprog and the someotheroption service, if it exists.

There is already an open DataReader associated with this Command which must be closed first

I dont know whether this is duplicate answer or not. If it is I am sorry. I just want to let the needy know how I solved my issue using ToList().

In my case I got same exception for below query.

int id = adjustmentContext.InformationRequestOrderLinks.Where(
             item => item.OrderNumber == irOrderLinkVO.OrderNumber 
                  && item.InformationRequestId == irOrderLinkVO.InformationRequestId)
             .Max(item => item.Id);

I solved like below

List<Entities.InformationRequestOrderLink> links = 
      adjustmentContext.InformationRequestOrderLinks
           .Where(item => item.OrderNumber == irOrderLinkVO.OrderNumber 
                       && item.InformationRequestId == irOrderLinkVO.InformationRequestId)
           .ToList();

int id = 0;

if (links.Any())
{
  id = links.Max(x => x.Id);
}
if (id == 0)
{
//do something here
}

CSS: On hover show and hide different div's at the same time?

Have you tried somethig like this?

.showme{display: none;}
.showhim:hover .showme{display : block;}
.hideme{display:block;}
.showhim:hover .hideme{display:none;}

<div class="showhim">HOVER ME
  <div class="showme">hai</div>
  <div class="hideme">bye</div>
</div>

I dont know any reason why it shouldn't be possible.

Checking whether a String contains a number value in Java

Looks like people like doing spoonfeeding, so I have decided to post the worst solution to an easy task:

public static boolean isNumber(String s) throws Exception {
    boolean result = false;
    byte[] bytes = s.getBytes("ASCII");
    int tmp, i = bytes.length;
    while (i >0  && (result = ((tmp = bytes[--i] - '0') >= 0) && tmp <= 9));
    return result;
}

About the worst code I could imagine, but there might be other people here who can come up with even worse solutions.

Hm, containsNumber is worse:

public static boolean containsNumber(String s) throws Exception {
    boolean result = false;
    byte[] bytes = s.getBytes("ASCII");
    int tmp, i = bytes.length;
    while (i >0  && (true | (result |= ((tmp = bytes[--i] - '0') >= 0) && tmp <= 9)));
    return result;
}

How to implement the Java comparable interface?

You would need to implement the interface and define the compareTo() method. For a good tutorial go to - Tutorials point link or MyKongLink

How to turn NaN from parseInt into 0 for an empty string?

Why not override the function? In that case you can always be sure it returns 0 in case of NaN:

(function(original) {
    parseInt = function() {
        return original.apply(window, arguments) || 0;
    };
})(parseInt);

Now, anywhere in your code:

parseInt('') === 0

Format a JavaScript string using placeholders and an object of substitutions?

As a quick example:

var name = 'jack';
var age = 40;
console.log('%s is %d yrs old',name,age);

The output is:

jack is 40 yrs old

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

just right click on your project, hover maven then click update project.. done!!

Status bar and navigation bar appear over my view's bounds in iOS 7

You don't have to calculate how far to shift everything down, there's a build in property for this. In Interface Builder, highlight your view controller, and then navigate to the attributes inspector. Here you'll see some check boxes next to the words "Extend Edges". As you can see, in the first screenshot, the default selection is for content to appear under top and bottom bars, but not under opaque bars, which is why setting the bar style to not translucent worked for you.

As you can somewhat see in the first screenshot, there are two UI elements hiding below the navigation bar. (I've enabled wireframes in IB to illustrate this) These elements, a UIButton and a UISegmentedControl both have their "y" origin set to zero, and the view controller is set to allow content below the top bar.

enter image description here

This second screenshot shows what happens when you deselect the "Under Top Bars" check box. As you can see, the view controllers view has been shifted down appropriately for its y origin to be right underneath the navigation bar.

enter image description here

This can also be accomplished programmatically through the usage of -[UIViewController edgesForExtendedLayout]. Here's a link to the class reference for edgeForExtendedLayout, and for UIRectEdge

[self setEdgesForExtendedLayout:UIRectEdgeNone];

How to copy data to clipboard in C#

My Experience with this issue using WPF C# coping to clipboard and System.Threading.ThreadStateException is here with my code that worked correctly with all browsers:

Thread thread = new Thread(() => Clipboard.SetText("String to be copied to clipboard"));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start(); 
thread.Join();

credits to this post here

But this works only on localhost, so don't try this on a server, as it's not going to work.

On server-side, I did it by using zeroclipboard. The only way, after a lot of research.

How get value from URL

Website URL:

http://www.example.com/?id=2

Code:

$id = intval($_GET['id']);
$results = mysql_query("SELECT * FROM next WHERE id=$id");    
while ($row = mysql_fetch_array($results))     
{       
    $url = $row['url'];
    echo $url; //Outputs: 2
}

How to send SMS in Java

There is Ogham library. The code to send SMS is easy to write (it automatically handles character encoding and message splitting). The real SMS is sent either using SMPP protocol (standard SMS protocol) or through a provider. You can even test your code locally with a SMPP server to check the result of your SMS before paying for real SMS sending.

package fr.sii.ogham.sample.standard.sms;

import java.util.Properties;

import fr.sii.ogham.core.builder.MessagingBuilder;
import fr.sii.ogham.core.exception.MessagingException;
import fr.sii.ogham.core.service.MessagingService;
import fr.sii.ogham.sms.message.Sms;

public class BasicSample {
    public static void main(String[] args) throws MessagingException {
        // [PREPARATION] Just do it once at startup of your application
        
        // configure properties (could be stored in a properties file or defined
        // in System properties)
        Properties properties = new Properties();
        properties.setProperty("ogham.sms.smpp.host", "<your server host>");                                 // <1>
        properties.setProperty("ogham.sms.smpp.port", "<your server port>");                                 // <2>
        properties.setProperty("ogham.sms.smpp.system-id", "<your server system ID>");                       // <3>
        properties.setProperty("ogham.sms.smpp.password", "<your server password>");                         // <4>
        properties.setProperty("ogham.sms.from.default-value", "<phone number to display for the sender>");  // <5>
        // Instantiate the messaging service using default behavior and
        // provided properties
        MessagingService service = MessagingBuilder.standard()                                               // <6>
                .environment()
                    .properties(properties)                                                                  // <7>
                    .and()
                .build();                                                                                    // <8>
        // [/PREPARATION]
        
        // [SEND A SMS]
        // send the sms using fluent API
        service.send(new Sms()                                                                               // <9>
                        .message().string("sms content")
                        .to("+33752962193"));
        // [/SEND A SMS]
    }
}

There are many other features and samples / spring samples.

MessageBox Buttons?

if(DialogResult.OK==MessageBox.Show("Do you Agree with me???"))
{
         //do stuff if yess
}
else
{
         //do stuff if No
}

Where Is Machine.Config?

It semi-depends though... mine is:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG

and

C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG

How to read data from a file in Lua

Just a little addition if one wants to parse a space separated text file line by line.

read_file = function (path)
local file = io.open(path, "rb") 
if not file then return nil end

local lines = {}

for line in io.lines(path) do
    local words = {}
    for word in line:gmatch("%w+") do 
        table.insert(words, word) 
    end    
  table.insert(lines, words)
end

file:close()
return lines;
end

Android set bitmap to Imageview

There is a library named Picasso which can efficiently load images from a URL. It can also load an image from a file.

Examples:

  1. Load URL into ImageView without generating a bitmap:

    Picasso.with(context) // Context
           .load("http://abc.imgur.com/gxsg.png") // URL or file
           .into(imageView); // An ImageView object to show the loaded image
    
  2. Load URL into ImageView by generating a bitmap:

    Picasso.with(this)
           .load(artistImageUrl)
           .into(new Target() {
               @Override
               public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
                   /* Save the bitmap or do something with it here */
    
                   // Set it in the ImageView
                   theView.setImageBitmap(bitmap)
               }
    
               @Override
               public void onBitmapFailed(Drawable errorDrawable) {
    
               }
    
               @Override
               public void onPrepareLoad(Drawable placeHolderDrawable) {
    
               }
           });
    

There are many more options available in Picasso. Here is the documentation.

Getting the error "Missing $ inserted" in LaTeX

also, I had this problem but the bib file wouldn't recompile. I removed the problem, which was an underscore in the note field, and compiled the tex file again, but kept getting the same errors. In the end I del'd the compiled bib file (.bbl I think) and it worked fine. I had to escape the _ using a backslash.

How to convert Nvarchar column to INT

If you want to convert from char to int, why not think about unicode number?

SELECT UNICODE(';') -- 59

This way you can convert any char to int without any error. Cheers.

Check whether there is an Internet connection available on Flutter app

I made a base class for widget state

Usage instead of State<LoginPage> use BaseState<LoginPage> then just use the boolean variable isOnline

Text(isOnline ? 'is Online' : 'is Offline')

First, add connectivity plugin:

dependencies:
  connectivity: ^0.4.3+2

Then add the BaseState class

import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/widgets.dart';

/// a base class for any statful widget for checking internet connectivity
abstract class BaseState<T extends StatefulWidget> extends State {

  void castStatefulWidget();

  final Connectivity _connectivity = Connectivity();

  StreamSubscription<ConnectivityResult> _connectivitySubscription;

  /// the internet connectivity status
  bool isOnline = true;

  /// initialize connectivity checking
  /// Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initConnectivity() async {
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      print(e.toString());
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) {
      return;
    }

    await _updateConnectionStatus().then((bool isConnected) => setState(() {
          isOnline = isConnected;
        }));
  }

  @override
  void initState() {
    super.initState();
    initConnectivity();
    _connectivitySubscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) async {
      await _updateConnectionStatus().then((bool isConnected) => setState(() {
            isOnline = isConnected;
          }));
    });
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

  Future<bool> _updateConnectionStatus() async {
    bool isConnected;
    try {
      final List<InternetAddress> result =
          await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        isConnected = true;
      }
    } on SocketException catch (_) {
      isConnected = false;
      return false;
    }
    return isConnected;
  }
}

And you need to cast the widget in your state like this

@override
  void castStatefulWidget() {
    // ignore: unnecessary_statements
    widget is StudentBoardingPage;
  }

How can I get the browser's scrollbar sizes?

For me, the most useful way was

(window.innerWidth - document.getElementsByTagName('html')[0].clientWidth)

with vanilla JavaScript.

enter image description here

How can I get screen resolution in java?

This code will enumerate the graphics devices on the system (if multiple monitors are installed), and you can use that information to determine monitor affinity or automatic placement (some systems use a little side monitor for real-time displays while an app is running in the background, and such a monitor can be identified by size, screen colors, etc.):

// Test if each monitor will support my app's window
// Iterate through each monitor and see what size each is
GraphicsEnvironment ge      = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[]    gs      = ge.getScreenDevices();
Dimension           mySize  = new Dimension(myWidth, myHeight);
Dimension           maxSize = new Dimension(minRequiredWidth, minRequiredHeight);
for (int i = 0; i < gs.length; i++)
{
    DisplayMode dm = gs[i].getDisplayMode();
    if (dm.getWidth() > maxSize.getWidth() && dm.getHeight() > maxSize.getHeight())
    {   // Update the max size found on this monitor
        maxSize.setSize(dm.getWidth(), dm.getHeight());
    }

    // Do test if it will work here
}

onclick or inline script isn't working in extension

I had the same problem, and didnĀ“t want to rewrite the code, so I wrote a function to modify the code and create the inline declarated events:

function compile(qSel){
    var matches = [];
    var match = null;
    var c = 0;

    var html = $(qSel).html();
    var pattern = /(<(.*?)on([a-zA-Z]+)\s*=\s*('|")(.*)('|")(.*?))(>)/mg;

    while (match = pattern.exec(html)) {
        var arr = [];
        for (i in match) {
            if (!isNaN(i)) {
                arr.push(match[i]);
            }
        }
        matches.push(arr);
    }
    var items_with_events = [];
    var compiledHtml = html;

    for ( var i in matches ){
        var item_with_event = {
            custom_id : "my_app_identifier_"+i,
            code : matches[i][5],
            on : matches[i][3],
        };
        items_with_events.push(item_with_event);
        compiledHtml = compiledHtml.replace(/(<(.*?)on([a-zA-Z]+)\s*=\s*('|")(.*)('|")(.*?))(>)/m, "<$2 custom_id='"+item_with_event.custom_id+"' $7 $8");
    }

    $(qSel).html(compiledHtml);

    for ( var i in items_with_events ){
        $("[custom_id='"+items_with_events[i].custom_id+"']").bind(items_with_events[i].on, function(){
            eval(items_with_events[i].code);
        });
    }
}

$(document).ready(function(){
    compile('#content');
})

This should remove all inline events from the selected node, and recreate them with jquery instead.