Programs & Examples On #Gcal

Node JS Promise.all and forEach

Just to add to the solution presented, in my case I wanted to fetch multiple data from Firebase for a list of products. Here is how I did it:

useEffect(() => {
  const fn = p => firebase.firestore().doc(`products/${p.id}`).get();
  const actions = data.occasion.products.map(fn);
  const results = Promise.all(actions);
  results.then(data => {
    const newProducts = [];
    data.forEach(p => {
      newProducts.push({ id: p.id, ...p.data() });
    });
    setProducts(newProducts);
  });
}, [data]);

How to resolve Value cannot be null. Parameter name: source in linq?

System.ArgumentNullException: Value cannot be null. Parameter name: value

This error message is not very helpful!

You can get this error in many different ways. The error may not always be with the parameter name: value. It could be whatever parameter name is being passed into a function.

As a generic way to solve this, look at the stack trace or call stack:

Test method GetApiModel threw exception: 
System.ArgumentNullException: Value cannot be null.
Parameter name: value
    at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)

You can see that the parameter name value is the first parameter for DeserializeObject. This lead me to check my AutoMapper mapping where we are deserializing a JSON string. That string is null in my database.

You can change the code to check for null.

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

Finally I solve the issues using below code. This type of error will happen when there is a mismatch between In/Out parameter as declare in procedure and in java code declareParameters. Here we need to defined oracle return tab

public class ManualSaleStoredProcedureDao {

private SimpleJdbcCall getAllSytemUsers;

public List<SystemUser> getAllSytemUsers(String clientCode) {

    MapSqlParameterSource in = new MapSqlParameterSource();
    in.addValue("pi_client_code", clientCode);
    Map<String, Object> result = getAllSytemUsers.execute(in);
    @SuppressWarnings("unchecked")
    List<SystemUser> systemUsers = (List<SystemUser>) result
            .get(VSCConstants.GET_SYSTEM_USER_OUT_PARAM1);
    return systemUsers;

}

public void setDataSource(DataSource dataSource) {

    getAllSytemUsers = new SimpleJdbcCall(dataSource)
            .withSchemaName(VSCConstants.SCHEMA)
            .withProcedureName(VSCConstants.GET_SYSTEM_USER_PROC_NAME)
            .declareParameters(
                    new SqlParameter(
                            "pi_client_code",
                            OracleTypes.NUMBER,
                            "pi_client_code"),
                    new SqlInOutParameter(
                            "po_system_users",
                            OracleTypes.ARRAY,
                            "T_SYSTEM_USER_TAB",
                            new OracleSystemUser()));

}

Using ng-click vs bind within link function of Angular Directive

You should use the controller in the directive and ng-click in the template html, as suggested previous responses. However, if you need to do DOM manipulation upon the event(click), such as on click of the button, you want to change the color of the button or so, then use the Link function and use the element to manipulate the dom.

If all you want to do is show some value on an HTML element or any such non-dom manipulative task, then you may not need a directive, and can directly use the controller.

How to log Apache CXF Soap Request and Soap Response using Log4j?

In your spring context configuring below would log the request and response soap messsage.

<bean id="loggingFeature" class="org.apache.cxf.feature.LoggingFeature">
    <property name="prettyLogging" value="true" />
</bean>

<cxf:bus>
    <cxf:features>
        <ref bean="loggingFeature" />
    </cxf:features>
</cxf:bus>

set column width of a gridview in asp.net

Set width

HeaderStyle-width

for Example HeaderStyle-width="10%"

How to make a phone call using intent in Android?

 if(ContextCompat.checkSelfPermission(
        mContext,android.Manifest.permission.CALL_PHONE) != 
              PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions((Activity) mContext, new 
                  String[]{android.Manifest.permission.CALL_PHONE}, 0);
                } else {
                    startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "Your Number")));
                }

How can I send emails through SSL SMTP with the .NET Framework?

As stated in a comment at

http://blogs.msdn.com/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx

with System.Net.Mail, use port 25 instead of 465:

You must set SSL=true and Port=25. Server responds to your request from unprotected 25 and then throws connection to protected 465.

Where can I find a list of Mac virtual key codes?

In addition to the keycodes supplied in other answers, there are also "usage IDs" used for key remapping in the newer APIs introduced in macOS Sierra:

Technical Note TN2450

Remapping Keys in macOS 10.12 Sierra

Under macOS Sierra 10.12, the mechanism for key remapping was changed. This Technical Note is for developers of key remapping software so that they can update their software to support macOS Sierra 10.12. We present 2 solutions for implementing key remapping functionality for macOS 10.12 in this Technical Note.

https://developer.apple.com/library/archive/technotes/tn2450/_index.html

Keyboard a and A - 0x04
Keyboard b and B - 0x05
Keyboard c and C - 0x06
Keyboard d and D - 0x07
Keyboard e and E - 0x08
...

Regex matching in a Bash if statement

In case someone wanted an example using variables...

#!/bin/bash

# Only continue for 'develop' or 'release/*' branches
BRANCH_REGEX="^(develop$|release//*)"

if [[ $BRANCH =~ $BRANCH_REGEX ]];
then
    echo "BRANCH '$BRANCH' matches BRANCH_REGEX '$BRANCH_REGEX'"
else
    echo "BRANCH '$BRANCH' DOES NOT MATCH BRANCH_REGEX '$BRANCH_REGEX'"
fi

Outlets cannot be connected to repeating content iOS

As most people have pointed out that subclassing UITableViewCell solves this issue. But the reason this not allowed because the prototype cell(UITableViewCell) is defined by Apple and you cannot add any of your own outlets to it.

How to efficiently use try...catch blocks in PHP

There is no reason against using a single block for multiple operations, since any thrown exception will prevent the execution of further operations after the failed one. At least as long as you can conclude which operation failed from the exception caught. That is as long as it is fine if some operations are not processed.

However I'd say that returning the exception makes only limited sense. A return value of a function should be the expected result of some action, not the exception. If you need to react on the exception in the calling scope then either do not catch the exception here inside your function, but in the calling scope or re-throw the exception for later processing after having done some debug logging and the like.

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

Yes it's possible. Follow these steps:

  1. Download Xcode 10.2 via this link (you need to be signed in with your Apple Id): https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_10.2/Xcode_10.2.xip and install it
  2. Edit Xcode.app/Contents/Info.plist and change the Minimum System Version to 10.13.6
  3. Do the same for Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/Info.plist (might require a restart of Xcode and/or Mac OS to make it open the simulator on run)
  4. Replace Xcode.app/Contents/Developer/usr/bin/xcodebuild with the one from 10.1 (or another version you have currently installed, such as 10.0).
  5. If there are problems with the simulator, reboot your Mac

Python Pandas iterate over rows and access column names

I also like itertuples()

for row in df.itertuples():
    print(row.A)
    print(row.Index)

since row is a named tuples, if you meant to access values on each row this should be MUCH faster

speed run :

df = pd.DataFrame([x for x in range(1000*1000)], columns=['A'])
st=time.time()
for index, row in df.iterrows():
    row.A
print(time.time()-st)
45.05799984931946

st=time.time()
for row in df.itertuples():
    row.A
print(time.time() - st)
0.48400020599365234

How to restart service using command prompt?

You can start and stop and query services using the SC command. As for innosetup i'm not sure.

Determine if Python is running inside virtualenv

A potential solution is:

os.access(sys.executable, os.W_OK)

In my case I really just wanted to detect if I could install items with pip as is. While it might not be the right solution for all cases, consider simply checking if you have write permissions for the location of the Python executable.

Note: this works in all versions of Python, but also returns True if you run the system Python with sudo. Here's a potential use case:

import os, sys
can_install_pip_packages = os.access(sys.executable, os.W_OK)

if can_install_pip_packages:
    import pip
    pip.main(['install', 'mypackage'])

How to center align the cells of a UICollectionView?

Put this into your collection view delegate. It considers more of the the basic flow layout settings than the other answers and is thereby more generic.

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    NSInteger cellCount = [collectionView.dataSource collectionView:collectionView numberOfItemsInSection:section];
    if( cellCount >0 )
    {
        CGFloat cellWidth = ((UICollectionViewFlowLayout*)collectionViewLayout).itemSize.width+((UICollectionViewFlowLayout*)collectionViewLayout).minimumInteritemSpacing;
        CGFloat totalCellWidth = cellWidth*cellCount + spacing*(cellCount-1);
        CGFloat contentWidth = collectionView.frame.size.width-collectionView.contentInset.left-collectionView.contentInset.right;
        if( totalCellWidth<contentWidth )
        {
            CGFloat padding = (contentWidth - totalCellWidth) / 2.0;
            return UIEdgeInsetsMake(0, padding, 0, padding);
        }
    }
    return UIEdgeInsetsZero;
}

swift version (thanks g0ld2k):

extension CommunityConnectViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

    // Translated from Objective-C version at: http://stackoverflow.com/a/27656363/309736

        let cellCount = CGFloat(viewModel.getNumOfItemsInSection(0))

        if cellCount > 0 {
            let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
            let cellWidth = flowLayout.itemSize.width + flowLayout.minimumInteritemSpacing
            let totalCellWidth = cellWidth*cellCount + spacing*(cellCount-1)
            let contentWidth = collectionView.frame.size.width - collectionView.contentInset.left - collectionView.contentInset.right

            if (totalCellWidth < contentWidth) {
                let padding = (contentWidth - totalCellWidth) / 2.0
                return UIEdgeInsetsMake(0, padding, 0, padding)
            }
        }

        return UIEdgeInsetsZero
    }
}

Find and Replace string in all files recursive using grep and sed

grep -rl SOSTITUTETHIS . | xargs sed -Ei 's/(.*)SOSTITUTETHIS(.*)/\1WITHTHIS\2/g'

bool to int conversion

Section 6.5.8.6 of the C standard says:

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.) The result has type int.

Configuring Log4j Loggers Programmatically

If someone comes looking for configuring log4j2 programmatically in Java, then this link could help: (https://www.studytonight.com/post/log4j2-programmatic-configuration-in-java-class)

Here is the basic code for configuring a Console Appender:

ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();

builder.setStatusLevel(Level.DEBUG);
// naming the logger configuration
builder.setConfigurationName("DefaultLogger");

// create a console appender
AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE")
                .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
// add a layout like pattern, json etc
appenderBuilder.add(builder.newLayout("PatternLayout")
                .addAttribute("pattern", "%d %p %c [%t] %m%n"));
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
rootLogger.add(builder.newAppenderRef("Console"));

builder.add(appenderBuilder);
builder.add(rootLogger);
Configurator.reconfigure(builder.build());

This will reconfigure the default rootLogger and will also create a new appender.

How do I do pagination in ASP.NET MVC?

I had the same problem and found a very elegant solution for a Pager Class from

http://blogs.taiga.nl/martijn/2008/08/27/paging-with-aspnet-mvc/

In your controller the call looks like:

return View(partnerList.ToPagedList(currentPageIndex, pageSize));

and in your view:

<div class="pager">
    Seite: <%= Html.Pager(ViewData.Model.PageSize, 
                          ViewData.Model.PageNumber,
                          ViewData.Model.TotalItemCount)%>
</div>

Laravel Password & Password_Confirmation Validation

Try doing it this way, it worked for me:

$this->validate($request, [
'name' => 'required|min:3|max:50',
'email' => 'email',
'vat_number' => 'max:13',
'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
'password_confirmation' => 'min:6'
]);`

Seems like the rule always has the validation on the first input among the pair...

How to jQuery clone() and change id?

$('#cloneDiv').click(function(){


  // get the last DIV which ID starts with ^= "klon"
  var $div = $('div[id^="klon"]:last');

  // Read the Number from that DIV's ID (i.e: 3 from "klon3")
  // And increment that number by 1
  var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;

  // Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
  var $klon = $div.clone().prop('id', 'klon'+num );

  // Finally insert $klon wherever you want
  $div.after( $klon.text('klon'+num) );

});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

What do .c and .h file extensions mean to C?

They're not really library files. They're just source files. Like Stefano said, the .c file is the C source file which actually uses/defines the actual source of what it merely outlined in the .h file, the header file. The header file usually outlines all of the function prototypes and structures that will be used in the actual source file. Think of it like a reference/appendix. This is evident upon looking at the header file, as you will see :) So then when you want to use something that was written in these source files, you #include the header file, which contains the information that the compiler will need to know.

How can one develop iPhone apps in Java?

You need to know at least basics of Objective-C to develop for iPhone. However, it is possible to use C++ classes.

As far as I know Adobe is working on building Flex/Flash applications for iPhone. Read more here: http://theflashblog.com/?p=1513

Posting a File and Associated Data to a RESTful WebService preferably as JSON

Please ensure that you have following import. Ofcourse other standard imports

import org.springframework.core.io.FileSystemResource


    void uploadzipFiles(String token) {

        RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)

        def zipFile = new File("testdata.zip")
        def Id = "001G00000"
        MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
        form.add("id", id)
        form.add('file',new FileSystemResource(zipFile))
        def urld ='''http://URL''';
        def resp = rest.post(urld) {
            header('X-Auth-Token', clientSecret)
            contentType "multipart/form-data"
            body(form)
        }
        println "resp::"+resp
        println "resp::"+resp.text
        println "resp::"+resp.headers
        println "resp::"+resp.body
        println "resp::"+resp.status
    }

How to add an image to the emulator gallery in android studio?

Workaround simple and quick. Upload file/photo on cloud (from outside the emulator) and download with browser on the emulator.

iOS application: how to clear notifications?

You need to add below code in your AppDelegate applicationDidBecomeActive method.

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];

NSDictionary - Need to check whether dictionary contains key-value pair or not

With literal syntax you can check as follows

static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
  NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
 NSLog(@"Key pair do not exits for key: %@", kKeyToCheck); 

How to click on hidden element in Selenium WebDriver?

I did it with jQuery:

page.execute_script %Q{ $('#some_id').prop('checked', true) }

jQuery / Javascript code check, if not undefined

I like this:

if (wlocation !== undefined)

But if you prefer the second way wouldn't be as you posted. It would be:

if (typeof wlocation  !== "undefined")

How to detect if a string contains at least a number?

  1. You could use CLR based UDFs or do a CONTAINS query using all the digits on the search column.

MySQL query to get column names?

The simplest solution out of all Answers:

DESC `table name`

or

DESCRIBE `table name`

or

SHOW COLUMNS FROM `table name`

CREATE TABLE LIKE A1 as A2

Your attempt wasn't that bad. You have to do it with LIKE, yes.

In the manual it says:

Use LIKE to create an empty table based on the definition of another table, including any column attributes and indexes defined in the original table.

So you do:

CREATE TABLE New_Users  LIKE Old_Users;

Then you insert with

INSERT INTO New_Users SELECT * FROM Old_Users GROUP BY ID;

But you can not do it in one statement.

Creating stored procedure with declare and set variables

I assume you want to pass the Order ID in. So:

CREATE PROCEDURE [dbo].[Procedure_Name]
(
    @OrderID INT
) AS
BEGIN
    Declare @OrderItemID AS INT
    DECLARE @AppointmentID AS INT
    DECLARE @PurchaseOrderID AS INT
    DECLARE @PurchaseOrderItemID AS INT
    DECLARE @SalesOrderID AS INT
    DECLARE @SalesOrderItemID AS INT

    SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
    SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
    SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END

Pandas: sum DataFrame rows for given columns

If you have just a few columns to sum, you can write:

df['e'] = df['a'] + df['b'] + df['d']

This creates new column e with the values:

   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

For longer lists of columns, EdChum's answer is preferred.

Setting the Textbox read only property to true using JavaScript

I find that document.getElementById('textbox-id').readOnly=true sometimes doesn't work reliably.

Instead, try:

document.getElementById('textbox-id').setAttribute('readonly', 'readonly') and document.getElementById('textbox-id').removeAttribute('readonly').

A little verbose but it seems to be dependable.

macro - open all files in a folder

You have to add this line just before loop

    MyFile = Dir
Loop

Show message box in case of exception

If you want just the summary of the exception use:

    try
    {
        test();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

If you want to see the whole stack trace (usually better for debugging) use:

    try
    {
        test();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

Another method I sometime use is:

    private DoSomthing(int arg1, int arg2, out string errorMessage)
    {
         int result ;
        errorMessage = String.Empty;
        try 
        {           
            //do stuff
            int result = 42;
        }
        catch (Exception ex)
        {

            errorMessage = ex.Message;//OR ex.ToString(); OR Free text OR an custom object
            result = -1;
        }
        return result;
    }

And In your form you will have something like:

    string ErrorMessage;
    int result = DoSomthing(1, 2, out ErrorMessage);
    if (!String.IsNullOrEmpty(ErrorMessage))
    {
        MessageBox.Show(ErrorMessage);
    }

Which UUID version to use?

That's a very general question. One answer is: "it depends what kind of UUID you wish to generate". But a better one is this: "Well, before I answer, can you tell us why you need to code up your own UUID generation algorithm instead of calling the UUID generation functionality that most modern operating systems provide?"

Doing that is easier and safer, and since you probably don't need to generate your own, why bother coding up an implementation? In that case, the answer becomes use whatever your O/S, programming language or framework provides. For example, in Windows, there is CoCreateGuid or UuidCreate or one of the various wrappers available from the numerous frameworks in use. In Linux there is uuid_generate.

If you, for some reason, absolutely need to generate your own, then at least have the good sense to stay away from generating v1 and v2 UUIDs. It's tricky to get those right. Stick, instead, to v3, v4 or v5 UUIDs.

Update: In a comment, you mention that you are using Python and link to this. Looking through the interface provided, the easiest option for you would be to generate a v4 UUID (that is, one created from random data) by calling uuid.uuid4().

If you have some data that you need to (or can) hash to generate a UUID from, then you can use either v3 (which relies on MD5) or v5 (which relies on SHA1). Generating a v3 or v5 UUID is simple: first pick the UUID type you want to generate (you should probably choose v5) and then pick the appropriate namespace and call the function with the data you want to use to generate the UUID from. For example, if you are hashing a URL you would use NAMESPACE_URL:

uuid.uuid3(uuid.NAMESPACE_URL, 'https://ripple.com')

Please note that this UUID will be different than the v5 UUID for the same URL, which is generated like this:

uuid.uuid5(uuid.NAMESPACE_URL, 'https://ripple.com')

A nice property of v3 and v5 URLs is that they should be interoperable between implementations. In other words, if two different systems are using an implementation that complies with RFC4122, they will (or at least should) both generate the same UUID if all other things are equal (i.e. generating the same version UUID, with the same namespace and the same data). This property can be very helpful in some situations (especially in content-addressible storage scenarios), but perhaps not in your particular case.

How do you scroll up/down on the console of a Linux VM

Press the Shift key when scrolling the mouse up/down works for me when loggin in Ubuntu using Terminal ssh in Yosemite.

Json.NET serialize object with root name

You can easily create your own serializer

var car = new Car() { Name = "Ford", Owner = "John Smith" };
string json = Serialize(car);

string Serialize<T>(T o)
{
    var attr = o.GetType().GetCustomAttribute(typeof(JsonObjectAttribute)) as JsonObjectAttribute;

    var jv = JValue.FromObject(o);

    return new JObject(new JProperty(attr.Title, jv)).ToString();
}

C# Return Different Types?

You could use external class, set the properties types as you wish, then use it in your function.

public class MultipleOpjects
{
    private List<string> _ObjectOne;
    public List<string> ObjectOne {
        get { return _ObjectOne; }
        set { _ObjectOne = value; }
    }
    private List<object> _ObjectTwo;
    public List<object> ObjectTwo {
        get { return _ObjectTwo; }
        set { _ObjectTwo = value; }
    }
    private object _ObjectThree;
    public object ObjectThree {
        get { return _ObjectThree; }
        set { _ObjectThree = value; }
    }
}
public MultipleOpjects GetAnything()
{
    MultipleOpjects Vrble = new MultipleOpjects();
    Vrble.ObjectOne  = SomeThing1;
    Vrble.ObjectTwo = SomeThing2;
    Vrble.ObjectThree = SomeThing3;

    return Vrble;      
}

Java String import

Everything in the java.lang package is implicitly imported (including String) and you do not need to do so yourself. This is simply a feature of the Java language. ArrayList and HashMap are however in the java.util package, which is not implicitly imported.

The package java.lang mostly includes essential features, such a class version of primitives, basic exceptions and the Object class. This being integral to most programs, forcing people to import them is redundant and thus the contents of this package are implicitly imported.

jQuery add required to input fields

I found that jquery 1.11.1 does not do this reliably.

I used $('#estimate').attr('required', true) and $('#estimate').removeAttr('required').

Removing required was not reliable. It would sometimes leave the required attribute without value. Since required is a boolean attibute, its mere presence, without value, is seen by the browser as true.

This bug was intermittent, and I got tired of messing with it. Switched to document.getElementById("estimate").required = true and document.getElementById("estimate").required = false.

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

What you need is to have a controller that responds to the url first which then renders your jsp. See this link for a solution.

How to use OKHTTP to make a post request?

You should check tutorials on lynda.com. Here is an example of how to encode the parameters, make HTTP request and then parse response to json object.

public JSONObject getJSONFromUrl(String str_url, List<NameValuePair> params) {      
        String reply_str = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(str_url);
            OkHttpClient client = new OkHttpClient();
            HttpURLConnection con = client.open(url);                           
            con.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
            writer.write(getEncodedParams(params));
            writer.flush();     
            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));           
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }           
            reply_str = sb.toString();              
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }

        // try parse the string to a JSON object. There are better ways to parse data.
        try {
            jObj = new JSONObject(reply_str);            
        } catch (JSONException e) {   
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }     
      return jObj;
    }

    //in this case it's NameValuePair, but you can use any container
    public String getEncodedParams(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        for (NameValuePair nvp : params) {
            String key = nvp.getName();
            String param_value = nvp.getValue();
            String value = null;
            try {
                value = URLEncoder.encode(param_value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(key + "=" + value);
        }
        return sb.toString();
    }

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

I had the same issue for bootstrap modal

import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

If this is your case just add the component to the module declarations and entryComponents as other responses suggest, but also add this to your module

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

imports: [
   NgbModule.forRoot(),
   ...
]

Is there a way to get the source code from an APK file?

I personally recommend Show Java Android App to get the source code. You can download it from play store or from here

Updating a date in Oracle SQL table

Here is how you set the date and time:

update user set expiry_date=TO_DATE('31/DEC/2017 12:59:59', 'dd/mm/yyyy hh24:mi:ss') where id=123;

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

You need to add this at start of your php page "login.php"

<?php header('Access-Control-Allow-Origin: *'); ?>

PHP: Inserting Values from the Form into MySQL

The following code just declares a string variable that contains a MySQL query:

$sql = "INSERT INTO users (username, password, email)
    VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

It does not execute the query. In order to do that you need to use some functions but let me explain something else first.

NEVER TRUST USER INPUT: You should never append user input (such as form input from $_GET or $_POST) directly to your query. Someone can carefully manipulate the input in such a way so that it can cause great damage to your database. That's called SQL Injection. You can read more about it here

To protect your script from such an attack you must use Prepared Statements. More on prepared statements here

Include prepared statements to your code like this:

$sql = "INSERT INTO users (username, password, email)
    VALUES (?,?,?)";

Notice how the ? are used as placeholders for the values. Next you should prepare the statement using mysqli_prepare:

$stmt = mysqli_prepare($sql);

Then start binding the input variables to the prepared statement:

$stmt->bind_param("sss", $_POST['username'], $_POST['email'], $_POST['password']);

And finally execute the prepared statements. (This is where the actual insertion takes place)

$stmt->execute();

NOTE Although not part of the question, I strongly advice you to never store passwords in clear text. Instead you should use password_hash to store a hash of the password

How to pass command line arguments to a rake task

Options and dependencies need to be inside arrays:

namespace :thing do
  desc "it does a thing"
  task :work, [:option, :foo, :bar] do |task, args|
    puts "work", args
  end
  
  task :another, [:option, :foo, :bar] do |task, args|
    puts "another #{args}"
    Rake::Task["thing:work"].invoke(args[:option], args[:foo], args[:bar])
    # or splat the args
    # Rake::Task["thing:work"].invoke(*args)
  end

end

Then

rake thing:work[1,2,3]
=> work: {:option=>"1", :foo=>"2", :bar=>"3"}

rake thing:another[1,2,3]
=> another {:option=>"1", :foo=>"2", :bar=>"3"}
=> work: {:option=>"1", :foo=>"2", :bar=>"3"}

NOTE: variable task is the task object, not very helpful unless you know/care about Rake internals.

RAILS NOTE:

If running the task from Rails, it's best to preload the environment by adding => [:environment] which is a way to setup dependent tasks.

  task :work, [:option, :foo, :bar] => [:environment] do |task, args|
    puts "work", args
  end

How to save the contents of a div as a image?

There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.

Error: Module not specified (IntelliJ IDEA)

This happened to me when I started to work with a colleque's project.

He was using jdk 12.0.2 .

If you are suspicious jdk difference might be the case (Your IDE complains about SDK, JDK etc.):

  1. Download the appropriate jdk
  2. Move new jdk to the folder of your choice. (I use C:\Program Files\Java)
  3. On Intellij, click to the dropdown on top middle bar. Click Edit Configurations. Change jdk.
  4. File -> Invalidate Caches and Restart.

Adding one day to a date

Simplest solution:

$date = new DateTime('+1 day');
echo $date->format('Y-m-d H:i:s');

How do I use FileSystemObject in VBA?

In excel 2013 the object creation string is:

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

instead of the code in the answer above:

Dim fs,fname
Set fs=Server.CreateObject("Scripting.FileSystemObject")

jQuery UI DatePicker - Change Date Format

If you need the date in yy-mm-dd format,you can use this:-

$("#datepicker").datepicker({ dateFormat: "yy-mm-dd" });

You can find all the supported format https://jqueryui.com/datepicker/#date-formats

I was in need of 06,Dec 2015,I did this:-

$("#datepicker").datepicker({ dateFormat: "d M,y" });

How to build a DataTable from a DataGridView?

one of best solution enjoyed it ;)

  public DataTable GetContentAsDataTable(bool IgnoreHideColumns=false)
        {
            try
            {
                if (dgv.ColumnCount == 0) return null;
                DataTable dtSource = new DataTable();
                foreach (DataGridViewColumn col in dgv.Columns)
                {
                    if (IgnoreHideColumns & !col.Visible) continue;
                    if (col.Name == string.Empty) continue;
                    dtSource.Columns.Add(col.Name, col.ValueType);
                    dtSource.Columns[col.Name].Caption = col.HeaderText;
                }
                if (dtSource.Columns.Count == 0) return null;
                foreach (DataGridViewRow row in dgv.Rows)
                {
                    DataRow drNewRow = dtSource.NewRow();
                    foreach (DataColumn  col in dtSource .Columns)
                    {
                        drNewRow[col.ColumnName] = row.Cells[col.ColumnName].Value;
                    }
                    dtSource.Rows.Add(drNewRow);
                }
                return dtSource;
            }
            catch { return null; }
        }

Stop an input field in a form from being submitted

_x000D_
_x000D_
$('#serialize').click(function () {_x000D_
  $('#out').text(_x000D_
    $('form').serialize()_x000D_
  );_x000D_
});_x000D_
_x000D_
$('#exclude').change(function () {_x000D_
  if ($(this).is(':checked')) {_x000D_
    $('[name=age]').attr('form', 'fake-form-id');_x000D_
  } else {_x000D_
    $('[name=age]').removeAttr('form');    _x000D_
  }_x000D_
  _x000D_
  $('#serialize').click();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="/">_x000D_
  <input type="text" value="John" name="name">_x000D_
  <input type="number" value="100" name="age">_x000D_
</form>_x000D_
_x000D_
<input type="button" value="serialize" id="serialize">_x000D_
<label for="exclude">  _x000D_
  <input type="checkbox" value="exclude age" id="exclude">_x000D_
  exlude age_x000D_
</label>_x000D_
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Set the absolute position of a view

In general, you can add a View in a specific position using a FrameLayout as container by specifying the leftMargin and topMargin attributes.

The following example will place a 20x20px ImageView at position (100,200) using a FrameLayout as fullscreen container:

XML

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:background="#33AAFF"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</FrameLayout>

Activity / Fragment / Custom view

//...
FrameLayout root = (FrameLayout)findViewById(R.id.root);
ImageView img = new ImageView(this);
img.setBackgroundColor(Color.RED);
//..load something inside the ImageView, we just set the background color

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(20, 20);
params.leftMargin = 100;
params.topMargin  = 200;
root.addView(img, params);
//...

This will do the trick because margins can be used as absolute (X,Y) coordinates without a RelativeLayout:

enter image description here

Can I write native iPhone apps using Python?

Not currently, currently the only languages available to access the iPhone SDK are C/C++, Objective C and Swift.

There is no technical reason why this could not change in the future but I wouldn't hold your breath for this happening in the short term.

That said, Objective-C and Swift really are not too scary...

2016 edit

Javascript with NativeScript framework is available to use now.

Add Legend to Seaborn point plot

I tried using Adam B's answer, however, it didn't work for me. Instead, I found the following workaround for adding legends to pointplots.

import matplotlib.patches as mpatches
red_patch = mpatches.Patch(color='#bb3f3f', label='Label1')
black_patch = mpatches.Patch(color='#000000', label='Label2')

In the pointplots, the color can be specified as mentioned in previous answers. Once these patches corresponding to the different plots are set up,

plt.legend(handles=[red_patch, black_patch])

And the legend ought to appear in the pointplot.

VBA Check if variable is empty

How you test depends on the Property's DataType:

| Type                                 | Test                            | Test2
| Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then        | 
| Boolen (True/False)                  | If Not obj.Property Then        | If obj.Property = False Then
| Object                               | If obj.Property Is Nothing Then |
| String                               | If obj.Property = "" Then       | If LenB(obj.Property) = 0 Then
| Variant                              | If obj.Property = Empty Then    |

You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)

Difference between private, public, and protected inheritance

These three keywords are also used in a completely different context to specify the visibility inheritance model.

This table gathers all of the possible combinations of the component declaration and inheritance model presenting the resulting access to the components when the subclass is completely defined.

enter image description here

The table above is interpreted in the following way (take a look at the first row):

if a component is declared as public and its class is inherited as public the resulting access is public.

An example:

 class Super {
    public:      int p;
    private:     int q;
    protected:   int r;
 };

 class Sub : private Super {};

 class Subsub : public Sub {};

The resulting access for variables p, q, r in class Subsub is none.

Another example:

class Super {
    private:     int x;
    protected:   int y;
    public:      int z;
 };
class Sub : protected Super {};

The resulting access for variables y, z in class Sub is protected and for variable x is none.

A more detailed example:

class Super {
private:
    int storage;
public:
    void put(int val) { storage = val;  }
    int  get(void)    { return storage; }
};
int main(void) {
    Super object;

    object.put(100);
    object.put(object.get());
    cout << object.get() << endl;
    return 0;
}

Now lets define a subclass:

class Sub : Super { };

int main(void) {
    Sub object;

    object.put(100);
    object.put(object.get());
    cout << object.get() << endl;
    return 0;
}

The defined class named Sub which is a subclass of class named Super or that Sub class is derived from the Super class. The Sub class introduces neither new variables nor new functions. Does it mean that any object of the Sub class inherits all the traits after the Super class being in fact a copy of a Super class’ objects?

No. It doesn’t.

If we compile the following code, we will get nothing but compilation errors saying that put and get methods are inaccessible. Why?

When we omit the visibility specifier, the compiler assumes that we are going to apply the so-called private inheritance. It means that all public superclass components turn into private access, private superclass components won't be accessible at all. It consequently means that you are not allowed to use the latter inside the subclass.

We have to inform the compiler that we want to preserve the previously used access policy.

class Sub : public Super { };

Don’t be misled: it doesn’t mean that private components of the Super class (like the storage variable) will turn into public ones in a somewhat magical way. Private components will remain private, public will remain public.

Objects of the Sub class may do "almost" the same things as their older siblings created from the Super class. "Almost" because the fact of being a subclass also means that the class lost access to the private components of the superclass. We cannot write a member function of the Sub class which would be able to directly manipulate the storage variable.

This is a very serious restriction. Is there any workaround?

Yes.

The third access level is called protected. The keyword protected means that the component marked with it behaves like a public one when used by any of the subclasses and looks like a private one to the rest of the world. -- This is true only for the publicly inherited classes (like the Super class in our example) --

class Super {
protected:
    int storage;
public:
    void put(int val) { storage = val;  }
    int  get(void)    { return storage; }
};

class Sub : public Super {
public:
    void print(void) {cout << "storage = " << storage;}
};

int main(void) {
    Sub object;

    object.put(100);
    object.put(object.get() + 1);
    object.print();
    return 0;
}

As you see in the example code we a new functionality to the Sub class and it does one important thing: it accesses the storage variable from the Super class.

It wouldn’t be possible if the variable was declared as private. In the main function scope the variable remains hidden anyway so if you write anything like:

object.storage = 0;

The compiler will inform you that it is an error: 'int Super::storage' is protected.

Finally, the last program will produce the following output:

storage = 101

Count elements with jQuery

$('.someclass').length

You could also use:

$('.someclass').size()

which is functionally equivalent, but the former is preferred. In fact, the latter is now deprecated and shouldn't be used in any new development.

Git Pull vs Git Rebase

git pull and git rebase are not interchangeable, but they are closely connected.

git pull fetches the latest changes of the current branch from a remote and applies those changes to your local copy of the branch. Generally this is done by merging, i.e. the local changes are merged into the remote changes. So git pull is similar to git fetch & git merge.

Rebasing is an alternative to merging. Instead of creating a new commit that combines the two branches, it moves the commits of one of the branches on top of the other.

You can pull using rebase instead of merge (git pull --rebase). The local changes you made will be rebased on top of the remote changes, instead of being merged with the remote changes.

Atlassian has some excellent documentation on merging vs. rebasing.

In Git, how do I figure out what my current revision is?

There are many ways git log -1 is the easiest and most common, I think

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

I happened to run with the same issue in iOS 7 (with some devices no simulators).

Looks like Safari in iOS 7 has a lower storage quota, which apparently is reached by having a long history log.

I guess the best practice will be to catch the exception.

The Modernizr project has an easy patch, you should try something similar: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js

How to use source: function()... and AJAX in JQuery UI autocomplete

This is completely new working code with sample AJAX call.

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>

<div>
    <div id="project-label">Select a project (type "j" for a start):</div>
    <img id="project-icon" src="images/transparent_1x1.png" class="ui-state-default" alt="" />
    <input id="project" />
    <input type="hidden" id="project-i" />
</div>


@*Auto Complete*@
<script>
    $(function () {

        $("#project").autocomplete({
            minLength: 0,
            source : function( request, response ) {
                $.ajax({
                    url: "http://jsonplaceholder.typicode.com/posts/1/comments",
                    dataType: "jsonp",
                    data: {
                        q: request.term
                    },
                    success: function (data) {
                        response( data );
                    }
                });
            },
            focus: function (event, ui) {
                $("#project").val(ui.item.label);
                return false;
            },
            select: function (event, ui) {
                $("#project").val(ui.item.name);
                $("#project-id").val(ui.item.email);                    

                return false;
            }
        })
            .data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("<li>")
                    .data("ui-autocomplete-item", item)
                    .append("<a> " + item.name + "<br>" + item.email + "</a>")
                    .appendTo(ul);
            };
    });
</script>

Show a leading zero if a number is less than 10

Try this

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

alert(pad("5", 2));

Example

http://jsfiddle.net/

Or

var number = 5;
var i;
if (number < 10) {
    alert("0"+number);
}

Example

http://jsfiddle.net/

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

I always tend to set the JAVA_HOME according to the /usr/bin/java.

JAVA_HOME="$(dirname -- "$(dirname -- "$(readlink -f /usr/bin/java)")")"

This way, both alternatives point to the same location

HTML character codes for this ? or this ?

The Big and small black triangles facing the 4 directions can be represented thus:

&#x25B2;

&#x25B4;

&#x25B6;

&#x25B8;

&#x25BA;

&#x25BC;

&#x25BE;

&#x25C0;

&#x25C2;

&#x25C4;

How do I break out of nested loops in Java?

You can use a named block around the loops:

search: {
    for (Type type : types) {
        for (Type t : types2) {
            if (some condition) {
                // Do something and break...
                break search;
            }
        }
    }
}

hibernate could not get next sequence value

Please use the following query and alter your table : CREATE SEQUENCE user_id_seq START 1; ALTER TABLE product.users ALTER COLUMN user_id SET DEFAULT nextval('user_id_seq'); ALTER SEQUENCE users.user_id_seq OWNED BY users.user_id;

and use the this in your entity class

@GeneratedValue(strategy = GenerationType.SEQUENCE,generator="user_id_seq")

Error message Strict standards: Non-static method should not be called statically in php

Instead of using the instance with the scope resolution operator :: because it wasn't defined like static function.

$r=Page::getInstanceByName($page);

change it to :

$r=Page->getInstanceByName($page);

And it will work like a charm.

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

I found some more information from this blog.

  • In a Class Library, when code is compiled, assemblies (dlls) are generated for each library. But with Shared Project it will not contain any header information so when you have a Shared Project reference it will be compiled as part of the parent application. There will not be separate dlls created.
  • In class library you are only allowed to write C# code while shared project can have any thing like C# code files, XAML files or JavaScript files etc.

How to insert values in table with foreign key using MySQL?

Case 1: Insert Row and Query Foreign Key

Here is an alternate syntax I use:

INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = (
       SELECT id_teacher
         FROM tab_teacher
        WHERE name_teacher = 'Dr. Smith')

I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department and expenses tables from the following:

enter image description here

Case 2: Insert Row and Then Insert Dependant Row

Luckily, MySQL supports LAST_INSERT_ID() exactly for this purpose.

INSERT INTO tab_teacher
   SET name_teacher = 'Dr. Smith';
INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = LAST_INSERT_ID()

Eloquent Collection: Counting and Detect Empty

You can use: $counter = count($datas);

How do I read text from the clipboard?

For my console program the answers with tkinter above did not quite work for me because the .destroy() always gave an error,:

can't invoke "event" command: application has been destroyed while executing...

or when using .withdraw() the console window did not get the focus back.

To solve this you also have to call .update() before the .destroy(). Example:

# Python 3
import tkinter

r = tkinter.Tk()
text = r.clipboard_get()
r.withdraw()
r.update()
r.destroy()

The r.withdraw() prevents the frame from showing for a milisecond, and then it will be destroyed giving the focus back to the console.

Woocommerce get products

<?php
$args     = array( 'post_type' => 'product', 'category' => 34, 'posts_per_page' => -1 );
$products = get_posts( $args ); 
?>

This should grab all the products you want, I may have the post type wrong though I can't quite remember what woo-commerce uses for the post type. It will return an array of products

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

If you don't see log4net.dll in %systemdrive%\windows\assembly\ on the machine you are attempting to deploy it on, it is likely you haven't successfully installed the redistributable for Crystal Reports for .Net Framework 4.0

Install (or reinstall) the latest service pack from http://scn.sap.com/docs/DOC-7824 (SAP Crystal Reports, developer version for Microsoft Visual Studio Updates & Runtime Downloads)

That runtime distribution should add log4net to the GAC along with a bunch of CrystalDecisions dll's

How to create a library project in Android Studio and an application project that uses the library project

To create a library:

File > New Module

select Android Library

Lib

To use the library add it as a dependancy:

File > Project Structure > Modules > Dependencies

dep

Then add the module (android library) as a module dependency.

add module

Run your project. It will work.

JFrame in full screen Java

Add:

frame.setExtendedState(JFrame.MAXIMIZED_BOTH); 
frame.setUndecorated(true);
frame.setVisible(true);

How to clear all data in a listBox?

What about

listbox1.Items.Clear();

How to get the filename without the extension from a path in Python?

In Python 3.4+ you can use the pathlib solution

from pathlib import Path

print(Path(your_path).resolve().stem)

Can I change the viewport meta tag in mobile safari on the fly?

This has been answered for the most part, but I will expand...

Step 1

My goal was to enable zoom at certain times, and disable it at others.

// enable pinch zoom
var $viewport = $('head meta[name="viewport"]');    
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=4');

// ...later...

// disable pinch zoom
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');

Step 2

The viewport tag would update, but pinch zoom was still active!! I had to find a way to get the page to pick up the changes...

It's a hack solution, but toggling the opacity of body did the trick. I'm sure there are other ways to accomplish this, but here's what worked for me.

// after updating viewport tag, force the page to pick up changes           
document.body.style.opacity = .9999;
setTimeout(function(){
    document.body.style.opacity = 1;
}, 1);

Step 3

My problem was mostly solved at this point, but not quite. I needed to know the current zoom level of the page so I could resize some elements to fit on the page (think of map markers).

// check zoom level during user interaction, or on animation frame
var currentZoom = $document.width() / window.innerWidth;

I hope this helps somebody. I spent several hours banging my mouse before finding a solution.

How to enable CORS in ASP.net Core WebAPI

Based on your comment in MindingData's answer, it has nothing to do with your CORS, it's working fine.

Your Controller action is returning the wrong data. HttpCode 415 means, "Unsupported Media type". This happens when you either pass the wrong format to the controller (i.e. XML to a controller which only accepts json) or when you return a wrong type (return Xml in a controller which is declared to only return xml).

For later one check existence of [Produces("...")]attribute on your action

Shortcut for creating single item list in C#

I would just do

var list = new List<string> { "hello" };

What's the difference setting Embed Interop Types true and false in Visual Studio?

This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.

It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.

Read more in Scott Hanselman's blog post about it and other VS improvements here.

As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:

The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

SELECT t.*,
       @rownum := @rownum +1 AS rank
  FROM TBL_FOO t
  JOIN (SELECT @rownum := 0) r
 WHERE t.name = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

What is the difference between id and class in CSS, and when should I use them?

For more info on this click here.

Example

<div id="header_id" class="header_class">Text</div>

#header_id {font-color:#fff}
.header_class {font-color:#000}

(Note that CSS uses the prefix # for IDs and . for Classes.)

However color was an HTML 4.01 <font> tag attribute deprecated in HTML 5. In CSS there is no "font-color", the style is color so the above should read:

Example

<div id="header_id" class="header_class">Text</div>

#header_id {color:#fff}
.header_class {color:#000}

The text would be white.

Why cannot cast Integer to String in java?

Use .toString instead like below:

String myString = myIntegerObject.toString();

Remove elements from collection while iterating

Only second approach will work. You can modify collection during iteration using iterator.remove() only. All other attempts will cause ConcurrentModificationException.

String contains another two strings

public static class StringExtensions
{
    public static bool Contains(this string s, params string[] predicates)
    {
        return predicates.All(s.Contains);
    }
}

string d = "You hit someone for 50 damage";
string a = "damage";
string b = "someone";
string c = "you";

if (d.Contains(a, b))
{
    Console.WriteLine("d contains a and b");
}

change the date format in laravel view page

Sometimes changing the date format doesn't work properly, especially in Laravel. So in that case, it's better to use:

$date1 = strtr($_REQUEST['date'], '/', '-');
echo date('Y-m-d', strtotime($date1));

Then you can avoid error like "1970-01-01"!

How do I filter query objects by date range in Django?

Is simple,

YourModel.objects.filter(YOUR_DATE_FIELD__date=timezone.now())

Works for me

How do you create a static class in C++?

You can also create a free function in a namespace:

In BitParser.h

namespace BitParser
{
    bool getBitAt(int buffer, int bitIndex);
}

In BitParser.cpp

namespace BitParser
{
    bool getBitAt(int buffer, int bitIndex)
    {
        //get the bit :)
    }
}

In general this would be the preferred way to write the code. When there's no need for an object don't use a class.

How do I parse JSON with Ruby on Rails?

These answers are a bit dated. Therefore I give you:

hash = JSON.parse string

Rails should automagically load the json module for you, so you don't need to add require 'json'.

error : expected unqualified-id before return in c++

if (chapeau) {

You forgot the ending brace to this if statement, so the subsequent else if is considered a syntax error. You need to add the brace when the if statement body is complete:

if (chapeau) {
    cout << "le Professeur Violet";
}
else if (moustaches) {
    cout << "le Colonel Moutarde";
}
// ...

Limiting Powershell Get-ChildItem by File Creation Date Range

Fixed it...

Get-ChildItem C:\Windows\ -recurse -include @("*.txt*","*.pdf") |
Where-Object {$_.CreationTime -gt "01/01/2013" -and $_.CreationTime -lt "12/02/2014"} | 
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} | 
Export-Csv C:\search_TXT-and-PDF_files_01012013-to-12022014_sort.txt

Javascript: How to remove the last character from a div or a string?

$('#mainn').text(function (_,txt) {
    return txt.slice(0, -1);
});

demo --> http://jsfiddle.net/d72ML/8/

Google Maps API 3 - Custom marker color for default (dot) marker

If you use Google Maps API v3 you can use setIcon e.g.

marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')

Or as part of marker init:

marker = new google.maps.Marker({
    icon: 'http://...'
});

Other colours:

Use the following piece of code to update default markers with different colors.

(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Your import has a subtle error:

import java.awt.List;

It should be:

import java.util.List;

The problem is that both awt and Java's util package provide a class called List. The former is a display element, the latter is a generic type used with collections. Furthermore, java.util.ArrayList extends java.util.List, not java.awt.List so if it wasn't for the generics, it would have still been a problem.

Edit: (to address further questions given by OP) As an answer to your comment, it seems that there is anther subtle import issue.

import org.omg.DynamicAny.NameValuePair;

should be

import org.apache.http.NameValuePair

nameValuePairs now uses the correct generic type parameter, the generic argument for new UrlEncodedFormEntity, which is List<? extends NameValuePair>, becomes valid, since your NameValuePair is now the same as their NameValuePair. Before, org.omg.DynamicAny.NameValuePair did not extend org.apache.http.NameValuePair and the shortened type name NameValuePair evaluated to org.omg... in your file, but org.apache... in their code.

Draw line in UIView

Maybe this is a bit late, but I want to add that there is a better way. Using UIView is simple, but relatively slow. This method overrides how the view draws itself and is faster:

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);

    // Draw them with a 2.0 stroke width so they are a bit more visible.
    CGContextSetLineWidth(context, 2.0f);

    CGContextMoveToPoint(context, 0.0f, 0.0f); //start at this point

    CGContextAddLineToPoint(context, 20.0f, 20.0f); //draw to this point

    // and now draw the Path!
    CGContextStrokePath(context);
}

rotate image with css

The trouble looks like the image isn't square and the browser adjusts as such. After rotation ensure the dimensions are retained by changing the image margin.

.imagetest img {
  transform: rotate(270deg);
  ...
  margin: 10px 0px;
}

The amount will depend on the difference in height x width of the image. You may also need to add display:inline-block; or display:block to get it to recognize the margin parameter.

What is the difference between IQueryable<T> and IEnumerable<T>?

We use IEnumerable and IQueryable to manipulate the data that is retrieved from database. IQueryable inherits from IEnumerable, so IQueryable does contain all the IEnumerable features. The major difference between IQueryable and IEnumerable is that IQueryable executes query with filters whereas IEnumerable executes the query first and then it filters the data based on conditions.

Find more detailed differentiation below :

IEnumerable

  1. IEnumerable exists in the System.Collections namespace
  2. IEnumerable execute a select query on the server side, load data in-memory on a client-side and then filter data
  3. IEnumerable is suitable for querying data from in-memory collections like List, Array
  4. IEnumerable is beneficial for LINQ to Object and LINQ to XML queries

IQueryable

  1. IQueryable exists in the System.Linq namespace
  2. IQueryable executes a 'select query' on server-side with all filters
  3. IQueryable is suitable for querying data from out-memory (like remote database, service) collections
  4. IQueryable is beneficial for LINQ to SQL queries

So IEnumerable is generally used for dealing with in-memory collection, whereas, IQueryable is generally used to manipulate collections.

Quickest way to clear all sheet contents VBA

Technically, and from Comintern's accepted workaround, I believe you actually want to Delete all the Cells in the Sheet. Which removes Formatting (See footnote for exceptions), etc. as well as the Cells Contents. I.e. Sheets("Zeroes").Cells.Delete

Combined also with UsedRange, ScreenUpdating and Calculation skipping it should be nearly intantaneous:

Sub DeleteCells ()
    Application.Calculation = XlManual
    Application.ScreenUpdating = False
    Sheets("Zeroes").UsedRange.Delete
    Application.ScreenUpdating = True
    Application.Calculation = xlAutomatic
End Sub

Or if you prefer to respect the Calculation State Excel is currently in:

Sub DeleteCells ()
    Dim SaveCalcState
    SaveCalcState = Application.Calculation
    Application.Calculation = XlManual
    Application.ScreenUpdating = False
    Sheets("Zeroes").UsedRange.Delete
    Application.ScreenUpdating = True
    Application.Calculation = SaveCalcState
End Sub

Footnote: If formatting was applied for an Entire Column, then it is not deleted. This includes Font Colour, Fill Colour and Borders, the Format Category (like General, Date, Text, Etc.) and perhaps other properties too, but

Conditional formatting IS deleted, as is Entire Row formatting.

(Entire Column formatting is quite useful if you are importing raw data repeatedly to a sheet as it will conform to the Formats originally applied if a simple Paste-Values-Only type import is done.)

Reading a string with spaces with sscanf

You want the %c conversion specifier, which just reads a sequence of characters without special handling for whitespace.

Note that you need to fill the buffer with zeroes first, because the %c specifier doesn't write a nul-terminator. You also need to specify the number of characters to read (otherwise it defaults to only 1):

memset(buffer, 0, 200);
sscanf("19 cool kid", "%d %199c", &age, buffer);

Getting each individual digit from a whole integer

RGB values fall nicely on bit boundaries; decimal digits don't. I don't think there's an easy way to do this using bitwise operators at all. You'd need to use decimal operators like modulo 10 (% 10).

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

The user and password are DEFINITELY incorrect. Oracle 11g credentials are case sensitive.

Try ALTER SYSTEM SET SEC_CASE_SENSITIVE_LOGON = FALSE; and alter password.

http://oracle-base.com/articles/11g/case-sensitive-passwords-11gr1.php

How to create separate AngularJS controller files?

Not so graceful, but the very much simple in implementation solution - using global variable.

In the "first" file:


window.myApp = angular.module("myApp", [])
....

in the "second" , "third", etc:


myApp.controller('MyController', function($scope) {
    .... 
    }); 

#1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

Remove the comma

receipt int(10),

And also AUTO INCREMENT should be a KEY

double datatype also requires the precision of decimal places so right syntax is double(10,2)

Regex to replace everything except numbers and a decimal point

Try this:

document.getElementById(target).value = newVal.replace(/^\d+(\.\d{0,2})?$/, "");

Difference between "module.exports" and "exports" in the CommonJs Module System

Renee's answer is well explained. Addition to the answer with an example:

Node does a lot of things to your file and one of the important is WRAPPING your file. Inside nodejs source code "module.exports" is returned. Lets take a step back and understand the wrapper. Suppose you have

greet.js

var greet = function () {
   console.log('Hello World');
};

module.exports = greet;

the above code is wrapped as IIFE(Immediately Invoked Function Expression) inside nodejs source code as follows:

(function (exports, require, module, __filename, __dirname) { //add by node

      var greet = function () {
         console.log('Hello World');
      };

      module.exports = greet;

}).apply();                                                  //add by node

return module.exports;                                      //add by node

and the above function is invoked (.apply()) and returned module.exports. At this time module.exports and exports pointing to the same reference.

Now, imagine you re-write greet.js as

exports = function () {
   console.log('Hello World');
};
console.log(exports);
console.log(module.exports);

the output will be

[Function]
{}

the reason is : module.exports is an empty object. We did not set anything to module.exports rather we set exports = function()..... in new greet.js. So, module.exports is empty.

Technically exports and module.exports should point to same reference(thats correct!!). But we use "=" when assigning function().... to exports, which creates another object in the memory. So, module.exports and exports produce different results. When it comes to exports we can't override it.

Now, imagine you re-write (this is called Mutation) greet.js (referring to Renee answer) as

exports.a = function() {
    console.log("Hello");
}

console.log(exports);
console.log(module.exports);

the output will be

{ a: [Function] }
{ a: [Function] }

As you can see module.exports and exports are pointing to same reference which is a function. If you set a property on exports then it will be set on module.exports because in JS, objects are pass by reference.

Conclusion is always use module.exports to avoid confusion. Hope this helps. Happy coding :)

Why do we usually use || over |? What is the difference?

Non short-circuiting can be useful. Sometimes you want to make sure that two expressions evaluate. For example, say you have a method that removes an object from two separate lists. You might want to do something like this:

class foo {

    ArrayList<Bar> list1 = new ArrayList<Bar>();
    ArrayList<Bar> list2 = new ArrayList<Bar>();

    //Returns true if bar is removed from both lists, otherwise false.
    boolean removeBar(Bar bar) {
        return (list1.remove(bar) & list2.remove(bar));
    }
}

If your method instead used the conditional operand, it would fail to remove the object from the second list if the first list returned false.

//Fails to execute the second remove if the first returns false.
boolean removeBar(Bar bar) {
    return (list1.remove(bar) && list2.remove(bar));
}

It's not amazingly useful, and (as with most programming tasks) you could achieve it with other means. But it is a use case for bitwise operands.

Check element exists in array

In Python you might be in for some surprises if you ask for forgiveness in this case.

try-except is not the right paradigm here.

If you accidentally get negative indices your in for a surprise.

Better solution is to provide the test function yourself:

def index_in_array(M, index):
    return index[0] >= 0 and index[1] >= 0 and index[0]< M.shape[0] and index[1] < M.shape[1]

Updating MySQL primary key

Next time, use a single "alter table" statement to update the primary key.

alter table xx drop primary key, add primary key(k1, k2, k3);

To fix things:

create table fixit (user_2, user_1, type, timestamp, n, primary key( user_2, user_1, type) );
lock table fixit write, user_interactions u write, user_interactions write;

insert into fixit 
select user_2, user_1, type, max(timestamp), count(*) n from user_interactions u 
group by user_2, user_1, type
having n > 1;

delete u from user_interactions u, fixit 
where fixit.user_2 = u.user_2 
  and fixit.user_1 = u.user_1 
  and fixit.type = u.type 
  and fixit.timestamp != u.timestamp;

alter table user_interactions add primary key (user_2, user_1, type );

unlock tables;

The lock should stop further updates coming in while your are doing this. How long this takes obviously depends on the size of your table.

The main problem is if you have some duplicates with the same timestamp.

Where is Python's sys.path initialized from?

Python really tries hard to intelligently set sys.path. How it is set can get really complicated. The following guide is a watered-down, somewhat-incomplete, somewhat-wrong, but hopefully-useful guide for the rank-and-file python programmer of what happens when python figures out what to use as the initial values of sys.path, sys.executable, sys.exec_prefix, and sys.prefix on a normal python installation.

First, python does its level best to figure out its actual physical location on the filesystem based on what the operating system tells it. If the OS just says "python" is running, it finds itself in $PATH. It resolves any symbolic links. Once it has done this, the path of the executable that it finds is used as the value for sys.executable, no ifs, ands, or buts.

Next, it determines the initial values for sys.exec_prefix and sys.prefix.

If there is a file called pyvenv.cfg in the same directory as sys.executable or one directory up, python looks at it. Different OSes do different things with this file.

One of the values in this config file that python looks for is the configuration option home = <DIRECTORY>. Python will use this directory instead of the directory containing sys.executable when it dynamically sets the initial value of sys.prefix later. If the applocal = true setting appears in the pyvenv.cfg file on Windows, but not the home = <DIRECTORY> setting, then sys.prefix will be set to the directory containing sys.executable.

Next, the PYTHONHOME environment variable is examined. On Linux and Mac, sys.prefix and sys.exec_prefix are set to the PYTHONHOME environment variable, if it exists, superseding any home = <DIRECTORY> setting in pyvenv.cfg. On Windows, sys.prefix and sys.exec_prefix is set to the PYTHONHOME environment variable, if it exists, unless a home = <DIRECTORY> setting is present in pyvenv.cfg, which is used instead.

Otherwise, these sys.prefix and sys.exec_prefix are found by walking backwards from the location of sys.executable, or the home directory given by pyvenv.cfg if any.

If the file lib/python<version>/dyn-load is found in that directory or any of its parent directories, that directory is set to be to be sys.exec_prefix on Linux or Mac. If the file lib/python<version>/os.py is is found in the directory or any of its subdirectories, that directory is set to be sys.prefix on Linux, Mac, and Windows, with sys.exec_prefix set to the same value as sys.prefix on Windows. This entire step is skipped on Windows if applocal = true is set. Either the directory of sys.executable is used or, if home is set in pyvenv.cfg, that is used instead for the initial value of sys.prefix.

If it can't find these "landmark" files or sys.prefix hasn't been found yet, then python sets sys.prefix to a "fallback" value. Linux and Mac, for example, use pre-compiled defaults as the values of sys.prefix and sys.exec_prefix. Windows waits until sys.path is fully figured out to set a fallback value for sys.prefix.

Then, (what you've all been waiting for,) python determines the initial values that are to be contained in sys.path.

  1. The directory of the script which python is executing is added to sys.path. On Windows, this is always the empty string, which tells python to use the full path where the script is located instead.
  2. The contents of PYTHONPATH environment variable, if set, is added to sys.path, unless you're on Windows and applocal is set to true in pyvenv.cfg.
  3. The zip file path, which is <prefix>/lib/python35.zip on Linux/Mac and os.path.join(os.dirname(sys.executable), "python.zip") on Windows, is added to sys.path.
  4. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  5. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  6. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  7. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  8. If on Windows, and PYTHONPATH was not set, the prefix was not found, and no registry keys were present, then the relative compile-time value of PYTHONPATH is added; otherwise, this step is ignored.
  9. Paths in the compile-time macro PYTHONPATH are added relative to the dynamically-found sys.prefix.
  10. On Mac and Linux, the value of sys.exec_prefix is added. On Windows, the directory which was used (or would have been used) to search dynamically for sys.prefix is added.

At this stage on Windows, if no prefix was found, then python will try to determine it by searching all the directories in sys.path for the landmark files, as it tried to do with the directory of sys.executable previously, until it finds something. If it doesn't, sys.prefix is left blank.

Finally, after all this, Python loads the site module, which adds stuff yet further to sys.path:

It starts by constructing up to four directories from a head and a tail part. For the head part, it uses sys.prefix and sys.exec_prefix; empty heads are skipped. For the tail part, it uses the empty string and then lib/site-packages (on Windows) or lib/pythonX.Y/site-packages and then lib/site-python (on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

What did the trick for me was to change the target machine from “ANY CPU” to “x64” or maybe in your case “x86” depending in your target machine’s architecture. I would try this first before moving into a more complex solution which indicates a more complex problem.

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

Tool to monitor HTTP, TCP, etc. Web Service traffic

I second Wireshark. It is very powerful and versatile. And since this tool will work not only on Windows but also on Linux or Mac OSX, investing your time to learn it (quite easy actually) makes sense. Whatever the platform or the language you use, it makes sense.

Regards,

Richard Just Programmer http://sili.co.nz/blog

Android - implementing startForeground for a service?

This is my code to set the service to foreground:

private void runAsForeground(){
    Intent notificationIntent = new Intent(this, RecorderMainActivity.class);
    PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
            notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

    Notification notification=new NotificationCompat.Builder(this)
                                .setSmallIcon(R.drawable.ic_launcher)
                                .setContentText(getString(R.string.isRecording))
                                .setContentIntent(pendingIntent).build();

    startForeground(NOTIFICATION_ID, notification);

}

I need to build a notification using PendingIntent, so that I can start my main activity from the notification.

To remove the notification, just call the stopForeground(true);

It is called in the onStartCommand(). Please refer to my code at : https://github.com/bearstand/greyparrot/blob/master/src/com/xiong/richard/greyparrot/Mp3Recorder.java

Class has no initializers Swift

My answer addresses the error in general and not the exact code of the OP. No answer mentioned this note so I just thought I add it.

The code below would also generate the same error:

class Actor {
    let agent : String? // BAD! // Its value is set to nil, and will always be nil and that's stupid so Xcode is saying not-accepted.  
    // Technically speaking you have a way around it, you can help the compiler and enforce your value as a constant. See Option3
}

Others mentioned that Either you create initializers or you make them optional types, using ! or ? which is correct. However if you have an optional member/property, that optional should be mutable ie var. If you make a let then it would never be able to get out of its nil state. That's bad!

So the correct way of writing it is:

Option1

class Actor {
    var agent : String? // It's defaulted to `nil`, but also has a chance so it later can be set to something different || GOOD!
}

Or you can write it as:

Option2

class Actor {
let agent : String? // It's value isn't set to nil, but has an initializer || GOOD!

init (agent: String?){
    self.agent = agent // it has a chance so its value can be set!
    }
}

or default it to any value (including nil which is kinda stupid)

Option3

class Actor {
let agent : String? = nil // very useless, but doable.
let company: String? = "Universal" 
}

If you are curious as to why let (contrary to var) isn't initialized to nil then read here and here

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

... or if you really want to use NOT IN you can use

SELECT * FROM match WHERE id NOT IN ( SELECT id FROM email WHERE id IS NOT NULL)

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

Store a cmdlet's result value in a variable in Powershell

Just access the Priority property of the object returned from the pipeline:

$var = (Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

(This won't work if Get-WSManInstance returns multiple objects.2)

For the second question: to get two properties there are several options, problably the simplest is to have have one variable* containing an object with two separate properties:

$var = (Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)

and then use, assuming only one process:

$var.Priority

and

$var.ProcessID

If there are multiple processes $var will be an array which you can index, so to get the properties of the first process (using the array literal syntax @(...) so it is always a collection1):

$var = @(Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)

and then use:

$var[0].Priority
$var[0].ProcessID

1 PowerShell helpfully for the command line, but not so helpfully in scripts has some extra logic when assigning the result of a pipeline to a variable: if no objects are returned then set $null, if one is returned then that object is assigned, otherwise an array is assigned. Forcing an array returns an array with zero, one or more (respectively) elements.

2 This changes in PowerShell V3 (at the time of writing in Release Candidate), using a member property on an array of objects will return an array of the value of those properties.

How to tell which commit a tag points to in Git?

Even though this is pretty old, I thought I would point out a cool feature I just found for listing tags with commits:

git log --decorate=full

It will show the branches which end/start at a commit, and the tags for commits.

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Complementing Marco Bonelli's answer: the best current way of interacting between frames/iframes is using window.postMessage, supported by all browsers

How do a LDAP search/authenticate against this LDAP in Java

Another approach is using UnboundID. Its api is very readable and shorter

Create a Ldap Connection

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}

Get filter result

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

Get all Oragnization Units and Containers

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific Organization Unit

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get all users under an Organizational Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific user under an Organization Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Display result

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

Formatting a field using ToText in a Crystal Reports formula field

I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))

You can use CCur to convert numbers or string to Curency formats. CCur(number) or CCur(string)


I think this may be what you are looking for,

Replace (ToText(CCur({field})),"$" , "") that will give the parentheses for negative numbers

It is a little hacky, but I'm not sure CR is very kind in the ways of formatting

Dynamically update values of a chartjs chart

You just need to change the chartObject.data.datasets value and call update() like this:

chartObject.data.datasets = newData.datasets;
chartObject.data.labels = newData.labels;
chartObject.update();

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

EX:

function test(){
    "use strict";
    let a = 1;
} 

How to do a https request with bad certificate?

Security note: Disabling security checks is dangerous and should be avoided

You can disable security checks globally for all requests of the default client:

package main

import (
    "fmt"
    "net/http"
    "crypto/tls"
)

func main() {
    http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
    _, err := http.Get("https://golang.org/")
    if err != nil {
        fmt.Println(err)
    }
}

You can disable security check for a client:

package main

import (
    "fmt"
    "net/http"
    "crypto/tls"
)

func main() {
    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    client := &http.Client{Transport: tr}
    _, err := client.Get("https://golang.org/")
    if err != nil {
        fmt.Println(err)
    }
}

How to assign multiple classes to an HTML container?

To assign multiple classes to an html element, include both class names within the quotations of the class attribute and have them separated by a space:

<article class="column wrapper"> 

In the above example, column and wrapper are two separate css classes, and both of their properties will be applied to the article element.

How to create a simple map using JavaScript/JQuery

Edit: Out of date answer, ECMAScript 2015 (ES6) standard javascript has a Map implementation, read here for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;

function get(k) {
    return map[k];
}

//map[myKey1] == get(myKey1);

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

About the version of Android SDK Build-tools, the answer is

By default, the Android SDK uses the most recent downloaded version of the Build Tools.

Source

In Eclipse, you can choose a specific version by using the sdk.buildtools property in the project.properties file.

There seems to be no official page explaining all the build tools. Here is what the Android team says about this.

The [build] tools, such as aidl, aapt, dexdump, and dx, are typically called by the Android build tools or Android Development Tools (ADT), so you rarely need to invoke these tools directly. As a general rule, you should rely on the build tools or the ADT plugin to call them as needed.

Source

Anyway, here is a synthesis of the differences between tools, platform-tools and build-tools:

  • Android SDK Tools
    • Location: $ANDROID_HOME/tools
    • Main tools: ant scripts (to build your APKs) and ddms (for debugging)
  • Android SDK Platform-tools
    • Location: $ANDROID_HOME/platform-tools
    • Main tool: adb (to manage the state of an emulator or an Android device)
  • Android SDK Build-tools
    • Location: $ANDROID_HOME/build-tools/$VERSION/
    • Documentation
    • Main tools: aapt (to generate R.java and unaligned, unsigned APKs), dx (to convert Java bytecode to Dalvik bytecode), and zipalign (to optimize your APKs)

Seeing the console's output in Visual Studio 2010?

Visual Studio is by itself covering the console window, try minimizing Visual Studio window they are drawn over each other.

Print ArrayList

since you haven't provide a custom implementation for toString() method it calls the default on which is going to print the address in memory for that object

solution in your Address class override the toString() method like this

public class Address {

int addressNo ; 
....
....
...

protected String toString(){
    return Integer.toString(addressNo);
}

now when you call

houseAddress.get(i)  in the `System.out.print()` method like this

System.out.print( houseAddress.get(i) ) the toString() of the Address object will be called

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

I ran into this problem and inspired by @Jeremy Cook's answer, I bit the bullet to find out what the heck caused IIS 7 Integrated mode to not like my web.config. Here's my scenario:

  1. Web API (version 4.0.030506.0 aka the old one)
  2. .NET 4.0
  3. Attribute Routing 3.5.6 for Web API [spoiler alert: it was this guy!]

I wanted to use attribute routing in a project that (unfortunately) had to use .NET 4 and hence could not use Web API 2.2 (which needs .NET 4.5). The well meaning NuGet package added this section under the <system.web> section:

<system.web>
<httpHandlers>
      <add verb="*" path="routes.axd" type="AttributeRouting.Web.Logging.LogRoutesHandler, AttributeRouting.Web" />
    </httpHandlers>
</system.web>

[I say well meaning, because this part is required on older versions of IIS]

Removing this section got me past the HTTP 500.23!!

Summary: I second Jeremy's words that it is important to understand why things don't work rather than just "masking the symptom". Even if you have to mask the symptom, you know what you are doing (and why) :-)

How to best display in Terminal a MySQL SELECT returning too many fields?

Using mysql's ego command

From mysql's help command:

ego          (\G) Send command to mysql server, display result vertically.

So by appending a \G to your select, you can get a very clean vertical output:

mysql> SELECT * FROM sometable \G

Using a pager

You can tell MySQL to use the less pager with its -S option that chops wide lines and gives you an output that you can scroll with the arrow keys:

mysql> pager less -S

Thus, next time you run a command with a wide output, MySQL will let you browse the output with the less pager:

mysql> SELECT * FROM sometable;

If you're done with the pager and want to go back to the regular output on stdout, use this:

mysql> nopager

How to insert pandas dataframe via mysqldb into database?

df.to_sql(name = "owner", con= db_connection, schema = 'aws', if_exists='replace', index = >True, index_label='id')

Change Default branch in gitlab

In the latest GitLab Community Edition version 9.2.2.:

  1. You have to click on 'Settings' tab located at right most on tabs panel after opening the project.
  2. Under 'Settings' you will get section 'Default Branch' dropdown which will give you all branches for the repository. Select the desired branch.
  3. Scroll down to hit green colored 'Save changes' button located just after 'Project Avatar'.

Please refer image below:

enter image description here

Two versions of python on linux. how to make 2.7 the default

Verify current version of python by:

$ python --version

then check python is symbolic link to which file.

  $ ll /usr/bin/python

Output Ex:

 lrwxrwxrwx 1 root root 9 Jun 16  2014 /usr/bin/python -> python2.7*

Check other available versions of python:

$ ls /usr/bin/python*

Output Ex:

/usr/bin/python     /usr/bin/python2.7-config  /usr/bin/python3.4         /usr/bin/python3.4m-config  /usr/bin/python3.6m         /usr/bin/python3m
/usr/bin/python2    /usr/bin/python2-config    /usr/bin/python3.4-config  /usr/bin/python3.6          /usr/bin/python3.6m-config  /usr/bin/python3m-config
/usr/bin/python2.7  /usr/bin/python3           /usr/bin/python3.4m        /usr/bin/python3.6-config   /usr/bin/python3-config     /usr/bin/python-config

If want to change current version of python to 3.6 version edit file ~/.bashrc:

vim ~/.bashrc

add below line in the end of file and save:

alias python=/usr/local/bin/python3.6

To install pip for python 3.6

$ sudo apt-get install python3.6 python3.6-dev
$ sudo curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python3.6
$ sudo easy_install pip

On Success, check current version of pip:

$ pip3 -V

Output Ex:

pip 1.5.4 from /usr/lib/python3/dist-packages (python 3.6)

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

ASCII - Software allocates only 8 bit byte in memory for a given character. It works well for English & adopted (loanwords like façade) characters as their corresponding decimal values falls below 128 in the decimal value. Example C program.

UTF-8 - Software allocates 1 to 4 variable 8 bit bytes for a given character. What does mean by variable here? Let us say you are sending the character 'A' through your HTML pages in the browser (HTML is UTF-8), the corresponding decimal value of A is 65, when you convert it into decimal it becomes 01000010. This requires only 1 bytes, 1 byte memory is allocated even for special adopted English characters like 'ç' in a word façade. However, when you want to store European characters, it requires 2 bytes, so you need UTF-8. However, when you go for Asian characters, you require minimum of 2 bytes and maximum of 4 bytes. Similarly, Emoji's require 3 to 4 bytes. UTF-8 will solve all your needs.

UTF-16 will allocate minimum 2 bytes and maximum of 4 bytes per character, it will not allocate 1 or 3 bytes. Each character is either represented in 16 bit or 32 bit.

Then why exists UTF-16? Originally, Unicode was 16 bit not 8 bit. Java adopted the original version of UTF-16.

In a nutshell, you don't need UTF-16 anywhere unless it has been already been adopted by the language or platform you are working on.

Java program invoked by web browsers uses UTF-16 but the web browser sends characters using UTF-8.

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

Common MySQL fields and their appropriate data types

Here are some common datatypes I use (I am not much of a pro though):

| Column           | Data type     | Note
| ---------------- | ------------- | -------------------------------------
| id               | INTEGER       | AUTO_INCREMENT, UNSIGNED                                                          |  
| uuid             | CHAR(36)      | or CHAR(16) binary                                                                |  
| title            | VARCHAR(255)  |                                                                                   |  
| full name        | VARCHAR(70)   |                                                                                   |  
| gender           | TINYINT       | UNSIGNED                                                                          |  
| description      | TINYTEXT      | often may not be enough, use TEXT 
                                     instead          
| post body        | TEXT          |                                                                                   |  
| email            | VARCHAR(255)  |                                                                                   |  
| url              | VARCHAR(2083) | MySQL version < 5.0.3 - use TEXT                                                  |  
| salt             | CHAR(x)       | randomly generated string, usually of 
                                     fixed length (x)    
| digest (md5)     | CHAR(32)      |                                                                                   |  
| phone number     | VARCHAR(20)   |                                                                                   |  
| US zip code      | CHAR(5)       | Use CHAR(10) if you store extended 
                                     codes      
| US/Canada p.code | CHAR(6)       |                                                                                   |  
| file path        | VARCHAR(255)  |                                                                                   |  
| 5-star rating    | DECIMAL(3,2)  | UNSIGNED                                                                          |  
| price            | DECIMAL(10,2) | UNSIGNED                                                                          |  
| date (creation)  | DATE/DATETIME | usually displayed as initial date of 
                                     a post                                       |  
| date (tracking)  | TIMESTAMP     | can be used for tracking changes in a 
                                     post                                        |  
| tags, categories | TINYTEXT      | comma separated values *                                                          |  
| status           | TINYINT(1)    | 1 – published, 0 – unpublished, … You 
                                     can also use ENUM for human-readable 
                                     values
| json data        | JSON          | or LONGTEXT       

How to reset all checkboxes using jQuery or pure JS?

 $(":checkbox:checked").each(function () {

 this.click(); 
});

to unchecked checked box, turn your logic around to do opposite

Referencing Row Number in R

Perhaps with dataframes one of the most easy and practical solution is:

data = dplyr::mutate(data, rownum=row_number())

What precisely does 'Run as administrator' do?

Windows 7 requires that you intentionally ask for certain privileges so that a malicious program can't do bad things to you. If the free calculator you downloaded needed to be run as an administrator, you would know something is up. There are OS commands to elevate the privilege of your application (which will request confirmation from the user).

A good description can be found at:

http://msdn.microsoft.com/en-us/magazine/cc163486.aspx#S4

The most accurate way to check JS object's type?

The best way to find out the REAL type of an object (including BOTH the native Object or DataType name (such as String, Date, Number, ..etc) AND the REAL type of an object (even custom ones); is by grabbing the name property of the object prototype's constructor:

Native Type Ex1:

var string1 = "Test";
console.log(string1.__proto__.constructor.name);

displays:

String

Ex2:

var array1 = [];
console.log(array1.__proto__.constructor.name);

displays:

Array

Custom Classes:

_x000D_
_x000D_
function CustomClass(){_x000D_
  console.log("Custom Class Object Created!");_x000D_
}_x000D_
var custom1 = new CustomClass();_x000D_
_x000D_
console.log(custom1.__proto__.constructor.name);
_x000D_
_x000D_
_x000D_

displays:

CustomClass

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

you may follow these steps :

  • set JAVA_HOME to jdk[without bin folder]
  • set PATH as %JAVA_HOME%/bin;
  • put java.exe , javaw.exe & javaws.exe to C:\ProgramData\Oracle\Java\javapath [I was having problem here].
  • double click on the java.exe
  • Also check and edit the registry value for JAVA current version if required.

it worked for me :)

C# how to create a Guid value?

var guid = new Guid();

Hey, its a 'valid', although not very useful, Guid.

(the guid is all zeros, if you don't know. Sometimes this is needed to indicate no guid, in cases where you don't want to use a nullable Guid)

Uncaught TypeError: undefined is not a function on loading jquery-min.js

Remember: Javascript functions are CASE SENSITIVE.

I had a case where I'm pretty sure that my code would run smoothly. But still, got an error and I checked the Javascript console of Google Chrome to check what it is.

My error line is

opt.SetAttribute("value",values[a]);

And got the same error message:

Uncaught TypeError: undefined is not a function

Nothing seems wrong with the code above but it was not running. I troubleshoot for almost an hour and then compared it with my other running code. My error is that it was set to SetAttribute, which should be setAttribute.

Regular expression to match any character being repeated more than 10 times

You can also use PowerShell to quickly replace words or character reptitions. PowerShell is for Windows. Current version is 3.0.

$oldfile = "$env:windir\WindowsUpdate.log"

$newfile = "$env:temp\newfile.txt"
$text = (Get-Content -Path $oldfile -ReadCount 0) -join "`n"

$text -replace '/(.)\1{9,}/', ' ' | Set-Content -Path $newfile

How can I clear previous output in Terminal in Mac OS X?

To clear the terminal manually:

?+K

Command+K for newer keyboards

To clear the terminal from within a shell script;

/usr/bin/osascript -e 'tell application "System Events" to tell process "Terminal" to keystroke "k" using command down'

Troubleshooting BadImageFormatException

Background

We started getting this today when we switched our WCF service from AnyCPU to x64 on a Windows 2012 R2 server running IIS 6.2.

First we checked the only referenced assembly 10 times, to ensure it was not actually an x86 dll. Next we checked the application pool many times to ensure it was not enabling 32 bit applications.

On a whim I tried toggling the setting. It turns out the application pools in IIS were defaulting to an Enable 32-Bit Applications value of False, but IIS was ignoring it on our server for some reason and always ran our service in x86 mode.

Solution

  • Select the app pool.
  • Choose Set Application Pool Defaults... or Advanced Settings....
  • Change Enable 32-Bit Applications to True.
  • Click OK.
  • Choose Set Application Pool Defaults... or Advanced Settings... again.
  • Change Enable 32-Bit Applications back to False.
  • Click OK.

Convert to date format dd/mm/yyyy

Try this:

$old_date = Date_create("2010-04-19 18:31:27");
$new_date = Date_format($old_date, "d/m/Y");

An efficient way to Base64 encode a byte array?

    public void ProcessRequest(HttpContext context)
    {
        string constring = ConfigurationManager.ConnectionStrings["SQL_Connection_String"].ConnectionString;
        SqlConnection conn = new SqlConnection(constring);
        conn.Open();
        SqlCommand cmd = new SqlCommand("select image1 from TestGo where TestId=1", conn);
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        MemoryStream str = new MemoryStream();

        context.Response.Clear();
        Byte[] bytes = (Byte[])dr[0];
        string d = System.Text.Encoding.Default.GetString(bytes);
        byte[] bytes2 = Convert.FromBase64String(d);
        //context.Response.Write(d);
        Image img = Image.FromStream(new MemoryStream(bytes2));
        img.Save(context.Response.OutputStream, ImageFormat.Png);
        context.Response.Flush();
        str.WriteTo(context.Response.OutputStream);
        str.Dispose();
        str.Close();
        conn.Close();
        context.Response.End();
    }

How to write a full path in a batch file having a folder name with space?

I made a **

automatic-network-drive connector

** using a batch file.

Suddenly there was a networkdrive called "Data for Analysation", and yeah with the double quotes it works proper!

looks a little bit different but works:

net use y: "\\share.blabla.com\Folder\Subfolder\Data for Analysation" /USER:domain\username PW /PERSISTENT:YES

Thx for the Hint :)

How do I crop an image in Java?

I'm giving this example because this actually work for my use case.

I was trying to use the AWS Rekognition API. The API returns a BoundingBox object:

BoundingBox boundingBox = faceDetail.getBoundingBox();

The code below uses it to crop the image:

import com.amazonaws.services.rekognition.model.BoundingBox;

private BufferedImage cropImage(BufferedImage image, BoundingBox box) {
        Rectangle goal = new Rectangle(Math.round(box.getLeft()* image.getWidth()),Math.round(box.getTop()* image.getHeight()),Math.round(box.getWidth() * image.getWidth()), Math.round(box.getHeight() * image.getHeight()));

        Rectangle clip = goal.intersection(new Rectangle(image.getWidth(), image.getHeight()));

        BufferedImage clippedImg = image.getSubimage(clip.x, clip.y , clip.width, clip.height);

        return clippedImg;
    }

How to stretch children to fill cross-axis?

  • The children of a row-flexbox container automatically fill the container's vertical space.

  • Specify flex: 1; for a child if you want it to fill the remaining horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
  flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • Specify flex: 1; for both children if you want them to fill equal amounts of the horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
  flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Passing arguments to angularjs filters

You can simply do like this In Template

<span ng-cloak>{{amount |firstFiler:'firstArgument':'secondArgument' }}</span>

In filter

angular.module("app")
.filter("firstFiler",function(){

    console.log("filter loads");
    return function(items, firstArgument,secondArgument){
        console.log("item is ",items); // it is value upon which you have to filter
        console.log("firstArgument is ",firstArgument);
        console.log("secondArgument ",secondArgument);

        return "hello";
    }
    });

How to set Internet options for Android emulator?

It was setting the DNS that did the trick for me. If you are using the Eclipse or Netbeans plugins, you can set it through Default Emulator options, or Emulator Options respectively. You can also use set it from the command line if you start your emulator from CLI. In all cases, the option is "-dns-server x.x.x.x,x.x.x.x" without the quotes. There is no option in the ADB gui to permanently associate the option with your virtual device.

How can I recover the return value of a function passed to multiprocessing.Process?

The pebble package has a nice abstraction leveraging multiprocessing.Pipe which makes this quite straightforward:

from pebble import concurrent

@concurrent.process
def function(arg, kwarg=0):
    return arg + kwarg

future = function(1, kwarg=1)

print(future.result())

Example from: https://pythonhosted.org/Pebble/#concurrent-decorators

EC2 Instance Cloning

To Answer your question: now AWS make cloning real easy see Launch instance from your Existing Instance

  1. On the EC2 Instances page, select the instance you want to use
  2. Choose Actions, and then Launch More Like This.
  3. Review & Launch

This will take the existing instance as a Template for the new once.

or you can also take a snapshot of the existing volume and use the snapshot with the AMI (existing one) which you ping during your instance launch

Making a Simple Ajax call to controller in asp.net mvc

First thing there is no need of having two different versions of jquery libraries in one page,either "1.9.1" or "2.0.0" is sufficient to make ajax calls work..

Here is your controller code:

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult FirstAjax(string a)
    {
        return Json("chamara", JsonRequestBehavior.AllowGet);
    }   

This is how your view should look like:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function () {
    var a = "Test";
    $.ajax({
        url: "../../Home/FirstAjax",
        type: "GET",
        data: { a : a },
        success: function (response) {
            alert(response);
        },
        error: function (response) {
            alert(response);
        }
    });
});
</script>

Error: [$injector:unpr] Unknown provider: $routeProvider

It looks like you forgot to include the ngRoute module in your dependency for myApp.

In Angular 1.2, they've made ngRoute optional (so you can use third-party route providers, etc.) and you have to explicitly depend on it in modules, along with including the separate file.

'use strict';

angular.module('myApp', ['ngRoute']).
    config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);

Invoking a PHP script from a MySQL trigger

I don't know if it's possible but I always pictured myself being able to do this with the CSV storage engine in MySQL. I don't know the details of this engine: http://dev.mysql.com/doc/refman/5.7/en/csv-storage-engine.html but you can look into it and have a file watcher in your operating system that triggers a PHP call if the file is modified.

Oracle SQL Developer spool output?

For Spooling in Oracle SQL Developer, here is the solution.

set heading on

set linesize 1500

set colsep '|'

set numformat 99999999999999999999

set pagesize 25000

spool E:\abc.txt

@E:\abc.sql;

spool off

The hint is :

  1. when we spool from sql plus , then the whole query is required.

  2. when we spool from Oracle Sql Developer , then the reference path of the query required as given in the specified example.

How to restart a node.js server

To say "nodemon" would answer the question.

But on how only to kill (all) node demon(s), the following works for me:

pkill -HUP node

typescript - cloning object

TypeScript/JavaScript has its own operator for shallow cloning:

let shallowClone = { ...original };

Select a date from date picker using Selenium webdriver

Please use this code for selecting date from Two Jquery calendar like Flight Booking site.

    Hashtable h=new Hashtable();
    h.put("January",0 );
    h.put("February",1);
    h.put("March",2);
    h.put("April",3);
    h.put("May",4);
    h.put("June",5);
    h.put("July",6);
    h.put("August",7);
    h.put("September",8);
    h.put("October",9);
    h.put("November",10);
    h.put("December",11);


    int expMonth;
    int expYear;

    // Calendar Month and Year
    String calMonth = null;
    String calYear = null;
    boolean dateNotFound;
    dateNotFound = true;
    expMonth= 5;
    expYear = 2014;

    while(dateNotFound)
    {

        calMonth = driver.findElement(By.className("ui-datepicker-month")).getText(); // get the text of month
        calYear = driver.findElement(By.className("ui-datepicker-year")).getText();




        if(((Integer)h.get(calMonth))+1 == expMonth && (expYear == Integer.parseInt(calYear)))
        {
            String block="//div[@class='monthBlock first']/table/tbody/tr/td";  // THIS IS FIRST CALENDAR
            selectDate(expDate,block); 
            dateNotFound = false; 
        }
        // parseInt - Converts String to integer and indexof( It will return the index position of String)
        else if(((Integer)h.get(calMonth))+1 < expMonth && (expYear == Integer.parseInt(calYear)) || expYear > Integer.parseInt(calYear))
        {
            String block="//div[@class='monthBlock last']/table/tbody/tr/td"; // THIS IS SECOND CALENDAR


                            selectDate(expDate,block); // PASSING DATE AND CALENDAR
                            dateNotFound = false; // Otherwise it will rotate continuously 
        }
        else if((Integer)h.get(calMonth)+1 > expMonth && (expYear == Integer.parseInt(calYear)) || expYear < Integer.parseInt(calYear))
        {
            System.out.println(" Please enter the date greater than Current date");
            dateNotFound = false;

        }
    }

    }
    //Thread.sleep(3000);


    public static void selectDate(String date,String block) throws IOException
    {

                    String monthblock=block;

        List<WebElement> dateWidget = driver.findElements(By.xpath(monthblock));    

        for (WebElement cell: dateWidget)
        {
            //Selects Date
            if (cell.getText().equals(date))
            {
                cell.findElement(By.linkText(date)).click();
                break;
            }

        }

        //Doubt : How to verify the expected results and how to sort the program



        driver.findElement(By.id("SearchBtn")).submit();

        //driver.quit();
    }

How to set a radio button in Android

Many times if your radio buttons belong to the same radioGroup then

radioButton.setChecked(true)

will not select the radio button properly. So to solve this problem try using your radioGroup.

radioGroup.check(R.id.radioButtonId)

Using GroupBy, Count and Sum in LINQ Lambda Expressions

    var ListByOwner = list.GroupBy(l => l.Owner)
                          .Select(lg => 
                                new { 
                                    Owner = lg.Key, 
                                    Boxes = lg.Count(),
                                    TotalWeight = lg.Sum(w => w.Weight), 
                                    TotalVolume = lg.Sum(w => w.Volume) 
                                });

How can I get an int from stdio in C?

The typical way is with scanf:

int input_value;

scanf("%d", &input_value);

In most cases, however, you want to check whether your attempt at reading input succeeded. scanf returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:

if (scanf("%d", &input_value) == 1)
    // it succeeded
else
    // it failed

Of course, the same is true of all the scanf family (sscanf, fscanf and so on).

C++ equivalent of Java's toString?

As an extension to what John said, if you want to extract the string representation and store it in a std::string do this:

#include <sstream>    
// ...
// Suppose a class A
A a;
std::stringstream sstream;
sstream << a;
std::string s = sstream.str(); // or you could use sstream >> s but that would skip out whitespace

std::stringstream is located in the <sstream> header.

Effective method to hide email from spam bots

See Making email addresses safe from bots on a webpage?

I like the way Facebook and others render an image of your email address.

I have also used The Enkoder in the past - thought it was very good to be honest!

Check if a row exists, otherwise insert

INSERT INTO table ( column1, column2, column3 )
SELECT $column1, $column2, $column3
EXCEPT SELECT column1, column2, column3
FROM table

How to use Switch in SQL Server

This is a select statement, so each branch of the case must return something. If you want to perform actions, just use an if.

Style jQuery autocomplete in a Bootstrap input field

The gap between the (bootstrap) input field and jquery-ui autocompleter seem to occur only in jQuery versions >= 3.2

When using jQuery version 3.1.1 it seem to not happen.

Possible reason is the notable update in v3.2.0 related to a bug fix on .width() and .height(). Check out the jQuery release notes for further details: v3.2.0 / v3.1.1

Bootstrap version 3.4.1 and jquery-ui version 1.12.0 used

Best way to do nested case statement logic in SQL Server

This example might help you, the picture shows how SQL case statement will look like when there are if and more than one inner if loops

enter image description here

Oracle comparing timestamp with date

You can truncate the date part:

select * from table1 where trunc(field1) = to_date('2012-01-01', 'YYYY-MM-DD')

The trouble with this approach is that any index on field1 wouldn't be used due to the function call.

Alternatively (and more index friendly)

select * from table1 
 where field1 >= to_timestamp('2012-01-01', 'YYYY-MM-DD') 
   and field1 < to_timestamp('2012-01-02', 'YYYY-MM-DD')

How to create the pom.xml for a Java project with Eclipse

If you have plugin for Maven in Eclipse, you can do following:

  • right click on your project -> Maven -> Enable Dependency Management

This will convert your project to Maven and creates a pom.xml. Fast and simple...

How to tell which disk Windows Used to Boot

You can use WMI to figure this out. The Win32_BootConfiguration class will tell you both the logical drive and the physical device from which Windows boots. Specifically, the Caption property will tell you which device you're booting from.

For example, in powershell, just type gwmi Win32_BootConfiguration to get your answer.

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

start/play embedded (iframe) youtube-video on click of an image

You are supposed to be able to specify a domain that is safe for scripting. the api document mentions "As an extra security measure, you should also include the origin parameter to the URL" http://code.google.com/apis/youtube/iframe_api_reference.html src="http://www.youtube.com/embed/J---aiyznGQ?enablejsapi=1&origin=mydomain.com" would be the src of your iframe.

however it is not very well documented. I am trying something similar right now.

C/C++ Struct vs Class

C++ uses structs primarily for 1) backwards compatibility with C and 2) POD types. C structs do not have methods, inheritance or visibility.

jQuery - getting custom attribute from selected option

Try this:

$(function() { 
    $("#location").change(function(){ 
        var element = $(this).find('option:selected'); 
        var myTag = element.attr("myTag"); 

        $('#setMyTag').val(myTag); 
    }); 
}); 

What to do with commit made in a detached head

In case of detached HEAD, commits work like normal, except no named branch gets updated. To get master branch updated with your committed changes, make a temporary branch where you are (this way the temporary branch will have all the committed changes you have made in the detached HEAD) , then switch to the master branch and merge the temporary branch with the master.

git branch  temp
git checkout master
git merge temp

How to check a string starts with numeric number?

I think you ought to use a regex:


import java.util.regex.*;

public class Test {
  public static void main(String[] args) {
    String neg = "-123abc";
    String pos = "123abc";
    String non = "abc123";
        /* I'm not sure if this regex is too verbose, but it should be
         * clear. It checks that the string starts with either a series
         * of one or more digits... OR a negative sign followed by 1 or
         * more digits. Anything can follow the digits. Update as you need
         * for things that should not follow the digits or for floating
         * point numbers.
         */
    Pattern pattern = Pattern.compile("^(\\d+.*|-\\d+.*)");
    Matcher matcher = pattern.matcher(neg);
    if(matcher.matches()) {
        System.out.println("matches negative number");
    }
    matcher = pattern.matcher(pos);
    if (matcher.matches()) {
        System.out.println("positive matches");
    }
    matcher = pattern.matcher(non);
    if (!matcher.matches()) {
        System.out.println("letters don't match :-)!!!");
    }
  }
}

You may want to adjust this to accept floating point numbers, but this will work for negatives. Other answers won't work for negatives because they only check the first character! Be more specific about your needs and I can help you adjust this approach.

UIDevice uniqueIdentifier deprecated - What to do now?

This is code I'm using to get ID for both iOS 5 and iOS 6, 7:

- (NSString *) advertisingIdentifier
{
    if (!NSClassFromString(@"ASIdentifierManager")) {
        SEL selector = NSSelectorFromString(@"uniqueIdentifier");
        if ([[UIDevice currentDevice] respondsToSelector:selector]) {
            return [[UIDevice currentDevice] performSelector:selector];
        }
    }
    return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
}

BeautifulSoup getText from between <p>, not picking up subsequent paragraphs

You are getting close!

# Find all of the text between paragraph tags and strip out the html
page = soup.find('p').getText()

Using find (as you've noticed) stops after finding one result. You need find_all if you want all the paragraphs. If the pages are formatted consistently ( just looked over one), you could also use something like

soup.find('div',{'id':'ctl00_PlaceHolderMain_RichHtmlField1__ControlWrapper_RichHtmlField'})

to zero in on the body of the article.

How do I watch a file for changes?

Well after a bit of hacking of Tim Golden's script, I have the following which seems to work quite well:

import os

import win32file
import win32con

path_to_watch = "." # look at the current directory
file_to_watch = "test.txt" # look for changes to a file called test.txt

def ProcessNewData( newData ):
    print "Text added: %s"%newData

# Set up the bits we'll need for output
ACTIONS = {
  1 : "Created",
  2 : "Deleted",
  3 : "Updated",
  4 : "Renamed from something",
  5 : "Renamed to something"
}
FILE_LIST_DIRECTORY = 0x0001
hDir = win32file.CreateFile (
  path_to_watch,
  FILE_LIST_DIRECTORY,
  win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
  None,
  win32con.OPEN_EXISTING,
  win32con.FILE_FLAG_BACKUP_SEMANTICS,
  None
)

# Open the file we're interested in
a = open(file_to_watch, "r")

# Throw away any exising log data
a.read()

# Wait for new data and call ProcessNewData for each new chunk that's written
while 1:
  # Wait for a change to occur
  results = win32file.ReadDirectoryChangesW (
    hDir,
    1024,
    False,
    win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
    None,
    None
  )

  # For each change, check to see if it's updating the file we're interested in
  for action, file in results:
    full_filename = os.path.join (path_to_watch, file)
    #print file, ACTIONS.get (action, "Unknown")
    if file == file_to_watch:
        newText = a.read()
        if newText != "":
            ProcessNewData( newText )

It could probably do with a load more error checking, but for simply watching a log file and doing some processing on it before spitting it out to the screen, this works well.

Thanks everyone for your input - great stuff!

Xcode Objective-C | iOS: delay function / NSTimer help?

A slightly less verbose way is to use the performSelector: withObject: afterDelay: which sets up the NSTimer object for you and can be easily cancelled

So continuing with the previous example this would be

[self performSelector:@selector(goToSecondButton) withObject:nil afterDelay:.06];

More info in the doc

How to use If Statement in Where Clause in SQL?

You have to use CASE Statement/Expression

Select * from Customer
WHERE  (I.IsClose=@ISClose OR @ISClose is NULL)  
AND    
    (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
AND 
     CASE @Value
         WHEN 2 THEN (CASE I.RecurringCharge WHEN @Total or @Total is NULL) 
         WHEN 3 THEN (CASE WHEN I.RecurringCharge like 
                               '%'+cast(@Total as varchar(50))+'%' 
                     or @Total is NULL )
     END

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

Instead of defining the width, you could just put a margin-left on your li, so that the spacing is consistent, and just make sure the margin(s)+li fit within 900px.

nav li {
  line-height: 87px;
  float: left;
  text-align: center;
  margin-left: 35px;
}

Hope this helps.

Register DLL file on Windows Server 2008 R2

What good technology podcasts are out there?

My list includes: Herding Code, Deep Fried Bytes, Polymorohic Podcast, Pixel8, .Net Rocks, Hanselminutes, Powerscripting podcast. Full list: http://rtipton.wordpress.com/podcasts/

What does random.sample() method in python do?

random.sample(population, k)

It is used for randomly sampling a sample of length 'k' from a population. returns a 'k' length list of unique elements chosen from the population sequence or set

it returns a new list and leaves the original population unchanged and the resulting list is in selection order so that all sub-slices will also be valid random samples

I am putting up an example in which I am splitting a dataset randomly. It is basically a function in which you pass x_train(population) as an argument and return indices of 60% of the data as D_test.

import random

def randomly_select_70_percent_of_data_from_1_to_length(x_train):
    return random.sample(range(0, len(x_train)), int(0.6*len(x_train)))

How do I programmatically set the value of a select box element using JavaScript?

function setSelectValue (id, val) {
    document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);

Load HTML File Contents to Div [without the use of iframes]

    document.getElementById("id").innerHTML='<object type="text/html" data="x.html"></object>';

Check if value is in select list with JQuery

Use the Attribute Equals Selector

var thevalue = 'foo';
var exists = 0 != $('#select-box option[value='+thevalue+']').length;

If the option's value was set via Javascript, that will not work. In this case we can do the following:

var exists = false;
$('#select-box option').each(function(){
    if (this.value == 'bar') {
        exists = true;
        return false;
    }
});