Programs & Examples On #Variadic functions

A function is variadic if it can accept a variable number of arguments; that is, its arity is not fixed. The abbreviation "varargs" is commonly used to refer to these types of functions.

What do 3 dots next to a parameter type mean in Java?

Just think of it as the keyword params in C#, if you are coming from that background :)

Variable number of arguments in C++?

In C++11 there is a way to do variable argument templates which lead to a really elegant and type safe way to have variable argument functions. Bjarne himself gives a nice example of printf using variable argument templates in the C++11FAQ.

Personally, I consider this so elegant that I wouldn't even bother with a variable argument function in C++ until that compiler has support for C++11 variable argument templates.

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

Given a function that has 3 items as argument

sum = lambda x, y, z: x + y + z
sum(1,2,3) # sum 3 items

sum([1,2,3]) # error, needs 3 items, not 1 list

x = [1,2,3][0]
y = [1,2,3][1]
z = [1,2,3][2]
sum(x,y,z) # ok

sum(*[1,2,3]) # ok, 1 list becomes 3 items

Imagine this toy with a bag of a triangle, a circle and a rectangle item. That bag does not directly fit. You need to unpack the bag to take those 3 items and now they fit. The Python * operator does this unpack process.

enter image description here

When do you use varargs in Java?

A good rule of thumb would be:

"Use varargs for any method (or constructor) that needs an array of T (whatever type T may be) as input".

That will make calls to these methods easier (no need to do new T[]{...}).

You could extend this rule to include methods with a List<T> argument, provided that this argument is for input only (ie, the list is not modified by the method).

Additionally, I would refrain from using f(Object... args) because its slips towards a programming way with unclear APIs.

In terms of examples, I have used it in DesignGridLayout, where I can add several JComponents in one call:

layout.row().grid(new JLabel("Label")).add(field1, field2, field3);

In the code above the add() method is defined as add(JComponent... components).

Finally, the implementation of such methods must take care of the fact that it may be called with an empty vararg! If you want to impose at least one argument, then you have to use an ugly trick such as:

void f(T arg1, T... args) {...}

I consider this trick ugly because the implementation of the method will be less straightforward than having just T... args in its arguments list.

Hopes this helps clarifying the point about varargs.

How to pass variable number of arguments to printf/sprintf

void Error(const char* format, ...)
{
    va_list argptr;
    va_start(argptr, format);
    vfprintf(stderr, format, argptr);
    va_end(argptr);
}

If you want to manipulate the string before you display it and really do need it stored in a buffer first, use vsnprintf instead of vsprintf. vsnprintf will prevent an accidental buffer overflow error.

Java variable number or arguments for a method

Yes, it's possible:

public void myMethod(int... numbers) { /* your code */ }

Passing variable number of arguments around

There's no way of calling (eg) printf without knowing how many arguments you're passing to it, unless you want to get into naughty and non-portable tricks.

The generally used solution is to always provide an alternate form of vararg functions, so printf has vprintf which takes a va_list in place of the .... The ... versions are just wrappers around the va_list versions.

Is it possible to send a variable number of arguments to a JavaScript function?

With ES6 you can use rest parameters for varagrs. This takes the argument list and converts it to an array.

function logArgs(...args) {
    console.log(args.length)
    for(let arg of args) {
        console.log(arg)
    }
}

How to pass an ArrayList to a varargs method parameter?

Source article: Passing a list as an argument to a vararg method


Use the toArray(T[] arr) method.

.getMap(locations.toArray(new WorldLocation[locations.size()]))

(toArray(new WorldLocation[0]) also works, but you would allocate a zero-length array for no reason.)


Here's a complete example:

public static void method(String... strs) {
    for (String s : strs)
        System.out.println(s);
}

...
    List<String> strs = new ArrayList<String>();
    strs.add("hello");
    strs.add("world");
    
    method(strs.toArray(new String[strs.size()]));
    //     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...

Concatenate two slices in Go

Appending to and copying slices

The variadic function append appends zero or more values x to s of type S, which must be a slice type, and returns the resulting slice, also of type S. The values x are passed to a parameter of type ...T where T is the element type of S and the respective parameter passing rules apply. As a special case, append also accepts a first argument assignable to type []byte with a second argument of string type followed by .... This form appends the bytes of the string.

append(s S, x ...T) S  // T is the element type of S

s0 := []int{0, 0}
s1 := append(s0, 2)        // append a single element     s1 == []int{0, 0, 2}
s2 := append(s1, 3, 5, 7)  // append multiple elements    s2 == []int{0, 0, 2, 3, 5, 7}
s3 := append(s2, s0...)    // append a slice              s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}

Passing arguments to ... parameters

If f is variadic with final parameter type ...T, then within the function the argument is equivalent to a parameter of type []T. At each call of f, the argument passed to the final parameter is a new slice of type []T whose successive elements are the actual arguments, which all must be assignable to the type T. The length of the slice is therefore the number of arguments bound to the final parameter and may differ for each call site.

The answer to your question is example s3 := append(s2, s0...) in the Go Programming Language Specification. For example,

s := append([]int{1, 2}, []int{3, 4}...)

Why use the params keyword?

No need to create overload methods, just use one single method with params as shown below

// Call params method with one to four integer constant parameters.
//
int sum0 = addTwoEach();
int sum1 = addTwoEach(1);
int sum2 = addTwoEach(1, 2);
int sum3 = addTwoEach(3, 3, 3);
int sum4 = addTwoEach(2, 2, 2, 2);

How to pass variable number of arguments to a PHP function

For those looking for a way to do this with $object->method:

call_user_func_array(array($object, 'method_name'), $array);

I was successful with this in a construct function that calls a variable method_name with variable parameters.

Possible heap pollution via varargs parameter

Heap pollution is a technical term. It refers to references which have a type that is not a supertype of the object they point to.

List<A> listOfAs = new ArrayList<>();
List<B> listOfBs = (List<B>)(Object)listOfAs; // points to a list of As

This can lead to "unexplainable" ClassCastExceptions.

// if the heap never gets polluted, this should never throw a CCE
B b = listOfBs.get(0); 

@SafeVarargs does not prevent this at all. However, there are methods which provably will not pollute the heap, the compiler just can't prove it. Previously, callers of such APIs would get annoying warnings that were completely pointless but had to be suppressed at every call site. Now the API author can suppress it once at the declaration site.

However, if the method actually is not safe, users will no longer be warned.

How can I convert the "arguments" object to an array in JavaScript?

_x000D_
_x000D_
function sortArgs(...args) {_x000D_
  return args.sort(function (a, b) { return a - b; });_x000D_
}_x000D_
_x000D_
document.body.innerHTML = sortArgs(1, 2, 3, 4).toString();
_x000D_
_x000D_
_x000D_

Can I pass an array as arguments to a method with variable arguments in Java?

jasonmp85 is right about passing a different array to String.format. The size of an array can't be changed once constructed, so you'd have to pass a new array instead of modifying the existing one.

Object newArgs = new Object[args.length+1];
System.arraycopy(args, 0, newArgs, 1, args.length);
newArgs[0] = extraVar; 
String.format(format, extraVar, args);

Display XML content in HTML page

If you treat the content as text, not HTML, then DOM operations should cause the data to be properly encoded. Here's how you'd do it in jQuery:

$('#container').text(xmlString);

Here's how you'd do it with standard DOM methods:

document.getElementById('container')
        .appendChild(document.createTextNode(xmlString));

If you're placing the XML inside of HTML through server-side scripting, there are bound to be encoding functions to allow you to do that (if you add what your server-side technology is, we can give you specific examples of how you'd do it).

How do I jump to a closing bracket in Visual Studio Code?

On French keyboard the default binding is : Ctrl+Shift+*

String MinLength and MaxLength validation don't work (asp.net mvc)

Try using this attribute, for example for password min length:

[StringLength(100, ErrorMessage = "???????????? ????? ?????? 20 ????????", MinimumLength = User.PasswordMinLength)]

Python Dictionary Comprehension

I really like the @mgilson comment, since if you have a two iterables, one that corresponds to the keys and the other the values, you can also do the following.

keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))

giving

d = {'a': 1, 'b': 2, 'c': 3}

symbol(s) not found for architecture i386

Thought to add my solution for this, after spending a few hours on the same error :(

The guys above were correct that the first thing you should check is whether you had missed adding any frameworks, see the steps provided by Pruthvid above.

My problem, it turned out, was a compile class missing after I deleted it, and later added it back in again.

Check your "Compile Sources" as shown for the reported error classes. Add in any missing classes that you created.

Using `date` command to get previous, current and next month

the following will do:

date -d "$(date +%Y-%m-1) -1 month" +%-m
date -d "$(date +%Y-%m-1) 0 month" +%-m
date -d "$(date +%Y-%m-1) 1 month" +%-m

or as you need:

LAST_MONTH=`date -d "$(date +%Y-%m-1) -1 month" +%-m`
NEXT_MONTH=`date -d "$(date +%Y-%m-1) 1 month" +%-m`
THIS_MONTH=`date -d "$(date +%Y-%m-1) 0 month" +%-m`

you asked for output like 9,10,11, so I used the %-m

%m (without -) will produce output like 09,... (leading zero)

this also works for more/less than 12 months:

date -d "$(date +%Y-%m-1) -13 month" +%-m

just try

date -d "$(date +%Y-%m-1) -13 month"

to see full result

Input from the keyboard in command line application

This works in xCode v6.2, I think that's Swift v1.2

func input() -> String {
    var keyboard = NSFileHandle.fileHandleWithStandardInput()
    var inputData = keyboard.availableData
    return NSString(data: inputData, encoding:NSUTF8StringEncoding)! as String
}

Copy file or directories recursively in Python

shutil.copy and shutil.copy2 are copying files.

shutil.copytree copies a folder with all the files and all subfolders. shutil.copytree is using shutil.copy2 to copy the files.

So the analog to cp -r you are saying is the shutil.copytree because cp -r targets and copies a folder and its files/subfolders like shutil.copytree. Without the -r cp copies files like shutil.copy and shutil.copy2 do.

How to handle onchange event on input type=file in jQuery?

 $('#fileupload').bind('change', function (e) { //dynamic property binding
alert('hello');// message you want to display
});

You can use this one also

dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac

in my case, I reinstall all packages installed with Homebrew

$ brew list | xargs brew reinstall

After that, I start to install my version that I need

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

This problem also happens if you want to design a small subview in a separate XIB file in Interface Builder, and in IB you set it to the same class as the parent view.

If you then show it like this:

UIViewController *vc = [[UIViewController alloc] initWithNibName:@"NameOfTheSubviewNibFile" bundle:nil];
[self.view addSubview:vc.view];

The view will appear, but if it's got IBOutlets connected to its File Owner, you'll get the error message. So, this should work instead:

  1. In your the parent view's code, declare an IBOutlet UIView *mySubview to reference the view in the subview's nib file
  2. In the subview's nib file, connect the File Owner to the view, and set it to mySubview
  3. show it by doing:
[[NSBundle mainBundle] loadNibNamed:@"NameOfTheSubviewNibFile" owner:self options:nil]
[self.view addSubview:mySubview];

and you will be fine!

Display encoded html with razor

You can also simply use the HtmlString class

    @(new HtmlString(Model.Content))

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

Imagine you have a numpy array of text like in a messenger

 >>> stex[40]
 array(['Know the famous thing ...

and you want to get statistics from the corpus (text col=11) you first must get the values from dataframe (df5) and then join all records together in one single corpus:

 >>> stex = (df5.ix[0:,[11]]).values
 >>> a_str = ','.join(str(x) for x in stex)
 >>> a_str = a_str.split()
 >>> fd2 = nltk.FreqDist(a_str)
 >>> fd2.most_common(50)

MemoryStream - Cannot access a closed Stream

when it gets out from the using statement the Dispose method will be called automatically closing the stream

try the below:

using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);

        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;
        using (var sr = new StreamReader(ms))
        {
            Console.WriteLine(sr.ReadToEnd());
        }
}    

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

How do I iterate over a range of numbers defined by variables in Bash?

Another layer of indirection:

for i in $(eval echo {1..$END}); do
    :

Observable.of is not a function

If anybody is having this problem while using Angular 6/rxjs 6 see the answers here: Could not use Observable.of in RxJs 6 and Angular 6

In short, you need to import it like this:

import { of } from 'rxjs';

And then instead of calling

Observable.of(res);

just use

of(res);

How to save a dictionary to a file?

I would suggest saving your data using the JSON format instead of pickle format as JSON's files are human-readable which makes your debugging easier since your data is small. JSON files are also used by other programs to read and write data. You can read more about it here

You'll need to install the JSON module, you can do so with pip:

pip install json


# To save the dictionary into a file:
json.dump( data, open( "myfile.json", 'w' ) )

This creates a json file with the name myfile.

# To read data from file:
data = json.load( open( "myfile.json" ) )

This reads and stores the myfile.json data in a data object.

how to compare the Java Byte[] array?

If you're trying to use the array as a generic HashMap key, that's not going to work. Consider creating a custom wrapper object that holds the array, and whose equals(...) and hashcode(...) method returns the results from the java.util.Arrays methods. For example...

import java.util.Arrays;

public class MyByteArray {
   private byte[] data;

   // ... constructors, getters methods, setter methods, etc...


   @Override
   public int hashCode() {
      return Arrays.hashCode(data);
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (getClass() != obj.getClass())
         return false;
      MyByteArray other = (MyByteArray) obj;
      if (!Arrays.equals(data, other.data))
         return false;
      return true;
   }


}

Objects of this wrapper class will work fine as a key for your HashMap<MyByteArray, OtherType> and will allow for clean use of equals(...) and hashCode(...) methods.

JQuery / JavaScript - trigger button click from another button click event

If it does not work by using the click() method like suggested in the accepted answer, then you can try this:

//trigger second button
$("#second").mousedown();
$("#second").mouseup();

What is time_t ultimately a typedef to?

time_t is of type long int on 64 bit machines, else it is long long int.

You could verify this in these header files:

time.h: /usr/include
types.h and typesizes.h: /usr/include/x86_64-linux-gnu/bits

(The statements below are not one after another. They could be found in the resp. header file using Ctrl+f search.)

1)In time.h

typedef __time_t time_t;

2)In types.h

# define __STD_TYPE     typedef  
__STD_TYPE __TIME_T_TYPE __time_t;  

3)In typesizes.h

#define __TIME_T_TYPE       __SYSCALL_SLONG_TYPE  
#if defined __x86_64__ && defined __ILP32__  
# define __SYSCALL_SLONG_TYPE   __SQUAD_TYPE  
#else
# define __SYSCALL_SLONG_TYPE   __SLONGWORD_TYPE
#endif  

4) Again in types.h

#define __SLONGWORD_TYPE    long int
#if __WORDSIZE == 32
# define __SQUAD_TYPE       __quad_t
#elif __WORDSIZE == 64
# define __SQUAD_TYPE       long int  

#if __WORDSIZE == 64
typedef long int __quad_t;  
#else
__extension__ typedef long long int __quad_t;

error C2220: warning treated as error - no 'object' file generated

This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):

warning C4101: 'i': unreferenced local variable

After I commented this unused i, and compiled it, the other error went away.

Change all files and folders permissions of a directory to 644/755

One approach could be using find:

for directories

find /desired_location -type d -print0 | xargs -0 chmod 0755

for files

find /desired_location -type f -print0 | xargs -0 chmod 0644

Python check if list items are integers?

Fast, simple, but maybe not always right:

>>> [x for x in mylist if x.isdigit()]
['1', '2', '3', '4']

More traditional if you need to get numbers:

new_list = []
for value in mylist:
    try:
        new_list.append(int(value))
    except ValueError:
        continue

Note: The result has integers. Convert them back to strings if needed, replacing the lines above with:

try:
    new_list.append(str(int(value)))

iPhone get SSID without private library

As of iOS 7 or 8, you can do this (need Entitlement for iOS 12+ as shown below):

@import SystemConfiguration.CaptiveNetwork;

/** Returns first non-empty SSID network info dictionary.
 *  @see CNCopyCurrentNetworkInfo */
- (NSDictionary *)fetchSSIDInfo {
    NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces());
    NSLog(@"%s: Supported interfaces: %@", __func__, interfaceNames);

    NSDictionary *SSIDInfo;
    for (NSString *interfaceName in interfaceNames) {
        SSIDInfo = CFBridgingRelease(
            CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName));
        NSLog(@"%s: %@ => %@", __func__, interfaceName, SSIDInfo);

        BOOL isNotEmpty = (SSIDInfo.count > 0);
        if (isNotEmpty) {
            break;
        }
    }
    return SSIDInfo;
}

Example output:

2011-03-04 15:32:00.669 ShowSSID[4857:307] -[ShowSSIDAppDelegate fetchSSIDInfo]: Supported interfaces: (
    en0
)
2011-03-04 15:32:00.693 ShowSSID[4857:307] -[ShowSSIDAppDelegate fetchSSIDInfo]: en0 => {
    BSSID = "ca:fe:ca:fe:ca:fe";
    SSID = XXXX;
    SSIDDATA = <01234567 01234567 01234567>;
}

Note that no ifs are supported on the simulator. Test on your device.

iOS 12

You must enable access wifi info from capabilities.

Important To use this function in iOS 12 and later, enable the Access WiFi Information capability for your app in Xcode. When you enable this capability, Xcode automatically adds the Access WiFi Information entitlement to your entitlements file and App ID. Documentation link

Swift 4.2

func getConnectedWifiInfo() -> [AnyHashable: Any]? {

    if let ifs = CFBridgingRetain( CNCopySupportedInterfaces()) as? [String],
        let ifName = ifs.first as CFString?,
        let info = CFBridgingRetain( CNCopyCurrentNetworkInfo((ifName))) as? [AnyHashable: Any] {

        return info
    }
    return nil

}

ssh remote host identification has changed

The problem is that you've previously accepted an SSH connection to a remote computer and that remote computer's digital fingerprint or SHA256 hash key has changed since you last connected. Thus when you try to SSH again or use github to pull code, which also uses SSH, you get an error. Why? Because you're using the same remote computer address as before but the remote computer is responding with a different fingerprint. Therefore, it's possible that someone is spoofing the computer you previously connected to. This is a security issue.

If you're 100% sure that the remote computer isn't compromised, hacked, being spoofed, etc then all you need to do is delete the entry in your known_hosts file for the remote computer. That will solve the issue as there will no longer be a mismatch with SHA256 fingerprint IDs when connecting.

On Mac here's what I did:

1) Find the line of output that reads RSA host key for servername:port has changed and you have requested strict checking. You'll need both the servername and potentially port from that log output.

2) Back up the SSH known hosts file cp /Users/yourmacusername/.ssh/known_hosts /Users/yourmacusername/.ssh/known_hosts.bak

3) Find the line where the computer's old fingerprint is stored and delete it. You can search for the specific offending remote computer fingerprint using the servername and port from step #1. nano /Users/yourmacusername/.ssh/known_hosts

4) CTRL-X to quit and choose Y to save changes

Now type ssh -p port servername and you will receive the original prompt you did when you first tried to SSH to that computer. You will then be given the option to save that remote computer's updated SHA256 fingerprint to your known_hosts file. If you're using SSH over port 22 then the -p argument is not necessary.

Any issues you can restore the original known_hosts file: cp /Users/yourmacusername/.ssh/known_hosts.bak /Users/yourmacusername/.ssh/known_hosts

Dynamically add child components in React

Firstly a warning: you should never tinker with DOM that is managed by React, which you are doing by calling ReactDOM.render(<SampleComponent ... />);

With React, you should use SampleComponent directly in the main App.

var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(<App/>, document.body);

The content of your Component is irrelevant, but it should be used like this:

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <SampleComponent name="SomeName"/>
            </div>
        );
    }
});

You can then extend your app component to use a list.

var App = React.createClass({
    render: function() {
        var componentList = [
            <SampleComponent name="SomeName1"/>,
            <SampleComponent name="SomeName2"/>
        ]; // Change this to get the list from props or state
        return (
            <div>
                <h1>App main component! </h1>
                {componentList}
            </div>
        );
    }
});

I would really recommend that you look at the React documentation then follow the "Get Started" instructions. The time you spend on that will pay off later.

https://facebook.github.io/react/index.html

How do I insert an image in an activity with android studio?

copy the image that you want to show in android app and paste in drawable folder. given below code

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/image"
 />

Open Jquery modal dialog on click event

Try adding this line before your dialog line.

$( "#dialog" ).dialog( "open" );

This method worked for me. It seems that the "close" command messes up the dialog opening again with only the .dialog() .

Using your code as an example, it would go in like this (note that you may need to add more to your code for it to make sense):

    <script type="text/javascript">
$(document).ready(function() {
    //$('#dialog').dialog();
    $('#dialog_link').click(function() {
$( "#dialog" ).dialog( "open" );        
$('#dialog').dialog();
        return false;
    });
});
</script>    
</head><body>
   <div id="dialog" title="Dialog Title" style="display:none"> Some text</div>  
   <p id="dialog_link">Open Dialog</p>  
</body></html>

Best way to check if object exists in Entity Framework?

I had some trouble with this - my EntityKey consists of three properties (PK with 3 columns) and I didn't want to check each of the columns because that would be ugly. I thought about a solution that works all time with all entities.

Another reason for this is I don't like to catch UpdateExceptions every time.

A little bit of Reflection is needed to get the values of the key properties.

The code is implemented as an extension to simplify the usage as:

context.EntityExists<MyEntityType>(item);

Have a look:

public static bool EntityExists<T>(this ObjectContext context, T entity)
        where T : EntityObject
    {
        object value;
        var entityKeyValues = new List<KeyValuePair<string, object>>();
        var objectSet = context.CreateObjectSet<T>().EntitySet;
        foreach (var member in objectSet.ElementType.KeyMembers)
        {
            var info = entity.GetType().GetProperty(member.Name);
            var tempValue = info.GetValue(entity, null);
            var pair = new KeyValuePair<string, object>(member.Name, tempValue);
            entityKeyValues.Add(pair);
        }
        var key = new EntityKey(objectSet.EntityContainer.Name + "." + objectSet.Name, entityKeyValues);
        if (context.TryGetObjectByKey(key, out value))
        {
            return value != null;
        }
        return false;
    }

Should I call Close() or Dispose() for stream objects?

The documentation says that these two methods are equivalent:

StreamReader.Close: This implementation of Close calls the Dispose method passing a true value.

StreamWriter.Close: This implementation of Close calls the Dispose method passing a true value.

Stream.Close: This method calls Dispose, specifying true to release all resources.

So, both of these are equally valid:

/* Option 1, implicitly calling Dispose */
using (StreamWriter writer = new StreamWriter(filename)) { 
   // do something
} 

/* Option 2, explicitly calling Close */
StreamWriter writer = new StreamWriter(filename)
try {
    // do something
}
finally {
    writer.Close();
}

Personally, I would stick with the first option, since it contains less "noise".

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

How to get character for a given ascii value

 string c = Char.ConvertFromUtf32(65);

c will contain "A"

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

This is what worked for me... I did not use curl.

I was able to access a particular API url via browser, but when used in file_get_contents, it gave the error " failed to open stream".

Then, I modified the API URL that I wanted to call by encoding all double quotes with urlencoding and kept everything else untouched.

Sample format is given below:

$url = 'https://stackoverflow.com/questions'.urlencode('"'.$variable1.'"');

Then use

file_get_contents($url);

How to make the 'cut' command treat same sequental delimiters as one?

As you comment in your question, awk is really the way to go. To use cut is possible together with tr -s to squeeze spaces, as kev's answer shows.

Let me however go through all the possible combinations for future readers. Explanations are at the Test section.

tr | cut

tr -s ' ' < file | cut -d' ' -f4

awk

awk '{print $4}' file

bash

while read -r _ _ _ myfield _
do
   echo "forth field: $myfield"
done < file

sed

sed -r 's/^([^ ]*[ ]*){3}([^ ]*).*/\2/' file

Tests

Given this file, let's test the commands:

$ cat a
this   is    line     1 more text
this      is line    2     more text
this    is line 3     more text
this is   line 4            more    text

tr | cut

$ cut -d' ' -f4 a
is
                        # it does not show what we want!


$ tr -s ' ' < a | cut -d' ' -f4
1
2                       # this makes it!
3
4
$

awk

$ awk '{print $4}' a
1
2
3
4

bash

This reads the fields sequentially. By using _ we indicate that this is a throwaway variable as a "junk variable" to ignore these fields. This way, we store $myfield as the 4th field in the file, no matter the spaces in between them.

$ while read -r _ _ _ a _; do echo "4th field: $a"; done < a
4th field: 1
4th field: 2
4th field: 3
4th field: 4

sed

This catches three groups of spaces and no spaces with ([^ ]*[ ]*){3}. Then, it catches whatever coming until a space as the 4th field, that it is finally printed with \1.

$ sed -r 's/^([^ ]*[ ]*){3}([^ ]*).*/\2/' a
1
2
3
4

How to remove origin from git repository

Fairly straightforward:

git remote rm origin

As for the filter-branch question - just add --prune-empty to your filter branch command and it'll remove any revision that doesn't actually contain any changes in your resulting repo:

git filter-branch --prune-empty --subdirectory-filter path/to/subtree HEAD

At runtime, find all classes in a Java application that extend a base class

This is a tough problem and you will need to find out this information using static analysis, its not available easily at runtime. Basically get the classpath of your app and scan through the available classes and read the bytecode information of a class which class it inherits from. Note that a class Dog may not directly inherit from Animal but might inherit from Pet which is turn inherits from Animal,so you will need to keep track of that hierarchy.

jQuery DIV click, with anchors

<div class="info">
   <h2>Takvim</h2>
   <a href="item-list.php"> Click Me !</a>
</div>


$(document).delegate("div.info", "click", function() {
   window.location = $(this).find("a").attr("href");
});

Passing structs to functions

bool data(sampleData *data)
{
}

You need to tell the method which type of struct you are using. In this case, sampleData.

Note: In this case, you will need to define the struct prior to the method for it to be recognized.

Example:

struct sampleData
{
   int N;
   int M;
   // ...
};

bool data(struct *sampleData)
{

}

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

      sampleData sd;
      data(&sd);

}

Note 2: I'm a C guy. There may be a more c++ish way to do this.

How to select specified node within Xpath node sets by index with Selenium?

There is no i in xpath is not entirely true. You can still use the count() to find the index.

Consider the following page

_x000D_
_x000D_
<html>_x000D_
_x000D_
 <head>_x000D_
  <title>HTML Sample table</title>_x000D_
 </head>_x000D_
_x000D_
 <style>_x000D_
 table, td, th {_x000D_
  border: 1px solid black;_x000D_
  font-size: 15px;_x000D_
  font-family: Trebuchet MS, sans-serif;_x000D_
 }_x000D_
 table {_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
 }_x000D_
_x000D_
 th, td {_x000D_
  text-align: left;_x000D_
  padding: 8px;_x000D_
 }_x000D_
_x000D_
 tr:nth-child(even){background-color: #f2f2f2}_x000D_
_x000D_
 th {_x000D_
  background-color: #4CAF50;_x000D_
  color: white;_x000D_
 }_x000D_
 </style>_x000D_
_x000D_
 <body>_x000D_
 <table>_x000D_
  <thead>_x000D_
   <tr>_x000D_
    <th>Heading 1</th>_x000D_
    <th>Heading 2</th>_x000D_
    <th>Heading 3</th>_x000D_
    <th>Heading 4</th>_x000D_
    <th>Heading 5</th>_x000D_
    <th>Heading 6</th>_x000D_
   </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
   <tr>_x000D_
    <td>Data row 1 col 1</td>_x000D_
    <td>Data row 1 col 2</td>_x000D_
    <td>Data row 1 col 3</td>_x000D_
    <td>Data row 1 col 4</td>_x000D_
    <td>Data row 1 col 5</td>_x000D_
    <td>Data row 1 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 2 col 1</td>_x000D_
    <td>Data row 2 col 2</td>_x000D_
    <td>Data row 2 col 3</td>_x000D_
    <td>Data row 2 col 4</td>_x000D_
    <td>Data row 2 col 5</td>_x000D_
    <td>Data row 2 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 3 col 1</td>_x000D_
    <td>Data row 3 col 2</td>_x000D_
    <td>Data row 3 col 3</td>_x000D_
    <td>Data row 3 col 4</td>_x000D_
    <td>Data row 3 col 5</td>_x000D_
    <td>Data row 3 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 4 col 1</td>_x000D_
    <td>Data row 4 col 2</td>_x000D_
    <td>Data row 4 col 3</td>_x000D_
    <td>Data row 4 col 4</td>_x000D_
    <td>Data row 4 col 5</td>_x000D_
    <td>Data row 4 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 5 col 1</td>_x000D_
    <td>Data row 5 col 2</td>_x000D_
    <td>Data row 5 col 3</td>_x000D_
    <td>Data row 5 col 4</td>_x000D_
    <td>Data row 5 col 5</td>_x000D_
    <td>Data row 5 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
   </tr>_x000D_
  </tbody>_x000D_
 </table>_x000D_
_x000D_
 </br>_x000D_
_x000D_
 <table>_x000D_
  <thead>_x000D_
   <tr>_x000D_
    <th>Heading 7</th>_x000D_
    <th>Heading 8</th>_x000D_
    <th>Heading 9</th>_x000D_
    <th>Heading 10</th>_x000D_
    <th>Heading 11</th>_x000D_
    <th>Heading 12</th>_x000D_
   </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
   <tr>_x000D_
    <td>Data row 1 col 1</td>_x000D_
    <td>Data row 1 col 2</td>_x000D_
    <td>Data row 1 col 3</td>_x000D_
    <td>Data row 1 col 4</td>_x000D_
    <td>Data row 1 col 5</td>_x000D_
    <td>Data row 1 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 2 col 1</td>_x000D_
    <td>Data row 2 col 2</td>_x000D_
    <td>Data row 2 col 3</td>_x000D_
    <td>Data row 2 col 4</td>_x000D_
    <td>Data row 2 col 5</td>_x000D_
    <td>Data row 2 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 3 col 1</td>_x000D_
    <td>Data row 3 col 2</td>_x000D_
    <td>Data row 3 col 3</td>_x000D_
    <td>Data row 3 col 4</td>_x000D_
    <td>Data row 3 col 5</td>_x000D_
    <td>Data row 3 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 4 col 1</td>_x000D_
    <td>Data row 4 col 2</td>_x000D_
    <td>Data row 4 col 3</td>_x000D_
    <td>Data row 4 col 4</td>_x000D_
    <td>Data row 4 col 5</td>_x000D_
    <td>Data row 4 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 5 col 1</td>_x000D_
    <td>Data row 5 col 2</td>_x000D_
    <td>Data row 5 col 3</td>_x000D_
    <td>Data row 5 col 4</td>_x000D_
    <td>Data row 5 col 5</td>_x000D_
    <td>Data row 5 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
   </tr>_x000D_
  </tbody>_x000D_
 </table>_x000D_
_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The page has 2 tables and has 6 columns each with unique column names and 6 rows with variable data. The last row has the Modify button in both the tables.

Assuming that the user has to select the 4th Modify button from the first table based on the heading

Use the xpath //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button

The count() operator comes in handy in situations like these.

Logic:

  1. Find the header for the Modify button using //th[.='Heading 4']
  2. Find the index of the header column using count(//tr/th[.='Heading 4']/preceding-sibling::th)+1

Note: Index starts at 0

  1. Get the rows for the corresponding header using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]

  2. Get the Modify button from the extracted node list using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button

Specifying onClick event type with Typescript and React.Konva

You're probably out of luck without some hack-y workarounds

You could try

onClick={(event: React.MouseEvent<HTMLElement>) => {
 makeMove(ownMark, (event.target as any).index)
}}

I'm not sure how strict your linter is - that might shut it up just a little bit

I played around with it for a bit, and couldn't figure it out, but you can also look into writing your own augmented definitions: https://www.typescriptlang.org/docs/handbook/declaration-merging.html

edit: please use the implementation in this reply it is the proper way to solve this issue (and also upvote him, while you're at it).

Implement paging (skip / take) functionality with this query

In SQL Server 2012 it is very very easy

SELECT col1, col2, ...
 FROM ...
 WHERE ... 
 ORDER BY -- this is a MUST there must be ORDER BY statement
-- the paging comes here
OFFSET     10 ROWS       -- skip 10 rows
FETCH NEXT 10 ROWS ONLY; -- take 10 rows

If we want to skip ORDER BY we can use

SELECT col1, col2, ...
  ...
 ORDER BY CURRENT_TIMESTAMP
OFFSET     10 ROWS       -- skip 10 rows
FETCH NEXT 10 ROWS ONLY; -- take 10 rows

(I'd rather mark that as a hack - but it's used, e.g. by NHibernate. To use a wisely picked up column as ORDER BY is preferred way)

to answer the question:

--SQL SERVER 2012
SELECT PostId FROM 
        ( SELECT PostId, MAX (Datemade) as LastDate
            from dbForumEntry 
            group by PostId 
        ) SubQueryAlias
 order by LastDate desc
OFFSET 10 ROWS -- skip 10 rows
FETCH NEXT 10 ROWS ONLY; -- take 10 rows

New key words offset and fetch next (just following SQL standards) were introduced.

But I guess, that you are not using SQL Server 2012, right? In previous version it is a bit (little bit) difficult. Here is comparison and examples for all SQL server versions: here

So, this could work in SQL Server 2008:

-- SQL SERVER 2008
DECLARE @Start INT
DECLARE @End INT
SELECT @Start = 10,@End = 20;


;WITH PostCTE AS 
 ( SELECT PostId, MAX (Datemade) as LastDate
   ,ROW_NUMBER() OVER (ORDER BY PostId) AS RowNumber
   from dbForumEntry 
   group by PostId 
 )
SELECT PostId, LastDate
FROM PostCTE
WHERE RowNumber > @Start AND RowNumber <= @End
ORDER BY PostId

How do I install g++ for Fedora?

Just make a sample 'Hello World' Program and try to compile it using "g++ sam.cpp" in terminal, and it will ask you if you wish to download the g++ package. Press y to install.

Regex to extract URLs from href attribute in HTML with Python

import re

url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'

urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)

>>> print urls
['http://example.com', 'http://example2.com']

Remove the newline character in a list read from a file

You want the String.strip(s[, chars]) function, which will strip out whitespace characters or whatever characters (such as '\n') you specify in the chars argument.

See http://docs.python.org/release/2.3/lib/module-string.html

Setting DIV width and height in JavaScript

The onclick attribute of a button takes a string of JavaScript, not an href like you provided. Just remove the "javascript:" part.

ASP.Net MVC Redirect To A Different View

I am not 100% sure what the conditions are for this, but for me the above didn't work directly, thought it got close. I think it was because I needed "id" for my view by in the model it was called "ObjectID".

I had a model with a variety of pieces of information. I just needed the id.

Before the above I created a new System.Web.Routing.RouteValueDictionary object and added the needed id.

(System.Web.Routing.)RouteValueDictionary RouteInfo = new RouteValueDictionary();
RouteInfo.Add("id", ObjectID);
return RedirectToAction("details", RouteInfo);

(Note: the MVC project in question I didn't create, so I don't know where all the right "fiddly" bits are.)

CSS Select box arrow style

Try to replace the

padding: 2px 30px 2px 2px;

with

padding: 2px 2px 2px 2px;

It should work.

var self = this?

Just adding to this that in ES6 because of arrow functions you shouldn't need to do this because they capture the this value.

How to change the Jupyter start-up folder

You can make windows bat file like this.

D: (your dexired drive)
cd \Your\Desired\Start\Derectory
Jupyter notebook

Save it as 'JupyterNB.bat' (or whatever you like), and double click it.

Pandas get the most frequent values of a column

Simply use this..

dataframe['name'].value_counts().nlargest(n)

The functions for frequencies largest and smallest are:

  • nlargest() for mostfrequent 'n' values
  • nsmallest() for least frequent 'n' values

No String-argument constructor/factory method to deserialize from String value ('')

Use below code snippet This worked for me

ObjectMapper objectMapper = new ObjectMapper();
String jsonString = "{\"symbol\":\"ABCD\}";
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
Trade trade = objectMapper.readValue(jsonString, new TypeReference<Symbol>() {});

Model Class

@JsonIgnoreProperties    public class Symbol {
    @JsonProperty("symbol")
    private String symbol;
}

How do I convert a TimeSpan to a formatted string?

You can use the following code.

public static class TimeSpanExtensions
{
  public static String Verbose(this TimeSpan timeSpan)
  {
    var hours = timeSpan.Hours;
    var minutes = timeSpan.Minutes;

    if (hours > 0) return String.Format("{0} hours {1} minutes", hours, minutes);
    return String.Format("{0} minutes", minutes);
  }
}

How do you create a daemon in Python?

There are many fiddly things to take care of when becoming a well-behaved daemon process:

  • prevent core dumps (many daemons run as root, and core dumps can contain sensitive information)

  • behave correctly inside a chroot gaol

  • set UID, GID, working directory, umask, and other process parameters appropriately for the use case

  • relinquish elevated suid, sgid privileges

  • close all open file descriptors, with exclusions depending on the use case

  • behave correctly if started inside an already-detached context, such as init, inetd, etc.

  • set up signal handlers for sensible daemon behaviour, but also with specific handlers determined by the use case

  • redirect the standard streams stdin, stdout, stderr since a daemon process no longer has a controlling terminal

  • handle a PID file as a cooperative advisory lock, which is a whole can of worms in itself with many contradictory but valid ways to behave

  • allow proper cleanup when the process is terminated

  • actually become a daemon process without leading to zombies

Some of these are standard, as described in canonical Unix literature (Advanced Programming in the UNIX Environment, by the late W. Richard Stevens, Addison-Wesley, 1992). Others, such as stream redirection and PID file handling, are conventional behaviour most daemon users would expect but that are less standardised.

All of these are covered by the PEP 3143 “Standard daemon process library” specification. The python-daemon reference implementation works on Python 2.7 or later, and Python 3.2 or later.

Turn on torch/flash on iPhone

See a better answer below: https://stackoverflow.com/a/10054088/308315


Old answer:

First, in your AppDelegate .h file:

#import <AVFoundation/AVFoundation.h>

@interface AppDelegate : NSObject <UIApplicationDelegate> {

    AVCaptureSession *torchSession;

}

@property (nonatomic, retain) AVCaptureSession * torchSession;

@end

Then in your AppDelegate .m file:

@implementation AppDelegate

@synthesize torchSession;

- (void)dealloc {
    [torchSession release];

    [super dealloc];
}

- (id) init {
    if ((self = [super init])) {

    // initialize flashlight
    // test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
        Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
        if (captureDeviceClass != nil) {

            AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

            if ([device hasTorch] && [device hasFlash]){

                if (device.torchMode == AVCaptureTorchModeOff) {

                NSLog(@"Setting up flashlight for later use...");

                    AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
                    AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];

                    AVCaptureSession *session = [[AVCaptureSession alloc] init];

                [session beginConfiguration];
                    [device lockForConfiguration:nil];

                    [session addInput:flashInput];
                    [session addOutput:output];

                    [device unlockForConfiguration];

                    [output release];

                [session commitConfiguration];
                [session startRunning];

                [self setTorchSession:session];
                [session release];
                    }

            }

        }
    } 
    return self;
}

Then anytime you want to turn it on, just do something like this:

// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    [device lockForConfiguration:nil];

    [device setTorchMode:AVCaptureTorchModeOn];
    [device setFlashMode:AVCaptureFlashModeOn];

    [device unlockForConfiguration];

}

And similar for turning it off:

// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    [device lockForConfiguration:nil];

    [device setTorchMode:AVCaptureTorchModeOff];
    [device setFlashMode:AVCaptureFlashModeOff];

    [device unlockForConfiguration];
}

How to get thread id of a pthread in linux c program?

You can use pthread_self()

The parent gets to know the thread id after the pthread_create() is executed sucessfully, but while executing the thread if we want to access the thread id we have to use the function pthread_self().

How to get form values in Symfony2 controller

I think that in order to get the request data, bound and validated by the form object, you must use this command :

$form->getViewData();
$form->getClientData(); // Deprecated since version 2.1, to be removed in 2.3.

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

This was a problem with the user having deny privileges as well; in my haste to grant permissions I basically gave the user everything. And deny was killing it. So as soon as I removed those permissions it worked.

How an 'if (A && B)' statement is evaluated?

for logical && both the parameters must be true , then it ll be entered in if {} clock otherwise it ll execute else {}. for logical || one of parameter or condition is true is sufficient to execute if {}.

if( (A) && (B) ){
     //if A and B both are true
}else{
}
if( (A) ||(B) ){
     //if A or B is true 
}else{
}

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

Google maps API V3 - multiple markers on exact same spot

How to get away with it.. [Swift]

    var clusterArray = [String]()
    var pinOffSet : Double = 0
    var pinLat = yourLat
    var pinLong = yourLong
    var location = pinLat + pinLong

A new marker is about to be created? check clusterArray and manipulate it's offset

 if(!clusterArray.contains(location)){
        clusterArray.append(location)
    } else {

        pinOffSet += 1
        let offWithIt = 0.00025 // reasonable offset with zoomLvl(14-16)
        switch pinOffSet {
        case 1 : pinLong = pinLong + offWithIt ; pinLat = pinLat + offWithIt
        case 2 : pinLong = pinLong + offWithIt ; pinLat = pinLat - offWithIt
        case 3 : pinLong = pinLong - offWithIt ; pinLat = pinLat - offWithIt
        case 4 : pinLong = pinLong - offWithIt ; pinLat = pinLat + offWithIt
        default : print(1)
        }


    }

result

enter image description here

Convert character to Date in R

The easiest way is to use lubridate:

library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)

This function automatically returns objects of class POSIXct and will work with either factors or characters.

Angular 4: How to include Bootstrap?

Step 1 : npm install bootstrap --save

Step : 2 : Paste below code in angular.json node_modules/bootstrap/dist/css/bootstrap.min.css

Step 3 : ng serve

enter image description here

How to use paths in tsconfig.json?

This works for me:

 yarn add --dev tsconfig-paths

 ts-node -r tsconfig-paths/register <your-index-file>.ts

This loads all paths in tsconfig.json. A sample tsconfig.json:

{
    "compilerOptions": {
        {…}
        "baseUrl": "./src",
        "paths": {
            "assets/*": [ "assets/*" ],
            "styles/*": [ "styles/*" ]
        }
    },
}

Make sure you have both baseUrl and paths for this to work

And then you can import like :

import {AlarmIcon} from 'assets/icons'

An error occurred while signing: SignTool.exe not found

Windows 10 users can find signtool.exe in C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64 folder (10.0.18362.0 in my case, or other version).


But first, make sure you've installed Windows 10 SDK

Then, check Windows SDK Signing Tools for Desktop Apps is installed by going to Control Panel > Programs > Programs and Features, choose Windows Software Development Kit - Windows 10.0.18362.1 (in my case, you version may be different), right-click, choose Change, choose options Change then click Next.

Using sed, Insert a line above or below the pattern?

More portable to use ed; some systems don't support \n in sed

printf "/^lorem ipsum dolor sit amet/a\nconsectetur adipiscing elit\n.\nw\nq\n" |\
    /bin/ed $filename

How to set the timeout for a TcpClient?

The answers above don't cover how to cleanly deal with a connection that has timed out. Calling TcpClient.EndConnect, closing a connection that succeeds but after the timeout, and disposing of the TcpClient.

It may be overkill but this works for me.

    private class State
    {
        public TcpClient Client { get; set; }
        public bool Success { get; set; }
    }

    public TcpClient Connect(string hostName, int port, int timeout)
    {
        var client = new TcpClient();

        //when the connection completes before the timeout it will cause a race
        //we want EndConnect to always treat the connection as successful if it wins
        var state = new State { Client = client, Success = true };

        IAsyncResult ar = client.BeginConnect(hostName, port, EndConnect, state);
        state.Success = ar.AsyncWaitHandle.WaitOne(timeout, false);

        if (!state.Success || !client.Connected)
            throw new Exception("Failed to connect.");

        return client;
    }

    void EndConnect(IAsyncResult ar)
    {
        var state = (State)ar.AsyncState;
        TcpClient client = state.Client;

        try
        {
            client.EndConnect(ar);
        }
        catch { }

        if (client.Connected && state.Success)
            return;

        client.Close();
    }

Finding even or odd ID values

ID % 2 reduces all integer (monetary and numeric are allowed, too) numbers to 0 and 1 effectively.
Read about the modulo operator in the manual.

Histogram Matplotlib

This might be useful for someone.

Numpy's histogram function returns the edges of each bin, rather than the value of the bin. This makes sense for floating-point numbers, which can lie within an interval, but may not be the desired result when dealing with discrete values or integers (0, 1, 2, etc). In particular, the length of bins returned from np.histogram is not equal to the length of the counts / density.

To get around this, I used np.digitize to quantize the input, and count the fraction of counts for each bin. You could easily edit to get the integer number of counts.

def compute_PMF(data):
    import numpy as np
    from collections import Counter
    _, bins = np.histogram(data, bins='auto', range=(data.min(), data.max()), density=False)
    h = Counter(np.digitize(data,bins) - 1)
    weights = np.asarray(list(h.values())) 
    weights = weights / weights.sum()
    values = np.asarray(list(h.keys()))
    return weights, values
####

Refs:

[1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html

[2] https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html

HttpListener Access Denied

The syntax was wrong for me, you must include the quotes:

netsh http add urlacl url="http://+:4200/" user=everyone

otherwise I received "The parameter is incorrect"

how do you view macro code in access?

You can try the following VBA code to export Macro contents directly without converting them to VBA first. Unlike Tables, Forms, Reports, and Modules, the Macros are in a container called Scripts. But they are there and can be exported and imported using SaveAsText and LoadFromText

Option Compare Database

Option Explicit

Public Sub ExportDatabaseObjects()
On Error GoTo Err_ExportDatabaseObjects

    Dim db As Database
    Dim d As Document
    Dim c As Container
    Dim sExportLocation As String

    Set db = CurrentDb()

    sExportLocation = "C:\SomeFolder\"
    Set c = db.Containers("Scripts")
    For Each d In c.Documents
        Application.SaveAsText acMacro, d.Name, sExportLocation & "Macro_" & d.Name & ".txt"
    Next d

An alternative object to use is as follows:

  For Each obj In Access.Application.CurrentProject.AllMacros
    Access.Application.SaveAsText acMacro, obj.Name, strFilePath & "\Macro_" & obj.Name & ".txt"
  Next

SQL: Return "true" if list of records exists?

You can use a SELECT CASE statement like so:

select case when EXISTS (
 select 1 
 from <table>
 where <condition>
 ) then TRUE else FALSE end

It returns TRUE when your query in the parents exists.

How to use java.Set

The first thing you need to study is the java.util.Set API.

Here's a small example of how to use its methods:

    Set<Integer> numbers = new TreeSet<Integer>();

    numbers.add(2);
    numbers.add(5);

    System.out.println(numbers); // "[2, 5]"
    System.out.println(numbers.contains(7)); // "false"

    System.out.println(numbers.add(5)); // "false"
    System.out.println(numbers.size()); // "2"

    int sum = 0;
    for (int n : numbers) {
        sum += n;
    }
    System.out.println("Sum = " + sum); // "Sum = 7"

    numbers.addAll(Arrays.asList(1,2,3,4,5));
    System.out.println(numbers); // "[1, 2, 3, 4, 5]"

    numbers.removeAll(Arrays.asList(4,5,6,7));
    System.out.println(numbers); // "[1, 2, 3]"

    numbers.retainAll(Arrays.asList(2,3,4,5));
    System.out.println(numbers); // "[2, 3]"

Once you're familiar with the API, you can use it to contain more interesting objects. If you haven't familiarized yourself with the equals and hashCode contract, already, now is a good time to start.

In a nutshell:

  • @Override both or none; never just one. (very important, because it must satisfied property: a.equals(b) == true --> a.hashCode() == b.hashCode()
    • Be careful with writing boolean equals(Thing other) instead; this is not a proper @Override.
  • For non-null references x, y, z, equals must be:
    • reflexive: x.equals(x).
    • symmetric: x.equals(y) if and only if y.equals(x)
    • transitive: if x.equals(y) && y.equals(z), then x.equals(z)
    • consistent: x.equals(y) must not change unless the objects have mutated
    • x.equals(null) == false
  • The general contract for hashCode is:
    • consistent: return the same number unless mutation happened
    • consistent with equals: if x.equals(y), then x.hashCode() == y.hashCode()
      • strictly speaking, object inequality does not require hash code inequality
      • but hash code inequality necessarily requires object inequality
  • What counts as mutation should be consistent between equals and hashCode.

Next, you may want to impose an ordering of your objects. You can do this by making your type implements Comparable, or by providing a separate Comparator.

Having either makes it easy to sort your objects (Arrays.sort, Collections.sort(List)). It also allows you to use SortedSet, such as TreeSet.


Further readings on stackoverflow:

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

We were getting this issue even after updating to the latest Adobe Reader version.

Two different methods solved this issue for us:

  • Using the free version of Foxit Reader application in place of Adobe Reader
  • But, since most of our clients use Adobe Reader, so instead of requiring users to use Foxit Reader, we started using window.open(url) to open the pdf instead of window.location.href = url. Adobe was losing the file handle on for some reason in different iframes when the pdf was opened using the window.location.href method.

How do I change the data type for a column in MySQL?

To change column data type there are change method and modify method

ALTER TABLE student_info CHANGE roll_no roll_no VARCHAR(255);

ALTER TABLE student_info MODIFY roll_no VARCHAR(255);

To change the field name also use the change method

ALTER TABLE student_info CHANGE roll_no identity_no VARCHAR(255);

How to distinguish mouse "click" and "drag"

All these solutions either break on tiny mouse movements, or are overcomplicated.

Here is a simple adaptable solution using two event listeners. Delta is the distance in pixels that you must move horizontally or vertically between the up and down events for the code to classify it as a drag rather than a click. This is because sometimes you will move the mouse or your finger a few pixels before lifting it.

const delta = 6;
let startX;
let startY;

element.addEventListener('mousedown', function (event) {
  startX = event.pageX;
  startY = event.pageY;
});

element.addEventListener('mouseup', function (event) {
  const diffX = Math.abs(event.pageX - startX);
  const diffY = Math.abs(event.pageY - startY);

  if (diffX < delta && diffY < delta) {
    // Click!
  }
});

Escape quotes in JavaScript

Escape whitespace as well. It sounds to me like Firefox is assuming three arguments instead of one. &nbsp; is the non-breaking space character. Even if it's not the whole problem, it may still be a good idea.

How to convert float number to Binary?

(d means decimal, b means binary)

  1. 12.25d is your float.
  2. You write 12d in binary and remove it from your float. Only the remainder (.25d) will be left.
  3. You write the dot.
  4. While the remainder (0.25d) is not zero (and/or you want more digits), multiply it with 2 (-> 0.50d), remove and write the digit left of the dot (0), and continue with the new remainder (.50d).

Reading a JSP variable from JavaScript

   <% String s="Hi"; %>
   var v ="<%=s%>"; 

How can I select from list of values in SQL Server

Select user id from list of user id:

SELECT * FROM my_table WHERE user_id IN (1,3,5,7,9,4);

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I've had the same issue today and I've not done any intermediate merges so from your opening post only #1 might apply - however i have made commits both from an svn client in ubuntu as well as tortoisesvn in windows. Luckily in my case no changes to the trunk were made so I could just replace the trunk with the branch. Possibly different svn versions then? That's quite worrying.

If you use the svn move / copy /delete functions though no history is lost in my case - i svn moved the trunk and then svn moved the branch to trunk.

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

$out.='<option value="'.$key.'">'.$value["name"];

me funciono con esta

"<a  href='javascript:void(0)' onclick='cargar_datos_cliente(\"$row->DSC_EST\")' class='button micro asignar margin-none'>Editar</a>";

Angular2 change detection: ngOnChanges not firing for nested object

I had to create a hack for it -

I created a Boolean Input variable and toggled it whenever array changed, which triggered change detection in the child component, hence achieving the purpose

How do you convert WSDLs to Java classes using Eclipse?

In Eclipse Kepler it is very easy to generate Web Service Client classes,You can achieve this by following steps .

RightClick on any Project->Create New Other ->Web Services->Web Service Client->Then paste the wsdl url(or location) in Service Definition->Next->Finish

You will see the generated classes are inside your src folder.

NOTE :Without eclipse also you can generate client classes from wsdl file by using wsimport command utility which ships with JDK.

refer this link Create Web service client using wsdl

How to prevent buttons from submitting forms

The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form). The javascript error console will usually give a pointer in this case.

Check out the function removeItem in the javascript part:

The line:

rows[rows.length-1].html('');

doesn't work. Try this instead:

rows.eq(rows.length-1).html('');

jQuery/JavaScript: accessing contents of an iframe

I think what you are doing is subject to the same origin policy. This should be the reason why you are getting permission denied type errors.

Compiler warning - suggest parentheses around assignment used as truth value

While that particular idiom is common, even more common is for people to use = when they mean ==. The convention when you really mean the = is to use an extra layer of parentheses:

while ((list = list->next)) { // yes, it's an assignment

How to compare LocalDate instances Java 8

I believe this snippet will also be helpful in a situation where the dates comparison spans more than two entries.

static final int COMPARE_EARLIEST = 0;

static final int COMPARE_MOST_RECENT = 1;


public LocalDate getTargetDate(List<LocalDate> datesList, int comparatorType) { 
   LocalDate refDate = null;
   switch(comparatorType)
   {
       case COMPARE_EARLIEST:         
       //returns the most earliest of the date entries
          refDate = (LocalDate) datesList.stream().min(Comparator.comparing(item -> 
                      item.toDateTimeAtCurrentTime())).get();
          break;

       case COMPARE_MOST_RECENT:
          //returns the most recent of the date entries 
          refDate = (LocalDate) datesList.stream().max(Comparator.comparing(item -> 
                    item.toDateTimeAtCurrentTime())).get();
          break;
   }

   return refDate;
}

Writing binary number system in C code

Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b prefix:

int foo = 0b1010;

If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:

#define B(x) S_to_binary_(#x)

static inline unsigned long long S_to_binary_(const char *s)
{
        unsigned long long i = 0;
        while (*s) {
                i <<= 1;
                i += *s++ - '0';
        }
        return i;
}

And then you can use it like this:

int foo = B(1010);

If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.

Proof:

The following code:

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


#define B(x) S_to_binary_(#x)

static inline unsigned long long S_to_binary_(const char *s)
{
    unsigned long long i = 0;
    while (*s) {
        i <<= 1;
        i += *s++ - '0';
    }
    return i;
}

int main()
{
    int foo = B(001100101);

    printf("%d\n", foo);

    return 0;
}

has been compiled using clang -o baz.S baz.c -Wall -O3 -S, and it produced the following assembly:

    .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp2:
    .cfi_def_cfa_offset 16
Ltmp3:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp4:
    .cfi_def_cfa_register %rbp
    leaq    L_.str1(%rip), %rdi
    movl    $101, %esi               ## <= This line!
    xorb    %al, %al
    callq   _printf
    xorl    %eax, %eax
    popq    %rbp
    ret
    .cfi_endproc

    .section    __TEXT,__cstring,cstring_literals
L_.str1:                                ## @.str1
    .asciz   "%d\n"


.subsections_via_symbols

So clang completely eliminated the call to the function, and replaced its return value with 101. Neat, huh?

Reading an integer from user input

I would suggest you use TryParse:

Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);

This way, your application does not throw an exception, if you try to parse something like "1q" or "23e", because somebody made a faulty input.

Int32.TryParse returns a boolean value, so you can use it in an if statement, to see whether or not you need to branch of your code:

int number;
if(!Int32.TryParse(input, out number))
{
   //no, not able to parse, repeat, throw exception, use fallback value?
}

To your question: You will not find a solution to read an integer because ReadLine() reads the whole command line, threfor returns a string. What you can do is, try to convert this input into and int16/32/64 variable.

There are several methods for this:

If you are in doubt about the input, which is to be converted, always go for the TryParse methods, no matter if you try to parse strings, int variable or what not.

Update In C# 7.0 out variables can be declared directly where they are passed in as an argument, so the above code could be condensed into this:

if(Int32.TryParse(input, out int number))
{
   /* Yes input could be parsed and we can now use number in this code block 
      scope */
}
else 
{
   /* No, input could not be parsed to an integer */
}

A complete example would look like this:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        var foo = Console.ReadLine();
        if (int.TryParse(foo, out int number1)) {
            Console.WriteLine($"{number1} is a number");
        }
        else
        {
            Console.WriteLine($"{foo} is not a number");
        }
        Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
        Console.ReadLine();
    }
}

Here you can see, that the variable number1 does get initialized even if the input is not a number and has the value 0 regardless, so it is valid even outside the declaring if block

Query to get all rows from previous month

Even though the answer for this question has been selected already, however, I believe the simplest query will be

SELECT * 
FROM table 
WHERE 
date_created BETWEEN (CURRENT_DATE() - INTERVAL 1 MONTH) AND CURRENT_DATE();

Why can't I use a list as a dict key in python?

Just found you can change List into tuple, then use it as keys.

d = {tuple([1,2,3]): 'value'}

OSError: [WinError 193] %1 is not a valid Win32 application

All above solution are logical and I think covers the root cause, but for me, none of the above worked. Hence putting it here as may be helpful for others.

My environment was messed up. As you can see from the traceback, there are two python environments involved here:

  1. C:\Users\example\AppData\Roaming\Python\Python37
  2. C:\Users\example\Anaconda3

I cleaned up the path and just deleted all the files from C:\Users\example\AppData\Roaming\Python\Python37.

Then it worked like the charm.

I hope others may find this helpful.

This link helped me to found the solution.

CSS change button style after click

Each link has five different states: link, hover, active, focus and visited.

Link is the normal appearance, hover is when you mouse over, active is the state when it's clicked, focus follows active and visited is the state you end up when you unfocus the recently clicked link.

I'm guessing you want to achieve a different style on either focus or visited, then you can add the following CSS:

a { color: #00c; }
a:visited { #ccc; }
a:focus { #cc0; }

A recommended order in your CSS to not cause any trouble is the following:

a
a:visited { ... }
a:focus { ... }
a:hover { ... }
a:active { ... }

You can use your web browser's developer tools to force the states of the element like this (Chrome->Developer Tools/Inspect Element->Style->Filter :hov): Force state in Chrome Developer Tools

Access index of the parent ng-repeat from child ng-repeat

According to ng-repeat docs http://docs.angularjs.org/api/ng.directive:ngRepeat, you can store the key or array index in the variable of your choice. (indexVar, valueVar) in values

so you can write

<div ng-repeat="(fIndex, f) in foos">
  <div>
    <div ng-repeat="b in foos.bars">
      <a ng-click="addSomething(fIndex)">Add Something</a>
    </div>
  </div>
</div>

One level up is still quite clean with $parent.$index but several parents up, things can get messy.

Note: $index will continue to be defined at each scope, it is not replaced by fIndex.

Android Get Application's 'Home' Data Directory

To get the path of file in application package;

ContextWrapper c = new ContextWrapper(this);
Toast.makeText(this, c.getFilesDir().getPath(), Toast.LENGTH_LONG).show();

dplyr change many data types

A more general way of achieving column type transformation is as follows:

If you want to transform all your factor columns to character columns, e.g., this can be done using one pipe:

df %>%  mutate_each_( funs(as.character(.)), names( .[,sapply(., is.factor)] ))

compareTo() vs. equals()

"equals" compare objects and return true or false and "compare to" return 0 if is true or an number [> 0] or [< 0] if is false here an example:

<!-- language: lang-java -->
//Objects Integer
Integer num1 = 1;
Integer num2 = 1;
//equal
System.out.println(num1.equals(num2));
System.out.println(num1.compareTo(num2));
//New Value
num2 = 3;//set value
//diferent
System.out.println(num1.equals(num2));
System.out.println(num1.compareTo(num2));

Results:

num1.equals(num2) =true
num1.compareTo(num2) =0
num1.equals(num2) =false
num1.compareTo(num2) =-1

Documentation Compare to: https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

Documentation Equals : https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)

How to center buttons in Twitter Bootstrap 3?

It works for me try to make an independent <div>then put the button into that. just like this :

<div id="contactBtn">
            <button type="submit" class="btn btn-primary ">Send</button>
</div>

Then Go to to your CSSStyle page and do the Text-align:center like this :

#contactBtn{text-align: center;}

Can I change the fill color of an svg path with CSS?

I came across an amazing resource on css-tricks: https://css-tricks.com/using-svg/

There are a handful of solutions explained there.

I preferred the one that required minimal edits to the source svg, and also didn't require it to be embedded into the html document. This option utilizes the <object> tag.


Add the svg file into your html using <object>; I also declared html attributes width and height. Using these width and heights the svg document does not get scaled, I worked around that using a css transform: scale(...) statement for the svg tag in my associated svg css file.

<object type="image/svg+xml" data="myfile.svg" width="64" height="64"></object>

Create a css file to attach to your svn document. My source svg path was scaled to 16px, I upscaled it to 64 with a factor of four. It only had one path so I did not need to select it more specifically, however the path had a fill attribute so I had to use !IMPORTANT to force the css to take precedent.

#svg2 {
    width: 64px; height: 64px;
    transform: scale(4);
}
path {
    fill: #333 !IMPORTANT;
}

Edit your target svg file, before the opening <svg tag, to include a stylesheet; Note that the href is relative to the svg file url.

<?xml-stylesheet type="text/css" href="myfile.css" ?>

"message failed to fetch from registry" while trying to install any module

I'm on Ubuntu. I used apt-get to install node. Npm was not included in that package, so it had to be installed separately. I assumed that would work, but apparently the npm version in the Ubuntu distribution was outdated.

The node wiki has this instruction:

Obtaining a recent version of Node or installing on older Ubuntu and other apt-based distributions may require a few extra steps. Example install:

sudo apt-get update
sudo apt-get install -y python-software-properties python g++ make
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

After that, npm was already included and worked perfectly.

How to check if a network port is open on linux?

In the Above,I found multiple solutions.But some solutions having a hanging issue or taking to much time in case of the port was not opened.Below solution worked for me :

import socket 

def port_check(HOST):
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.settimeout(2) #Timeout in case of port not open
   try:
      s.connect((HOST, 22)) #Port ,Here 22 is port 
      return True
   except:
      return False

port_check("127.0.1.1")

Linking to an external URL in Javadoc?

Javadocs don't offer any special tools for external links, so you should just use standard html:

See <a href="http://groversmill.com/">Grover's Mill</a> for a history of the
Martian invasion.

or

@see <a href="http://groversmill.com/">Grover's Mill</a> for a history of 
the Martian invasion.

Don't use {@link ...} or {@linkplain ...} because these are for links to the javadocs of other classes and methods.

'ls' is not recognized as an internal or external command, operable program or batch file

If you want to use Unix shell commands on Windows, you can use Windows Powershell, which includes both Windows and Unix commands as aliases. You can find more info on it in the documentation.

PowerShell supports aliases to refer to commands by alternate names. Aliasing allows users with experience in other shells to use common command names that they already know for similar operations in PowerShell.

The PowerShell equivalents may not produce identical results. However, the results are close enough that users can do work without knowing the PowerShell command name.

Get a list of URLs from a site

I would look into any number of online sitemap generation tools. Personally, I've used this one (java based)in the past, but if you do a google search for "sitemap builder" I'm sure you'll find lots of different options.

Multiple axis line chart in excel

There is a way of displaying 3 Y axis see here.

Excel supports Secondary Axis, i.e. only 2 Y axis. Other way would be to chart the 3rd one separately, and overlay on top of the main chart.

Laravel - Form Input - Multiple select for a one to many relationship

Laravel 4.2

@SamMonk gave the best alternative, I followed his example and build the final piece of code

<select class="chosen-select" multiple="multiple" name="places[]" id="places">
    @foreach($places as $place)
        <option value="{{$place->id}}" @foreach($job->places as $p) @if($place->id == $p->id)selected="selected"@endif @endforeach>{{$place->name}}</option>
    @endforeach
</select>

In my project I'm going to have many table relationships like this so I wrote an extension to keep it clean. To load it, put it in some configuration file like "app/start/global.php". I've created a file "macros.php" under "app/" directory and included it in the EOF of global.php

// app/start/global.php
require app_path().'/macros.php';

// macros.php
Form::macro("chosen", function($name, $defaults = array(), $selected = array(), $options = array()){

    // For empty Input::old($name) session, $selected is an empty string
    if(!$selected) $selected = array();

    $opts = array(
        'class' => 'chosen-select',
        'id' => $name,
        'name' => $name . '[]',
        'multiple' => true
    );
    $options = array_merge($opts, $options);
    $attributes = HTML::attributes($options);

    // need an empty array to send if all values are unselected
    $ret = '<input type="hidden" name="' . HTML::entities($name) . '[]">';
    $ret .= '<select ' . $attributes . '>';
    foreach($defaults as $def) {
        $ret .= '<option value="' . $def->id . '"';
        foreach($selected as $p) {
            // session array or passed stdClass obj
            $current = @$p->id ? $p->id: $p;
            if($def->id == $current) {
                $ret .= ' selected="selected"';
            }
        }
        $ret .= '>' . HTML::entities($def->name) . '</option>';
    }
    $ret .= '</select>';
    return $ret;
});

Usage

List without pre-selected items (create view)

{{ Form::chosen('places', $places, Input::old('places')) }}

Preselections (edit view)

{{ Form::chosen('places', $places, $job->places) }}

Complete usage

{{ Form::chosen('places', $places, $job->places, ['multiple': false, 'title': 'I\'m a selectbox', 'class': 'bootstrap_is_mainstream']) }}

How to make the python interpreter correctly handle non-ASCII characters in string operations?

Way too late for an answer, but the original string was in UTF-8 and '\xc2\xa0' is UTF-8 for NO-BREAK SPACE. Simply decode the original string as s.decode('utf-8') (\xa0 displays as a space when decoded incorrectly as Windows-1252 or latin-1:

Example (Python 3)

s = b'6\xc2\xa0918\xc2\xa0417\xc2\xa0712'
print(s.decode('latin-1')) # incorrectly decoded
u = s.decode('utf8') # correctly decoded
print(u)
print(u.replace('\N{NO-BREAK SPACE}','_'))
print(u.replace('\xa0','-')) # \xa0 is Unicode for NO-BREAK SPACE

Output

6 918 417 712
6 918 417 712
6_918_417_712
6-918-417-712

How to make a loop in x86 assembly language?

You need to use conditional jmp commands. This isn't the same syntax as you're using; looks like MASM, but using GAS here's an example from some code I wrote to calculate gcd:

gcd_alg:
    subl    %ecx, %eax      /* a = a - c */
    cmpl    $0, %eax        /* if a == 0 */
    je      gcd_done        /* jump to end */
    cmpl    %ecx, %eax      /* if a < c */
    jl      gcd_preswap     /* swap and start over */
    jmp     gcd_alg         /* keep subtracting */

Basically, I compare two registers with the cmpl instruction (compare long). If it is less the JL (jump less) instruction jumps to the preswap location, otherwise it jumps back to the same label.

As for clearing the screen, that depends on the system you're using.

Handling the TAB character in Java

Yes the tab character is one character. You can match it in java with "\t".

Is it possible to install another version of Python to Virtualenv?

Pre-requisites:

  1. sudo easy_install virtualenv
  2. sudo pip install virtualenvwrapper

Installing virtualenv with Python2.6:

  1. You could manually download, build and install another version of Python to /usr/local or another location.

  2. If it's another location other than /usr/local, add it to your PATH.

  3. Reload your shell to pick up the updated PATH.

  4. From this point on, you should be able to call the following 2 python binaries from your shell python2.5 and python2.6

  5. Create a new instance of virtualenv with python2.6:

    mkvirtualenv --python=python2.6 yournewenv

Resize background image in div using css

i would recommend using this:

  background-repeat:no-repeat;
  background-image: url(your file location here);
  background-size:cover;(will only work with css3)

hope it helps :D

And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.

Detecting when the 'back' button is pressed on a navbar

self.navigationController.isMovingFromParentViewController is not working anymore on iOS8 and 9 I use :

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.navigationController.topViewController != self)
    {
        // Is Popping
    }
}

How to store token in Local or Session Storage in Angular 2?

Here is the best practice: https://github.com/PillowPillow/ng2-webstorage

I was use it in AngularJs, now with Angular2. Wery usefull.

Smooth scroll without the use of jQuery

<script>
var set = 0;

function animatescroll(x, y) {
    if (set == 0) {
        var val72 = 0;
        var val73 = 0;
        var setin = 0;
        set = 1;

        var interval = setInterval(function() {
            if (setin == 0) {
                val72++;
                val73 += x / 1000;
                if (val72 == 1000) {
                    val73 = 0;
                    interval = clearInterval(interval);
                }
                document.getElementById(y).scrollTop = val73;
            }
        }, 1);
    }
}
</script>

x = scrollTop
y = id of the div that is used to scroll

Note: For making the body to scroll give the body an ID.

static function in C

Making a function static hides it from other translation units, which helps provide encapsulation.

helper_file.c

int f1(int);        /* prototype */
static int f2(int); /* prototype */

int f1(int foo) {
    return f2(foo); /* ok, f2 is in the same translation unit */
                    /* (basically same .c file) as f1         */
}

int f2(int foo) {
    return 42 + foo;
}

main.c:

int f1(int); /* prototype */
int f2(int); /* prototype */

int main(void) {
    f1(10); /* ok, f1 is visible to the linker */
    f2(12); /* nope, f2 is not visible to the linker */
    return 0;
}

Get URL of ASP.Net Page in code-behind

I use this in my code in a custom class. Comes in handy for sending out emails like [email protected] "no-reply@" + BaseSiteUrl Works fine on any site.

// get a sites base urll ex: example.com
public static string BaseSiteUrl
{
    get
    {
        HttpContext context = HttpContext.Current;
        string baseUrl = context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/');
        return baseUrl;
    }

}

If you want to use it in codebehind get rid of context.

How do you get the current time of day?

This will show you only the current time, in 24 hour format:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString().ToString());
        Console.WriteLine(DateTime.Now.ToShortTimeString().ToString());
        Console.ReadLine();
    }
}

Regards
K

Android camera intent

Try the following I found here

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == Activity.RESULT_OK && requestCode == 0) {
    String result = data.toURI();
    // ...
  }
}

Store boolean value in SQLite

But,if you want to store a bunch of them you could bit-shift them and store them all as one int, a little like unix file permissions/modes.

For mode 755 for instance, each digit refers to a different class of users: owner, group, public. Within each digit 4 is read, 2 is write, 1 is execute so 7 is all of them like binary 111. 5 is read and execute so 101. Make up your own encoding scheme.

I'm just writing something for storing TV schedule data from Schedules Direct and I have the binary or yes/no fields: stereo, hdtv, new, ei, close captioned, dolby, sap in Spanish, season premiere. So 7 bits, or an integer with a maximum of 127. One character really.

A C example from what I'm working on now. has() is a function that returns 1 if the 2nd string is in the first one. inp is the input string to this function. misc is an unsigned char initialized to 0.

if (has(inp,"sap='Spanish'") > 0)
  misc += 1;
if (has(inp,"stereo='true'") > 0)
  misc +=2;
if (has(inp,"ei='true'") > 0)
  misc +=4;
if (has(inp,"closeCaptioned='true'") > 0)
  misc += 8;
if (has(inp,"dolby=") > 0)
  misc += 16;
if (has(inp,"new='true'") > 0)
  misc += 32;
if (has(inp,"premier_finale='") > 0)
  misc += 64;
if (has(inp,"hdtv='true'") > 0)
  misc += 128;

So I'm storing 7 booleans in one integer with room for more.

Android Studio Gradle Configuration with name 'default' not found

I had this issue when I manually pasted google-play-services_lib into my project. Obviously, play-services didn't have a build.gradle file in it. The solution, I learned, is to put this dependency in my project's build.gradle (instead of hard-copying the play-services directory):

    compile 'com.google.android.gms:play-services:4.0.+'

How do I make an Event in the Usercontrol and have it handled in the Main Form?

Try mapping it. Try placing this code in your UserControl:

public event EventHandler ValueChanged {
  add { numericUpDown1.ValueChanged += value; }
  remove { numericUpDown1.ValueChanged -= value; }
}

then your UserControl will have the ValueChanged event you normally see with the NumericUpDown control.

How to find the kafka version in linux

Kafka 2.0 have the fix(KIP-278) for it:

kafka-topics.sh --version

Using confluent utility:

Kakfa version check can be done with confluent utility which comes by default with Confluent platform(confluent utility can be added to cluster separately as well - credits cricket_007).

${confluent.home}/bin/confluent version kafka

Checking the version of other Confluent platform components like ksql schema-registry and connect

[confluent-4.1.0]$ ./bin/confluent version kafka
1.1.0-cp1

[confluent-4.1.0]$ ./bin/confluent version connect
4.1.0

[confluent-4.1.0]$ ./bin/confluent version schema-registry
4.1.0

[confluent-4.1.0]$ ./bin/confluent version ksql-server
4.1.0

Detecting arrow key presses in JavaScript

Modern answer since keyCode is now deprecated in favor of key:

document.onkeydown = function (e) {
    switch (e.key) {
        case 'ArrowUp':
            // up arrow
            break;
        case 'ArrowDown':
            // down arrow
            break;
        case 'ArrowLeft':
            // left arrow
            break;
        case 'ArrowRight':
            // right arrow
    }
};

JQuery: detect change in input field

You can bind the 'input' event to the textbox. This would fire every time the input changes, so when you paste something (even with right click), delete and type anything.

$('#myTextbox').on('input', function() {
    // do something
});

If you use the change handler, this will only fire after the user deselects the input box, which may not be what you want.

There is an example of both here: http://jsfiddle.net/6bSX6/

Getting RSA private key from PEM BASE64 Encoded private key file

Make sure your id_rsa file doesn't have any extension like .txt or .rtf. Rich Text Format adds additional characters to your file and those gets added to byte array. Which eventually causes invalid private key error. Long story short, Copy the file, not content.

SimpleXml to string

Actually asXML() converts the string into xml as it name says:

<id>5</id>

This will display normally on a web page but it will cause problems when you matching values with something else.

You may use strip_tags function to get real value of the field like:

$newString = strip_tags($xml->asXML());

PS: if you are working with integers or floating numbers, you need to convert it into integer with intval() or floatval().

$newNumber = intval(strip_tags($xml->asXML()));

How to replace a hash key with another key

If all the keys are strings and all of them have the underscore prefix, then you can patch up the hash in place with this:

h.keys.each { |k| h[k[1, k.length - 1]] = h[k]; h.delete(k) }

The k[1, k.length - 1] bit grabs all of k except the first character. If you want a copy, then:

new_h = Hash[h.map { |k, v| [k[1, k.length - 1], v] }]

Or

new_h = h.inject({ }) { |x, (k,v)| x[k[1, k.length - 1]] = v; x }

You could also use sub if you don't like the k[] notation for extracting a substring:

h.keys.each { |k| h[k.sub(/\A_/, '')] = h[k]; h.delete(k) }
Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }

And, if only some of the keys have the underscore prefix:

h.keys.each do |k|
  if(k[0,1] == '_')
    h[k[1, k.length - 1]] = h[k]
    h.delete(k)
  end
end

Similar modifications can be done to all the other variants above but these two:

Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }

should be okay with keys that don't have underscore prefixes without extra modifications.

How to use MD5 in javascript to transmit a password

if you're using php jquery, this might help:

   $.ajax({
        url:'phpmd5file.php',
        data:{'mypassword',mypassword},
        dataType:"json",
        method:"POST",
        success:function(mymd5password){
            alert(mymd5password);
        }
    });

on your phpmd5.php file:

echo json_encode($_POST["mypassword"]);

no jsplugins needed. just use ajax and let php md5() do the job.

Very Simple, Very Smooth, JavaScript Marquee

I've made very simple function for marquee. See: http://jsfiddle.net/vivekw/pHNpk/2/ It pauses on mouseover & resumes on mouseleave. Speed can be varied. Easy to understand.

function marquee(a, b) {
var width = b.width();
var start_pos = a.width();
var end_pos = -width;

function scroll() {
    if (b.position().left <= -width) {
        b.css('left', start_pos);
        scroll();
    }
    else {
        time = (parseInt(b.position().left, 10) - end_pos) *
            (10000 / (start_pos - end_pos)); // Increase or decrease speed by changing value 10000
        b.animate({
            'left': -width
        }, time, 'linear', function() {
            scroll();
        });
    }
}

b.css({
    'width': width,
    'left': start_pos
});
scroll(a, b);
b.mouseenter(function() {     // Remove these lines
    b.stop();                 //
    b.clearQueue();           // if you don't want
});                           //
b.mouseleave(function() {     // marquee to pause
    scroll(a, b);             //
});                           // on mouse over
}

$(document).ready(function() {
    marquee($('#display'), $('#text'));  //Enter name of container element & marquee element
});

MySQL show status - active or total connections?

To see a more complete list you can run:

show session status;

or

show global status;

See this link to better understand the usage.

If you want to know details about the database you can run:

status;

Bootstrap 4 dropdown with search

I took the answer from PirateApp and made it reusable. If you include this script it will transform all selects with the class '.dropdown' to searchable dropdowns.

_x000D_
_x000D_
$('.dropdown').each(function(index, dropdown) {

  //Find the input search box
  let search = $(dropdown).find('.search');

  //Find every item inside the dropdown
  let items = $(dropdown).find('.dropdown-item');

  //Capture the event when user types into the search box
  $(search).on('input', function() {
    filter($(search).val().trim().toLowerCase())
  });

  //For every word entered by the user, check if the symbol starts with that word
  //If it does show the symbol, else hide it
  function filter(word) {
    let length = items.length
    let collection = []
    let hidden = 0
    for (let i = 0; i < length; i++) {
      if (items[i].value.toString().toLowerCase().includes(word)) {
        $(items[i]).show()
      } else {
        $(items[i]).hide()
        hidden++
      }
    }

    //If all items are hidden, show the empty view
    if (hidden === length) {
      $(dropdown).find('.dropdown_empty').show();
    } else {
      $(dropdown).find('.dropdown_empty').hide();
    }
  }

  //If the user clicks on any item, set the title of the button as the text of the item
  $(dropdown).find('.dropdown-menu').find('.menuItems').on('click', '.dropdown-item', function() {
    $(dropdown).find('.dropdown-toggle').text($(this)[0].value);
    $(dropdown).find('.dropdown-toggle').dropdown('toggle');
  })
});
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div class="dropdown">
  <button class="btn btn-sm btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Benutzer
    </button>
  <div class="dropdown-menu" aria-labelledby="dropdown_user">
    <form class="px-4 py-2">
      <input type="search" class="form-control search" placeholder="Suche.." autofocus="autofocus">
    </form>
    <div class="menuItems">
      <input type="button" class="dropdown-item" type="button" value="Test1" />
      <input type="button" class="dropdown-item" type="button" value="Test2" />
      <input type="button" class="dropdown-item" type="button" value="Test3" />
    </div>
    <div style="display:none;" class="dropdown-header dropdown_empty">No entry found</div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Executing a batch script on Windows shutdown

I found this topic while searching for run script for startup and shutdown Windows 10. Those answers above didn't working. For me on windows 10 worked when I put scripts to task scheduler. How to do this: press window key and write Task scheduler, open it, then on the right is Add task... button. Here you can add scripts. PS: I found action for startup and logout user, there is not for shutdown.

jquery mobile background image

I think your answer will be background-size:cover.

.ui-page
{
background: #000;
background-image:url(image.gif);
background-size:cover;  
}

Server certificate verification failed: issuer is not trusted

string cmdArguments = $@"/k svn log --trust-server-cert --non-interactive ""{servidor}"" --username alex --password alex -r {numeroRevisao}";
ProcessStartInfo cmd = new ProcessStartInfo("cmd.exe", cmdArguments);

cmd.CreateNoWindow = true;
cmd.RedirectStandardOutput = true;
cmd.RedirectStandardError = true;
cmd.WindowStyle = ProcessWindowStyle.Hidden;
cmd.UseShellExecute = false;

Process reg = Process.Start(cmd);
string output = "";

using (System.IO.StreamReader myOutput = reg.StandardOutput)
{
    output += myOutput.ReadToEnd();
}
using (System.IO.StreamReader myError = reg.StandardError)
{
    output += myError.ReadToEnd();
}

return output;

Write lines of text to a file in R

tidyverse edition with pipe and write_lines() from readr

library(tidyverse)
c('Hello', 'World') %>% write_lines( "output.txt")

Batch not-equal (inequality) operator

NEQ is usually used for numbers and == is typically used for string comparison.

I cannot find any documentation that mentions a specific and equivalent inequality operand for string comparison (in place of NEQ). The solution using IF NOT == seems the most sound approach. I can't immediately think of a circumstance in which the evaluation of operations in a batch file would cause an issue or unexpected behavior when applying the IF NOT == comparison method to strings.

I wish I could offer insight into how the two functions behave differently on a lower level - would disassembling separate batch files (that use NEQ and IF NOT ==) offer any clues in terms of which (unofficially documented) native API calls conhost.exe is utilizing?

INSERT INTO from two different server database

You cannot directly copy a table into a destination server database from a different database if source db is not in your linked servers. But one way is possible that, generate scripts (schema with data) of the desired table into one table temporarily in the source server DB, then execute the script in the destination server DB to create a table with your data. Finally use INSERT INTO [DESTINATION_TABLE] select * from [TEMPORARY_SOURCE_TABLE]. After getting the data into your destination table drop the temporary one.

I found this solution when I faced the same situation. Hope this helps you too.

How to efficiently concatenate strings in go

strings.Join() from the "strings" package

If you have a type mismatch(like if you are trying to join an int and a string), you do RANDOMTYPE (thing you want to change)

EX:

package main

import (
    "fmt"
    "strings"
)

var intEX = 0
var stringEX = "hello all you "
var stringEX2 = "people in here"


func main() {
    s := []string{stringEX, stringEX2}
    fmt.Println(strings.Join(s, ""))
}

Output :

hello all you people in here

SQL Query - Using Order By in UNION

For Sql Server 2014/2012/Others(Not Checked) :

SELECT * FROM 
(
  SELECT table1.field1 FROM table1 ORDER BY table1.field1
) 
as DUMMY_ALIAS1

UNION ALL

SELECT * FROM
( 
  SELECT table2.field1 FROM table2 ORDER BY table2.field1
) 
as DUMMY_ALIAS2

Increment a Integer's int value?

Java 7 and 8. Increment DOES change the reference, so it references to another Integer object. Look:

@Test
public void incInteger()
{
    Integer i = 5;
    Integer iOrig = i;
    ++i; // Same as i = i + 1;
    Assert.assertEquals(6, i.intValue());
    Assert.assertNotEquals(iOrig, i);
}

Integer by itself is still immutable.

Get current date in milliseconds

An extension on date is probably the best way to about it.

extension NSDate {
    func msFromEpoch() -> Double {
        return self.timeIntervalSince1970 * 1000
    }
}

regular expression for anything but an empty string

Create "regular expression to detect empty string", and then inverse it. Invesion of regular language is the regular language. I think regular expression library in what you leverage - should support it, but if not you always can write your own library.

grep --invert-match

Difference between try-catch and throw in java

All these keywords try, catch and throw are related to the exception handling concept in java. An exception is an event that occurs during the execution of programs. Exception disrupts the normal flow of an application. Exception handling is a mechanism used to handle the exception so that the normal flow of application can be maintained. Try-catch block is used to handle the exception. In a try block, we write the code which may throw an exception and in catch block we write code to handle that exception. Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions.

For more detail visit Java tutorial for beginners.

Way to get number of digits in an int?

How about plain old Mathematics? Divide by 10 until you reach 0.

public static int getSize(long number) {
        int count = 0;
        while (number > 0) {
            count += 1;
            number = (number / 10);
        }
        return count;
    }

Using braces with dynamic variable names in PHP

i have a solution for dynamically created variable value and combined all value in a variable.

if($_SERVER['REQUEST_METHOD']=='POST'){
    $r=0;
    for($i=1; $i<=4; $i++){
        $a = $_POST['a'.$i];
        $r .= $a;
    }
    echo $r;
}

How to use NULL or empty string in SQL

SELECT *
FROM   TableName
WHERE  columnNAme IS NULL OR 
       LTRIM(RTRIM(columnName)) = ''

Angular 2 / 4 / 5 - Set base href dynamically

In angular4, you can also configure the baseHref in .angular-cli.json apps.

in .angular-cli.json

{   ....
 "apps": [
        {
            "name": "myapp1"
            "baseHref" : "MY_APP_BASE_HREF_1"
         },
        {
            "name": "myapp2"
            "baseHref" : "MY_APP_BASE_HREF_2"
         },
    ],
}

this will update base href in index.html to MY_APP_BASE_HREF_1

ng build --app myapp1

Difference between r+ and w+ in fopen()

There are 2 differences, unlike r+, w+ will:

  • create the file if it does not already exist
  • first truncate it, i.e., will delete its contents

What is the difference between json.dump() and json.dumps() in python?

In memory usage and speed.

When you call jsonstr = json.dumps(mydata) it first creates a full copy of your data in memory and only then you file.write(jsonstr) it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.

When you call json.dump(mydata, file) -- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.

Source: I checked the source code of json.dump() and json.dumps() and also tested both the variants measuring the time with time.time() and watching the memory usage in htop.

Android Emulator sdcard push error: Read-only file system

Try this in a Terminal Emulator as root:

restorecon -v -R /data/media

Why do some functions have underscores "__" before and after the function name?

Actually I use _ method names when I need to differ between parent and child class names. I've read some codes that used this way of creating parent-child classes. As an example I can provide this code:

class ThreadableMixin:
   def start_worker(self):
       threading.Thread(target=self.worker).start()

   def worker(self):
      try:
        self._worker()
    except tornado.web.HTTPError, e:
        self.set_status(e.status_code)
    except:
        logging.error("_worker problem", exc_info=True)
        self.set_status(500)
    tornado.ioloop.IOLoop.instance().add_callback(self.async_callback(self.results))

...

and the child that have a _worker method

class Handler(tornado.web.RequestHandler, ThreadableMixin):
   def _worker(self):
      self.res = self.render_string("template.html",
        title = _("Title"),
        data = self.application.db.query("select ... where object_id=%s", self.object_id)
    )

...

How to get named excel sheets while exporting from SSRS

Put the tab name on the page header or group TableRow1 in your report so that it will appear in the "A1" position on each Excel sheet. Then run this macro in your Excel workbook.

Sub SelectSheet()
        For i = 1 To ThisWorkbook.Sheets.Count
        mysheet = "Sheet" & i
        On Error GoTo 10
        Sheets(mysheet).Select
        Set Target = Range("A1")
        If Target = "" Then Exit Sub
        On Error GoTo Badname
        ActiveSheet.Name = Left(Target, 31)
        GoTo 10
Badname:
        MsgBox "Please revise the entry in A1." & Chr(13) _
        & "It appears to contain one or more " & Chr(13) _
        & "illegal characters." & Chr(13)
        Range("A1").Activate
10
        Next i
End Sub

"unmappable character for encoding" warning in Java

For those wondering why this happens on some systems and not on others (with the same source, build parameters, and so on), check your LANG environment variable. I get the warning/error when LANG=C.UTF-8, but not when LANG=en_US.UTF-8.

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

Using Eloquent ORM in Laravel to perform search of database using LIKE

Use double quotes instead of single quote eg :

where('customer.name', 'LIKE', "%$findcustomer%")

Below is my code:

public function searchCustomer($findcustomer)
{
    $customer = DB::table('customer')
                  ->where('customer.name', 'LIKE', "%$findcustomer%")
                  ->orWhere('customer.phone', 'LIKE', "%$findcustomer%")
                  ->get();

    return View::make("your view here");
}

How can I change the class of an element with jQuery>

<script>
$(document).ready(function(){
      $('button').attr('class','btn btn-primary');
}); </script>

How do I use CREATE OR REPLACE?

Following script should do the trick on Oracle:

BEGIN
  EXECUTE IMMEDIATE 'drop TABLE tablename';
EXCEPTION
  WHEN OTHERS THEN
    IF sqlcode != -0942 THEN RAISE; 
    END IF;
END;

Access-Control-Allow-Origin: * in tomcat

I had to restart the browser after changing the ip address (laptop wireless DHCP) which was my "cross-host" I was referring to in my web app, which resolved the issue.

Also make sure all the cors headers being added by your browser/host are accepted/allowed by including then in the cors.allowed.headers

LINQ Orderby Descending Query

You need to choose a Property to sort by and pass it as a lambda expression to OrderByDescending

like:

.OrderByDescending(x => x.Delivery.SubmissionDate);

Really, though the first version of your LINQ statement should work. Is t.Delivery.SubmissionDate actually populated with valid dates?

How to Scroll Down - JQuery

$('.btnMedio').click(function(event) {
    // Preventing default action of the event
    event.preventDefault();
    // Getting the height of the document
    var n = $(document).height();
    $('html, body').animate({ scrollTop: n }, 50);
//                                       |    |
//                                       |    --- duration (milliseconds) 
//                                       ---- distance from the top
});

How can a Javascript object refer to values in itself?

This is not JSON. JSON was designed to be simple; allowing arbitrary expressions is not simple.

In full JavaScript, I don't think you can do this directly. You cannot refer to this until the object called obj is fully constructed. So you need a workaround, that someone with more JavaScript-fu than I will provide.

Where can I find error log files?

For unix cli users:

Most probably the error_log ini entry isn't set. To verify:

php -i | grep error_log
// error_log => no value => no value

You can either set it in your php.ini cli file, or just simply quickly pipe all STDERR yourself to a file:

./myprog 2> myerror.log

Then quickly:

tail -f myerror.log

Functional programming vs Object Oriented programming

  1. If you're in a heavily concurrent environment, then pure functional programming is useful. The lack of mutable state makes concurrency almost trivial. See Erlang.

  2. In a multiparadigm language, you may want to model some things functionally if the existence of mutable state is must an implementation detail, and thus FP is a good model for the problem domain. For example, see list comprehensions in Python or std.range in the D programming language. These are inspired by functional programming.

HashSet vs. List performance

You can use a HybridDictionary which automaticly detects the breaking point, and accepts null-values, making it essentialy the same as a HashSet.

Get image dimensions

You can use the getimagesize function like this:

list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " .  $height;

(413) Request Entity Too Large | uploadReadAheadSize

For me, setting the uploadReadAheadSize to int.MaxValue also fixed the problem, after also increasing the limits on the WCF binding.

It seems that, when using SSL, the entire request entity body is preloaded, for which this metabase property is used.

For more info, see:

The page was not displayed because the request entity is too large. iis7

Set encoding and fileencoding to utf-8 in Vim

You can set the variable 'fileencodings' in your .vimrc.

This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.

See :help filencodings

If you often work with e.g. cp1252, you can add it there:

set fileencodings=ucs-bom,utf-8,cp1252,default,latin9

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

If you compile with optimizations enabled, then many variables will be removed; for example:

SomeType value = GetValue();
DoSomething(value);

here the local variable value would typically get removed, keeping the value on the stack instead - a bit like as if you had written:

DoSomething(GetValue());

Also, if a return value isn't used at all, then it will be dropped via "pop" (rather than stored in a local via "stloc", and again; the local will not exist).

Because of this, in such a build the debugger can't get the current value of value because it doesn't exist - it only exists for the brief instant between GetValue() and DoSomething(...).

So; if you want to debug... don't use a release build! or at least, disable optimizations while you debug.

How to find the type of an object in Go?

you can use reflect.TypeOf.

  • basic type(e.g.: int, string): it will return its name (e.g.: int, string)
  • struct: it will return something in the format <package name>.<struct name> (e.g.: main.test)

How to check if PHP array is associative or sequential?

Surely this is a better alternative.

<?php
$arr = array(1,2,3,4);
$isIndexed = array_values($arr) === $arr;

Xcode build failure "Undefined symbols for architecture x86_64"

I had the same error, because instead of deleting a file I simply removed references to it. Locating the file in Finder and removing it helped.

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

We can simply map a Controller method for the default view. For eg, we have a index.html as the default page.

@RequestMapping(value = "/", method = GET)
public String index() {
    return "index";
}

once done we can access the page with default application context.

E.g http://localhost:8080/myapp

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

Change GitHub Account username

Yes, this is an old question. But it's misleading, as this was the first result in my search, and both the answers aren't correct anymore.

You can change your Github account name at any time.

To do this, click your profile picture > Settings > Account Settings > Change Username.

Links to your repositories will redirect to the new URLs, but they should be updated on other sites because someone who chooses your abandoned username can override the links. Links to your profile page will be 404'd.

For more information, see the official help page.

And furthermore, if you want to change your username to something else, but that specific username is being taken up by someone else who has been completely inactive for the entire time their account has existed, you can report their account for name squatting.

Match groups in Python

Less efficient, but simpler-looking:

m0 = re.match("I love (\w+)", statement)
m1 = re.match("Ich liebe (\w+)", statement)
m2 = re.match("Je t'aime (\w+)", statement)
if m0:
  print "He loves",m0.group(1)
elif m1:
  print "Er liebt",m1.group(1)
elif m2:
  print "Il aime",m2.group(1)

The problem with the Perl stuff is the implicit updating of some hidden variable. That's simply hard to achieve in Python because you need to have an assignment statement to actually update any variables.

The version with less repetition (and better efficiency) is this:

pats = [
    ("I love (\w+)", "He Loves {0}" ),
    ("Ich liebe (\w+)", "Er Liebe {0}" ),
    ("Je t'aime (\w+)", "Il aime {0}")
 ]
for p1, p3 in pats:
    m= re.match( p1, statement )
    if m:
        print p3.format( m.group(1) )
        break

A minor variation that some Perl folk prefer:

pats = {
    "I love (\w+)" : "He Loves {0}",
    "Ich liebe (\w+)" : "Er Liebe {0}",
    "Je t'aime (\w+)" : "Il aime {0}",
}
for p1 in pats:
    m= re.match( p1, statement )
    if m:
        print pats[p1].format( m.group(1) )
        break

This is hardly worth mentioning except it does come up sometimes from Perl programmers.

How can I concatenate strings in VBA?

The main (very interesting) difference for me is that:
"string" & Null -> "string"
while
"string" + Null -> Null

But that's probably more useful in database apps like Access.

How can I put a database under git (version control)?

I'm starting to think of a really simple solution, don't know why I didn't think of it before!!

  • Duplicate the database, (both the schema and the data).
  • In the branch for the new-major-changes, simply change the project configuration to use the new duplicate database.

This way I can switch branches without worrying about database schema changes.

EDIT:

By duplicate, I mean create another database with a different name (like my_db_2); not doing a dump or anything like that.

Loop in react-native

 render() {
    var myloop = [];

    for (let i = 0; i < 10; i++) {
      myloop.push(
        <View key={i}>
        <Text style={{ textAlign: 'center', marginTop: 5 }} >{i}</Text>
        </View>
      );
    }

     return (

            <View >
              <Text >Welcome to React Native!</Text>
               {myloop}
            </View>


        );
      }

Output 1 2 3 4 5 6 7 8 9

How to make a link open multiple pages when clicked

I did it in a simple way:

    <a href="http://virtual-doctor.net" onclick="window.open('http://runningrss.com');
return true;">multiopen</a>

It'll open runningrss in a new window and virtual-doctor in same window.

How to center Font Awesome icons horizontally?

It's a really old topic but as it still comes up top in search results:

Nowadays you can add additional class fa-fw to set it fixed width.

Example:

<i class="fa fa-pencil fa-fw" aria-hidden="true"></i>

java.time.format.DateTimeParseException: Text could not be parsed at index 21

The following worked for me

import java.time.*;
import java.time.format.*;

public class Times {

  public static void main(String[] args) {
    final String dateTime = "2012-02-22T02:06:58.147Z";
    DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
    final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter.withZone(ZoneId.of("UTC")));
    System.out.println(parsed.toLocalDateTime());
  }
}

and gave me output as

2012-02-22T02:06:58.147

Android - How to get application name? (Not package name)

Java

public static String getApplicationName(Context context) {
    return context.getApplicationInfo().loadLabel(context.getPackageManager()).toString();
}

Kotlin (as extension)

fun Context.getAppName(): String = applicationInfo.loadLabel(packageManager).toString()

javascript: using a condition in switch case

if the possible values are integers you can bunch up cases. Otherwise, use ifs.

var api, tem;

switch(liCount){
    case 0:
    tem= 'start';
    break;
    case 1: case 2: case 3: case 4: case 5:
    tem= 'upload1Row';
    break;
    case 6: case 7: case 8: case 9: case 10:
    tem= 'upload2Rows';
    break;
    default:
    break;
}
if(tem) setLayoutState((tem);
api= $('#UploadList').data('jsp');
api.reinitialise();

How can I connect to MySQL on a WAMP server?

Change localhost:8080 to localhost:3306.

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

I found this brilliant solution here, it uses the simple logic NAN!=NAN. https://www.codespeedy.com/check-if-a-given-string-is-nan-in-python/

Using above example you can simply do the following. This should work on different type of objects as it simply utilize the fact that NAN is not equal to NAN.

 import numpy as np
 s = pd.Series(['apple', np.nan, 'banana'])
 s.apply(lambda x: x!=x)
 out[252]
 0    False
 1     True
 2    False
 dtype: bool

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

Currently working with Entity Framework Core 3.1.3. None of the above solutions fixed my issue.

However, installing the package Microsoft.EntityFrameworkCore.Proxies on my project fixed the issue. Now I can access the UseLazyLoadingProxies() method call when setting my DBContext options.

Hope this helps someone. See the following article:

Lazy Loading in EF Core

CodeIgniter htaccess and URL rewrite issues

There are 3 steps to remove index.php.

  1. Make below changes in application/config.php file

    $config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/Your Ci folder_name';
    $config['index_page'] = '';
    $config['uri_protocol'] = 'AUTO';
    
  2. Make .htaccess file in your root directory using below code

    RewriteEngine on
    RewriteCond $1 !^(index\.php|resources|robots\.txt)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L,QSA]
    
  3. Enable the rewrite engine (if not already enabled)

    i. First, initiate it with the following command:

    a2enmod rewrite
    

    ii. Edit the file /etc/apache2/sites-enabled/000-default

    Change all AllowOverride None to AllowOverride All.

    Note: In latest version you need to change in /etc/apache2/apache2.conf file

    iii. Restart your server with the following command:

    sudo /etc/init.d/apache2 restart
    

How to pass parameter to a promise function

Try this:

function someFunction(username, password) {
      return new Promise((resolve, reject) => {
        // Do something with the params username and password...
        if ( /* everything turned out fine */ ) {
          resolve("Stuff worked!");
        } else {
          reject(Error("It didn't work!"));
        }
      });
    }
    
    someFunction(username, password)
      .then((result) => {
        // Do something...
      })
      .catch((err) => {
        // Handle the error...
      });

Change Activity's theme programmatically

I have used this code to implement dark mode...it worked fine for me...You can use it in a switch on....listener...

//setting up Night Mode...
 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
//Store current mode in a sharedprefernce to retrieve on restarting app
            editor.putBoolean("NightMode", true);
            editor.apply();
//restart all the activities to apply changed mode...
            TaskStackBuilder.create(getActivity())
                    .addNextIntent(new Intent(getActivity(), MainActivity.class))
                    .addNextIntent(getActivity().getIntent())
                    .startActivities();

How do you get the magnitude of a vector in Numpy?

The function you're after is numpy.linalg.norm. (I reckon it should be in base numpy as a property of an array -- say x.norm() -- but oh well).

import numpy as np
x = np.array([1,2,3,4,5])
np.linalg.norm(x)

You can also feed in an optional ord for the nth order norm you want. Say you wanted the 1-norm:

np.linalg.norm(x,ord=1)

And so on.

Need to combine lots of files in a directory

Yes , A plugin is available named "combine" for notepad++.Link: .>> Combine Plugin for Notepad++

You can install it via plugin manager. Extra benifit of this plugin is: "You can maintain the sequence of files while merging, it's according to the sequence of opened files are opened (see tabs)".

How to set bot's status

.setGame is discontinued. Use:

client.user.setActivity("Game"); 

To set a playing game status.

As an addition, if you were using an earlier version of discord.js, try this:

client.user.setGame("Game");

In newer versions of discord.js, this is deprecated.

How to declare variable and use it in the same Oracle SQL script?

One possible approach, if you just need to specify a parameter once and replicate it in several places, is to do something like this:

SELECT
  str_size  /* my variable usage */
  , LPAD(TRUNC(DBMS_RANDOM.VALUE * POWER(10, str_size)), str_size, '0') rand
FROM
  dual  /* or any other table, or mixed of joined tables */
  CROSS JOIN (SELECT 8 str_size FROM dual);  /* my variable declaration */

This code generates a string of 8 random digits.

Notice that I create a kind of alias named str_size that holds the constant 8. It is cross-joined to be used more than once in the query.