Programs & Examples On #Outlook object model

The Outlook Object Model is the hierarchy of objects, methods and properties exposed by Outlook and available through VBA.

Get SELECT's value and text in jQuery

on the basis of your only jQuery tag :)

HTML

<select id="my-select">
<option value="1">This is text 1</option>
<option value="2">This is text 2</option>
<option value="3">This is text 3</option>
</select>

For text --

$(document).ready(function() {
    $("#my-select").change(function() {
        alert($('#my-select option:selected').html());
    });
});

For value --

$(document).ready(function() {
    $("#my-select").change(function() {
        alert($(this).val());
    });
});

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

How to use concerns in Rails 4

So I found it out by myself. It is actually a pretty simple but powerful concept. It has to do with code reuse as in the example below. Basically, the idea is to extract common and / or context specific chunks of code in order to clean up the models and avoid them getting too fat and messy.

As an example, I'll put one well known pattern, the taggable pattern:

# app/models/product.rb
class Product
  include Taggable

  ...
end

# app/models/concerns/taggable.rb
# notice that the file name has to match the module name 
# (applying Rails conventions for autoloading)
module Taggable
  extend ActiveSupport::Concern

  included do
    has_many :taggings, as: :taggable
    has_many :tags, through: :taggings

    class_attribute :tag_limit
  end

  def tags_string
    tags.map(&:name).join(', ')
  end

  def tags_string=(tag_string)
    tag_names = tag_string.to_s.split(', ')

    tag_names.each do |tag_name|
      tags.build(name: tag_name)
    end
  end

  # methods defined here are going to extend the class, not the instance of it
  module ClassMethods

    def tag_limit(value)
      self.tag_limit_value = value
    end

  end

end

So following the Product sample, you can add Taggable to any class you desire and share its functionality.

This is pretty well explained by DHH:

In Rails 4, we’re going to invite programmers to use concerns with the default app/models/concerns and app/controllers/concerns directories that are automatically part of the load path. Together with the ActiveSupport::Concern wrapper, it’s just enough support to make this light-weight factoring mechanism shine.

RegEx to match stuff between parentheses

If s is your string:

s.replace(/^[^(]*\(/, "") // trim everything before first parenthesis
 .replace(/\)[^(]*$/, "") // trim everything after last parenthesis
 .split(/\)[^(]*\(/);      // split between parenthesis

Getting the screen resolution using PHP

Use JavaScript (screen.width and screen.height IIRC, but I may be wrong, haven't done JS in a while). PHP cannot do it.

paint() and repaint() in Java

It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.

AVD Manager - No system image installed for this target

you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image

if not installed ARM EABI v7a System Image, you should install all.

Android: disabling highlight on listView click

in code

listView.setSelector(getResources().getDrawable(R.drawable.transparent));

and add small transparent image to drawable folder.

Like: transparent.xml

<?xml version="1.0" encoding="utf-8"?>    
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#00000000"/>
</shape>

Java reverse an int value without using array

It's good that you wrote out your original code. I have another way to code this concept of reversing an integer. I'm only going to allow up to 10 digits. However, I am going to make the assumption that the user will not enter a zero.

if((inputNum <= 999999999)&&(inputNum > 0 ))
{
   System.out.print("Your number reversed is: ");

   do
   {
      endInt = inputNum % 10; //to get the last digit of the number
      inputNum /= 10;
      system.out.print(endInt);
   }
   While(inputNum != 0);
 System.out.println("");

}
 else
   System.out.println("You used an incorrect number of integers.\n");

System.out.println("Program end");

Invalid default value for 'create_date' timestamp field

You could just change this:

`create_date` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',

To something like this:

`create_date` TIMESTAMP NOT NULL DEFAULT '2018-04-01 12:00:00',

Should I use 'border: none' or 'border: 0'?

This is the result in Firefox 78.0.2 (64-Bit):

img {
    border: none;
        border-top-color: currentcolor;
        border-top-style: none;
        border-top-width: medium;
        border-right-color: currentcolor;
        border-right-style: none;
        border-right-width: medium;
        border-bottom-color: currentcolor;
        border-bottom-style: none;
        border-bottom-width: medium;
        border-left-color: currentcolor;
        border-left-style: none;
        border-left-width: medium;
}

img {
    border: 0;
        border-top-color: currentcolor;
        border-top-style: none;
        border-top-width: 0px;
        border-right-color: currentcolor;
        border-right-style: none;
        border-right-width: 0px;
        border-bottom-color: currentcolor;
        border-bottom-style: none;
        border-bottom-width: 0px;
        border-left-color: currentcolor;
        border-left-style: none;
        border-left-width: 0px;
        border-image-outset: 0;
        border-image-repeat: stretch;
        border-image-slice: 100%;
        border-image-source: none;
        border-image-width: 1;
}

Date: 20200720

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

https://stackabuse.com/how-to-uninstall-node-js-from-mac-osx/

Run following commands to remove node completely from system in MACOS

sudo rm -rf ~/.npm ~/.nvm ~/node_modules ~/.node-gyp ~/.npmrc ~/.node_repl_history
sudo rm -rf /usr/local/bin/npm /usr/local/bin/node-debug /usr/local/bin/node /usr/local/bin/node-gyp
sudo rm -rf /usr/local/share/man/man1/node* /usr/local/share/man/man1/npm*
sudo rm -rf /usr/local/include/node /usr/local/include/node_modules
sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /usr/local/lib/dtrace/node.d
sudo rm -rf /opt/local/include/node /opt/local/bin/node /opt/local/lib/node
sudo rm -rf /usr/local/share/doc/node
sudo rm -rf /usr/local/share/systemtap/tapset/node.stp

brew uninstall node
brew doctor
brew cleanup --prune-prefix



After this i will suggest to use following command to install node using nvm

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash

from https://github.com/nvm-sh/nvm

Reflection - get attribute name and value on property

While the above most upvoted answers definitely work, I'd suggest using a slightly different approach in some cases.

If your class has multiple properties with always the same attribute and you want to get those attributes sorted into a dictionary, here is how:

var dict = typeof(Book).GetProperties().ToDictionary(p => p.Name, p => p.GetCustomAttributes(typeof(AuthorName), false).Select(a => (AuthorName)a).FirstOrDefault());

This still uses cast but ensures that the cast will always work as you will only get the custom attributes of the type "AuthorName". If you had multiple Attributes above answers would get a cast exception.

Positioning background image, adding padding

In case anyone else needs to add padding to something with background-image and background-size: contain or cover, I used the following which is a nice way of doing it. You can replace the border-width with 10% or 2vw or whatever you like.

.bg-image {
    background: url("/image/logo.png") no-repeat center #ffffff / contain;
    border: inset 10px transparent;
    box-sizing: border-box;
}

This means you don't have to define a width.

Parse (split) a string in C++ using string delimiter (standard C++)

std::vector<std::string> split(const std::string& s, char c) {
  std::vector<std::string> v;
  unsigned int ii = 0;
  unsigned int j = s.find(c);
  while (j < s.length()) {
    v.push_back(s.substr(i, j - i));
    i = ++j;
    j = s.find(c, j);
    if (j >= s.length()) {
      v.push_back(s.substr(i, s,length()));
      break;
    }
  }
  return v;
}

How to access a property of an object (stdClass Object) member/element of an array?

To access an array member you use $array['KEY'];

To access an object member you use $obj->KEY;

To access an object member inside an array of objects:
$array[0] // Get the first object in the array
$array[0]->KEY // then access its key

You may also loop over an array of objects like so:

foreach ($arrayOfObjs as $key => $object) {
    echo $object->object_property;
}

Think of an array as a collection of things. It's a bag where you can store your stuff and give them a unique id (key) and access them (or take the stuff out of the bag) using that key. I want to keep things simple here, but this bag can contain other bags too :)

Update (this might help someone understand better):

An array contains 'key' and 'value' pairs. Providing a key for an array member is optional and in this case it is automatically assigned a numeric key which starts with 0 and keeps on incrementing by 1 for each additional member. We can retrieve a 'value' from the array by it's 'key'.

So we can define an array in the following ways (with respect to keys):

First method:

$colorPallete = ['red', 'blue', 'green'];

The above array will be assigned numeric keys automatically. So the key assigned to red will be 0, for blue 1 and so on.

Getting values from the above array:

$colorPallete[0]; // will output 'red'
$colorPallete[1]; // will output 'blue'
$colorPallete[2]; // will output 'green'

Second method:

$colorPallete = ['love' => 'red', 'trust' => 'blue', 'envy' => 'green']; // we expliicitely define the keys ourself.

Getting values from the above array:

$colorPallete['love']; // will output 'red'
$colorPallete['trust']; // will output 'blue'
$colorPallete['envy']; // will output 'green'

Remove last specific character in a string c#

Dim psValue As String = "1,5,12,34,123,12"
psValue = psValue.Substring(0, psValue.LastIndexOf(","))

output:

1,5,12,34,123

Change project name on Android Studio

it will work fine for me

Change Following.

Step 1: Make sure ApplicationId And PackageName will Same. example :

  android {
  defaultConfig {
                     applicationId "com.example.myapplication"
                 }
       }
 and package name the same. package="com.example.myapplication"

Step 2 delete iml file in my case :

  Go To Project> >C:\Users\ashif\Documents\MyApplication  .iml file // delete 
if you forget Project Path Then Go To android Studio Right Click on app and go to  Show in Explorer you get your Project and remove .iml file

Step 3 Close Project

Step 4 Now Copy Your old Project and Paste Any other Root or copy Project Folder and paste Any other Dir.

 Example C:\Users\ashif\Documents/MyApplication 

Step 5

Now open Android Studio and open Existing Project 
C:\Users\ashif\Documents/MyApplication 

Try it will work

What is the cleanest way to get the progress of JQuery ajax request?

Follow the steps to display Progress of Ajax Request:

  1. Create a Spinner using Html & CSS or use Bootstrap Spinner.
  2. Display the Spinner when the end-user is requesting for the AJAX Data for infinite loop or for threshold limit time.
  3. So, after a SUCCESS / ERROR result of AJAX Request, remove the Spinner which is currently displayed and show your results.

To make it easy I recommend you using JS Classes for dynamically Displaying & Hiding the spinner for this purpose.

I Hope this helps!

Is there a git-merge --dry-run option?

I know this is theoretically off-topic, but practically very on-topic for people landing here from a Google search.

When in doubt, you can always use the Github interface to create a pull-request and check if it indicates a clean merge is possible.

Oracle ORA-12154: TNS: Could not resolve service name Error?

Hours of problems SOLVED. I had installed the Beta Entity Framework for Oracle and in in visual studio 2010 MVC 3 project I was referencing under the tab .NET the Oracle.DataAccess ... This kept giving me the "Oracle ORA-12154: TNS: Could not..." error. I finally just browsed to the previous Oracle install under c:\Oracle\product.... using the old 10.2.0.100 version of the dll. Finally it works now. Hope it helps someone else.

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

How to increase heap size for jBoss server

What to change?

set "JAVA_OPTS=%JAVA_OPTS% -Xms1024m -Xmx2048m"

Where to change? (Normally)

bin/standalone.conf(Linux) standalone.conf.bat(Windows)

What if you are using custom script which overrides the existing settings? then?

setAppServerEnvironment.cmd/.sh (kind of file name will be there)

More information are already provided by one of our committee members! BalusC.

Cordova : Requirements check failed for JDK 1.8 or greater

Today I also got this error Cordova : Requirements check failed for JDK 1.8 or greater in my Mac OS while build Ionic App when I run command ionic cordova build --release android via terminal.

Below command resolve my issue :-

export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home"

Hope it will help someone in future!

how to generate a unique token which expires after 24 hours?

Use Dictionary<string, DateTime> to store token with timestamp:

static Dictionary<string, DateTime> dic = new Dictionary<string, DateTime>();

Add token with timestamp whenever you create new token:

dic.Add("yourToken", DateTime.Now);

There is a timer running to remove any expired tokens out of dic:

 timer = new Timer(1000*60); //assume run in 1 minute
 timer.Elapsed += timer_Elapsed;

 static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        var expiredTokens = dic.Where(p => p.Value.AddDays(1) <= DateTime.Now)
                              .Select(p => p.Key);

        foreach (var key in expiredTokens)
            dic.Remove(key);
    }

So, when you authenticate token, just check whether token exists in dic or not.

Strip out HTML and Special Characters

Probably better here for a regex replace

// Strip HTML Tags
$clear = strip_tags($des);
// Clean up things like &amp;
$clear = html_entity_decode($clear);
// Strip out any url-encoded stuff
$clear = urldecode($clear);
// Replace non-AlNum characters with space
$clear = preg_replace('/[^A-Za-z0-9]/', ' ', $clear);
// Replace Multiple spaces with single space
$clear = preg_replace('/ +/', ' ', $clear);
// Trim the string of leading/trailing space
$clear = trim($clear);

Or, in one go

$clear = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($des))))));

Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

If you want to use scrollWidth to get the "REAL" CONTENT WIDTH/HEIGHT (as content can be BIGGER than the css-defined width/height-Box) the scrollWidth/Height is very UNRELIABLE as some browser seem to "MOVE" the paddingRIGHT & paddingBOTTOM if the content is to big. They then place the paddings at the RIGHT/BOTTOM of the "too broad/high content" (see picture below).

==> Therefore to get the REAL CONTENT WIDTH in some browsers you have to substract BOTH paddings from the scrollwidth and in some browsers you only have to substract the LEFT Padding.

I found a solution for this and wanted to add this as a comment, but was not allowed. So I took the picture and made it a bit clearer in the regard of the "moved paddings" and the "unreliable scrollWidth". In the BLUE AREA you find my solution on how to get the "REAL" CONTENT WIDTH!

Hope this helps to make things even clearer!

enter image description here

Get my phone number in android

Method 1:

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

With below permission

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

Method 2:

There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.

Try below code:

String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
        main_data, "mimetype=?",
        new String[]{"vnd.android.cursor.item/phone_v2"},
        "is_primary DESC");
if (object != null) {
    do {
        if (!((Cursor) (object)).moveToNext())
            break;
        String s1 = ((Cursor) (object)).getString(4);
    } while (true);
    ((Cursor) (object)).close();
}

You will need to add these two permissions.

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />

Hope this helps, Thanks!

Returning multiple values from a C++ function

I would just do it by reference if it's only a few return values but for more complex types you can also just do it like this :

static struct SomeReturnType {int a,b,c; string str;} SomeFunction()
{
  return {1,2,3,string("hello world")}; // make sure you return values in the right order!
}

use "static" to limit the scope of the return type to this compilation unit if it's only meant to be a temporary return type.

 SomeReturnType st = SomeFunction();
 cout << "a "   << st.a << endl;
 cout << "b "   << st.b << endl;
 cout << "c "   << st.c << endl;
 cout << "str " << st.str << endl;

This is definitely not the prettiest way to do it but it will work.

How to find all the tables in MySQL with specific column names in them?

For those searching for the inverse of this, i.e. looking for tables that do not contain a certain column name, here is the query...

SELECT DISTINCT TABLE_NAME FROM information_schema.columns WHERE 
TABLE_SCHEMA = 'your_db_name' AND TABLE_NAME NOT IN (SELECT DISTINCT 
TABLE_NAME FROM information_schema.columns WHERE column_name = 
'column_name' AND TABLE_SCHEMA = 'your_db_name');

This came in really handy when we began to slowly implement use of InnoDB's special ai_col column and needed to figure out which of our 200 tables had yet to be upgraded.

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

My solution is as follows:

I didn't find a root folder under C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files.

Google told me that it might be a permission issue against current user, then I found I have a current Identity: IIS APPPOOL in the malfunctioning server where the rest of the server has Current Identity: NT AUTHORITY\NETWORK SERVICE.

Then I changed Current Identity from IIS APPPOOL to NT AUTHORITY\NETWORK SERVICE.

From here, I found that resetting the web app rebuilds the temporary ASP.NET cache, solving the issue.

Can HTML checkboxes be set to readonly?

No, input checkboxes can't be readonly.

But you can make them readonly with javascript!

Add this code anywhere at any time to make checkboxes readonly work as assumed, by preventing the user from modifying it in any way.

_x000D_
_x000D_
jQuery(document).on('click', function(e){_x000D_
      // check for type, avoid selecting the element for performance_x000D_
      if(e.target.type == 'checkbox') {_x000D_
          var el = jQuery(e.target);_x000D_
          if(el.prop('readonly')) {_x000D_
              // prevent it from changing state_x000D_
              e.preventDefault();_x000D_
          }_x000D_
      }_x000D_
});
_x000D_
input[type=checkbox][readonly] {_x000D_
    cursor: not-allowed;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label><input type="checkbox" checked readonly> I'm readonly!</label>
_x000D_
_x000D_
_x000D_

You can add this script at any time after jQuery has loaded.

It will work for dynamically added elements.

It works by picking up the click event (that happens before the change event) on any element on the page, it then checks if this element is a readonly checkbox, and if it is, then it blocks the change.

There are so many ifs to make it not affect the performance of the page.

how can I debug a jar at runtime?

Even though it is a runnable jar, you can still run it from a console -- open a terminal window, navigate to the directory containing the jar, and enter "java -jar yourJar.jar". It will run in that terminal window, and sysout and syserr output will appear there, including stack traces from uncaught exceptions. Be sure to have your debug set to true when you compile. And good luck.


Just thought of something else -- if you're on Win7, it often has permission problems with user applications writing files to specific directories. Make sure the directory to which you are writing your output file is one for which you have permissions.

In a future project, if it's big enough, you can use one of the standard logging facilities for 'debug' output; then it will be easy(ier) to redirect it to a file instead of depending on having a console. But for a smaller job like this, this should be fine.

Xcode 6: Keyboard does not show up in simulator

To enable/disable simulator keyboard,

? + K (Ctrl + k)

To disable input from your keyboard,

iOS Simulator -> Hardware -> Keyboard -> Uncheck "Connect Hardware Keyboard"

curl Failed to connect to localhost port 80

If anyone else comes across this and the accepted answer doesn't work (it didn't for me), check to see if you need to specify a port other than 80. In my case, I was running a rails server at localhost:3000 and was just using curl http://localhost, which was hitting port 80.

Changing the command to curl http://localhost:3000 is what worked in my case.

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Make sure the format of the cell is set to 'general' not 'text' (right click on cell and choose format cell)

Formula should look something like this:

=1+2

How do I get the coordinate position after using jQuery drag and drop?

I would start with something like this. Then update that to use the position plugin and that should get you where you want to be.

Equivalent VB keyword for 'break'

Exit [construct], and intelisense will tell you which one(s) are valid in a particular place.

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

Oh my God. not need to do anything special. only in your post section do as follows:

    $.post(yourURL,{ '': results})(function(e){ ...}

In server use this:

   public ActionResult MethodName(List<yourViewModel> model){...}

this link help you to done ...

How to do a background for a label will be without color?

If you picture box in the background then use this:

label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent;

Put this code below InitializeComponent(); or in Form_Load Method.

Ref: https://www.c-sharpcorner.com/blogs/how-to-make-a-transparent-label-over-a-picturebox1

How to get the cell value by column name not by index in GridView in asp.net

//get the value of a gridview
public string getUpdatingGridviewValue(GridView gridviewEntry, string fieldEntry)
    {//start getGridviewValue
        //scan gridview for cell value
            string result = Convert.ToString(functionsOther.getCurrentTime()); 
            for(int i = 0; i < gridviewEntry.HeaderRow.Cells.Count; i++)
                {//start i for
                    if(gridviewEntry.HeaderRow.Cells[i].Text == fieldEntry)
                        {//start check field match
                            result = gridviewEntry.Rows[rowUpdateIndex].Cells[i].Text;
                            break;
                        }//end check field match
                }//end i for
        //return
            return result;
    }//end getGridviewValue

Stretch background image css?

Just paste this into your line of codes:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

According to this page https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/Attributes.html it is only available if (Enabled only in a UIWebView with the allowsInlineMediaPlayback property set to YES.) I understand in Mobile Safari this is YES on iPad and NO on iPhone and iPod Touch.

How to get unique device hardware id in Android?

Please read this official blog entry on Google developer blog: http://android-developers.blogspot.be/2011/03/identifying-app-installations.html

Conclusion For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.

There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices

.

SQL Update to the SUM of its joined values

Use a sub query similar to the below.

UPDATE P
SET extrasPrice = sub.TotalPrice from
BookingPitches p
inner join 
(Select PitchID, Sum(Price) TotalPrice
    from  dbo.BookingPitchExtras
    Where [Required] = 1
    Group by Pitchid
) as Sub
on p.Id = e.PitchId 
where p.BookingId = 1

Can I clear cell contents without changing styling?

you can use ClearContents. ex,

Range("X").Cells.ClearContents

How do I change the value of a global variable inside of a function

Just use the name of that variable.

In JavaScript, variables are only local to a function, if they are the function's parameter(s) or if you declare them as local explicitely by typing the var keyword before the name of the variable.

If the name of the local value has the same name as the global value, use the window object

See this jsfiddle

_x000D_
_x000D_
x = 1;_x000D_
y = 2;_x000D_
z = 3;_x000D_
_x000D_
function a(y) {_x000D_
  // y is local to the function, because it is a function parameter_x000D_
  console.log('local y: should be 10:', y); // local y through function parameter_x000D_
  y = 3; // will only overwrite local y, not 'global' y_x000D_
  console.log('local y: should be 3:', y); // local y_x000D_
  // global value could be accessed by referencing through window object_x000D_
  console.log('global y: should be 2:', window.y) // global y, different from local y ()_x000D_
_x000D_
  var x; // makes x a local variable_x000D_
  x = 4; // only overwrites local x_x000D_
  console.log('local x: should be 4:', x); // local x_x000D_
  _x000D_
  z = 5; // overwrites global z, because there is no local z_x000D_
  console.log('local z: should be 5:', z); // local z, same as global_x000D_
  console.log('global z: should be 5 5:', window.z, z) // global z, same as z, because z is not local_x000D_
}_x000D_
a(10);_x000D_
console.log('global x: should be 1:', x); // global x_x000D_
console.log('global y: should be 2:', y); // global y_x000D_
console.log('global z: should be 5:', z); // global z, overwritten in function a
_x000D_
_x000D_
_x000D_

Edit

With ES2015 there came two more keywords const and let, which also affect the scope of a variable (Language Specification)

Vue.js - How to properly watch for nested data

I've found it works this way too:

watch: {
    "details.position"(newValue, oldValue) {
        console.log("changes here")
    }
},
data() {
    return {
      details: {
          position: ""
      }
    }
}

Easily measure elapsed time

As I can see from your question, it looks like you want to know the elapsed time after execution of some piece of code. I guess you would be comfortable to see the results in second(s). If so, try using difftime() function as shown below. Hope this solves your problem.

#include <time.h>
#include <stdio.h>

time_t start,end;
time (&start);
.
.
.
<your code>
.
.
.
time (&end);
double dif = difftime (end,start);
printf ("Elasped time is %.2lf seconds.", dif );

What is the difference between null and undefined in JavaScript?

I picked this from here

The undefined value is a primitive value used when a variable has not been assigned a value.

The null value is a primitive value that represents the null, empty, or non-existent reference.

When you declare a variable through var and do not give it a value, it will have the value undefined. By itself, if you try to WScript.Echo() or alert() this value, you won't see anything. However, if you append a blank string to it then suddenly it'll appear:

var s;
WScript.Echo(s);
WScript.Echo("" + s);

You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". This is a small difference indeed.

You can even compare a variable that is undefined to null or vice versa, and the condition will be true:

undefined == null
null == undefined

They are, however, considered to be two different types. While undefined is a type all to itself, null is considered to be a special object value. You can see this by using typeof() which returns a string representing the general type of a variable:

var a;
WScript.Echo(typeof(a));
var b = null;
WScript.Echo(typeof(b));

Running the above script will result in the following output:

undefined
object

Regardless of their being different types, they will still act the same if you try to access a member of either one, e.g. that is to say they will throw an exception. With WSH you will see the dreaded "'varname' is null or not an object" and that's if you're lucky (but that's a topic for another article).

You can explicitely set a variable to be undefined, but I highly advise against it. I recommend only setting variables to null and leave undefined the value for things you forgot to set. At the same time, I really encourage you to always set every variable. JavaScript has a scope chain different than that of C-style languages, easily confusing even veteran programmers, and setting variables to null is the best way to prevent bugs based on it.

Another instance where you will see undefined pop up is when using the delete operator. Those of us from a C-world might incorrectly interpret this as destroying an object, but it is not so. What this operation does is remove a subscript from an Array or a member from an Object. For Arrays it does not effect the length, but rather that subscript is now considered undefined.

var a = [ 'a', 'b', 'c' ];
delete a[1];
for (var i = 0; i < a.length; i++)
WScript.Echo((i+".) "+a[i]);

The result of the above script is:

0.) a
1.) undefined
2.) c

You will also get undefined returned when reading a subscript or member that never existed.

The difference between null and undefined is: JavaScript will never set anything to null, that's usually what we do. While we can set variables to undefined, we prefer null because it's not something that is ever done for us. When you're debugging this means that anything set to null is of your own doing and not JavaScript. Beyond that, these two special values are nearly equivalent.

Uncaught TypeError: Cannot read property 'value' of null

HTML : Pass the whole body inside on click

div class="calculate" id="calculate">
            <div class="button" id="button" onclick="myCode(this.body)"> CALCULATE ! </div>
        </div>

Then write the JavaScript code inside the function "myCode()"

function myCode()
{
    var bill = document.getElementById("currency").value ;

    var people_count = document.getElementById("number1").value;
    var select_value = document.getElementById("select").value;

    var calculate = document.getElementById("calculate");

    calculate.addEventListener("click" ,function()
    {
        console.log(bill);
        console.log(people_count);
        console.log(select_value);
    });
}

you will get your values I am using visual studio code editor

Get selected value from combo box in C# WPF

Well.. I found a simpler solution.

String s = comboBox1.Text;

This way I get the selected value as string.

Check if a string contains an element from a list (of strings)

Have you tested the speed?

i.e. Have you created a sample set of data and profiled it? It may not be as bad as you think.

This might also be something you could spawn off into a separate thread and give the illusion of speed!

onclick="location.href='link.html'" does not load page in Safari

try

_x000D_
_x000D_
<select onchange="location=this.value">_x000D_
    <option value="unit_01.htm">Unit 1</option>_x000D_
    <option value="#5.2" selected >Bookmark 2</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

What is the difference between URL parameters and query strings?

The query component is indicated by the first ? in a URI. "Query string" might be a synonym (this term is not used in the URI standard).

Some examples for HTTP URIs with query components:

http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b

(list of allowed characters in the query component)

The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b.

Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.

Example URI with parameters in the path, the query, and the fragment:

http://example.com/foo;key1=value1?key2=value2#key3=value3

¹ The URI standard says about the query component:

[…] query components are often used to carry identifying information in the form of "key=value" pairs […]

² The URI standard says about the path component:

[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.

Annotation-specified bean name conflicts with existing, non-compatible bean def

I had a similar problem, with two jar libraries (app1 and app2) in one project. The bean "BeanName" is defined in app1 and is extended in app2 and the bean redefined with the same name.

In app1:

package com.foo.app1.pkg1;

@Component("BeanName")
public class Class1 { ... }

In app2:

package com.foo.app2.pkg2;

@Component("BeanName")
public class Class2 extends Class1 { ... }

This causes the ConflictingBeanDefinitionException exception in the loading of the applicationContext due to the same component bean name.

To solve this problem, in the Spring configuration file applicationContext.xml:

    <context:component-scan base-package="com.foo.app2.pkg2"/>
    <context:component-scan base-package="com.foo.app1.pkg1">
        <context:exclude-filter type="assignable" expression="com.foo.app1.pkg1.Class1"/>
    </context:component-scan>

So the Class1 is excluded to be automatically component-scanned and assigned to a bean, avoiding the name conflict.

Pass multiple arguments into std::thread

If you're getting this, you may have forgotten to put #include <thread> at the beginning of your file. OP's signature seems like it should work.

Convert a python dict to a string and back

If you care about the speed use ujson (UltraJSON), which has the same API as json:

import ujson
ujson.dumps([{"key": "value"}, 81, True])
# '[{"key":"value"},81,true]'
ujson.loads("""[{"key": "value"}, 81, true]""")
# [{u'key': u'value'}, 81, True]

How to add background image for input type="button"?

You need to type it without the word image.

background: url('/image/btn.png') no-repeat;

Tested both ways and this one works.

Example:

<html>
    <head>
        <style type="text/css">
            .button{
                background: url(/image/btn.png) no-repeat;
                cursor:pointer;
                border: none;
            }
        </style>
    </head>
    <body>
        <input type="button" name="button" value="Search" onclick="showUser()" class="button"/>
        <input type="image" name="button" value="Search" onclick="showUser()" class="button"/>
        <input type="submit" name="button" value="Search" onclick="showUser()" class="button"/>
    </body>
</html>

Adding rows to tbody of a table using jQuery

I have never ever come across such a strange problem like this! o.O

Do you know what the problem was? $ isn't working. I tried the same code with jQuery like jQuery("#tblEntAttributes tbody").append(newRowContent); and it works like a charm!

No idea why this strange problem occurs!

How do I calculate percentiles with python/numpy?

The definition of percentile I usually see expects as a result the value from the supplied list below which P percent of values are found... which means the result must be from the set, not an interpolation between set elements. To get that, you can use a simpler function.

def percentile(N, P):
    """
    Find the percentile of a list of values

    @parameter N - A list of values.  N must be sorted.
    @parameter P - A float value from 0.0 to 1.0

    @return - The percentile of the values.
    """
    n = int(round(P * len(N) + 0.5))
    return N[n-1]

# A = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# B = (15, 20, 35, 40, 50)
#
# print percentile(A, P=0.3)
# 4
# print percentile(A, P=0.8)
# 9
# print percentile(B, P=0.3)
# 20
# print percentile(B, P=0.8)
# 50

If you would rather get the value from the supplied list at or below which P percent of values are found, then use this simple modification:

def percentile(N, P):
    n = int(round(P * len(N) + 0.5))
    if n > 1:
        return N[n-2]
    else:
        return N[0]

Or with the simplification suggested by @ijustlovemath:

def percentile(N, P):
    n = max(int(round(P * len(N) + 0.5)), 2)
    return N[n-2]

Error: Segmentation fault (core dumped)

In my case: I forgot to activate virtualenv

I installed "pip install example" in the wrong virtualenv

Why do I always get the same sequence of random numbers with rand()?

Seeding the rand()

void srand (unsigned int seed)

This function establishes seed as the seed for a new series of pseudo-random numbers. If you call rand before a seed has been established with srand, it uses the value 1 as a default seed.

To produce a different pseudo-random series each time your program is run, do srand (time (0))

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

Alternatively if you want to grab the private and public keys from a PuTTY formated key file you can use puttygen on *nix systems. For most apt-based systems puttygen is part of the putty-tools package.

Outputting a private key from a PuTTY formated keyfile:

$ puttygen keyfile.pem -O private-openssh -o avdev.pvk

For the public key:

$ puttygen keyfile.pem -L

Passing data between different controller action methods

HTTP and redirects

Let's first recap how ASP.NET MVC works:

  1. When an HTTP request comes in, it is matched against a set of routes. If a route matches the request, the controller action corresponding to the route will be invoked.
  2. Before invoking the action method, ASP.NET MVC performs model binding. Model binding is the process of mapping the content of the HTTP request, which is basically just text, to the strongly typed arguments of your action method

Let's also remind ourselves what a redirect is:

An HTTP redirect is a response that the webserver can send to the client, telling the client to look for the requested content under a different URL. The new URL is contained in a Location header that the webserver returns to the client. In ASP.NET MVC, you do an HTTP redirect by returning a RedirectResult from an action.

Passing data

If you were just passing simple values like strings and/or integers, you could pass them as query parameters in the URL in the Location header. This is what would happen if you used something like

return RedirectToAction("ActionName", "Controller", new { arg = updatedResultsDocument });

as others have suggested

The reason that this will not work is that the XDocument is a potentially very complex object. There is no straightforward way for the ASP.NET MVC framework to serialize the document into something that will fit in a URL and then model bind from the URL value back to your XDocument action parameter.

In general, passing the document to the client in order for the client to pass it back to the server on the next request, is a very brittle procedure: it would require all sorts of serialisation and deserialisation and all sorts of things could go wrong. If the document is large, it might also be a substantial waste of bandwidth and might severely impact the performance of your application.

Instead, what you want to do is keep the document around on the server and pass an identifier back to the client. The client then passes the identifier along with the next request and the server retrieves the document using this identifier.

Storing data for retrieval on the next request

So, the question now becomes, where does the server store the document in the meantime? Well, that is for you to decide and the best choice will depend upon your particular scenario. If this document needs to be available in the long run, you may want to store it on disk or in a database. If it contains only transient information, keeping it in the webserver's memory, in the ASP.NET cache or the Session (or TempData, which is more or less the same as the Session in the end) may be the right solution. Either way, you store the document under a key that will allow you to retrieve the document later:

int documentId = _myDocumentRepository.Save(updatedResultsDocument);

and then you return that key to the client:

return RedirectToAction("UpdateConfirmation", "ApplicationPoolController ", new { id = documentId });

When you want to retrieve the document, you simply fetch it based on the key:

 public ActionResult UpdateConfirmation(int id)
 {
      XDocument doc = _myDocumentRepository.GetById(id);

      ConfirmationModel model = new ConfirmationModel(doc);

      return View(model);
 }

Cleanest way to toggle a boolean variable in Java?

Unfortunately, there is no short form like numbers have increment/decrement:

i++;

I would like to have similar short expression to invert a boolean, dmth like:

isEmpty!;

Copy directory contents into a directory with python

You can also use glob2 to recursively collect all paths (using ** subfolders wildcard) and then use shutil.copyfile, saving the paths

glob2 link: https://code.activestate.com/pypm/glob2/

Simulator or Emulator? What is the difference?

Both are models of an object that you have some means of controlling inputs to and observing outputs from.

The key difference is that:

  • With an emulator, you want the output exactly match what the object you are emulating would produce.
  • With a simulator, you want certain properties of your output to be similar to what the object would produce.

Let me give an example -- suppose you want to do some system testing to see how adding a new sensor (like a thermometer) to a system would affect the system. You know that the thermometer sends a message 8 time a second containing its measurement.

Simulation -- if you do not have the thermometer yet, but you want to test that this message rate will not overload you system, you can simulate the sensor by attaching a unit that sends a random number 8 times a second. You can run any test that does not rely on the actual value the sensor sends.

Emulation -- suppose you have a very expensive thermometer that measures to 0.001 C, and you want to see if you can get by with a cheaper thermometer that only measures to the nearest 0.5 C. You can emulate the cheaper thermometer using an expensive thermometer and then rounding the reading to the nearest 0.5 C and running tests that rely on the temperature values.

Note that simulations can also be used for forecasting or predicting behavior. Finite element analysis simulations are used in many applications, including weather prediction and virtual wind tunnels.

The definitions of the terms:

  • emulation -- surpass or exactly match
  • simulate -- imitate in appearance or character

How to print Boolean flag in NSLog?

NSArray *array1 = [NSArray arrayWithObjects:@"todd1", @"todd2", @"todd3", nil];
bool objectMembership = [array1 containsObject:@"todd1"];
NSLog(@"%d",objectMembership);  // prints 1 or 0

How to use Lambda in LINQ select statement

Why not just use all Lambda syntax?

database.Stores.Where(s => s.CompanyID == curCompany.ID)
               .Select(s => new SelectListItem
                   {
                       Value = s.Name,
                       Text = s.ID
                   });

How to tell if JRE or JDK is installed

@maciej-cygan described the process well, however in order to find your java path:

$ which java

it gives you the path of java binary file which is a linked file in /usr/bin directory. next:

$ cd /usr/bin/ && ls -la | grep java

find the pointed location which is something as follows (for me):

enter image description here then cd to the pointed directory to find the real home directory for Java. next:

$ ls -la | grep java

which is as follows in this case:

enter image description here

so as it's obvious in the screenshot, my Java home directory is /usr/lib/jvm/java-11-openjdk-amd64. So accordingly I need to add JAVA_HOME to my bash profile (.bashrc, .bash_profile, etc. depending on your OS) like below:

JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"

Here you go!

How do you test that a Python function throws an exception?

I just discovered that the Mock library provides an assertRaisesWithMessage() method (in its unittest.TestCase subclass), which will check not only that the expected exception is raised, but also that it is raised with the expected message:

from testcase import TestCase

import mymod

class MyTestCase(TestCase):
    def test1(self):
        self.assertRaisesWithMessage(SomeCoolException,
                                     'expected message',
                                     mymod.myfunc)

How do I request and process JSON with python?

Python's standard library has json and urllib2 modules.

import json
import urllib2

data = json.load(urllib2.urlopen('http://someurl/path/to/json'))

Using str_replace so that it only acts on the first match?

The easiest way would be to use regular expression.

The other way is to find the position of the string with strpos() and then an substr_replace()

But i would really go for the RegExp.

OSError: [Errno 8] Exec format error

OSError: [Errno 8] Exec format error can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:

>>> with open('a','w') as f: f.write('exit 0') # create the script
... 
>>> import os
>>> os.chmod('a', 0b111101101) # rwxr-xr-x make it executable                       
>>> os.execl('./a', './a')     # execute it                                            
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/os.py", line 312, in execl
    execv(file, args)
OSError: [Errno 8] Exec format error

To fix it, just add the shebang e.g., if it is a shell script; prepend #!/bin/sh at the top of your script:

>>> with open('a','w') as f: f.write('#!/bin/sh\nexit 0')
... 
>>> os.execl('./a', './a')

It executes exit 0 without any errors.


On POSIX systems, shell parses the command line i.e., your script won't see spaces around = e.g., if script is:

#!/usr/bin/env python
import sys
print(sys.argv)

then running it in the shell:

$ /usr/local/bin/script hostname = '<hostname>' -p LONGLIST

produces:

['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']

Note: no spaces around '='. I've added quotes around <hostname> to escape the redirection metacharacters <>.

To emulate the shell command in Python, run:

from subprocess import check_call

cmd = ['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']
check_call(cmd)

Note: no shell=True. And you don't need to escape <> because no shell is run.

"Exec format error" might indicate that your script has invalid format, run:

$ file /usr/local/bin/script

to find out what it is. Compare the architecture with the output of:

$ uname -m

Linux command to check if a shell script is running or not

The simplest and efficient solution is :

pgrep -fl aa.sh

How to remove item from array by value?

You can achieve this using Lodash _.remove function.

_x000D_
_x000D_
var array = ['three', 'seven', 'eleven'];_x000D_
var evens = _.remove(array, function(e) {_x000D_
  return e !== 'seven';_x000D_
});_x000D_
_x000D_
console.log(evens);
_x000D_
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

How do I replace multiple spaces with a single space in C#?

Another approach which uses LINQ:

 var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
 str = string.Join(" ", list);

How to avoid annoying error "declared and not used"

In case others have a hard time making sense of this, I think it might help to explain it in very straightforward terms. If you have a variable that you don't use, for example a function for which you've commented out the invocation (a common use-case):

myFn := func () { }
// myFn()

You can assign a useless/blank variable to the function so that it's no longer unused:

myFn := func () { }
_ = myFn
// myFn()

Pivoting rows into columns dynamically in Oracle

Oracle 11g provides a PIVOT operation that does what you want.

Oracle 11g solution

select * from
(select id, k, v from _kv) 
pivot(max(v) for k in ('name', 'age', 'gender', 'status')

(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)

I obtained this solution from: http://orafaq.com/wiki/PIVOT

EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html)

select * from
(select id, k, v from _kv) 
pivot xml (max(v)
for k in (any) )

(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)

Edit2: Changed v in the pivot and pivot xml statements to max(v) since it is supposed to be aggregated as mentioned in one of the comments. I also added the in clause which is not optional for pivot. Of course, having to specify the values in the in clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

your .key file contains illegal characters. you can check .key file like this:

# file server.key

output "server.key: UTF-8 Unicode (with BOM) text" means it is a plain text, not a key file. The correct output should be "server.key: PEM RSA private key".

use below command to remove illegal characters:

# tail -c +4 server.key > new_server.key

The new_server.key should be correct.

For more detail, you can click here, thanks for the post.

Operation must use an updatable query. (Error 3073) Microsoft Access

In essence, while your SQL looks perfectly reasonable, Jet has never supported the SQL standard syntax for UPDATE. Instead, it uses its own proprietary syntax (different again from SQL Server's proprietary UPDATE syntax) which is very limited. Often, the only workarounds "Operation must use an updatable query" are very painful. Seriously consider switching to a more capable SQL product.

For some more details about your specific problems and some possible workarounds, see Update Query Based on Totals Query Fails.

jQuery "blinking highlight" effect on div?

Check it out -

<input type="button" id="btnclick" value="click" />
var intervalA;
        var intervalB;

        $(document).ready(function () {

            $('#btnclick').click(function () {
                blinkFont();

                setTimeout(function () {
                    clearInterval(intervalA);
                    clearInterval(intervalB);
                }, 5000);
            });
        });

        function blinkFont() {
            document.getElementById("blink").style.color = "red"
            document.getElementById("blink").style.background = "black"
            intervalA = setTimeout("blinkFont()", 500);
        }

        function setblinkFont() {
            document.getElementById("blink").style.color = "black"
            document.getElementById("blink").style.background = "red"
            intervalB = setTimeout("blinkFont()", 500);
        }

    </script>

    <div id="blink" class="live-chat">
        <span>This is blinking text and background</span>
    </div>

How to resize superview to fit all subviews with autolayout?

Eric Baker's comment tipped me off to the core idea that in order for a view to have its size be determined by the content placed within it, then the content placed within it must have an explicit relationship with the containing view in order to drive its height (or width) dynamically. "Add subview" does not create this relationship as you might assume. You have to choose which subview is going to drive the height and/or width of the container... most commonly whatever UI element you have placed in the lower right hand corner of your overall UI. Here's some code and inline comments to illustrate the point.

Note, this may be of particular value to those working with scroll views since it's common to design around a single content view that determines its size (and communicates this to the scroll view) dynamically based on whatever you put in it. Good luck, hope this helps somebody out there.

//
//  ViewController.m
//  AutoLayoutDynamicVerticalContainerHeight
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end

@implementation ViewController

- (void)viewDidLoad
{
    // INVOKE SUPER
    [super viewDidLoad];

    // INIT ALL REQUIRED UI ELEMENTS
    self.contentView = [[UIView alloc] init];
    self.myLabel = [[UILabel alloc] init];
    self.myOtherLabel = [[UILabel alloc] init];
    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);

    // TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // ESTABLISH VIEW HIERARCHY
    [self.view addSubview:self.contentView]; // View adds content view
    [self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
    [self.contentView addSubview:self.myOtherLabel];

    // LAYOUT

    // Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
    // Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet

    /* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
    // ^To me this is what's weird... but okay once you understand...

    // Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];

    // Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
    // Note, this is the view that we are choosing to use to drive the height (and width) of our container...

    // The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // COLOR VIEWS
    self.view.backgroundColor = [UIColor purpleColor];
    self.contentView.backgroundColor = [UIColor redColor];
    self.myLabel.backgroundColor = [UIColor orangeColor];
    self.myOtherLabel.backgroundColor = [UIColor greenColor];

    // CONFIGURE VIEWS

    // Configure MY LABEL
    self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
    self.myLabel.numberOfLines = 0; // Let it flow

    // Configure MY OTHER LABEL
    self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
    self.myOtherLabel.numberOfLines = 0;
    self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}

@end

How to resize superview to fit all subviews with autolayout.png

how to upload a file to my server using html

On top of what the others have already stated, some sort of server-side scripting is necessary in order for the server to read and save the file.

Using PHP might be a good choice, but you're free to use any server-side scripting language. http://www.w3schools.com/php/php_file_upload.asp may be of use on that end.

Maximum number of threads per process in Linux?

It probably shouldn't matter. You are going to get much better performance designing your algorithm to use a fixed number of threads (eg, 4 or 8 if you have 4 or 8 processors). You can do this with work queues, asynchronous IO, or something like libevent.

Ruby String to Date Conversion

What is wrong with Date.parse method?

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
date = Date.parse str
=> #<Date: 4910837/2,0,2299161>
puts date
2010-08-10

It seems to work.

The only problem here is time zone. If you want date in UTC time zone, then it is better to use Time object, suppose we have string:

str = "Tue, 10 Aug 2010 01:20:19 +0400"
puts Date.parse str
2010-08-10
puts Date.parse(Time.parse(str).utc.to_s)
2010-08-09

I couldn't find simpler method to convert Time to Date.

How to get Url Hash (#) from server side

Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX). Regards Artur

You may see also how to play with back button and browser history at Malcan

Are one-line 'if'/'for'-statements good Python style?

You could do all of that in one line by omitting the example variable:

if "exam" in "example": print "yes!"

AngularJS - Access to child scope

One possible workaround is inject the child controller in the parent controller using a init function.

Possible implementation:

<div ng-controller="ParentController as parentCtrl">
   ...

    <div ng-controller="ChildController as childCtrl" 
         ng-init="ChildCtrl.init()">
       ...
    </div>
</div>

Where in ChildController you have :

app.controller('ChildController',
    ['$scope', '$rootScope', function ($scope, $rootScope) {
    this.init = function() {
         $scope.parentCtrl.childCtrl = $scope.childCtrl;
         $scope.childCtrl.test = 'aaaa';
    };

}])

So now in the ParentController you can use :

app.controller('ParentController',
    ['$scope', '$rootScope', 'service', function ($scope, $rootScope, service) {

    this.save = function() {
        service.save({
            a:  $scope.parentCtrl.ChildCtrl.test
        });
     };

}])

Important:
To work properly you have to use the directive ng-controller and rename each controller using as like i did in the html eg.

Tips:
Use the chrome plugin ng-inspector during the process. It's going to help you to understand the tree.

Insert data into hive table

Try to use this with single quotes in data:

insert into table test_hive values ('1','puneet');

How to count the frequency of the elements in an unordered list?

Simple solution using a dictionary.

def frequency(l):
     d = {}
     for i in l:
        if i in d.keys():
           d[i] += 1
        else:
           d[i] = 1

     for k, v in d.iteritems():
        if v ==max (d.values()):
           return k,d.keys()

print(frequency([10,10,10,10,20,20,20,20,40,40,50,50,30]))

Quick Sort Vs Merge Sort

It is not true that quicksort is better. ALso, it depends on what you mean better, memory consumption, or speed.

In terms of memory consumption, in worst case, but quicksort can use n^2 memory (i.e. each partition is 1 to n-1), whereas merge sort uses nlogn.

The above follows in terms of speed.

How Do I Convert an Integer to a String in Excel VBA?

Try the CStr() function

Dim myVal as String;
Dim myNum as Integer;

myVal = "My number is:"
myVal = myVal & CStr(myNum);

How to add a button to UINavigationBar?

Why not use the following: (from Draw custom Back button on iPhone Navigation Bar)

// Add left
UINavigationItem *previousItem = [[UINavigationItem alloc] initWithTitle:@"Back title"];
UINavigationItem *currentItem = [[UINavigationItem alloc] initWithTitle:@"Main Title"];
[self.navigationController.navigationBar setItems:[NSArray arrayWithObjects:previousItem, currentItem, nil] animated:YES];

// set the delegate to self
[self.navigationController.navigationBar setDelegate:self];

How to run code after some delay in Flutter?

await Future.delayed(Duration(milliseconds: 1000));

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

No 'Access-Control-Allow-Origin' header is present on the requested resource error

Try this - set Ajax call by setting up the header as follows:

var uri = "http://localhost:50869/odata/mydatafeeds"
$.ajax({
    url: uri,
    beforeSend: function (request) {
        request.setRequestHeader("Authorization", "Negotiate");
    },
    async: true,
    success: function (data) {
        alert(JSON.stringify(data));
    },
    error: function (xhr, textStatus, errorMessage) {
        alert(errorMessage);
    }                
});

Then run your code by opening Chrome with the following command line:

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

Sending and Parsing JSON Objects in Android

You can use org.json.JSONObject and org.json.JSONTokener. you don't need any external libraries since these classes come with Android SDK

Change Image of ImageView programmatically in Android

If the above solutions are not working just delete this entire line from XML

android:src="@drawable/image"

& only try

imageView.setBackgroundResource(R.drawable.image);

Convert timestamp to date in MySQL query

Just use mysql's DATE function:

mysql> select DATE(mytimestamp) from foo;

Update TensorFlow

Upgrading to Tensorflow 2.0 using pip. Requires Python > 3.4 and pip >= 19.0

CST:~ USERX$ pip3 show tensorflow
Name: tensorflow
Version: 1.13.1

CST:~ USERX$ python3 --version
Python 3.7.3

CST:~ USERX$ pip3 install --upgrade tensorflow

CST:~ USERX$ pip3 show tensorflow
Name: tensorflow
Version: 2.0.0

Bash command to sum a column of numbers

Does two lines count?

awk '{ sum += $1; }
     END { print sum; }' "$@"

You can then use it without the superfluous 'cat':

sum < FileWithColumnOfNumbers.txt
sum   FileWithColumnOfNumbers.txt

FWIW: on MacOS X, you can do it with a one-liner:

awk '{ sum += $1; } END { print sum; }' "$@"

How to add a scrollbar to an HTML5 table?

<!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Scrollable Table</title>
    <style type="text/css">
      * { padding: 0; margin: 0; }
      table.my_table { 
        font-family: verdana, arial, helvetica, sans-serif;
        font-size: 11px;
        cellspacing: 0; 
        border-collapse: collapse; 
        width: 283px;    
        }
      table.my_table th, table.my_table td { 
        border-bottom: 1px solid #999; 
        border-right: 1px solid #999; 
        }
      table.my_table th { background: #ffb; }
      table.my_table td { background: #ffe; }

      div.scrollableContainer { 
        height: 100px; 
        overflow: auto;  
        width: 300px; 
        margin: 40px;    
        border: 1px solid #999;
        background: #ffb;     
        }

    </style>
    </head>
    <body>
    <div class="scrollableContainer">
        <table class="my_table scrollable">
          <thead>
            <tr>
              <th>URL</th>
                </tr>
        </thead>

        <tbody>
                <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td> 
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td>                   
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td> 
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td>                   
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td> 
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td>                   
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td> 
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td>                   
                    </tr>
            </tbody>
          </table>
        </div>
      </body>
    </html>

html cellpadding the left side of a cell

Well, as suggested by Hellfire you can use td width or you could place an element in the td and adjust its width. We could not use

CSS property Padding

as in Microsoft Outlook padding does not work. So what I had to do is,

<table>
    <tr>
        <td><span style="display: inline-block; width: 40px;"></span><span>Content<span></td>
        <td>Content</td>
    </tr>
</table>

With this you can adjust right and left spacing. For top and bottom spacing you could use td's height property. Like,

 <table>
        <tr>
            <td style="vertical-align: top; height: 100px;">Content</td>
            <td>Content</td>
        </tr>
    </table>

This will increase bottom space.

Hope it will work for you guys. :)

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

Start systemd service after specific service?

After= dependency is only effective when service including After= and service included by After= are both scheduled to start as part of your boot up.

Ex:

a.service
[Unit]
After=b.service

This way, if both a.service and b.service are enabled, then systemd will order b.service after a.service.

If I am not misunderstanding, what you are asking is how to start b.service when a.service starts even though b.service is not enabled.

The directive for this is Wants= or Requires= under [Unit].

website.service
[Unit]
Wants=mongodb.service
After=mongodb.service

The difference between Wants= and Requires= is that with Requires=, a failure to start b.service will cause the startup of a.service to fail, whereas with Wants=, a.service will start even if b.service fails. This is explained in detail on the man page of .unit.

pip: no module named _internal

I fixed this problem by

sudo apt-get install python3-pip

this worked even for python2.7, amazing...

Output data with no column headings using PowerShell

The -expandproperty does not work with more than 1 object. You can use this one :

Select-Object Name | ForEach-Object {$_.Name}

If there is more than one value then :

Select-Object Name, Country | ForEach-Object {$_.Name + " " + $Country}

Trimming text strings in SQL Server 2008

You can use the RTrim function to trim all whitespace from the right. Use LTrim to trim all whitespace from the left. For example

UPDATE Table SET Name = RTrim(Name)

Or for both left and right trim

UPDATE Table SET Name = LTrim(RTrim(Name))

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

To solve this problem just call jQuery file before the bootstrap file

Selecting default item from Combobox C#

This means that your selectedindex is out of the range of the array of items in the combobox. The array of items in your combo box is zero-based, so if you have 2 items, it's item 0 and item 1.

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

Youtube autoplay not working on mobile devices with embedded HTML5 player

As it turns out, autoplay cannot be done on iOS devices (iPhone, iPad, iPod touch) and Android.

See https://stackoverflow.com/a/8142187/2054512 and https://stackoverflow.com/a/3056220/2054512

Python glob multiple filetypes

So many answers that suggest globbing as many times as number of extensions, I'd prefer globbing just once instead:

from pathlib import Path

files = {p.resolve() for p in Path(path).glob("**/*") if p.suffix in [".c", ".cc", ".cpp", ".hxx", ".h"]}

Unresolved external symbol on static class members

Since this is the first SO thread that seemed to come up for me when searching for "unresolved externals with static const members" in general, I'll leave another hint to solve one problem with unresolved externals here:

For me, the thing that I forgot was to mark my class definition __declspec(dllexport), and when called from another class (outside that class's dll's boundaries), I of course got the my unresolved external error.
Still, easy to forget when you're changing an internal helper class to a one accessible from elsewhere, so if you're working in a dynamically linked project, you might as well check that, too.

ReactJs: What should the PropTypes be for this.props.children?

The PropTypes documentation has the following

// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalNode: PropTypes.node,

So, you can use PropTypes.node to check for objects or arrays of objects

static propTypes = {
   children: PropTypes.node.isRequired,
}

Pandas Split Dataframe into two Dataframes at a specific row

use np.split(..., axis=1):

Demo:

In [255]: df = pd.DataFrame(np.random.rand(5, 6), columns=list('abcdef'))

In [256]: df
Out[256]:
          a         b         c         d         e         f
0  0.823638  0.767999  0.460358  0.034578  0.592420  0.776803
1  0.344320  0.754412  0.274944  0.545039  0.031752  0.784564
2  0.238826  0.610893  0.861127  0.189441  0.294646  0.557034
3  0.478562  0.571750  0.116209  0.534039  0.869545  0.855520
4  0.130601  0.678583  0.157052  0.899672  0.093976  0.268974

In [257]: dfs = np.split(df, [4], axis=1)

In [258]: dfs[0]
Out[258]:
          a         b         c         d
0  0.823638  0.767999  0.460358  0.034578
1  0.344320  0.754412  0.274944  0.545039
2  0.238826  0.610893  0.861127  0.189441
3  0.478562  0.571750  0.116209  0.534039
4  0.130601  0.678583  0.157052  0.899672

In [259]: dfs[1]
Out[259]:
          e         f
0  0.592420  0.776803
1  0.031752  0.784564
2  0.294646  0.557034
3  0.869545  0.855520
4  0.093976  0.268974

np.split() is pretty flexible - let's split an original DF into 3 DFs at columns with indexes [2,3]:

In [260]: dfs = np.split(df, [2,3], axis=1)

In [261]: dfs[0]
Out[261]:
          a         b
0  0.823638  0.767999
1  0.344320  0.754412
2  0.238826  0.610893
3  0.478562  0.571750
4  0.130601  0.678583

In [262]: dfs[1]
Out[262]:
          c
0  0.460358
1  0.274944
2  0.861127
3  0.116209
4  0.157052

In [263]: dfs[2]
Out[263]:
          d         e         f
0  0.034578  0.592420  0.776803
1  0.545039  0.031752  0.784564
2  0.189441  0.294646  0.557034
3  0.534039  0.869545  0.855520
4  0.899672  0.093976  0.268974

Use .htaccess to redirect HTTP to HTTPs

Redirect from http to https://www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

This will work for sure!

How to write a caption under an image?

<table>
<tr><td><img ...><td><img ...>
<tr><td>caption1<td>caption2
</table>

Style as desired.

Rails: Can't verify CSRF token authenticity when making a POST request

Since Rails 5 you can also create a new class with ::API instead of ::Base:

class ApiController < ActionController::API
end

Multiple values in single-value context

How about this way?

package main

import (
    "fmt"
    "errors"
)

type Item struct {
    Value int
    Name string
}

var items []Item = []Item{{Value:0, Name:"zero"}, 
                        {Value:1, Name:"one"}, 
                        {Value:2, Name:"two"}}

func main() {
    var err error
    v := Get(3, &err).Value
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(v)

}

func Get(value int, err *error) Item {
    if value > (len(items) - 1) {
        *err = errors.New("error")
        return Item{}
    } else {
        return items[value]
    }
}

Use of for_each on map elements

You can iterate through a std::map object. Each iterator will point to a std::pair<const T,S> where T and S are the same types you specified on your map.

Here this would be:

for (std::map<int, MyClass>::iterator it = Map.begin(); it != Map.end(); ++it)
{
  it->second.Method();
}

If you still want to use std::for_each, pass a function that takes a std::pair<const int, MyClass>& as an argument instead.

Example:

void CallMyMethod(std::pair<const int, MyClass>& pair) // could be a class static method as well
{
  pair.second.Method();
}

And pass it to std::for_each:

std::for_each(Map.begin(), Map.end(), CallMyMethod);

Angular 2 Cannot find control with unspecified name attribute on formArrays

Remove the brackets from

[formArrayName]="areas" 

and use only

formArrayName="areas"

This, because with [ ] you are trying to bind a variable, which this is not. Also notice your submit, it should be:

(ngSubmit)="onSubmit(areasForm.value)"

instead of areasForm.values.

Oracle SQL: Use sequence in insert with Select Statement

I tested and the script run ok!

INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
WITH DATA AS
(
    SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
    FROM HISTORICAL_CAR_STATS
    WHERE YEAR = '2010' AND MONTH = '12'
    AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;

you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287

How can I get (query string) parameters from the URL in Next.js?

import { useRouter } from 'next/router';

function componentName() {
    const router = useRouter();
    console.log('router obj', router);
}

We can find the query object inside a router using which we can get all query string parameters.

Print text instead of value from C enum

i'm new to this but a switch statement will defenitely work

#include <stdio.h>

enum mycolor;

int main(int argc, const char * argv[])

{
enum Days{Sunday=1,Monday=2,Tuesday=3,Wednesday=4,Thursday=5,Friday=6,Saturday=7};

enum Days TheDay;


printf("Please enter the day of the week (0 to 6)\n");

scanf("%d",&TheDay);

switch (TheDay)
 {

case Sunday:
        printf("the selected day is sunday");
        break;
    case Monday:
        printf("the selected day is monday");
        break;
    case Tuesday:
        printf("the selected day is Tuesday");
        break;
    case Wednesday:
        printf("the selected day is Wednesday");
        break;
    case Thursday:
        printf("the selected day is thursday");
        break;
    case Friday:
        printf("the selected day is friday");
        break;
    case Saturday:
        printf("the selected day is Saturaday");
        break;
    default:
        break;
}

return 0;
}

#1292 - Incorrect date value: '0000-00-00'

You have 3 options to make your way:
1. Define a date value like '1970-01-01'
2. Select NULL from the dropdown to keep it blank.
3. Select CURRENT_TIMESTAMP to set current datetime as default value.

Sorting a Python list by two fields

In ascending order you can use:

sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]))

or in descending order you can use:

sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]),reverse=True)

Combining multiple commits before pushing in Git

You probably want to use Interactive Rebasing, which is described in detail in that link.

You can find other good resources if you search for "git rebase interactive".

Center Plot title in ggplot2

The ggeasy package has a function called easy_center_title() to do just that. I find it much more appealing than theme(plot.title = element_text(hjust = 0.5)) and it's so much easier to remember.

ggplot(data = dat, aes(time, total_bill, fill = time)) + 
  geom_bar(colour = "black", fill = "#DD8888", width = .8, stat = "identity") + 
  guides(fill = FALSE) +
  xlab("Time of day") +
  ylab("Total bill") +
  ggtitle("Average bill for 2 people") +
  ggeasy::easy_center_title()

enter image description here

Note that as of writing this answer you will need to install the development version of ggeasy from GitHub to use easy_center_title(). You can do so by running remotes::install_github("jonocarroll/ggeasy").

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

I have got the same error as :

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/

As, said by @Agaline, i download the outside wheel from this Christoph Gohlke.

If your is Python 3.7 then try to PyAudio-0.2.11-cp37-cp37m-win_amd64.whl and use command as, go to the download directroy and:

pip install PyAudio-0.2.11-cp37-cp37m-win_amd64.whl and it works.

jQuery Scroll to Div

You can also use 'name' instead of 'href' for a cleaner url:

    $('a[name^=#]').click(function(){
    var target = $(this).attr('name');
    if (target == '#')
      $('html, body').animate({scrollTop : 0}, 600);
    else
      $('html, body').animate({
        scrollTop: $(target).offset().top - 100
    }, 600);
});

Where is nodejs log file?

There is no log file. Each node.js "app" is a separate entity. By default it will log errors to STDERR and output to STDOUT. You can change that when you run it from your shell to log to a file instead.

node my_app.js > my_app_log.log 2> my_app_err.log

Alternatively (recommended), you can add logging inside your application either manually or with one of the many log libraries:

React Native TextInput that only accepts numeric characters

Using a RegExp to replace any non digit. Take care the next code will give you the first digit he found, so if user paste a paragraph with more than one number (xx.xx) the code will give you the first number. This will help if you want something like price, not a mobile phone.

Use this for your onTextChange handler:

onChanged (text) {
    this.setState({
        number: text.replace(/[^(((\d)+(\.)\d)|((\d)+))]/g,'_').split("_"))[0],
    });
}

pull/push from multiple remote locations

You can add remotes with:

git remote add a urla
git remote add b urlb

Then to update all the repos do:

git remote update

Remove files from Git commit

If you want to preserve your commit (maybe you already spent some time writing a detailed commit message and don't want to lose it), and you only want to remove the file from the commit, but not from the repository entirely:

git checkout origin/<remote-branch> <filename>
git commit --amend

How to get build time stamp from Jenkins build variables?

Generate environment variables from script (Unix script) :

echo "BUILD_DATE=$(date +%F-%T)"

BitBucket - download source as ZIP

I was trying to figure out if it's possible to browse the code of an earlier commit like you can on GitHub and it brought me here. I used the information I found here, and after fiddling around with the urls, I actually found a way to browse code of old commits as well. Even though the question/answer is about downloading the code of an earlier commit, I thought I'd just add an answer for browsing the code also.

When you're browsing your code the URL is something like:

https://bitbucket.org/user/repo/src/

and by adding a commit hash at the end like this:

https://bitbucket.org/user/repo/src/a0328cb

You can browse the code at the point of that commit. I don't understand why there's no dropdown box for choosing a commit directly, the feature is already there. Strange.

What does it mean when MySQL is in the state "Sending data"?

In this state:

The thread is reading and processing rows for a SELECT statement, and sending data to the client.

Because operations occurring during this this state tend to perform large amounts of disk access (reads).

That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.

Creating an instance using the class name and calling constructor

You can use Class.forName() to get a Class object of the desired class.

Then use getConstructor() to find the desired Constructor object.

Finally, call newInstance() on that object to get your new instance.

Class<?> c = Class.forName("mypackage.MyClass");
Constructor<?> cons = c.getConstructor(String.class);
Object object = cons.newInstance("MyAttributeValue");

Method List in Visual Studio Code

CTRL+F12 (CMD+F12 for Mac) - opens for me all methods and members in PHP class.

Visual Studio Post Build Event - Copy to Relative Directory Location

I think this is related, but I had a problem when building directly using msbuild command line (from a batch file) vs building from within VS.

Using something like the following:

<PostBuildEvent>
  MOVE /Y "$(TargetDir)something.file1" "$(ProjectDir)something.file1"
  start XCOPY /Y /R "$(SolutionDir)SomeConsoleApp\bin\$(ConfigurationName)\*" "$(ProjectDir)App_Data\Consoles\SomeConsoleApp\"
</PostBuildEvent>

(note: start XCOPY rather than XCOPY used to get around a permissions issue which prevented copying)

The macro $(SolutionDir) evaluated to ..\ when executing msbuild from a batchfile, which resulted in the XCOPY command failing. It otherwise worked fine when built from within Visual Studio. Confirmed using /verbosity:diagnostic to see the evaluated output.

Using the macro $(ProjectDir)..\ instead, which amounts to the same thing, worked fine and retained the full path in both build scenarios.

VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory

The issue turned out to be certificate-related. The WCF service called by the console app uses an X509 cert for authentication, which is installed on the servers that this script is hosted and run from.

On other servers, where the same services are consumed, the certificates were configured as follows:

winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "NETWORK SERVICE"

As they ran within the context of IIS. However, when the script was being run as it would in production, it's under the context of the user themselves. So, the script needed to be modified to the following:

winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "USERS"

Once that change was made, all was well. Thanks to everyone who offered assistance.

TypeError: 'module' object is not callable

socket is a module, containing the class socket.

You need to do socket.socket(...) or from socket import socket:

>>> import socket
>>> socket
<module 'socket' from 'C:\Python27\lib\socket.pyc'>
>>> socket.socket
<class 'socket._socketobject'>
>>>
>>> from socket import socket
>>> socket
<class 'socket._socketobject'>

This is what the error message means:
It says module object is not callable, because your code is calling a module object. A module object is the type of thing you get when you import a module. What you were trying to do is to call a class object within the module object that happens to have the same name as the module that contains it.

Here is a way to logically break down this sort of error:

  • "module object is not callable. Python is telling me my code trying to call something that cannot be called. What is my code trying to call?"
  • "The code is trying to call on socket. That should be callable! Is the variable socket is what I think it is?`
  • I should print out what socket is and check print socket

Repository Pattern Step by Step Explanation

This is a nice example: The Repository Pattern Example in C#

Basically, repository hides the details of how exactly the data is being fetched/persisted from/to the database. Under the covers:

  • for reading, it creates the query satisfying the supplied criteria and returns the result set
  • for writing, it issues the commands necessary to make the underlying persistence engine (e.g. an SQL database) save the data

Best Timer for using in a Windows service

Either one should work OK. In fact, System.Threading.Timer uses System.Timers.Timer internally.

Having said that, it's easy to misuse System.Timers.Timer. If you don't store the Timer object in a variable somewhere, then it is liable to be garbage collected. If that happens, your timer will no longer fire. Call the Dispose method to stop the timer, or use the System.Threading.Timer class, which is a slightly nicer wrapper.

What problems have you seen so far?

Add to python path mac os x

Not sure why Matthew's solution didn't work for me (could be that I'm using OSX10.8 or perhaps something to do with macports). But I added the following to the end of the file at ~/.profile

export PYTHONPATH=/path/to/dir:$PYTHONPATH

my directory is now on the pythonpath -

my-macbook:~ aidan$ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/path/to/dir', ...  

and I can import modules from that directory.

How to set the custom border color of UIView programmatically?

swift 3.0

self.uiTextView.layer.borderWidth = 0.5
    self.txtItemShortDes.layer.borderColor = UIColor(red:205.0/255.0, green:205.0/255.0, blue:205.0/255.0, alpha: 1.0).cgColor

How do I reset the setInterval timer?

If by "restart", you mean to start a new 4 second interval at this moment, then you must stop and restart the timer.

function myFn() {console.log('idle');}

var myTimer = setInterval(myFn, 4000);

// Then, later at some future time, 
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);

You could also use a little timer object that offers a reset feature:

function Timer(fn, t) {
    var timerObj = setInterval(fn, t);

    this.stop = function() {
        if (timerObj) {
            clearInterval(timerObj);
            timerObj = null;
        }
        return this;
    }

    // start timer using current settings (if it's not already running)
    this.start = function() {
        if (!timerObj) {
            this.stop();
            timerObj = setInterval(fn, t);
        }
        return this;
    }

    // start with new or original interval, stop current interval
    this.reset = function(newT = t) {
        t = newT;
        return this.stop().start();
    }
}

Usage:

var timer = new Timer(function() {
    // your function here
}, 5000);


// switch interval to 10 seconds
timer.reset(10000);

// stop the timer
timer.stop();

// start the timer
timer.start();

Working demo: https://jsfiddle.net/jfriend00/t17vz506/

Can Google Chrome open local links?

It's not really an anwser but a workaround to open a local link in chrome using python.

Copy the local link you want to run then run the code bellow (using a shortcut), it will open your link.

import win32clipboard
import os

win32clipboard.OpenClipboard()
clipboard_data= win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()

os.system("start "+clipboard_data)

How do I find out what all symbols are exported from a shared object?

If it is a Windows DLL file and your OS is Linux then use winedump:

$ winedump -j export pcre.dll

Contents of pcre.dll: 229888 bytes

Exports table:

  Name:            pcre.dll
  Characteristics: 00000000
  TimeDateStamp:   53BBA519 Tue Jul  8 10:00:25 2014
  Version:         0.00
  Ordinal base:    1
  # of functions:  31
  # of Names:      31
Addresses of functions: 000375C8
Addresses of name ordinals: 000376C0
Addresses of names: 00037644

  Entry Pt  Ordn  Name
  0001FDA0     1 pcre_assign_jit_stack
  000380B8     2 pcre_callout
  00009030     3 pcre_compile
...

Why do we use web.xml?

Web.xml is called as deployment descriptor file and its is is an XML file that contains information on the configuration of the web application, including the configuration of servlets.

How to set the min and max height or width of a Frame?

There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.

Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.

import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

How to convert current date to epoch timestamp?

Your code will behave strange if 'TZ' is not set properly, e.g. 'UTC' or 'Asia/Kolkata'

So, you need to do below

>>> import time, os
>>> d='2014-12-11 00:00:00'
>>> p='%Y-%m-%d %H:%M:%S'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418236200
>>> os.environ['TZ']='UTC'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418256000

Vue.js redirection to another page

If you are using vue-router, you should use router.go(path) to navigate to any particular route. The router can be accessed from within a component using this.$router.

Otherwise, window.location.href = 'some url'; works fine for non single-page apps.

EDIT: router.go() changed in VueJS 2.0. You can use router.push({ name: "yourroutename"}) or just router.push("yourroutename") now to redirect.

Documentation

P.S: In controllers use: this.$router.push({ name: 'routename' })

Using if-else in JSP

Instead of if-else condition use if in both conditions. it will work that way but not sure why.

Html.DropdownListFor selected value not being set

Linq to Dropdown with empty item, selected item (works 100%)
(Strongly Typed,Chances for error minimum) Any model changes will be reflected in the binding

Controller

public ActionResult ManageSurveyGroup()
    {
        tbl_Survey sur = new tbl_Survey();
        sur.Survey_Est = "3";

        return View(sur);
    }

View

        @{


    //Step One : Getting all the list
    var CompEstdList = (from ComType in db.tbl_CompEstdt orderby ComType.Comp_EstdYr select ComType).ToList();

    //Step Two  : Adding a no Value item **
    CompEstdList.Insert(0, new eDurar.Models.tbl_CompEstdt { Comp_Estdid = 0, Comp_EstdYr = "--Select Company Type--" });

    //Step Three : Setting selected Value if value is present
    var selListEstd= CompEstdList.Select(s => new SelectListItem { Text = s.Comp_EstdYr, Value = s.Comp_Estdid.ToString() });

        }
        @Html.DropDownListFor(model => model.Survey_Est, selListEstd)
        @Html.ValidationMessageFor(model => model.Survey_Est)

This method for binding data also possible

var selList = CompTypeList.Select(s => new SelectListItem { Text = s.CompTyp_Name, Value = s.CompTyp_Id.ToString(), Selected = s.CompTyp_Id == 3 ? true : false });

How do I get the current username in .NET using C#?

I went over most of the answers here and none of them gave me the right user name.

In my case I wanted to get the logged in user name, while running my app from a different user, like when shift+right click on a file and "Run as a different user".

The answers I tried gave me the 'other' username.

This blog post supplies a way to get the logged in user name, which works even in my scenario:
https://smbadiwe.github.io/post/track-activities-windows-service/

It uses Wtsapi

How to make a char string from a C macro's value?

#include <stdio.h>

#define QUOTEME(x) #x

#ifndef TEST_FUN
#  define TEST_FUN func_name
#  define TEST_FUN_NAME QUOTEME(TEST_FUN)
#endif

int main(void)
{
    puts(TEST_FUN_NAME);
    return 0;
}

Reference: Wikipedia's C preprocessor page

Node.js: Python not found exception due to node-sass and node-gyp

This is 2 years old, but none of them helped me.

I uninstalled my NodeJS v12.8.1 (Current) and installed a brand new v10.16.3 (LTS) and my ng build --prod worked.

How to convert object to Dictionary<TKey, TValue> in C#?

You can create a generic extension method and then use it on the object like:

public static class Extensions
{
    public static KeyValuePair<TKey, TValue> ToKeyValuePair<TKey, TValue>(this Object obj)
    {
        // if obj is null throws exception
        Contract.Requires(obj != null);

        // gets the type of the obj parameter
        var type = obj.GetType();
        // checks if obj is of type KeyValuePair
        if (type.IsGenericType && type == typeof(KeyValuePair<TKey, TValue>))
        {

            return new KeyValuePair<TKey, TValue>(
                                                    (TKey)type.GetProperty("Key").GetValue(obj, null), 
                                                    (TValue)type.GetProperty("Value").GetValue(obj, null)
                                                 );

        }
        // if obj type does not match KeyValuePair throw exception
        throw new ArgumentException($"obj argument must be of type KeyValuePair<{typeof(TKey).FullName},{typeof(TValue).FullName}>");   
 }

and usage would be like:

KeyValuePair<string,long> kvp = obj.ToKeyValuePair<string,long>();

How can I search (case-insensitive) in a column using LIKE wildcard?

SELECT  *
FROM    trees
WHERE   trees.`title` COLLATE UTF8_GENERAL_CI LIKE '%elm%'

Actually, if you add COLLATE UTF8_GENERAL_CI to your column's definition, you can just omit all these tricks: it will work automatically.

ALTER TABLE trees 
 MODIFY COLUMN title VARCHAR(…) CHARACTER 
 SET UTF8 COLLATE UTF8_GENERAL_CI. 

This will also rebuild any indexes on this column so that they could be used for the queries without leading '%'

When is std::weak_ptr useful?

shared_ptr : holds the real object.

weak_ptr : uses lock to connect to the real owner or returns a NULL shared_ptr otherwise.

weak ptr

Roughly speaking, weak_ptr role is similar to the role of housing agency. Without agents, to get a house on rent we may have to check random houses in the city. The agents make sure that we visit only those houses which are still accessible and available for rent.

MySQL - count total number of rows in php

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";

if ($result=mysqli_query($con,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
  echo "number of rows: ",$rowcount;
  // Free result set
  mysqli_free_result($result);
  }

mysqli_close($con);
?>

it is best way (I think) to get the number of special row in mysql with php.

PostgreSQL visual interface similar to phpMyAdmin?

pgAdmin 4 is a powerful and popular web-based database management tool for PostgreSQL - http://www.pgadmin.org/

Shell script to send email

mail -s "Your Subject" [email protected] < /file/with/mail/content

(/file/with/mail/content should be a plaintext file, not a file attachment or an image, etc)

How to add buttons at top of map fragment API v2 layout

You can use the below code to change the button to Left side.

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zakasoft.mymap.MapsActivity" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left|top"
        android:text="Send"
        android:padding="10dp"
        android:layout_marginTop="20dp"
        android:paddingRight="10dp"/>

</fragment>

How to add a border just on the top side of a UIView

Here's a Swift 4 version of Pauls's answer

func addTopBorder(color: UIColor, thickness: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
    border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: thickness)
    addSubview(border)
}

func addBottomBorder(color: UIColor, thickness: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
    border.frame = CGRect(x: 0, y: frame.size.height - thickness, width: frame.size.width, height: thickness)
    addSubview(border)
}

func addLeftBorder(color: UIColor, thickness: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleHeight, .flexibleRightMargin]
    border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.size.height)
    addSubview(border)
}

func addRightBorder(color: UIColor, thickness: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin]
    border.frame = CGRect(x: frame.size.width - thickness, y: 0, width: thickness, height: frame.size.height)
    addSubview(border)
}

For homebrew mysql installs, where's my.cnf?

I believe the answer is no. Installing one in ~/.my.cnf or /usr/local/etc seems to be the preferred solution.

Retrieving the output of subprocess.call()

Output from subprocess.call() should only be redirected to files.

You should use subprocess.Popen() instead. Then you can pass subprocess.PIPE for the stderr, stdout, and/or stdin parameters and read from the pipes by using the communicate() method:

from subprocess import Popen, PIPE

p = Popen(['program', 'arg1'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate(b"input data that is passed to subprocess' stdin")
rc = p.returncode

The reasoning is that the file-like object used by subprocess.call() must have a real file descriptor, and thus implement the fileno() method. Just using any file-like object won't do the trick.

See here for more info.

Invalid default value for 'dateAdded'

Change the type from datetime to timestamp and it will work! I had the same issue for mysql 5.5.56-MariaDB - MariaDB Server Hope it can help... sorry if depricated

Detecting endianness programmatically in a C++ program

The C++ way has been to use boost, where preprocessor checks and casts are compartmentalized away inside very thoroughly-tested libraries.

The Predef Library (boost/predef.h) recognizes four different kinds of endianness.

The Endian Library was planned to be submitted to the C++ standard, and supports a wide variety of operations on endian-sensitive data.

As stated in answers above, Endianness will be a part of c++20.

How to open a WPF Popup when another control is clicked, using XAML markup only?

I had some issues with the MouseDown part of this, but here is some code that might get your started.

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Control VerticalAlignment="Top">
            <Control.Template>
                <ControlTemplate>
                    <StackPanel>
                    <TextBox x:Name="MyText"></TextBox>
                    <Popup x:Name="Popup" PopupAnimation="Fade" VerticalAlignment="Top">
                        <Border Background="Red">
                            <TextBlock>Test Popup Content</TextBlock>
                        </Border>
                    </Popup>
                    </StackPanel>
                    <ControlTemplate.Triggers>
                        <EventTrigger RoutedEvent="UIElement.MouseEnter" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="True"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="UIElement.MouseLeave" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="False"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Control.Template>
        </Control>
    </Grid>
</Window>

SELECT COUNT in LINQ to SQL C#

You should be able to do the count on the purch variable:

purch.Count();

e.g.

var purch = from purchase in myBlaContext.purchases
select purchase;

purch.Count();

How to write connection string in web.config file and read from it?

Are you sure that your configuration file (web.config) is at the right place and the connection string is really in the (generated) file? If you publish your file, the content of web.release.config might be copied.

The configuration and the access to the Connection string looks all right to me. I would always add a providername

<connectionStrings>
  <add name="Dbconnection" 
       connectionString="Server=localhost; Database=OnlineShopping; 
       Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Object variable or With block variable not set (Error 91)

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

Difference between objectForKey and valueForKey?

I'll try to provide a comprehensive answer here. Much of the points appear in other answers, but I found each answer incomplete, and some incorrect.

First and foremost, objectForKey: is an NSDictionary method, while valueForKey: is a KVC protocol method required of any KVC complaint class - including NSDictionary.

Furthermore, as @dreamlax wrote, documentation hints that NSDictionary implements its valueForKey: method USING its objectForKey: implementation. In other words - [NSDictionary valueForKey:] calls on [NSDictionary objectForKey:].

This implies, that valueForKey: can never be faster than objectForKey: (on the same input key) although thorough testing I've done imply about 5% to 15% difference, over billions of random access to a huge NSDictionary. In normal situations - the difference is negligible.

Next: KVC protocol only works with NSString * keys, hence valueForKey: will only accept an NSString * (or subclass) as key, whilst NSDictionary can work with other kinds of objects as keys - so that the "lower level" objectForKey: accepts any copy-able (NSCopying protocol compliant) object as key.

Last, NSDictionary's implementation of valueForKey: deviates from the standard behavior defined in KVC's documentation, and will NOT emit a NSUnknownKeyException for a key it can't find - unless this is a "special" key - one that begins with '@' - which usually means an "aggregation" function key (e.g. @"@sum, @"@avg"). Instead, it will simply return a nil when a key is not found in the NSDictionary - behaving the same as objectForKey:

Following is some test code to demonstrate and prove my notes.

- (void) dictionaryAccess {
    NSLog(@"Value for Z:%@", [@{@"X":@(10), @"Y":@(20)} valueForKey:@"Z"]); // prints "Value for Z:(null)"

    uint32_t testItemsCount = 1000000;
    // create huge dictionary of numbers
    NSMutableDictionary *d = [NSMutableDictionary dictionaryWithCapacity:testItemsCount];
    for (long i=0; i<testItemsCount; ++i) {
        // make new random key value pair:
        NSString *key = [NSString stringWithFormat:@"K_%u",arc4random_uniform(testItemsCount)];
        NSNumber *value = @(arc4random_uniform(testItemsCount));
        [d setObject:value forKey:key];
    }
    // create huge set of random keys for testing.
    NSMutableArray *keys = [NSMutableArray arrayWithCapacity:testItemsCount];
    for (long i=0; i<testItemsCount; ++i) {
        NSString *key = [NSString stringWithFormat:@"K_%u",arc4random_uniform(testItemsCount)];
        [keys addObject:key];
    }

    NSDictionary *dict = [d copy];
    NSTimeInterval vtotal = 0.0, ototal = 0.0;

    NSDate *start;
    NSTimeInterval elapsed;

    for (int i = 0; i<10; i++) {

        start = [NSDate date];
        for (NSString *key in keys) {
            id value = [dict valueForKey:key];
        }
        elapsed = [[NSDate date] timeIntervalSinceDate:start];
        vtotal+=elapsed;
        NSLog (@"reading %lu values off dictionary via valueForKey took: %10.4f seconds", keys.count, elapsed);

        start = [NSDate date];
        for (NSString *key in keys) {
            id obj = [dict objectForKey:key];
        }
        elapsed = [[NSDate date] timeIntervalSinceDate:start];
        ototal+=elapsed;
        NSLog (@"reading %lu objects off dictionary via objectForKey took: %10.4f seconds", keys.count, elapsed);
    }

    NSString *slower = (vtotal > ototal) ? @"valueForKey" : @"objectForKey";
    NSString *faster = (vtotal > ototal) ? @"objectForKey" : @"valueForKey";
    NSLog (@"%@ takes %3.1f percent longer then %@", slower, 100.0 * ABS(vtotal-ototal) / MAX(ototal,vtotal), faster);
}

Get client IP address via third party web service

If you face an issue of CORS, you can use https://api.ipify.org/.

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}


publicIp = httpGet("https://api.ipify.org/");
alert("Public IP: " + publicIp);

I agree that using synchronous HTTP call is not good idea. You can use async ajax call then.

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

UPDATE 11/22/2013 - this is the latest WebApi package:

Install-Package Microsoft.AspNet.WebApi

Original answer (this is an older WebApi package)

Install-Package AspNetWebApi

More details.

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

Could me multiple reason for this. But you want might forget to add as @Bean for component which you have did @Autowired.

In my case, i have forgot to decorate with @Bean which causing this issue.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

Show special characters in Unix while using 'less' Command

In the same spirit as https://stackoverflow.com/a/6943976/7154924:

cat -A

-A, --show-all
       equivalent to -vET
-v, --show-nonprinting
       use ^ and M- notation, except for LFD and TAB
-E, --show-ends
       display $ at end of each line
-T, --show-tabs
       display TAB characters as ^I

Alternatively, or at the same time, you can pipe to tr to substitute arbitrary characters to the desired ones for display, before piping to a pager like less if desired.

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

Rails: Check output of path helper from console

Remember if your route is name-spaced, Like:

product GET  /products/:id(.:format)  spree/products#show

Then try :

helper.link_to("test", app.spree.product_path(Spree::Product.first), method: :get)

output

Spree::Product Load (0.4ms)  SELECT  "spree_products".* FROM "spree_products"  WHERE "spree_products"."deleted_at" IS NULL  ORDER BY "spree_products"."id" ASC LIMIT 1
=> "<a data-method=\"get\" href=\"/products/this-is-the-title\">test</a>" 

How to get the selected date of a MonthCalendar control in C#

"Just set the MaxSelectionCount to 1 so that users cannot select more than one day. Then in the SelectionRange.Start.ToString(). There is nothing available to show the selection of only one day." - Justin Etheredge

From here.

Undefined reference to `sin`

You need to link with the math library, libm:

$ gcc -Wall foo.c -o foo -lm 

Is there any advantage of using map over unordered_map in case of trivial keys?

From: http://www.cplusplus.com/reference/map/map/

"Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).

map containers are generally slower than unordered_map containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order."

How to move (and overwrite) all files from one directory to another?

It's also possible by using rsync, for example:

rsync -va --delete-after src/ dst/

where:

  • -v, --verbose: increase verbosity
  • -a, --archive: archive mode; equals -rlptgoD (no -H,-A,-X)
  • --delete-after: delete files on the receiving side be done after the transfer has completed

If you've root privileges, prefix with sudo to override potential permission issues.

jQuery: Performing synchronous AJAX requests

You're using the ajax function incorrectly. Since it's synchronous it'll return the data inline like so:

var remote = $.ajax({
    type: "GET",
    url: remote_url,
    async: false
}).responseText;

Tools to get a pictorial function call graph of code

You can check out my bash-based C call tree generator here. It lets you specify one or more C functions for which you want caller and/or called information, or you can specify a set of functions and determine the reachability graph of function calls that connects them... I.e. tell me all the ways main(), foo(), and bar() are connected. It uses graphviz/dot for a graphing engine.

Query for documents where array size is greater than 1

I know its old question, but I am trying this with $gte and $size in find. I think to find() is faster.

db.getCollection('collectionName').find({ name : { $gte : {  $size : 1 } }})

C++ "was not declared in this scope" compile error

What's wrong:

The definition of "nonrecursivecountcells" has no parameter named grid. You need to pass the type AND variable name to the function. You only passed the type.

Note if you use the name grid for the parameter, that name has nothing to do with your main() declaration of grid. You could have used any other name as well.

***Also you can't pass arrays as values.


How to fix:

The easy way to fix this is to pass a pointer to an array to the function "nonrecursivecountcells".

int nonrecursivecountcells(color[ROW_SIZE][COL_SIZE], int, int);

better and type safe ->

int nonrecursivecountcells(color (&grid)[ROW_SIZE][COL_SIZE], int, int);

About scope:

A variable created on the stack comes out of scope when the block it is declared in is terminated. A block is anything within an opening and matching closing brace. For example an if() { }, function() { }, while() {}, ...

Note I said variable and not data. For example you can allocate memory on the heap and that data will still remain valid even outside of the scope. But the variable that originally pointed to it would still come out of scope.

What is the difference between a function expression vs declaration in JavaScript?

They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.

Function declarations load before any code is executed.

Function expressions load only when the interpreter reaches that line of code.

So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.

Example: Function Expression

alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; } 

Example: Function Declaration

alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; } 


As for the second part of your question:

var foo = function foo() { return 5; } is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.

Converting an integer to a hexadecimal string in Ruby

To summarize:

p 10.to_s(16) #=> "a"
p "%x" % 10 #=> "a"
p "%02X" % 10 #=> "0A"
p sprintf("%02X", 10) #=> "0A"
p "#%02X%02X%02X" % [255, 0, 10] #=> "#FF000A"