Programs & Examples On #Directory browsing

Get current clipboard content?

You can use

window.clipboardData.getData('Text')

to get the content of user's clipboard in IE. However, in other browser you may need to use flash to get the content, since there is no standard interface to access the clipboard. May be you can have try this plugin Zero Clipboard

AngularJS ui router passing data between states without URL

We can use params, new feature of the UI-Router:

API Reference / ui.router.state / $stateProvider

params A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.

See the part: "...or defines additional non-url parameters..."

So the state def would be:

$stateProvider
  .state('home', {
    url: "/home",
    templateUrl: 'tpl.html',
    params: { hiddenOne: null, }
  })

Few examples form the doc mentioned above:

// define a parameter's default value
params: {
  param1: { value: "defaultValue" }
}
// shorthand default values
params: {
  param1: "defaultValue",
  param2: "param2Default"
}

// param will be array []
params: {
  param1: { array: true }
}

// handling the default value in url:
params: {
  param1: {
    value: "defaultId",
    squash: true
} }
// squash "defaultValue" to "~"
params: {
  param1: {
    value: "defaultValue",
    squash: "~"
  } }

EXTEND - working example: http://plnkr.co/edit/inFhDmP42AQyeUBmyIVl?p=info

Here is an example of a state definition:

 $stateProvider
  .state('home', {
      url: "/home",
      params : { veryLongParamHome: null, },
      ...
  })
  .state('parent', {
      url: "/parent",
      params : { veryLongParamParent: null, },
      ...
  })
  .state('parent.child', { 
      url: "/child",
      params : { veryLongParamChild: null, },
      ...
  })

This could be a call using ui-sref:

<a ui-sref="home({veryLongParamHome:'Home--f8d218ae-d998-4aa4-94ee-f27144a21238'
  })">home</a>

<a ui-sref="parent({ 
    veryLongParamParent:'Parent--2852f22c-dc85-41af-9064-d365bc4fc822'
  })">parent</a>

<a ui-sref="parent.child({
    veryLongParamParent:'Parent--0b2a585f-fcef-4462-b656-544e4575fca5',  
    veryLongParamChild:'Child--f8d218ae-d998-4aa4-94ee-f27144a61238'
  })">parent.child</a>

Check the example here

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

I solved the problem by adding the line skip-grant-tables to the my.ini:

# The MySQL server
[mysqld]
skip-grant-tables
port= 3306
...

Under XAMPP Control Panel > Section "MySQL" > Config > my.ini

How can I rollback an UPDATE query in SQL server 2005?

You can rollback the statements you've executed within a transaction. Instead of commiting the transaction, rollback the transaction.

If you have updated something and want to rollback those updates, and you haven't done this inside a (not-yet-commited) transaction, then I think it's though luck ...

(Manually repair, or, restore backups)

How to check if an element is visible with WebDriver

Even though I'm somewhat late answering the question:

You can now use WebElement.isDisplayed() to check if an element is visible.

Note:

There are many reasons why an element could be invisible. Selenium tries cover most of them, but there are edge cases where it does not work as expected.

For example, isDisplayed() does return false if an element has display: none or opacity: 0, but at least in my test, it does not reliably detect if an element is covered by another due to CSS positioning.

Rendering an array.map() in React

Add up to Dmitry's answer, if you don't want to handle unique key IDs manually, you can use React.Children.toArray as proposed in the React documentation

React.Children.toArray

Returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.

Note:

React.Children.toArray() changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, toArray prefixes each key in the returned array so that each element’s key is scoped to the input array containing it.

 <div>
    <ul>
      {
        React.Children.toArray(
          this.state.data.map((item, i) => <li>Test</li>)
        )
      }
    </ul>
  </div>

How is __eq__ handled in Python and in what order?

The a == b expression invokes A.__eq__, since it exists. Its code includes self.value == other. Since int's don't know how to compare themselves to B's, Python tries invoking B.__eq__ to see if it knows how to compare itself to an int.

If you amend your code to show what values are being compared:

class A(object):
    def __eq__(self, other):
        print("A __eq__ called: %r == %r ?" % (self, other))
        return self.value == other
class B(object):
    def __eq__(self, other):
        print("B __eq__ called: %r == %r ?" % (self, other))
        return self.value == other

a = A()
a.value = 3
b = B()
b.value = 4
a == b

it will print:

A __eq__ called: <__main__.A object at 0x013BA070> == <__main__.B object at 0x013BA090> ?
B __eq__ called: <__main__.B object at 0x013BA090> == 3 ?

How to set multiple commands in one yaml file with Kubernetes?

I am not sure if the question is still active but due to the fact that I did not find the solution in the above answers I decided to write it down.

I use the following approach:

readinessProbe:
  exec:
    command:
    - sh
    - -c
    - |
      command1
      command2 && command3

I know my example is related to readinessProbe, livenessProbe, etc. but suspect the same case is for the container commands. This provides flexibility as it mirrors a standard script writing in Bash.

How can I remove all objects but one from the workspace in R?

require(gdata)
keep(object_1,...,object_n,sure=TRUE)
ls()

What is the difference between a pandas Series and a single-column DataFrame?

Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index. The basic method to create a Series is to call:

s = pd.Series(data, index=index)

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.

 d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
 two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
 df = pd.DataFrame(d)

undefined reference to 'std::cout'

Makefiles

If you're working with a makefile and you ended up here like me, then this is probably what you're looking or:

If you're using a makefile, then you need to change cc as shown below

my_executable : main.o
    cc -o my_executable main.o

to

CC = g++

my_executable : main.o
    $(CC) -o my_executable main.o

How to hide the soft keyboard from inside a fragment?

Exception for DialogFragment though, focus of the embedded Dialog must be hidden, instead only the first EditText within the embedded Dialog

this.getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

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

On Mac OS X Terminal, this functionality is already built in to the Terminal Application as menu View ? Clear Scrollback (the default is CMD + K).

So you can re-assign this as you like with Apple's Keyboard shortcuts. Just add a new shortcut for Terminal with the command "Clear Scrollback". (I use CMD + L, because it's similar to Ctrl + L to clear the current screen contents, without clearing the buffer.)

I am not sure how you would use this in a script (maybe AppleScript as others have pointed out).

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

It looks like you are calling a non static member (a property or method, specifically setTextboxText) from a static method (specifically SumData). You will need to either:

  1. Make the called member static also:

    static void setTextboxText(int result)
    {
        // Write static logic for setTextboxText.  
        // This may require a static singleton instance of Form1.
    }
    
  2. Create an instance of Form1 within the calling method:

    private static void SumData(object state)
    {
        int result = 0;
        //int[] icount = (int[])state;
        int icount = (int)state;
    
        for (int i = icount; i > 0; i--)
        {
            result += i;
            System.Threading.Thread.Sleep(1000);
        }
        Form1 frm1 = new Form1();
        frm1.setTextboxText(result);
    }
    

    Passing in an instance of Form1 would be an option also.

  3. Make the calling method a non-static instance method (of Form1):

    private void SumData(object state)
    {
        int result = 0;
        //int[] icount = (int[])state;
        int icount = (int)state;
    
        for (int i = icount; i > 0; i--)
        {
            result += i;
            System.Threading.Thread.Sleep(1000);
        }
        setTextboxText(result);
    }
    

More info about this error can be found on MSDN.

How many threads is too many?

ryeguy, I am currently developing a similar application and my threads number is set to 15. Unfortunately if I increase it at 20, it crashes. So, yes, I think the best way to handle this is to measure whether or not your current configuration allows more or less than a number X of threads.

Understanding the ngRepeat 'track by' expression

If you are working with objects track by the identifier(e.g. $index) instead of the whole object and you reload your data later, ngRepeat will not rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones.

Another Repeated column in mapping for entity error

If you are stuck with a legacy database where someone already placed JPA annotations on but did NOT define the relationships and you are now trying to define them for use in your code, then you might NOT be able to delete the customerId @Column since other code may directly reference it already. In that case, define the relationships as follows:

@ManyToOne(optional=false)
@JoinColumn(name="productId",referencedColumnName="id_product", insertable=false, updatable=false)
private Product product;

@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer", insertable=false, updatable=false)
private Customer customer;

This allows you to access the relationships. However, to add/update to the relationships you will have to manipulate the foreign keys directly via their defined @Column values. It's not an ideal situation, but if you are handed this sort of situation, at least you can define the relationships so that you can use JPQL successfully.

The performance impact of using instanceof in Java

instanceof is very efficient, so your performance is unlikely to suffer. However, using lots of instanceof suggests a design issue.

If you can use xClass == String.class, this is faster. Note: you don't need instanceof for final classes.

Absolute Positioning & Text Alignment

This should work:

#my-div { 
  left: 0; 
  width: 100%; 
}

Python, how to read bytes from file and save it?

Use the open function to open the file. The open function returns a file object, which you can use the read and write to files:

file_input = open('input.txt') #opens a file in reading mode
file_output = open('output.txt') #opens a file in writing mode

data = file_input.read(1024) #read 1024 bytes from the input file
file_output.write(data) #write the data to the output file

JavaScript ternary operator example with functions

I know question is already answered.

But let me add one point here. This is not only case of true or false. See below:

var val="Do";

Var c= (val == "Do" || val == "Done")
          ? 7
          : 0

Here if val is Do or Done then c will be 7 else it will be zero. In this case c will be 7.

This is actually another perspective of this operator.

Git merge with force overwrite

You can try "ours" option in git merge,

git merge branch -X ours

This option forces conflicting hunks to be auto-resolved cleanly by favoring our version. Changes from the other tree that do not conflict with our side are reflected to the merge result. For a binary file, the entire contents are taken from our side.

What port number does SOAP use?

SOAP (communication protocol) for communication between applications. Uses HTTP (port 80) or SMTP ( port 25 or 2525 ), for message negotiation and transmission.

How to use hex() without 0x in Python?

You can simply write

hex(x)[2:]

to get the first two characters removed.

Best way to check that element is not present using Selenium WebDriver with java

public boolean isDisplayed(WebElement element) {
        try {
            return element.isDisplayed();
        } catch (NoSuchElementException e) {
            return false;
        }
    }

If you wan t to check that element is displayed on the page your check should be:

if(isDisplayed(yourElement){
...
}
else{
...
}

Change drawable color programmatically

Syntax

"your image name".setColorFilter("your context".getResources().getColor("color name"));

Example

myImage.setColorFilter(mContext.getResources().getColor(R.color.deep_blue_new));

How do I localize the jQuery UI Datepicker?

This solution may help.

_x000D_
_x000D_
$(document).ready(function () {_x000D_
  var userLang = navigator.language || navigator.userLanguage;_x000D_
_x000D_
  var options = $.extend({},_x000D_
    $.datepicker.regional["ja"], {_x000D_
      dateFormat: "yy/mm/dd",_x000D_
      changeMonth: true,_x000D_
      changeYear: true,_x000D_
      highlightWeek: true_x000D_
    }_x000D_
  );_x000D_
_x000D_
  $("#japaneseCalendar").datepicker(options);_x000D_
});
_x000D_
#ui-datepicker-div {_x000D_
  font-size: 14px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <link rel="stylesheet" type="text/css"_x000D_
          href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.min.css">_x000D_
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>_x000D_
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<h3>Japanese JQuery UI Datepicker</h3>_x000D_
<input type="text" id="japaneseCalendar"/>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to lock orientation of one view controller to portrait mode only in Swift

Things can get quite messy when you have a complicated view hierarchy, like having multiple navigation controllers and/or tab view controllers.

This implementation puts it on the individual view controllers to set when they would like to lock orientations, instead of relying on the App Delegate to find them by iterating through subviews.

Swift 3, 4, 5

In AppDelegate:

/// set orientations you want to be allowed in this property by default
var orientationLock = UIInterfaceOrientationMask.all

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return self.orientationLock
}

In some other global struct or helper class, here I created AppUtility:

struct AppUtility {

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
    
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }

    /// OPTIONAL Added method to adjust lock and rotate to the desired orientation
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
   
        self.lockOrientation(orientation)
    
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
        UINavigationController.attemptRotationToDeviceOrientation()
    }

}

Then in the desired ViewController you want to lock orientations:

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    AppUtility.lockOrientation(.portrait)
    // Or to rotate and lock
    // AppUtility.lockOrientation(.portrait, andRotateTo: .portrait)
    
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    // Don't forget to reset when view is being removed
    AppUtility.lockOrientation(.all)
}

If iPad or Universal App

Make sure that "Requires full screen" is checked in Target Settings -> General -> Deployment Info. supportedInterfaceOrientationsFor delegate will not get called if that is not checked. enter image description here

MySQL count occurrences greater than 2

SELECT count(word) as count 
FROM words 
GROUP BY word
HAVING count >= 2;

Where can I find WcfTestClient.exe (part of Visual Studio)

Mine was here: "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE"

Get current date, given a timezone in PHP?

The other answers set the timezone for all dates in your system. This doesn't always work well if you want to support multiple timezones for your users.

Here's the short version:

<?php
$date = new DateTime("now", new DateTimeZone('America/New_York') );
echo $date->format('Y-m-d H:i:s');

Works in PHP >= 5.2.0

List of supported timezones: php.net/manual/en/timezones.php


Here's a version with an existing time and setting timezone by a user setting

<?php

$usersTimezone = 'America/New_York';
$date = new DateTime( 'Thu, 31 Mar 2011 02:05:59 GMT', new DateTimeZone($usersTimezone) );
echo $date->format('Y-m-d H:i:s');

Here is a more verbose version to show the process a little more clearly

<?php

// Date for a specific date/time:
$date = new DateTime('Thu, 31 Mar 2011 02:05:59 GMT');

// Output date (as-is)
echo $date->format('l, F j Y g:i:s A');     

// Output line break (for testing)
echo "\n<br />\n";

// Example user timezone (to show it can be used dynamically)
$usersTimezone = 'America/New_York';

// Convert timezone
$tz = new DateTimeZone($usersTimezone);
$date->setTimeZone($tz);

// Output date after 
echo $date->format('l, F j Y g:i:s A');

Libraries

  • Carbon — A very popular date library.
  • Chronos — A drop-in replacement for Carbon focused on immutability. See below on why that's important.
  • jenssegers/date — An extension of Carbon that adds multi-language support.

I'm sure there are a number of other libraries available, but these are a few I'm familiar with.


Bonus Lesson: Immutable Date Objects

While you're here, let me save you some future headache. Let's say you want to calculate 1 week from today and 2 weeks from today. You might write some code like:

<?php

// Create a datetime (now, in this case 2017-Feb-11)
$today = new DateTime();

echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";

$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));

echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";
echo "\n<br>";

The output:

2017-02-11 
--- 
2017-03-04 
2017-03-04 
2017-03-04

Hmmmm... That's not quite what we wanted. Modifying a traditional DateTime object in PHP not only returns the updated date but modifies the original object as well.

This is where DateTimeImmutable comes in.

$today = new DateTimeImmutable();

echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";

$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));

echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";

The output:

2017-02-11 
--- 
2017-02-11 
2017-02-18 
2017-02-25 

In this second example, we get the dates we expected back. By using DateTimeImmutable instead of DateTime, we prevent accidental state mutations and prevent potential bugs.

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

The jersey-container-servlet actually uses the jersey-container-servlet-core dependency. But if you use maven, that does not really matter. If you just define the jersey-container-servlet usage, it will automatically download the dependency as well.

But for those who add jar files to their project manually (i.e. without maven) It is important to know that you actually need both jar files. The org.glassfish.jersey.servlet.ServletContainer class is actually part of the core dependency.

convert base64 to image in javascript/jquery

Html

<img id="imgElem"></img>

Js

string baseStr64="/9j/4AAQSkZJRgABAQE...";
imgElem.setAttribute('src', "data:image/jpg;base64," + baseStr64);

Changing the sign of a number in PHP?

A trivial

$num = $num <= 0 ? $num : -$num ;

or, the better solution, IMHO:

$num = -1 * abs($num)

As @VegardLarsen has posted,

the explicit multiplication can be avoided for shortness but I prefer readability over shortness

I suggest to avoid if/else (or equivalent ternary operator) especially if you have to manipulate a number of items (in a loop or using a lambda function), as it will affect performance.

"If the float is a negative, make it a positive."

In order to change the sign of a number you can simply do:

$num = 0 - $num;

or, multiply it by -1, of course :)

Visual Studio Code - Convert spaces to tabs

If you want to change tabs to spaces in a lot of files, but don't want to open them individually, I have found that it works equally as well to just use the Find and Replace option from the left-most tools bar.

In the first box (Find), copy and paste a tab from the source code.

In the second box (Replace), enter the number of spaces that you wish to use (i.e. 2 or 4).

If you press the ... button, you can specify directories to include or ignore (i.e. src/Data/Json).

Finally, inspect the result preview and press Replace All. All files in the workspace may be affected.

How do I create dynamic properties in C#?

Couldn't you just have your class expose a Dictionary object? Instead of "attaching more properties to the object", you could simply insert your data (with some identifier) into the dictionary at run time.

How to create an instance of System.IO.Stream stream

System.IO.Stream stream = new System.IO.MemoryStream();

What do I use on linux to make a python program executable

Another way to do it could be by creating an alias. For example in terminal write:

alias printhello='python /home/hello_world.py'

Writing printhello will run hello_world.py, but this is only temporary. To make aliases permanent, you have to add them to bashrc, you can edit it by writing this in the terminal:

gedit ~/.bashrc

React - How to get parameter value from query string?

React Router v4

Using component

<Route path="/users/:id" component={UserPage}/> 
this.props.match.params.id

The component is automatically rendered with the route props.


Using render

<Route path="/users/:id" render={(props) => <UserPage {...props} />}/> 
this.props.match.params.id

Route props are passed to the render function.

What is Scala's yield?

yield is more flexible than map(), see example below

val aList = List( 1,2,3,4,5 )

val res3 = for ( al <- aList if al > 3 ) yield al + 1 
val res4 = aList.map( _+ 1 > 3 ) 

println( res3 )
println( res4 )

yield will print result like: List(5, 6), which is good

while map() will return result like: List(false, false, true, true, true), which probably is not what you intend.

How to combine date from one field with time from another field - MS SQL Server

This is an alternative solution without any char conversions:

DATEADD(ms, DATEDIFF(ms, '00:00:00', [Time]), CONVERT(DATETIME, [Date]))

You will only get milliseconds accuracy this way, but that would normally be OK. I have tested this in SQL Server 2008.

How should I copy Strings in Java?

Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).

With this in mind, the first version should be preferred.

How to slice an array in Bash

There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.

version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}"    # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}"    # 7 1

Can I use a binary literal in C or C++?

A few compilers (usually the ones for microcontrollers) has a special feature implemented within recognizing literal binary numbers by prefix "0b..." preceding the number, although most compilers (C/C++ standards) don't have such feature and if it is the case, here it is my alternative solution:

#define B_0000    0
#define B_0001    1
#define B_0010    2
#define B_0011    3
#define B_0100    4
#define B_0101    5
#define B_0110    6
#define B_0111    7
#define B_1000    8
#define B_1001    9
#define B_1010    a
#define B_1011    b
#define B_1100    c
#define B_1101    d
#define B_1110    e
#define B_1111    f

#define _B2H(bits)    B_##bits
#define B2H(bits)    _B2H(bits)
#define _HEX(n)        0x##n
#define HEX(n)        _HEX(n)
#define _CCAT(a,b)    a##b
#define CCAT(a,b)   _CCAT(a,b)

#define BYTE(a,b)        HEX( CCAT(B2H(a),B2H(b)) )
#define WORD(a,b,c,d)    HEX( CCAT(CCAT(B2H(a),B2H(b)),CCAT(B2H(c),B2H(d))) )
#define DWORD(a,b,c,d,e,f,g,h)    HEX( CCAT(CCAT(CCAT(B2H(a),B2H(b)),CCAT(B2H(c),B2H(d))),CCAT(CCAT(B2H(e),B2H(f)),CCAT(B2H(g),B2H(h)))) )

// Using example
char b = BYTE(0100,0001); // Equivalent to b = 65; or b = 'A'; or b = 0x41;
unsigned int w = WORD(1101,1111,0100,0011); // Equivalent to w = 57155; or w = 0xdf43;
unsigned long int dw = DWORD(1101,1111,0100,0011,1111,1101,0010,1000); //Equivalent to dw = 3745774888; or dw = 0xdf43fd28;

Disadvantages (it's not such a big ones):

  • The binary numbers have to be grouped 4 by 4;
  • The binary literals have to be only unsigned integer numbers;

Advantages:

  • Total preprocessor driven, not spending processor time in pointless operations (like "?.. :..", "<<", "+") to the executable program (it may be performed hundred of times in the final application);
  • It works "mainly in C" compilers and C++ as well (template+enum solution works only in C++ compilers);
  • It has only the limitation of "longness" for expressing "literal constant" values. There would have been earlyish longness limitation (usually 8 bits: 0-255) if one had expressed constant values by parsing resolve of "enum solution" (usually 255 = reach enum definition limit), differently, "literal constant" limitations, in the compiler allows greater numbers;
  • Some other solutions demand exaggerated number of constant definitions (too many defines in my opinion) including long or several header files (in most cases not easily readable and understandable, and make the project become unnecessarily confused and extended, like that using "BOOST_BINARY()");
  • Simplicity of the solution: easily readable, understandable and adjustable for other cases (could be extended for grouping 8 by 8 too);

Using cURL with a username and password?

It is safer to do:

curl --netrc-file my-password-file http://example.com

...as passing a plain user/password string on the command line, is a bad idea.

The format of the password file is (as per man curl):

machine <example.com> login <username> password <password>

Note:

  1. Machine name must not include https:// or similar! Just the hostname.
  2. The words 'machine', 'login', and 'password' are just keywords; the actual information is the stuff after those keywords.

Replace all double quotes within String

This is to remove double quotes in a string.

str1 = str.replace(/"/g, "");
alert(str1);

Importing the private-key/public-certificate pair in the Java KeyStore

A keystore needs a keystore file. The KeyStore class needs a FileInputStream. But if you supply null (instead of FileInputStream instance) an empty keystore will be loaded. Once you create a keystore, you can verify its integrity using keytool.

Following code creates an empty keystore with empty password

  KeyStore ks2 = KeyStore.getInstance("jks");
  ks2.load(null,"".toCharArray());
  FileOutputStream out = new FileOutputStream("C:\\mykeytore.keystore");
  ks2.store(out, "".toCharArray());

Once you have the keystore, importing certificate is very easy. Checkout this link for the sample code.

How do you connect to multiple MySQL databases on a single webpage?

Instead of mysql_connect use mysqli_connect.

mysqli is provide a functionality for connect multiple database at a time.

$Db1 = new mysqli($hostname,$username,$password,$db_name1); 
// this is connection 1 for DB 1

$Db2 = new mysqli($hostname,$username,$password,$db_name2); 
// this is connection 2 for DB 2

Specifying width and height as percentages without skewing photo proportions in HTML

From W3Schools

The height in percent of the containing element (like "20%").

So I think they mean the element where the div is in?

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

I had PuTTY working and then one day got this error.

Solution: I had revised the folder path name containing my certificates (private keys), and this caused Pageant to lose track of the certificates and so was empty.

Once I re-installed the certificate into Pageant then Putty started working again.

Python data structure sort list alphabetically

You're dealing with a python list, and sorting it is as easy as doing this.

my_list = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
my_list.sort()

asp.net: How can I remove an item from a dropdownlist?

I would add an identifying Id or class to the dropbox and remove using Javascript.

The article here should help.

D

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

There's the more general but perhaps not as helpful to you Wireshark.

One of the SO server sites might be better suited for your question. In fact, it's already been asked on SuperUser.

Closing database connections in Java

When you are done with using your Connection, you need to explicitly close it by calling its close() method in order to release any other database resources (cursors, handles, etc.) the connection may be holding on to.

Actually, the safe pattern in Java is to close your ResultSet, Statement, and Connection (in that order) in a finally block when you are done with them. Something like this:

Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
    // Do stuff
    ...

} catch (SQLException ex) {
    // Exception handling stuff
    ...
} finally {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) { /* Ignored */}
    }
    if (ps != null) {
        try {
            ps.close();
        } catch (SQLException e) { /* Ignored */}
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) { /* Ignored */}
    }
}

The finally block can be slightly improved into (to avoid the null check):

} finally {
    try { rs.close(); } catch (Exception e) { /* Ignored */ }
    try { ps.close(); } catch (Exception e) { /* Ignored */ }
    try { conn.close(); } catch (Exception e) { /* Ignored */ }
}

But, still, this is extremely verbose so you generally end up using an helper class to close the objects in null-safe helper methods and the finally block becomes something like this:

} finally {
    DbUtils.closeQuietly(rs);
    DbUtils.closeQuietly(ps);
    DbUtils.closeQuietly(conn);
}

And, actually, the Apache Commons DbUtils has a DbUtils class which is precisely doing that, so there isn't any need to write your own.

How to write data with FileOutputStream without losing old data?

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

How do I set the selected item in a comboBox to match my string using C#?

Supposing test1, test2, test3 belong to comboBox1 collection following statement will work.

comboBox1.SelectedIndex = 0; 

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

Update @angular-devkit/build-angular to "^0.13.9" . Then run npm install and after that, run npm serve.

Specs:

Angular: 7.2.15
Angular CLI: 7.3.9
Node: 11.2.0
OS: darwin x64

define() vs. const

To add on NikiC's answer. const can be used within classes in the following manner:

class Foo {
    const BAR = 1;

    public function myMethod() {
        return self::BAR;
    }
}

You can not do this with define().

file_put_contents: Failed to open stream, no such file or directory

I was also stuck on the same kind of problem and I followed the simple steps below.

Just get the exact url of the file to which you want to copy, for example:

http://www.test.com/test.txt (file to copy)

Then pass the exact absolute folder path with filename where you do want to write that file.

  1. If you are on a Windows machine then d:/xampp/htdocs/upload/test.txt

  2. If you are on a Linux machine then /var/www/html/upload/test.txt

You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT'].

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

Querying Datatable with where condition

You can do it with Linq, as mamoo showed, but the oldies are good too:

var filteredDataTable = dt.Select(@"EmpId > 2
    AND (EmpName <> 'abc' OR EmpName <> 'xyz')
    AND EmpName like '%il%'" );

"Failed to install the following Android SDK packages as some licences have not been accepted" error

This works for me:

yes | ./sdkmanager "platforms;android-28"

yes | ./sdkmanager "build-tools;28.0.3"

yes | ./sdkmanager --licenses

Replace only text inside a div using jquery

Another approach is keep that element, change the text, then append that element back

const star_icon = $(li).find('.stars svg')
$(li).find('.stars').text(repo.stargazers_count).append(star_icon)

How to use http.client in Node.js if there is basic authorization

var username = "Ali";
var password = "123";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var request = require('request');
var url = "http://localhost:5647/contact/session/";

request.get( {
    url : url,
    headers : {
        "Authorization" : auth
    }
  }, function(error, response, body) {
      console.log('body : ', body);
  } );

Best practices for copying files with Maven

<build>
    <plugins>
        ...
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.3</version>
        </plugin>
    </plugins>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include> **/*.properties</include>
            </includes>
        </resource>
    </resources>
    ...
</build>

changing kafka retention period during runtime

The correct config key is retention.ms

$ bin/kafka-topics.sh --zookeeper zk.prod.yoursite.com --alter --topic as-access --config retention.ms=86400000
Updated config for topic "my-topic".

Add a new element to an array without specifying the index in Bash

With an indexed array, you can to something like this:

declare -a a=()
a+=('foo' 'bar')

Disabling of EditText in Android

As some answer mention it, if you disable the editText he become gray and if you set focusable false the cursor is displaying.

If you would like to do it only with xml this did the trick

       <YourFloatLabel
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

            <EditText
                android:id="@+id/view_ads_search_select"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:focusable="true"
                android:clickable="true"/>  
       </YourFloatLabel>

I simply add a FrameLayout appear above the editText and set it focusable and clickable so the editText can't be click.

How can I get city name from a latitude and longitude point?

In node.js we can use node-geocoder npm module to get address from lat, lng.,

geo.js

var NodeGeocoder = require('node-geocoder');

var options = {
  provider: 'google',
  httpAdapter: 'https', // Default
  apiKey: ' ', // for Mapquest, OpenCage, Google Premier
  formatter: 'json' // 'gpx', 'string', ...
};

var geocoder = NodeGeocoder(options);

geocoder.reverse({lat:28.5967439, lon:77.3285038}, function(err, res) {
  console.log(res);
});

output:

node geo.js

[ { formattedAddress: 'C-85B, C Block, Sector 8, Noida, Uttar Pradesh 201301, India',
    latitude: 28.5967439,
    longitude: 77.3285038,
    extra: 
     { googlePlaceId: 'ChIJkTdx9vzkDDkRx6LVvtz1Rhk',
       confidence: 1,
       premise: 'C-85B',
       subpremise: null,
       neighborhood: 'C Block',
       establishment: null },
    administrativeLevels: 
     { level2long: 'Gautam Buddh Nagar',
       level2short: 'Gautam Buddh Nagar',
       level1long: 'Uttar Pradesh',
       level1short: 'UP' },
    city: 'Noida',
    country: 'India',
    countryCode: 'IN',
    zipcode: '201301',
    provider: 'google' } ]

How to create dynamic href in react render function?

Use string concatenation:

href={'/posts/' + post.id}

The JSX syntax allows either to use strings or expressions ({...}) as values. You cannot mix both. Inside an expression you can, as the name suggests, use any JavaScript expression to compute the value.

Select2() is not a function

This error raises if your js files where you have bounded the select2 with select box is loading before select2 js files. Please make sure files should be in this order like..

  • Jquery
  • select2 js
  • your js

Python: Append item to list N times

For immutable data types:

l = [0] * 100
# [0, 0, 0, 0, 0, ...]

l = ['foo'] * 100
# ['foo', 'foo', 'foo', 'foo', ...]

For values that are stored by reference and you may wish to modify later (like sub-lists, or dicts):

l = [{} for x in range(100)]

(The reason why the first method is only a good idea for constant values, like ints or strings, is because only a shallow copy is does when using the <list>*<number> syntax, and thus if you did something like [{}]*100, you'd end up with 100 references to the same dictionary - so changing one of them would change them all. Since ints and strings are immutable, this isn't a problem for them.)

If you want to add to an existing list, you can use the extend() method of that list (in conjunction with the generation of a list of things to add via the above techniques):

a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]

Remove the last character in a string in T-SQL?

e.g.

DECLARE @String VARCHAR(100)
SET @String = 'TEST STRING'

-- Chop off the end character
SET @String = 
     CASE @String WHEN null THEN null 
     ELSE (
         CASE LEN(@String) WHEN 0 THEN @String 
            ELSE LEFT(@String, LEN(@String) - 1) 
         END 
     ) END


SELECT @String

System.BadImageFormatException An attempt was made to load a program with an incorrect format

For running it on any CPU either 62 bit or 32 bit follow these steps: Right click on the name of the project in Solution Explorer> Properties>Build and have these under Configuration: Active(Release), Platform:Active(Any CPU) and Target:x86. and just beside the Run button Select option Release and Any CPU from the options. And then Save it and Run.

Could not find a version that satisfies the requirement tensorflow

if you are using anaconda, python 3.7 is installed by default, so you have to downgrade it to 3.6:

conda install python=3.6

then:

pip install tensorflow

it worked for me in Ubuntu.

How to check if a Ruby object is a Boolean

I find this to be concise and self-documenting:

[true, false].include? foo

If using Rails or ActiveSupport, you can even do a direct query using in?

foo.in? [true, false]

Checking against all possible values isn't something I'd recommend for floats, but feasible when there are only two possible values!

python: order a list of numbers without built-in sort, min, max function

l = [64, 25, 12, 22, 11, 1,2,44,3,122, 23, 34]

for i in range(len(l)):
    for j in range(i + 1, len(l)):

        if l[i] > l[j]:
           l[i], l[j] = l[j], l[i]

print l

Output:

[1, 2, 3, 11, 12, 22, 23, 25, 34, 44, 64, 122]

CSS3 Transform Skew One Side

Maybe you want to use CSS "clip-path" (Works with transparency and background)

"clip-path" reference: https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path

Generator: http://bennettfeely.com/clippy/

Example:

_x000D_
_x000D_
/* With percent */_x000D_
.element-percent {_x000D_
  background: red;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  _x000D_
  clip-path: polygon(0 0, 100% 0%, 75% 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With pixel */_x000D_
.element-pixel {_x000D_
  background: blue;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  _x000D_
  clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With background */_x000D_
.element-background {_x000D_
  background: url(https://images.pexels.com/photos/170811/pexels-photo-170811.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260) no-repeat center/cover;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  _x000D_
  clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}
_x000D_
<div class="element-percent"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-pixel"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-background"></div>
_x000D_
_x000D_
_x000D_

See line breaks and carriage returns in editor

VI shows newlines (LF character, code x0A) by showing the subsequent text on the next line.

Use the -b switch for binary mode. Eg vi -b filename or vim -b filename --.

It will then show CR characters (x0D), which are not normally used in Unix style files, as the characters ^M.

Insert Picture into SQL Server 2005 Image Field using only SQL

CREATE TABLE Employees
(
    Id int,
    Name varchar(50) not null,
    Photo varbinary(max) not null
)


INSERT INTO Employees (Id, Name, Photo) 
SELECT 10, 'John', BulkColumn 
FROM Openrowset( Bulk 'C:\photo.bmp', Single_Blob) as EmployeePicture

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

On your branch - say master, pull and allow unrelated histories

git pull origin master --allow-unrelated-histories

Worked for me.

Python object.__repr__(self) should be an expression?

'repr' means represention. First,we create an instance of class coordinate.

x = Coordinate(3, 4) 

Then if we input x into console,th output is

<__main__.Coordinate at 0x7fcd40ab27b8>

If you use repr():

>>> repr(x)
Coordinate(3, 4)

the output is as same as 'Coordinate(3, 4)',except it is a string.You can use it to recreate a instance of coordinate.

In conclusion,repr() meathod is print out a string,which is the representation of the obeject.

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

How to show text on image when hovering?

HTML
<img id="close" className="fa fa-close" src="" alt="" title="Close Me" />

CSS
#close[title]:hover:after {
  color: red;
  content: attr(title);
  position: absolute;
  left: 50px;
}

Setting an environment variable before a command in Bash is not working for the second command in a pipe

How about exporting the variable, but only inside the subshell?:

(export FOO=bar && somecommand someargs | somecommand2)

Keith has a point, to unconditionally execute the commands, do this:

(export FOO=bar; somecommand someargs | somecommand2)

Attach event to dynamic elements in javascript

You must attach the event after insert elements, like that you don't attach a global event on your document but a specific event on the inserted elements.

e.g.

_x000D_
_x000D_
document.getElementById('form').addEventListener('submit', function(e) {_x000D_
  e.preventDefault();_x000D_
  var name = document.getElementById('txtName').value;_x000D_
  var idElement = 'btnPrepend';_x000D_
  var html = `_x000D_
    <ul>_x000D_
      <li>${name}</li>_x000D_
    </ul>_x000D_
    <input type="button" value="prepend" id="${idElement}" />_x000D_
  `;_x000D_
  /* Insert the html into your DOM */_x000D_
  insertHTML('form', html);_x000D_
  /* Add an event listener after insert html */_x000D_
  addEvent(idElement);_x000D_
});_x000D_
_x000D_
const insertHTML = (tag = 'form', html, position = 'afterend', index = 0) => {_x000D_
  document.getElementsByTagName(tag)[index].insertAdjacentHTML(position, html);_x000D_
}_x000D_
const addEvent = (id, event = 'click') => {_x000D_
  document.getElementById(id).addEventListener(event, function() {_x000D_
    insertHTML('ul', '<li>Prepending data</li>', 'afterbegin')_x000D_
  });_x000D_
}
_x000D_
<form id="form">_x000D_
  <div>_x000D_
    <label for="txtName">Name</label>_x000D_
    <input id="txtName" name="txtName" type="text" />_x000D_
  </div>_x000D_
  <input type="submit" value="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

How do I put variable values into a text string in MATLAB?

I was looking for something along what you wanted, but wanted to put it back into a variable.

So this is what I did

variable = ['hello this is x' x ', this is now y' y ', finally this is d:' d]

basically

variable = [str1 str2 str3 str4 str5 str6]

Angular 4 - get input value

<form (submit)="onSubmit()">
   <input [(ngModel)]="playerName">
</form>

let playerName: string;
onSubmit() {
  return this.playerName;
}

Combine hover and click functions (jQuery)?

Use basic programming composition: create a method and pass the same function to click and hover as a callback.

var hoverOrClick = function () {
    // do something common
}
$('#target').click(hoverOrClick).hover(hoverOrClick);

Second way: use bindon:

$('#target').on('click mouseover', function () {
    // Do something for both
});

jQuery('#target').bind('click mouseover', function () {
    // Do something for both
});

How to implement a simple scenario the OO way

You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.

Delete all data rows from an Excel table (apart from the first)

Your code can be narrowed down to

Sub DeleteTableRows(ByRef Table As ListObject)
    On Error Resume Next
    '~~> Clear Header Row `IF` it exists
    Table.DataBodyRange.Rows(1).ClearContents
    '~~> Delete all the other rows `IF `they exist
    Table.DataBodyRange.Offset(1, 0).Resize(Table.DataBodyRange.Rows.Count - 1, _
    Table.DataBodyRange.Columns.Count).Rows.Delete
    On Error GoTo 0
End Sub

Edit:

On a side note, I would add proper error handling if I need to intimate the user whether the first row or the other rows were deleted or not

How do I add more members to my ENUM-type column in MySQL?

The discussion I had with Asaph may be unclear to follow as we went back and forth quite a bit.

I thought that I might clarify the upshot of our discourse for others who might face similar situations in the future to benefit from:

ENUM-type columns are very difficult beasts to manipulate. I wanted to add two countries (Malaysia & Sweden) to the existing set of countries in my ENUM.

It seems that MySQL 5.1 (which is what I am running) can only update the ENUM by redefining the existing set in addition to what I want:

This did not work:

ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia') DEFAULT NULL;

The reason was that the MySQL statement was replacing the existing ENUM with another containing the entries 'Malaysia' and 'Sweden' only. MySQL threw up an error because the carmake table already had values like 'England' and 'USA' which were not part of the new ENUM's definition.

Surprisingly, the following did not work either:

ALTER TABLE carmake CHANGE country country ENUM('Australia','England','USA'...'Sweden','Malaysia') DEFAULT NULL;

It turns out that even the order of elements of the existing ENUM needs to be preserved while adding new members to it. So if my existing ENUM looks something like ENUM('England','USA'), then my new ENUM has to be defined as ENUM('England','USA','Sweden','Malaysia') and not ENUM('USA','England','Sweden','Malaysia'). This problem only becomes manifest when there are records in the existing table that use 'USA' or 'England' values.

BOTTOM LINE:

Only use ENUMs when you do not expect your set of members to change once defined. Otherwise, lookup tables are much easier to update and modify.

Math.random() versus Random.nextInt(int)

Here is the detailed explanation of why "Random.nextInt(n) is both more efficient and less biased than Math.random() * n" from the Sun forums post that Gili linked to:

Math.random() uses Random.nextDouble() internally.

Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).

Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.

Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.

Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.

You will be waiting a very long time rolling dice for this effect to show up.

Math.random() also requires about twice the processing and is subject to synchronization.

How to create byte array from HttpPostedFile

It won't work if your file InputStream.Position is set to the end of the stream. My additional lines:

Stream stream = file.InputStream;
stream.Position = 0;

Show Curl POST Request Headers? Is there a way to do this?

You can see the information regarding the transfer by doing:

curl_setopt($curl_exect, CURLINFO_HEADER_OUT, true);

before the request, and

$information = curl_getinfo($curl_exect);

after the request

View: http://www.php.net/manual/en/function.curl-getinfo.php

You can also use the CURLOPT_HEADER in your curl_setopt

curl_setopt($curl_exect, CURLOPT_HEADER, true);

$httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);

return $httpcode == 200;

These are just some methods of using the headers.

Generating an array of letters in the alphabet

You could do something like this, based on the ascii values of the characters:

char[26] alphabet;

for(int i = 0; i <26; i++)
{
     alphabet[i] = (char)(i+65); //65 is the offset for capital A in the ascaii table
}

(See the table here.) You are just casting from the int value of the character to the character value - but, that only works for ascii characters not different languages etc.

EDIT: As suggested by Mehrdad in the comment to a similar solution, it's better to do this:

alphabet[i] = (char)(i+(int)('A'));

This casts the A character to it's int value and then increments based on this, so it's not hardcoded.

How to access JSON decoded array in PHP

$data = json_decode(...);
$firstId = $data[0]["id"];
$secondSeatNo = $data[1]["seat_no"];

Just like this :)

how to log in to mysql and query the database from linux terminal

if u got still no access to db, 1. in ur error message is set no password right? then first do mysqlpasswd 'username' after that enter and then give it a password type again as requested and then try to access again with mysql -p if you are root

Why aren't python nested functions called closures?

A closure occurs when a function has access to a local variable from an enclosing scope that has finished its execution.

def make_printer(msg):
    def printer():
        print msg
    return printer

printer = make_printer('Foo!')
printer()

When make_printer is called, a new frame is put on the stack with the compiled code for the printer function as a constant and the value of msg as a local. It then creates and returns the function. Because the function printer references the msg variable, it is kept alive after the make_printer function has returned.

So, if your nested functions don't

  1. access variables that are local to enclosing scopes,
  2. do so when they are executed outside of that scope,

then they are not closures.

Here's an example of a nested function which is not a closure.

def make_printer(msg):
    def printer(msg=msg):
        print msg
    return printer

printer = make_printer("Foo!")
printer()  #Output: Foo!

Here, we are binding the value to the default value of a parameter. This occurs when the function printer is created and so no reference to the value of msg external to printer needs to be maintained after make_printer returns. msg is just a normal local variable of the function printer in this context.

Auto-scaling input[type=text] to width of value?

try canvas measureText solution

css:

    input{
        min-width:10px!important;
        max-width:99.99%!important;
        transition: width 0.1s;
        border-width:1px;
    }

javascript:

function getWidthOfInput(input){
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var text = input.value.length ? input.value : input.placeholder;
    var style = window.getComputedStyle(input);
    ctx.lineWidth = 1;
    ctx.font = style.font;
    var text_width = ctx.measureText(text).width;
    return text_width;
}

function resizable (el, factor) {
    function resize() {
        var width = getWidthOfInput(el);
        el.style.width = width + 'px';
    }
    var e = 'keyup,keypress,focus,blur,change'.split(',');
    for (var i in e){
        el.addEventListener(e[i],resize,false);
    }
    resize();
}

$( "input" ).each( function(i){
    resizable(this);
});

Using isKindOfClass with Swift

The proper Swift operator is is:

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}

Of course, if you also need to assign the view to a new constant, then the if let ... as? ... syntax is your boy, as Kevin mentioned. But if you don't need the value and only need to check the type, then you should use the is operator.

How to Find And Replace Text In A File With C#

i tend to use simple forward code as much as i can ,below code worked fine with me

using System;
using System.IO;
using System.Text.RegularExpressions;

/// <summary>
/// Replaces text in a file.
/// </summary>
/// <param name="filePath">Path of the text file.</param>
/// <param name="searchText">Text to search for.</param>
/// <param name="replaceText">Text to replace the search text.</param>
static public void ReplaceInFile( string filePath, string searchText, string replaceText )
{
    StreamReader reader = new StreamReader( filePath );
    string content = reader.ReadToEnd();
    reader.Close();

    content = Regex.Replace( content, searchText, replaceText );

    StreamWriter writer = new StreamWriter( filePath );
    writer.Write( content );
    writer.Close();
}

In laymans terms, what does 'static' mean in Java?

Above points are correct and I want to add some more important points about Static keyword.

Internally what happening when you are using static keyword is it will store in permanent memory(that is in heap memory),we know that there are two types of memory they are stack memory(temporary memory) and heap memory(permanent memory),so if you are not using static key word then will store in temporary memory that is in stack memory(or you can call it as volatile memory).

so you will get a doubt that what is the use of this right???

example: static int a=10;(1 program)

just now I told if you use static keyword for variables or for method it will store in permanent memory right.

so I declared same variable with keyword static in other program with different value.

example: static int a=20;(2 program)

the variable 'a' is stored in heap memory by program 1.the same static variable 'a' is found in program 2 at that time it won`t create once again 'a' variable in heap memory instead of that it just replace value of a from 10 to 20.

In general it will create once again variable 'a' in stack memory(temporary memory) if you won`t declare 'a' as static variable.

overall i can say that,if we use static keyword
  1.we can save memory
  2.we can avoid duplicates
  3.No need of creating object in-order to access static variable with the help of class name you can access it.

Opacity of div's background without affecting contained element in IE 8?

Maybe there's a more simple answer, try to add any background color you like to the code, like background-color: #fff;

#alpha {
 background-color: #fff;
 opacity: 0.8;
 filter: alpha(opacity=80);
}

The term "Add-Migration" is not recognized

?What I had to do...

1) Tools -> Nuget Package Manger -> Package Manager Settings

2) General Tab

3) Clear All NuGet Cache(s)

4) Restart Visual Studio

How to print a int64_t type in C

In windows environment, use

%I64d

in Linux, use

%lld

What's a clean way to stop mongod on Mac OS X?

If you have installed mongodb community server via homebrew, then you can do:

brew services list

This will list the current services as below:

Name              Status  User          Plist
mongodb-community started thehaystacker /Users/thehaystacker/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist

redis             stopped

Then you can restart mongodb by first stopping and restart:

brew services stop mongodb
brew services start mongodb

Use of the MANIFEST.MF file in Java

Manifest.MF contains information about the files contained in the JAR file.

Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:

Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)

These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.

Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,

Main-Class: {fully qualified classname}

The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.

Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,

Class-Path: {jar1-name jar2-name directory-name/jar3-name}

This header can be used to specify the external JAR files on the same local network and not inside the current JAR.

Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:

Headers in a manifest
Header                  | Definition
-------------------------------------------------------------------
Name                    | The name of the specification.
Specification-Title     | The title of the specification.
Specification-Version   | The version of the specification.
Specification-Vendor    | The vendor of the specification.
Implementation-Title    | The title of the implementation.
Implementation-Version  | The build number of the implementation.
Implementation-Vendor   | The vendor of the implementation.

Package sealing related headers:

We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,

Name: {package/some-package/} Sealed:true

Here, the package name must end with ‘/’.

Enhancing security with manifest files:

We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.

META-INF folder:

This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.

Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

jQuery UI Slider (setting programmatically)

It's possible to manually trigger events like this:

Apply the slider behavior to the element

var s = $('#slider').slider();

...

Set the slider value

s.slider('value',10);

Trigger the slide event, passing a ui object

s.trigger('slide',{ ui: $('.ui-slider-handle', s), value: 10 });

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

You can automatically encode into Json, your complex entity with:

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;

$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new 
JsonEncoder()));
$json = $serializer->serialize($entity, 'json');

Open an html page in default browser with VBA?

If you want a more robust solution with ShellExecute that will open ANY file, folder or URL using the default OS associated program to do so, here is a function taken from http://access.mvps.org/access/api/api0018.htm:

'************ Code Start **********
' This code was originally written by Dev Ashish.
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code Courtesy of
' Dev Ashish
'
Private Declare Function apiShellExecute Lib "shell32.dll" _
    Alias "ShellExecuteA" _
    (ByVal hwnd As Long, _
    ByVal lpOperation As String, _
    ByVal lpFile As String, _
    ByVal lpParameters As String, _
    ByVal lpDirectory As String, _
    ByVal nShowCmd As Long) _
    As Long

'***App Window Constants***
Public Const WIN_NORMAL = 1         'Open Normal
Public Const WIN_MAX = 3            'Open Maximized
Public Const WIN_MIN = 2            'Open Minimized

'***Error Codes***
Private Const ERROR_SUCCESS = 32&
Private Const ERROR_NO_ASSOC = 31&
Private Const ERROR_OUT_OF_MEM = 0&
Private Const ERROR_FILE_NOT_FOUND = 2&
Private Const ERROR_PATH_NOT_FOUND = 3&
Private Const ERROR_BAD_FORMAT = 11&

'***************Usage Examples***********************
'Open a folder:     ?fHandleFile("C:\TEMP\",WIN_NORMAL)
'Call Email app:    ?fHandleFile("mailto:[email protected]",WIN_NORMAL)
'Open URL:          ?fHandleFile("http://home.att.net/~dashish", WIN_NORMAL)
'Handle Unknown extensions (call Open With Dialog):
'                   ?fHandleFile("C:\TEMP\TestThis",Win_Normal)
'Start Access instance:
'                   ?fHandleFile("I:\mdbs\CodeNStuff.mdb", Win_NORMAL)
'****************************************************

Function fHandleFile(stFile As String, lShowHow As Long)
Dim lRet As Long, varTaskID As Variant
Dim stRet As String
    'First try ShellExecute
    lRet = apiShellExecute(hWndAccessApp, vbNullString, _
            stFile, vbNullString, vbNullString, lShowHow)

    If lRet > ERROR_SUCCESS Then
        stRet = vbNullString
        lRet = -1
    Else
        Select Case lRet
            Case ERROR_NO_ASSOC:
                'Try the OpenWith dialog
                varTaskID = Shell("rundll32.exe shell32.dll,OpenAs_RunDLL " _
                        & stFile, WIN_NORMAL)
                lRet = (varTaskID <> 0)
            Case ERROR_OUT_OF_MEM:
                stRet = "Error: Out of Memory/Resources. Couldn't Execute!"
            Case ERROR_FILE_NOT_FOUND:
                stRet = "Error: File not found.  Couldn't Execute!"
            Case ERROR_PATH_NOT_FOUND:
                stRet = "Error: Path not found. Couldn't Execute!"
            Case ERROR_BAD_FORMAT:
                stRet = "Error:  Bad File Format. Couldn't Execute!"
            Case Else:
        End Select
    End If
    fHandleFile = lRet & _
                IIf(stRet = "", vbNullString, ", " & stRet)
End Function
'************ Code End **********

Just put this into a separate module and call fHandleFile() with the right parameters.

When do I need to use a semicolon vs a slash in Oracle SQL?

I know this is an old thread, but I just stumbled upon it and I feel this has not been explained completely.

There is a huge difference in SQL*Plus between the meaning of a / and a ; because they work differently.

The ; ends a SQL statement, whereas the / executes whatever is in the current "buffer". So when you use a ; and a / the statement is actually executed twice.

You can easily see that using a / after running a statement:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:37:20 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> drop table foo;

Table dropped.

SQL> /
drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

In this case one actually notices the error.


But assuming there is a SQL script like this:

drop table foo;
/

And this is run from within SQL*Plus then this will be very confusing:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:38:05 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> @drop

Table dropped.

drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

The / is mainly required in order to run statements that have embedded ; like a CREATE PROCEDURE statement.

What is the shortcut in IntelliJ IDEA to find method / functions?

CTRL + F12 brings up the File Structure navigation menu, which lets you search for members of the currently open file.

Pass data to layout that are common to all pages

You don't have to mess with actions or change the model, just use a base controller and cast the existing controller from the layout viewcontext.

Create a base controller with the desired common data (title/page/location etc) and action initialization...

public abstract class _BaseController:Controller {
    public Int32 MyCommonValue { get; private set; }

    protected override void OnActionExecuting(ActionExecutingContext filterContext) {

        MyCommonValue = 12345;

        base.OnActionExecuting(filterContext);
    }
}

Make sure every controller uses the base controller...

public class UserController:_BaseController {...

Cast the existing base controller from the view context in your _Layout.cshml page...

@{
    var myController = (_BaseController)ViewContext.Controller;
}

Now you can refer to values in your base controller from your layout page.

@myController.MyCommonValue

UPDATE

You could also create a page extension that would allow you to use this.

//Allows typed "this.Controller()." in cshtml files
public static class MyPageExtensions {
    public static _BaseController Controller(this WebViewPage page) => Controller<_BaseController>(page);
    public static T Controller<T>(this WebViewPage page) where T : _BaseController => (T)page.ViewContext.Controller;
}

Then you only have to remember to use this.Controller() when you want the controller.

@{
    var myController = this.Controller(); //_BaseController
}

or specific controller that inherits from _BaseController...

@{
    var myController = this.Controller<MyControllerType>();
}

How to create batch file in Windows using "start" with a path and command with spaces

Actually, his example won't work (although at first I thought that it would, too). Based on the help for the Start command, the first parameter is the name of the newly created Command Prompt window, and the second and third should be the path to the application and its parameters, respectively. If you add another "" before path to the app, it should work (at least it did for me). Use something like this:

start "" "c:\path with spaces\app.exe" param1 "param with spaces"

You can change the first argument to be whatever you want the title of the new command prompt to be. If it's a Windows app that is created, then the command prompt won't be displayed, and the title won't matter.

Failure during conversion to COFF: file invalid or corrupt

Do you have Visual Studio 2012 installed as well? If so, 2012 stomps your 2010 IDE, possibly because of compatibility issues with .NET 4.5 and .NET 4.0.

See http://social.msdn.microsoft.com/Forums/da-DK/vssetup/thread/d10adba0-e082-494a-bb16-2bfc039faa80

What is the most effective way for float and double comparison?

`return fabs(a - b) < EPSILON;

This is fine if:

  • the order of magnitude of your inputs don't change much
  • very small numbers of opposite signs can be treated as equal

But otherwise it'll lead you into trouble. Double precision numbers have a resolution of about 16 decimal places. If the two numbers you are comparing are larger in magnitude than EPSILON*1.0E16, then you might as well be saying:

return a==b;

I'll examine a different approach that assumes you need to worry about the first issue and assume the second is fine your application. A solution would be something like:

#define VERYSMALL  (1.0E-150)
#define EPSILON    (1.0E-8)
bool AreSame(double a, double b)
{
    double absDiff = fabs(a - b);
    if (absDiff < VERYSMALL)
    {
        return true;
    }

    double maxAbs  = max(fabs(a) - fabs(b));
    return (absDiff/maxAbs) < EPSILON;
}

This is expensive computationally, but it is sometimes what is called for. This is what we have to do at my company because we deal with an engineering library and inputs can vary by a few dozen orders of magnitude.

Anyway, the point is this (and applies to practically every programming problem): Evaluate what your needs are, then come up with a solution to address your needs -- don't assume the easy answer will address your needs. If after your evaluation you find that fabs(a-b) < EPSILON will suffice, perfect -- use it! But be aware of its shortcomings and other possible solutions too.

Where do you include the jQuery library from? Google JSAPI? CDN?

jQuery 1.3.1 min is only 18k in size. I don't think that's too much of a hit to ask on the initial page load. It'll be cached after that. As a result, I host it myself.

Programmatically stop execution of python script?

You could raise SystemExit(0) instead of going to all the trouble to import sys; sys.exit(0).

How to make the Facebook Like Box responsive?

Colin's example for me clashed with the like button. So I adapted it to only target the Like Box.

.fb-like-box, .fb-like-box span, .fb-like-box span iframe[style] { width: 100% !important; }

Tested in most modern browsers.

Why is Thread.Sleep so harmful

Sleep is used in cases where independent program(s) that you have no control over may sometimes use a commonly used resource (say, a file), that your program needs to access when it runs, and when the resource is in use by these other programs your program is blocked from using it. In this case, where you access the resource in your code, you put your access of the resource in a try-catch (to catch the exception when you can't access the resource), and you put this in a while loop. If the resource is free, the sleep never gets called. But if the resource is blocked, then you sleep for an appropriate amount of time, and attempt to access the resource again (this why you're looping). However, bear in mind that you must put some kind of limiter on the loop, so it's not a potentially infinite loop. You can set your limiting condition to be N number of attempts (this is what I usually use), or check the system clock, add a fixed amount of time to get a time limit, and quit attempting access if you hit the time limit.

Read/write to file using jQuery

Yes it is possible.

The technique is described below

http://jquery.tiddlywiki.org/twFile.html

python: urllib2 how to send cookie with urlopen request

Cookie is just another HTTP header.

import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

See urllib2 examples for other ways how to add HTTP headers to your request.

There are more ways how to handle cookies. Some modules like cookielib try to behave like web browser - remember what cookies did you get previously and automatically send them again in following requests.

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

How to get a unix script to run every 15 seconds?

I would use cron to run a script every minute, and make that script run your script four times with a 15-second sleep between runs.

(That assumes your script is quick to run - you could adjust the sleep times if not.)

That way, you get all the benefits of cron as well as your 15 second run period.

Edit: See also @bmb's comment below.

How to convert an int to string in C?

Converting anything to a string should either 1) allocate the resultant string or 2) pass in a char * destination and size. Sample code below:

Both work for all int including INT_MIN. They provide a consistent output unlike snprintf() which depends on the current locale.

Method 1: Returns NULL on out-of-memory.

#define INT_DECIMAL_STRING_SIZE(int_type) ((CHAR_BIT*sizeof(int_type)-1)*10/33+3)

char *int_to_string_alloc(int x) {
  int i = x;
  char buf[INT_DECIMAL_STRING_SIZE(int)];
  char *p = &buf[sizeof buf - 1];
  *p = '\0';
  if (i >= 0) {
    i = -i;
  }
  do {
    p--;
    *p = (char) ('0' - i % 10);
    i /= 10;
  } while (i);
  if (x < 0) {
    p--;
    *p = '-';
  }
  size_t len = (size_t) (&buf[sizeof buf] - p);
  char *s = malloc(len);
  if (s) {
    memcpy(s, p, len);
  }
  return s;
}

Method 2: It returns NULL if the buffer was too small.

static char *int_to_string_helper(char *dest, size_t n, int x) {
  if (n == 0) {
    return NULL;
  }
  if (x <= -10) {
    dest = int_to_string_helper(dest, n - 1, x / 10);
    if (dest == NULL) return NULL;
  }
  *dest = (char) ('0' - x % 10);
  return dest + 1;
}

char *int_to_string(char *dest, size_t n, int x) {
  char *p = dest;
  if (n == 0) {
    return NULL;
  }
  n--;
  if (x < 0) {
    if (n == 0) return NULL;
    n--;
    *p++ = '-';
  } else {
    x = -x;
  }
  p = int_to_string_helper(p, n, x);
  if (p == NULL) return NULL;
  *p = 0;
  return dest;
}

[Edit] as request by @Alter Mann

(CHAR_BIT*sizeof(int_type)-1)*10/33+3 is at least the maximum number of char needed to encode the some signed integer type as a string consisting of an optional negative sign, digits, and a null character..

The number of non-sign bits in a signed integer is no more than CHAR_BIT*sizeof(int_type)-1. A base-10 representation of a n-bit binary number takes up to n*log10(2) + 1 digits. 10/33 is slightly more than log10(2). +1 for the sign char and +1 for the null character. Other fractions could be used like 28/93.


Method 3: If one wants to live on the edge and buffer overflow is not a concern, a simple C99 or later solution follows which handles all int.

#include <limits.h>
#include <stdio.h>

static char *itoa_simple_helper(char *dest, int i) {
  if (i <= -10) {
    dest = itoa_simple_helper(dest, i/10);
  }
  *dest++ = '0' - i%10;
  return dest;
}

char *itoa_simple(char *dest, int i) {
  char *s = dest;
  if (i < 0) {
    *s++ = '-';
  } else {
    i = -i;
  }
  *itoa_simple_helper(s, i) = '\0';
  return dest;
}

int main() {
  char s[100];
  puts(itoa_simple(s, 0));
  puts(itoa_simple(s, 1));
  puts(itoa_simple(s, -1));
  puts(itoa_simple(s, 12345));
  puts(itoa_simple(s, INT_MAX-1));
  puts(itoa_simple(s, INT_MAX));
  puts(itoa_simple(s, INT_MIN+1));
  puts(itoa_simple(s, INT_MIN));
}

Sample output

0
1
-1
12345
2147483646
2147483647
-2147483647
-2147483648

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

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

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

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

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

Drop a temporary table if it exists

What you asked for is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##CLIENTS_KEYWORD

       CREATE TABLE ##CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##TEMP_CLIENTS_KEYWORD

       CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##CLIENTS_KEYWORD

CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##TEMP_CLIENTS_KEYWORD

CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

Get the Selected value from the Drop down box in PHP

Couldn't you just pass the a name attribute and wrap it in a form?

<form id="form" action="do_stuff.php" method="post">
    <select id="select_catalog" name="select_catalog_query">
    <?php <<<INSERT THE SELECT OPTION LOOP>>> ?>
    </select>
</form>

And then look for $_POST['select_catalog_query'] ?

Best way to strip punctuation from a string

string.punctuation is ASCII only! A more correct (but also much slower) way is to use the unicodedata module:

# -*- coding: utf-8 -*-
from unicodedata import category
s = u'String — with -  «punctation »...'
s = ''.join(ch for ch in s if category(ch)[0] != 'P')
print 'stripped', s

You can generalize and strip other types of characters as well:

''.join(ch for ch in s if category(ch)[0] not in 'SP')

It will also strip characters like ~*+§$ which may or may not be "punctuation" depending on one's point of view.

Maximum execution time in phpMyadmin

ini_set('max_execution_time', 0); or create file name called php.ini and enter the first line max_execution_time=0 then save it and put the file in your root folder of your application.

That's it. Good luck.

Adding a line break in MySQL INSERT INTO text

MySQL can record linebreaks just fine in most cases, but the problem is, you need <br /> tags in the actual string for your browser to show the breaks. Since you mentioned PHP, you can use the nl2br() function to convert a linebreak character ("\n") into HTML <br /> tag.

Just use it like this:

<?php
echo nl2br("Hello, World!\n I hate you so much");
?>

Output (in HTML):

Hello, World!<br>I hate you so much

Here's a link to the manual: http://php.net/manual/en/function.nl2br.php

SQL query for today's date minus two months

If you are using SQL Server try this:

SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())

Based on your update it would be:

SELECT * FROM FB WHERE Dte <  DATEADD(month, -2, GETDATE())

TypeError: 'module' object is not callable

It seems like what you've done is imported the socket module as import socket. Therefore socket is the module. You either need to change that line to self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM), as well as every other use of the socket module, or change the import statement to from socket import socket.

Or you've got an import socket after your from socket import *:

>>> from socket import *
>>> serv = socket(AF_INET,SOCK_STREAM)
>>> import socket
>>> serv = socket(AF_INET,SOCK_STREAM)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'module' object is not callable

How to compare binary files to check if they are the same?

md5sum binary1 binary2

If the md5sum is same, binaries are same

E.g

md5sum new*
89c60189c3fa7ab5c96ae121ec43bd4a  new.txt
89c60189c3fa7ab5c96ae121ec43bd4a  new1.txt
root@TinyDistro:~# cat new*
aa55 aa55 0000 8010 7738
aa55 aa55 0000 8010 7738


root@TinyDistro:~# cat new*
aa55 aa55 000 8010 7738
aa55 aa55 0000 8010 7738
root@TinyDistro:~# md5sum new*
4a7f86919d4ac00c6206e11fca462c6f  new.txt
89c60189c3fa7ab5c96ae121ec43bd4a  new1.txt

Cannot stop or restart a docker container

For anyone on a Mac who has Docker Desktop installed. I was able to just click the tray icon and say Restart Docker. Once it restarted was able to delete the containers.

How to draw a line with matplotlib?

Just want to mention another option here.

You can compute the coefficients using numpy.polyfit(), and feed the coefficients to numpy.poly1d(). This function can construct polynomials using the coefficients, you can find more examples here

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.poly1d.html

Let's say, given two data points (-0.3, -0.5) and (0.8, 0.8)

import numpy as np
import matplotlib.pyplot as plt

# compute coefficients
coefficients = np.polyfit([-0.3, 0.8], [-0.5, 0.8], 1) 

# create a polynomial object with the coefficients
polynomial = np.poly1d(coefficients)

# for the line to extend beyond the two points, 
# create the linespace using the min and max of the x_lim
# I'm using -1 and 1 here
x_axis = np.linspace(-1, 1)

# compute the y for each x using the polynomial
y_axis = polynomial(x_axis)

fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 1, 1])
axes.set_xlim(-1, 1)
axes.set_ylim(-1, 1)
axes.plot(x_axis, y_axis)
axes.plot(-0.3, -0.5, 0.8, 0.8, marker='o', color='red')

enter image description here

Hope it helps.

How do I abort/cancel TPL Tasks?

I use a mixed approach to cancel a task.

  • Firstly, I'm trying to Cancel it politely with using the Cancellation.
  • If it's still running (e.g. due to a developer's mistake), then misbehave and kill it using an old-school Abort method.

Checkout an example below:

private CancellationTokenSource taskToken;
private AutoResetEvent awaitReplyOnRequestEvent = new AutoResetEvent(false);

void Main()
{
    // Start a task which is doing nothing but sleeps 1s
    LaunchTaskAsync();
    Thread.Sleep(100);
    // Stop the task
    StopTask();
}

/// <summary>
///     Launch task in a new thread
/// </summary>
void LaunchTaskAsync()
{
    taskToken = new CancellationTokenSource();
    Task.Factory.StartNew(() =>
        {
            try
            {   //Capture the thread
                runningTaskThread = Thread.CurrentThread;
                // Run the task
                if (taskToken.IsCancellationRequested || !awaitReplyOnRequestEvent.WaitOne(10000))
                    return;
                Console.WriteLine("Task finished!");
            }
            catch (Exception exc)
            {
                // Handle exception
            }
        }, taskToken.Token);
}

/// <summary>
///     Stop running task
/// </summary>
void StopTask()
{
    // Attempt to cancel the task politely
    if (taskToken != null)
    {
        if (taskToken.IsCancellationRequested)
            return;
        else
            taskToken.Cancel();
    }

    // Notify a waiting thread that an event has occurred
    if (awaitReplyOnRequestEvent != null)
        awaitReplyOnRequestEvent.Set();

    // If 1 sec later the task is still running, kill it cruelly
    if (runningTaskThread != null)
    {
        try
        {
            runningTaskThread.Join(TimeSpan.FromSeconds(1));
        }
        catch (Exception ex)
        {
            runningTaskThread.Abort();
        }
    }
}

How to clear Tkinter Canvas?

Items drawn to the canvas are persistent. create_rectangle returns an item id that you need to keep track of. If you don't remove old items your program will eventually slow down.

From Fredrik Lundh's An Introduction to Tkinter:

Note that items added to the canvas are kept until you remove them. If you want to change the drawing, you can either use methods like coords, itemconfig, and move to modify the items, or use delete to remove them.

Disabling swap files creation in vim

Set the following variables in .vimrc or /etc/vimrc to make vim put swap, backup and undo files in a special location instead of the working directory of the file being edited:

set backupdir=~/.vim/backup//
set directory=~/.vim/swap//
set undodir=~/.vim/undo//

Using double trailing slashes in the path tells vim to enable a feature where it avoids name collisions. For example, if you edit a file in one location and another file in another location and both files have the same name, you don't want a name collision to occur in ~/.vim/swap/. If you specify ~/.vim/swap// with two trailing slashes vim will create swap files using the whole path of the files being edited to avoid collisions (slashes in the file's path will be replaced by percent symbol %).

For example, if you edit /path/one/foobar.txt and /path/two/foobar.txt, then you will see two swap files in ~/.vim/swap/ that are named %path%one%foobar.txt and %path%two%foobar.txt, respectively.

PHP passing $_GET in linux command prompt

Sometimes you don't have the option of editing the php file to set $_GET to the parameters passed in, and sometimes you can't or don't want to install php-cgi.

I found this to be the best solution for that case:

php -r '$_GET["key"]="value"; require_once("script.php");' 

This avoids altering your php file and lets you use the plain php command. If you have php-cgi installed, by all means use that, but this is the next best thing. Thought this options was worthy of mention

the -r means run the php code in the string following. you set the $_GET value manually there, and then reference the file you want to run.

Its worth noting you should run this in the right folder, often but not always the folder the php file is in. Requires statements will use the location of your command to resolve relative urls, NOT the location of the file

How to convert an array of key-value tuples into an object

You could do this easily using array reduce in ES6

In this example we create a reducer function and pass an object '{}' as initial value to the reduce function along with the reducer

_x000D_
_x000D_
const arr =    [ [ 'cardType', 'iDEBIT' ],_x000D_
  [ 'txnAmount', '17.64' ],_x000D_
  [ 'txnId', '20181' ],_x000D_
  [ 'txnType', 'Purchase' ],_x000D_
  [ 'txnDate', '2015/08/13 21:50:04' ],_x000D_
  [ 'respCode', '0' ],_x000D_
  [ 'isoCode', '0' ],_x000D_
  [ 'authCode', '' ],_x000D_
  [ 'acquirerInvoice', '0' ],_x000D_
  [ 'message', '' ],_x000D_
  [ 'isComplete', 'true' ],_x000D_
  [ 'isTimeout', 'false' ] ];_x000D_
_x000D_
const reducer = (obj, item) => {_x000D_
  obj[item[0]] = item[1];_x000D_
  return obj;_x000D_
};_x000D_
_x000D_
const result = arr.reduce(reducer, {});_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

How to set time to midnight for current day?

You can use the Date property of the DateTime object - eg

DateTime midnight = DateTime.Now.Date;

So your code example becomes

private DateTime _Begin = DateTime.Now.Date;
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }

PS. going back to your original code setting the hours to 12 will give you time of noon for the current day, so instead you could have used 0...

var now = DateTime.Now;
new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);

Fastest way to get the first n elements of a List into an Array

It mostly depends on how big n is.

If n==0, nothing beats option#1 :)

If n is very large, toArray(new String[n]) is faster.

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

Angular 4/5/6 Global Variables

You can access Globals entity from any point of your App via Angular dependency injection. If you want to output Globals.role value in some component's template, you should inject Globals through the component's constructor like any service:

// hello.component.ts
import { Component } from '@angular/core';
import { Globals } from './globals';

@Component({
  selector: 'hello',
  template: 'The global role is {{globals.role}}',
  providers: [ Globals ] // this depends on situation, see below
})

export class HelloComponent {
  constructor(public globals: Globals) {}
}

I provided Globals in the HelloComponent, but instead it could be provided in some HelloComponent's parent component or even in AppModule. It will not matter until your Globals has only static data that could not be changed (say, constants only). But if it's not true and for example different components/services might want to change that data, then the Globals must be a singleton. In that case it should be provided in the topmost level of the hierarchy where it is going to be used. Let's say this is AppModule:

import { Globals } from './globals'

@NgModule({
  // ... imports, declarations etc
  providers: [
    // ... other global providers
    Globals // so do not provide it into another components/services if you want it to be a singleton
  ]
})

Also, it's impossible to use var the way you did, it should be

// globals.ts
import { Injectable } from '@angular/core';

@Injectable()
export class Globals {
  role: string = 'test';
}

Update

At last, I created a simple demo on stackblitz, where single Globals is being shared between 3 components and one of them can change the value of Globals.role.

Git - Ignore files during merge

You could use .gitignore to keep the config.xml out of the repository, and then use a post commit hook to upload the appropriate config.xml file to the server.

How to convert LINQ query result to List?

You need to somehow convert each tbcourse object to an instance of course. For instance course could have a constructor that takes a tbcourse. You could then write the query like this:

var qry = from c in obj.tbCourses
          select new course(c);

List<course> lst = qry.ToList();

Escape quote in web.config connection string

Odeds answer is almost complete. Just one thing to add.

  1. Escape xml special chars like Emanuele Greco said.
  2. Put the password in single quotes like Oded said
  3. (this one is new) Escape single ticks with another single tick (ref)

having this password="'; this sould be a valid connection string:

connectionString='Server=dbsrv;User ID=myDbUser;Password='&quot;&amp;&amp;;'

Assigning a function to a variable

You simply don't call the function.

>>>def x():
>>>    print(20)
>>>y = x
>>>y()
20

The brackets tell python that you are calling the function, so when you put them there, it calls the function and assigns y the value returned by x (which in this case is None).

Sharing link on WhatsApp from mobile website (not application) for Android

Currently, it's very easy to achieve this. You only need to add the following code to your pages:

<a href="whatsapp://send?text=<<HERE GOES THE URL ENCODED TEXT YOU WANT TO SHARE>>" data-action="share/whatsapp/share">Share via Whatsapp</a>

And that's it. No Javascript needed, nothing else needed. Of course you can style it as you want and include a nice Whatsapp icon.

I tested this in my Android device with Google Chrome. The versions:

  • Android 4.1.2 (Jelly Bean)
  • Chrome Mobile 37.0.2062.117. Also tested on Firefox Mobile 31.0.
  • Whatsapp V 2.11.399

It also works on iOS. I've made a quick test on an iPhone 5 with Safari and it works as well.

Hope this helps someone. :-)

ImportError: numpy.core.multiarray failed to import

run this codes worked for me, seems to be issue with version.

pip uninstall numpy

pip install numpy==1.19.3

Efficiently test if a port is open on Linux?

ss -tl4 '( sport = :22 )'

2ms is quick enough ?

Add the colon and this works on Linux

How do I move an existing Git submodule within a Git repository?

[Update: 2014-11-26] As Yar summarizes nicely below, before you do anything, make sure you know the URL of the submodule. If unknown, open .git/.gitmodules and examine the keysubmodule.<name>.url.

What worked for me was to remove the old submodule using git submodule deinit <submodule> followed by git rm <submodule-folder>. Then add the submodule again with the new folder name and commit. Checking git status before committing shows the old submodule renamed to the new name and .gitmodule modified.

$ git submodule deinit foo
$ git rm foo
$ git submodule add https://bar.com/foo.git new-foo
$ git status
renamed:    foo -> new-foo
modified:   .gitmodules
$ git commit -am "rename foo submodule to new-foo"

How do I count the number of rows and columns in a file using bash?

Columns: awk '{print NF}' file | sort -nu | tail -n 1

Use head -n 1 for lowest column count, tail -n 1 for highest column count.

Rows: cat file | wc -l or wc -l < file for the UUOC crowd.

Call Python script from bash with argument

To execute a python script in a bash script you need to call the same command that you would within a terminal. For instance

> python python_script.py var1 var2

To access these variables within python you will need

import sys
print sys.argv[0] # prints python_script.py
print sys.argv[1] # prints var1
print sys.argv[2] # prints var2

What is the difference between String and string in C#?

String is not a keyword and it can be used as Identifier whereas string is a keyword and cannot be used as Identifier. And in function point of view both are same.

JUnit tests pass in Eclipse but fail in Maven Surefire

This doesn't exactly apply to your situation, but I had the same thing -- tests that would pass in Eclipse failed when the test goal from Maven was run.

It turned out to be a test earlier in my suite, in a different package. This took me a week to solve!

An earlier test was testing some Logback classes, and created a Logback context from a config file.

The later test was testing a subclass of Spring's SimpleRestTemplate, and somehow, the earlier Logback context was held, with DEBUG on. This caused extra calls to be made in RestTemplate to log HttpStatus, etc.

It's another thing to check if one ever gets into this situation. I fixed my problem by injecting some Mocks into my Logback test class, so that no real Logback contexts were created.

How to redirect to previous page in Ruby On Rails?

For those who are interested, here is my implementation extending MBO's original answer (written against rails 4.2.4, ruby 2.1.5).

class ApplicationController < ActionController::Base
  after_filter :set_return_to_location

  REDIRECT_CONTROLLER_BLACKLIST = %w(
    sessions
    user_sessions
    ...
    etc.
  )

  ...

  def set_return_to_location
    return unless request.get?
    return unless request.format.html?
    return unless %w(show index edit).include?(params[:action])
    return if REDIRECT_CONTROLLER_BLACKLIST.include?(controller_name)
    session[:return_to] = request.fullpath
  end

  def redirect_back_or_default(default_path = root_path)
    redirect_to(
      session[:return_to].present? && session[:return_to] != request.fullpath ?
        session[:return_to] : default_path
    )
  end
end

How to convert ISO8859-15 to UTF8?

I found this to work for me:

iconv -f ISO-8859-14 Agreement.txt -t UTF-8 -o agreement.txt

Counting repeated characters in a string in Python

import collections

d = collections.defaultdict(int)
for c in thestring:
    d[c] += 1

A collections.defaultdict is like a dict (subclasses it, actually), but when an entry is sought and not found, instead of reporting it doesn't have it, it makes it and inserts it by calling the supplied 0-argument callable. Most popular are defaultdict(int), for counting (or, equivalently, to make a multiset AKA bag data structure), and defaultdict(list), which does away forever with the need to use .setdefault(akey, []).append(avalue) and similar awkward idioms.

So once you've done this d is a dict-like container mapping every character to the number of times it appears, and you can emit it any way you like, of course. For example, most-popular character first:

for c in sorted(d, key=d.get, reverse=True):
  print '%s %6d' % (c, d[c])

Does adding a duplicate value to a HashSet/HashMap replace the previous value

To say it differently: When you insert a key-value-pair into a HashMap where the key already exists (in a sense hashvalue() gives the same value und equal() is true, but the two objects can still differ in several ways), the key isn't replaced but the value is overwritten. The key is just used to get the hashvalue() and find the value in the table with it. Since HashSet uses the keys of a HashMap and sets arbitrary values which don't really matter (to the user) as a result the Elements of the Set aren't replaced either.

how to save canvas as png image?

I really like Tovask's answer but it doesn't work due to the function having the name download (this answer explains why). I also don't see the point in replacing "data:image/..." with "data:application/...".

The following code has been tested in Chrome and Firefox and seems to work fine in both.

JavaScript:

function prepDownload(a, canvas, name) {
    a.download = name
    a.href = canvas.toDataURL()
}

HTML:

<a href="#" onclick="prepDownload(this, document.getElementById('canvasId'), 'imgName.png')">Download</a>
<canvas id="canvasId"></canvas>

Ruby/Rails: converting a Date to a UNIX timestamp

Solution for Ruby 1.8 when you have an arbitrary DateTime object:

1.8.7-p374 :001 > require 'date'
 => true 
1.8.7-p374 :002 > DateTime.new(2012, 1, 15).strftime('%s')
 => "1326585600"

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

dict((el,0) for el in a) will work well.

Python 2.7 and above also support dict comprehensions. That syntax is {el:0 for el in a}.

What is __main__.py?

If your script is a directory or ZIP file rather than a single python file, __main__.py will be executed when the "script" is passed as an argument to the python interpreter.

Return file in ASP.Net Core Web API

You can return FileResult with this methods:

1: Return FileStreamResult

    [HttpGet("get-file-stream/{id}"]
    public async Task<FileStreamResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        var stream = await GetFileStreamById(id);

        return new FileStreamResult(stream, mimeType)
        {
            FileDownloadName = fileName
        };
    }

2: Return FileContentResult

    [HttpGet("get-file-content/{id}"]
    public async Task<FileContentResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        var fileBytes = await GetFileBytesById(id);

        return new FileContentResult(fileBytes, mimeType)
        {
            FileDownloadName = fileName
        };
    }

cut or awk command to print first field of first row

Specify the Line Number using NR built-in variable.

awk 'NR==1{print $1}' /etc/*release

Google Maps V3 marker with label

If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..

<script type="text/javascript">
    var point = { lat: 22.5667, lng: 88.3667 };
    var markerSize = { x: 22, y: 40 };


    google.maps.Marker.prototype.setLabel = function(label){
        this.label = new MarkerLabel({
          map: this.map,
          marker: this,
          text: label
        });
        this.label.bindTo('position', this, 'position');
    };

    var MarkerLabel = function(options) {
        this.setValues(options);
        this.span = document.createElement('span');
        this.span.className = 'map-marker-label';
    };

    MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
        onAdd: function() {
            this.getPanes().overlayImage.appendChild(this.span);
            var self = this;
            this.listeners = [
            google.maps.event.addListener(this, 'position_changed', function() { self.draw();    })];
        },
        draw: function() {
            var text = String(this.get('text'));
            var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
            this.span.innerHTML = text;
            this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
            this.span.style.top = (position.y - markerSize.y + 40) + 'px';
        }
    });
    function initialize(){
        var myLatLng = new google.maps.LatLng(point.lat, point.lng);
        var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 5,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var myMarker = new google.maps.Marker({
            map: gmap,
            position: myLatLng,
            label: 'Hello World!',
            draggable: true
        });
    }
</script>
<style>
    .map-marker-label{
        position: absolute;
    color: blue;
    font-size: 16px;
    font-weight: bold;
    }
</style>

This will work.

Create patch or diff file from git repository and apply it to another different git repository

you can apply two commands

  1. git diff --patch > mypatch.patch // to generate the patch
  2. git apply mypatch.patch // to apply the patch

How do I get Flask to run on port 80?

you can easily disable any process running on port 80 and then run this command

flask run --host 0.0.0.0 --port 80

or if u prefer running it within the .py file

if __name__ == "__main__":
    app.run(host=0.0.0.0, port=80)

Max tcp/ip connections on Windows Server 2008

How many thousands of users?

I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.

Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.

If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.

Edited to add details from the comment below...

If you're already thinking of multiple servers I'd take the following approach.

  1. Use the free tools that I link to and prove to yourself that you can create a reasonable number of connections onto your target OS (beware of the Windows limits on dynamic ports which may cause your client connections to fail, search for MAX_USER_PORT).

  2. during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html

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

Since Jet 4, all queries that have a join to a SQL statement that summarizes data will be non-updatable. You aren't using a JOIN, but the WHERE clause is exactly equivalent to a join, and thus, the Jet query optimizer treats it the same way it treats a join.

I'm afraid you're out of luck without a temp table, though maybe somebody with greater Jet SQL knowledge than I can come up with a workaround.

BTW, it might have been updatable in Jet 3.5 (Access 97), as a whole lot of queries were updatable then that became non-updatable when upgraded to Jet 4.

--

How do you make a HTTP request with C++?

Although a little bit late. You may prefer https://github.com/Taymindis/backcurl .

It allows you to do http call on mobile c++ development. Suitable for Mobile game developement

bcl::init(); // init when using

bcl::execute<std::string>([&](bcl::Request *req) {
    bcl::setOpts(req, CURLOPT_URL , "http://www.google.com",
             CURLOPT_FOLLOWLOCATION, 1L,
             CURLOPT_WRITEFUNCTION, &bcl::writeContentCallback,
             CURLOPT_WRITEDATA, req->dataPtr,
             CURLOPT_USERAGENT, "libcurl-agent/1.0",
             CURLOPT_RANGE, "0-200000"
            );
}, [&](bcl::Response * resp) {
    std::string ret =  std::string(resp->getBody<std::string>()->c_str());
    printf("Sync === %s\n", ret.c_str());
});


bcl::cleanUp(); // clean up when no more using

How do I properly 'printf' an integer and a string in C?

scanf("%s",str) scans only until it finds a whitespace character. With the input "A 1", it will scan only the first character, hence s2 points at the garbage that happened to be in str, since that array wasn't initialised.

Compress images on client side before uploading

I read about an experiment here: http://webreflection.blogspot.com/2010/12/100-client-side-image-resizing.html

The theory is that you can use canvas to resize the images on the client before uploading. The prototype example seems to work only in recent browsers, interesting idea though...

However, I’m not sure about using canvas to compress images, but you can certainly resize them.

How do I print part of a rendered HTML page in JavaScript?

Try this JavaScript code:

function printout() {

    var newWindow = window.open();
    newWindow.document.write(document.getElementById("output").innerHTML);
    newWindow.print();
}

Java: Getting a substring from a string starting after a particular character

A very simple implementation with String.split():

String path = "/abc/def/ghfj.doc";
// Split path into segments
String segments[] = path.split("/");
// Grab the last segment
String document = segments[segments.length - 1];

How do you reindex an array in PHP but with indexes starting from 1?

Sorting is just a sort(), reindexing seems a bit silly but if it is needed this will do it. Though not in-place. Use array_walk() if you will do this in a bunch of places, just use a for-key-value loop if this is a one-time operation.

<?php

function reindex(&$item, $key, &$reindexedarr) {
    $reindexedarr[$key+1] = $item;
}

$arr = Array (2 => 'c', 1 => 'b', 0 => 'a');

sort($arr);
$newarr = Array();
array_walk($arr, reindex, &$newarr);
$arr = $newarr;
print_r($arr); // Array ( [1] => a [2] => b [3] => c )

?>

Is there a way to delete all the data from a topic or delete the topic before every run?

As of kafka 2.3.0 version, there is an alternate way to soft deletion of Kafka (old approach are deprecated ).

Update retention.ms to 1 sec (1000ms) then set it again after a min, to default setting i.e 7 days (168 hours, 604,800,000 in ms )

Soft deletion:- (rentention.ms=1000) (using kafka-configs.sh)

bin/kafka-configs.sh --zookeeper 192.168.1.10:2181 --alter --entity-name kafka_topic3p3r --entity-type topics  --add-config retention.ms=1000
Completed Updating config for entity: topic 'kafka_topic3p3r'.

Setting to default:- 7 days (168 hours , retention.ms= 604800000)

bin/kafka-configs.sh --zookeeper 192.168.1.10:2181 --alter --entity-name kafka_topic3p3r --entity-type topics  --add-config retention.ms=604800000

How can I see what I am about to push with git?

If you are using Mac OS X, I would recommend you get Tower, it's a wonderful program that has made dealing with Git a pleasure for me. I now longer have to remember terminal commands and it offers a great GUI to view, track and solve differences in files.

And no, I'm not affiliated with them, I just use their software and really like it.

http://www.git-tower.com/

What's the difference between lists and tuples?

It's been mentioned that the difference is largely semantic: people expect a tuple and list to represent different information. But this goes further than a guideline; some libraries actually behave differently based on what they are passed. Take NumPy for example (copied from another post where I ask for more examples):

>>> import numpy as np
>>> a = np.arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> idx = (1,1)
>>> a[idx]
4
>>> idx = [1,1]
>>> a[idx]
array([[3, 4, 5],
       [3, 4, 5]])

The point is, while NumPy may not be part of the standard library, it's a major Python library, and within NumPy lists and tuples are completely different things.

Set height of chart in Chart.js

I created a container and set it the desired height of the view port (depending on the number of charts or chart specific sizes):

.graph-container {
width: 100%;
height: 30vh;
}

To be dynamic to screen sizes I set the container as follows:

*Small media devices specific styles*/
@media screen and (max-width: 800px) {
.graph-container {
        display: block;
        float: none;
        width: 100%;
        margin-top: 0px;
        margin-right:0px;
        margin-left:0px;
        height: auto;
    }
}

Of course very important (as have been referred to numerous times) set the following option properties of your chart:

options:{
    maintainAspectRatio: false,
    responsive: true,
}

awk partly string match (if column/word partly matches)

GNU sed

sed '/\s*\(\S\+\s\+\)\{2\}\bsnow\(man\)\?\b/!d' file

Input:

C1    C2    C3    
1     a     snow   
2     b     snowman 
snow     c     sowman
      snow     snow     snowmanx

..output:

1     a     snow
2     b     snowman

How do you get a string from a MemoryStream?

I need to integrate with a class that need a Stream to Write on it:

XmlSchema schema;
// ... Use "schema" ...

var ret = "";

using (var ms = new MemoryStream())
{
    schema.Write(ms);
    ret = Encoding.ASCII.GetString(ms.ToArray());
}
//here you can use "ret"
// 6 Lines of code

I create a simple class that can help to reduce lines of code for multiples use:

public static class MemoryStreamStringWrapper
{
    public static string Write(Action<MemoryStream> action)
    {
        var ret = "";
        using (var ms = new MemoryStream())
        {
            action(ms);
            ret = Encoding.ASCII.GetString(ms.ToArray());
        }

        return ret;
    }
}

then you can replace the sample with a single line of code

var ret = MemoryStreamStringWrapper.Write(schema.Write);

Matplotlib: ValueError: x and y must have same first dimension

Changing your lists to numpy arrays will do the job!!

import matplotlib.pyplot as plt
from scipy import stats
import numpy as np 

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78]) # x is a numpy array now
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,0.478,0.335,0.365,0.424,0.390,0.585,0.511]) # y is a numpy array now
xerr = [0.01]*15
yerr = [0.001]*15

plt.rc('font', family='serif', size=13)
m, b = np.polyfit(x, y, 1)
plt.plot(x,y,'s',color='#0066FF')
plt.plot(x, m*x + b, 'r-') #BREAKS ON THIS LINE
plt.errorbar(x,y,xerr=xerr,yerr=0,linestyle="None",color='black')
plt.xlabel('$\Delta t$ $(s)$',fontsize=20)
plt.ylabel('$\Delta p$ $(hPa)$',fontsize=20)
plt.autoscale(enable=True, axis=u'both', tight=False)
plt.grid(False)
plt.xlim(0.2,1.2)
plt.ylim(0,0.8)
plt.show()

enter image description here

What does 'const static' mean in C and C++?

Yes, it hides a variable in a module from other modules. In C++, I use it when I don't want/need to change a .h file that will trigger an unnecessary rebuild of other files. Also, I put the static first:

static const int foo = 42;

Also, depending on its use, the compiler won't even allocate storage for it and simply "inline" the value where it's used. Without the static, the compiler can't assume it's not being used elsewhere and can't inline.

File upload from <input type="file">

Another way using template reference variable and ViewChild, as proposed by Frelseren:

import { ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" #fileInput/>
    </div>
  `
})  
export class AppComponent {
  @ViewChild("fileInput") fileInputVariable: any;
  randomMethod() {
    const files = this.fileInputVariable.nativeElement.files;
    console.log(files);
  }
}

Also see https://stackoverflow.com/a/40165524/4361955

client denied by server configuration

this worked for me..

<Location />
 Allow from all
 Order Deny,Allow
</Location>

I have included this code in my /etc/apache2/apache2.conf

How to install the current version of Go in Ubuntu Precise

Best way to install Go on Ubuntu is to download required version from here. Here you could have all stable and releases, along with archived versions.

after downloading you selected version you can follow further steps, i will suggest you to download tar.gz format for ubuntu machine:

  1. first of all fully remove the older version from your local by doing this

sudo rm -rf /usr/local/go /usr/local/gocache

this will remove all the local go code base but wait something more we have to do to remove fully from local, i was missing this step and it took so much time until I understood what i am missing so here is the purge stuff to remove from list

sudo apt-get purge golang

or

sudo apt remove golang-go
  1. Now install / extract your downloaded version of go inside /usr/local/go, by hitting terminal with this

tar -C /usr/local -xzf go1.10.8.linux-amd64.tar.gz

  1. after doing all above stuff , don't forget or check to GOROOT variable value you can check the value by go env if not set then export PATH=$PATH:/usr/local/go
  2. Better to test a small go program to make sure. write this inside /home/yourusername/go/test.php if you haven't changed set GOPATH value:
package main

import "fmt"

func main() {
    fmt.Println("hello world")
}
  1. run this by go run test.go

i hope it works for you!!

linq query to return distinct field values from a list of objects

If just want to use Linq, you can override Equals and GetHashCode methods.

Product class:

public class Product
{
    public string ProductName { get; set; }
    public int Id { get; set; }


    public override bool Equals(object obj)
    {
        if (!(obj is Product))
        {
            return false;
        }

        var other = (Product)obj;
        return Id == other.Id;
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}

Main Method:

static void Main(string[] args)
    {

        var products = new List<Product>
        {
            new Product{ ProductName="Product 1",Id = 1},
            new Product{ ProductName="Product 2",Id = 2},
            new Product{ ProductName="Product 4",Id = 5},
            new Product{ ProductName="Product 3",Id = 3},
            new Product{ ProductName="Product 4",Id = 4},
            new Product{ ProductName="Product 6",Id = 4},
            new Product{ ProductName="Product 6",Id = 4},
        };

        var itemsDistinctByProductName = products.Distinct().ToList();

        foreach (var product in itemsDistinctByProductName)
        {
            Console.WriteLine($"Product Id : {product.Id} ProductName : {product.ProductName} ");
        }

        Console.ReadKey();
    }

warning: incompatible implicit declaration of built-in function ‘xyz’

I met these warnings on mempcpy function. Man page says this function is a GNU extension and synopsis shows:

#define _GNU_SOURCE
#include <string.h>

When #define is added to my source before the #include, declarations for the GNU extensions are made visible and warnings disappear.

SQL Update Multiple Fields FROM via a SELECT Statement

Something like this should work (can't test it right now - from memory):

UPDATE SHIPMENT
SET
  OrgAddress1     = BD.OrgAddress1,
  OrgAddress2     = BD.OrgAddress2,
  OrgCity         = BD.OrgCity,
  OrgState        = BD.OrgState,
  OrgZip          = BD.OrgZip,
  DestAddress1    = BD.DestAddress1,
  DestAddress2    = BD.DestAddress2,
  DestCity        = BD.DestCity,
  DestState       = BD.DestState,
  DestZip         = BD.DestZip
FROM
   BookingDetails BD
WHERE 
   SHIPMENT.MyID2 = @MyID2
   AND
   BD.MyID = @MyID

Does that help?

Open CSV file via VBA (performance)

This may help you, also it depends how your CSV file is formated.

  1. Open your excel sheet & go to menu Data > Import External Data > Import Data.
  2. Choose your CSV file.
  3. Original data type: choose Fixed width, then Next.
  4. It will autmaticall delimit your columns. then, you may check the splitted columns in Data preview panel.
  5. Then Finish & see.

Note: you may also go with Delimited as Original data type. In that case, you need to key-in your delimiting character.

HTH!

How to stop a function

def player(game_over):
    do something here
    game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
    if not game_over: 
        computer(game_over)  #We are only going to do this if check_winner comes back as False

def check_winner(): 
    check something
    #here needs to be an if / then statement deciding if the game is over, return True if over, false if not
    if score == 100:
        return True
    else:
        return False

def computer(game_over):
    do something here
    game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
    if not game_over:
        player(game_over) #We are only going to do this if check_winner comes back as False

game_over = False   #We need a variable to hold wether the game is over or not, we'll start it out being false.
player(game_over)   #Start your loops, sending in the status of game_over

Above is a pretty simple example... I made up a statement for check_winner using score = 100 to denote the game being over.

You will want to use similar method of passing score into check_winner, using game_over = check_winner(score). Then you can create a score at the beginning of your program and pass it through to computer and player just like game_over is being handled.

understanding private setters

I think a few folks have danced around this, but for me, the value of private setters is that you can encapsulate the behavior of a property, even within a class. As abhishek noted, if you want to fire a property changed event every time a property changes, but you don't want a property to be read/write to the public, then you either must use a private setter, or you must raise the event anywhere you modify the backing field. The latter is error prone because you might forget. Relatedly, if updating a property value results in some calculation being performed or another field being modified, or a lazy initialization of something, then you will also want to wrap that up in the private setter rather than having to remember to do it everywhere you make use of the backing field.