Programs & Examples On #Visual c++ 2008

The November 2007 release of Microsoft Visual C++, a C and C++ compiler for Windows.

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

"project property - CUDA Runtime API - GPU - NVCC Compilation Type"

Set the 64 bit compile option -m64 -cubin

The hint is at compile log. Like this:

nvcc.exe ~~~~~~ -machine 32 -ccbin ~~~~~

That "-machine 32" is problem.

First set 64bit compile option, next re setting hybrid compile option. Then u can see the succeed.

POST: sending a post request in a url itself

In Java you can use GET which shows requested data on URL.But POST method cannot , because POST has body but GET donot have body.

Validate phone number using javascript

Can any one explain why??

This happening because your regular expression doesn't end with any anchor meta-character such as the end of line $ or a word boundary \b.

So when you ask the regex engine whether 123-345-34567 is valid phone number it will try to find a match within this string, so it matches 123- with this part (\([0-9]{3}\) |[0-9]{3}-) then it matches 345- with this part [0-9]{3}- then it matches 3456 with this part [0-9]{4}.

Now the engine finds that it has walked the entire regex and found a string inside your input that matches the regex although a character was left - the number 7- in the input string, so it stops and returns success because it found a sub-string that matches.

If you had included $ or \b at the end of your regex, the engine walks the same way as before then it tries to match $ or \b but finds the last number - the 7 - and it is not a word boundary \b nor a an end of line $ so it stops and fails to find a match.

"unrecognized import path" with go get

I installed Go with brew on OSX 10.11, and found I had to set GOROOT to:

/usr/local/Cellar/go/1.5.1/libexec

(Of course replace the version in this path with go version you have)

Brew uses symlinks, which were fooling the gotool. So follow the links home.

What does ON [PRIMARY] mean?

It refers to which filegroup the object you are creating resides on. So your Primary filegroup could reside on drive D:\ of your server. you could then create another filegroup called Indexes. This filegroup could reside on drive E:\ of your server.

Can't import org.apache.http.HttpResponse in Android Studio

Main build.gradle - /build.gradle

buildscript {
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.1' 
        // Versions: http://jcenter.bintray.com/com/android/tools/build/gradle/
    }
    ...
}

Module specific build.gradle - /app/build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    ...
    useLibrary 'org.apache.http.legacy'
    ...
}

How to change the font on the TextView?

It's a little old, but I improved the class CustomFontLoader a little bit and I wanted to share it so it can be helpfull. Just create a new class with this code.

 import android.content.Context;
 import android.graphics.Typeface;

public enum FontLoader {

ARIAL("arial"),
TIMES("times"),
VERDANA("verdana"),
TREBUCHET("trbuchet"),
GEORGIA("georgia"),
GENEVA("geneva"),
SANS("sans"),
COURIER("courier"),
TAHOMA("tahoma"),
LUCIDA("lucida");   


private final String name;
private Typeface typeFace;


private FontLoader(final String name) {
    this.name = name;

    typeFace=null;  
}

public static Typeface getTypeFace(Context context,String name){
    try {
        FontLoader item=FontLoader.valueOf(name.toUpperCase(Locale.getDefault()));
        if(item.typeFace==null){                
            item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");                 
        }           
        return item.typeFace;
    } catch (Exception e) {         
        return null;
    }                   
}
public static Typeface getTypeFace(Context context,int id){
    FontLoader myArray[]= FontLoader.values();
    if(!(id<myArray.length)){           
        return null;
    } 
    try {
        if(myArray[id].typeFace==null){     
            myArray[id].typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+myArray[id].name+".ttf");                       
        }       
        return myArray[id].typeFace;    
    }catch (Exception e) {          
        return null;
    }   

}

public static Typeface getTypeFaceByName(Context context,String name){      
    for(FontLoader item: FontLoader.values()){              
        if(name.equalsIgnoreCase(item.name)){
            if(item.typeFace==null){
                try{
                    item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");     
                }catch (Exception e) {          
                    return null;
                }   
            }
            return item.typeFace;
        }               
    }
    return null;
}   

public static void loadAllFonts(Context context){       
    for(FontLoader item: FontLoader.values()){              
        if(item.typeFace==null){
            try{
                item.typeFace=Typeface.createFromAsset(context.getAssets(), "fonts/"+item.name+".ttf");     
            }catch (Exception e) {
                item.typeFace=null;
            }   
        }                
    }       
}   
}

Then just use this code on you textview:

 Typeface typeFace=FontLoader.getTypeFace(context,"arial");  
 if(typeFace!=null) myTextView.setTypeface(typeFace);

How to set image to UIImage

UIImage *img = [UIImage imageNamed:@"anyImageName"];

imageNamed:
Returns the image object associated with the specified filename.

    + (UIImage *)imageNamed:(NSString *)name

Parameters
name
The name of the file. If this is the first time the image is being loaded, the method looks for an image with the specified name in the application’s main bundle.
Return Value
The image object for the specified file, or nil if the method could not find the specified image.

Discussion
This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.

php_network_getaddresses: getaddrinfo failed: Name or service not known

Try to set ENV PATH. Add PHP path in to ENV PATH.

In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libeay32.dll

http://php.net/manual/en/openssl.installation.php

Why is System.Web.Mvc not listed in Add References?

Best way is to use NuGet package manager.

Just update the below MVC package and it should work.

enter image description here

finding and replacing elements in a list

a = [1,2,3,4,5,1,2,3,4,5,1,12]
for i in range (len(a)):
    if a[i]==2:
        a[i]=123

You can use a for and or while loop; however if u know the builtin Enumerate function, then it is recommended to use Enumerate.1

Django: save() vs update() to update the database?

Both looks similar, but there are some key points:

  1. save() will trigger any overridden Model.save() method, but update() will not trigger this and make a direct update on the database level. So if you have some models with overridden save methods, you must either avoid using update or find another way to do whatever you are doing on that overridden save() methods.

  2. obj.save() may have some side effects if you are not careful. You retrieve the object with get(...) and all model field values are passed to your obj. When you call obj.save(), django will save the current object state to record. So if some changes happens between get() and save() by some other process, then those changes will be lost. use save(update_fields=[.....]) for avoiding such problems.

  3. Before Django version 1.5, Django was executing a SELECT before INSERT/UPDATE, so it costs 2 query execution. With version 1.5, that method is deprecated.

In here, there is a good guide or save() and update() methods and how they are executed.

PHP Fatal error: Cannot access empty property

You access the property in the wrong way. With the $this->$my_value = .. syntax, you set the property with the name of the value in $my_value. What you want is $this->my_value = ..

$var = "my_value";
$this->$var = "test";

is the same as

$this->my_value = "test";

To fix a few things from your example, the code below is a better aproach

class my_class {

    public  $my_value = array();

    function __construct ($value) {
        $this->my_value[] = $value;
    }

    function set_value ($value) {
        if (!is_array($value)) {
            throw new Exception("Illegal argument");
        }

        $this->my_value = $value;
    }

    function add_value($value) {
        $this->my_value = $value;
    }
}

$a = new my_class ('a');
$a->my_value[] = 'b';
$a->add_value('c');
$a->set_value(array('d'));

This ensures, that my_value won't change it's type to string or something else when you call set_value. But you can still set the value of my_value direct, because it's public. The final step is, to make my_value private and only access my_value over getter/setter methods

A project with an Output Type of Class Library cannot be started directly

Your project type is a class library one would suspect, add a ConsoleApplication or WindowsApplication and use that as your startup object. Reference this project and then access the code.

Add Marker function with Google Maps API

THis is other method
You can also use setCenter method with add new marker

check below code

$('#my_map').gmap3({
      action: 'setCenter',
      map:{
         options:{
          zoom: 10
         }
      },
      marker:{
         values:
          [
            {latLng:[position.coords.latitude, position.coords.longitude], data:"Netherlands !"}
          ]
      }
   });

How to convert Json array to list of objects in c#

This is possible too:

using System.Web.Helpers;
var listOfObjectsResult = Json.Decode<List<DataType>>(JsonData);

React.js inline style best practices

I usually have scss file associated to each React component. But, I don't see reason why you wouldn't encapsulate the component with logic and look in it. I mean, you have similar thing with web components.

GIT commit as different user without email / or only email

An alternative if the concern is to hide the real email address...If you are committing to Github you don't need a real email you can use <username>@users.noreply.github.com

Regardless of using Github or not, you probably first want change your committer details (on windows use SET GIT_...)

GIT_COMMITTER_NAME='username' 
GIT_COMMITTER_EMAIL='[email protected]'

Then set the author

git commit --author="username <[email protected]>"

https://help.github.com/articles/keeping-your-email-address-private

How can I print message in Makefile?

$(info your_text) : Information. This doesn't stop the execution.

$(warning your_text) : Warning. This shows the text as a warning.

$(error your_text) : Fatal Error. This will stop the execution.

.htaccess - how to force "www." in a generic way?

This is an older question, and there are many different ways to do this. The most complete answer, IMHO, is found here: https://gist.github.com/vielhuber/f2c6bdd1ed9024023fe4 . (Pasting and formatting the code here didn't work for me)

Check if a string matches a regex in Bash script

I would use expr match instead of =~:

expr match "$date" "[0-9]\{8\}" >/dev/null && echo yes

This is better than the currently accepted answer of using =~ because =~ will also match empty strings, which IMHO it shouldn't. Suppose badvar is not defined, then [[ "1234" =~ "$badvar" ]]; echo $? gives (incorrectly) 0, while expr match "1234" "$badvar" >/dev/null ; echo $? gives correct result 1.

We have to use >/dev/null to hide expr match's output value, which is the number of characters matched or 0 if no match found. Note its output value is different from its exit status. The exit status is 0 if there's a match found, or 1 otherwise.

Generally, the syntax for expr is:

expr match "$string" "$lead"

Or:

expr "$string" : "$lead"

where $lead is a regular expression. Its exit status will be true (0) if lead matches the leading slice of string (Is there a name for this?). For example expr match "abcdefghi" "abc"exits true, but expr match "abcdefghi" "bcd" exits false. (Credit to @Carlo Wood for pointing out this.

What does the term "canonical form" or "canonical representation" in Java mean?

The word "canonical" is just a synonym for "standard" or "usual". It doesn`t have any Java-specific meaning.

Iterator Loop vs index loop

The special thing about iterators is that they provide the glue between algorithms and containers. For generic code, the recommendation would be to use a combination of STL algorithms (e.g. find, sort, remove, copy) etc. that carries out the computation that you have in mind on your data structure (vector, list, map etc.), and to supply that algorithm with iterators into your container.

Your particular example could be written as a combination of the for_each algorithm and the vector container (see option 3) below), but it's only one out of four distinct ways to iterate over a std::vector:

1) index-based iteration

for (std::size_t i = 0; i != v.size(); ++i) {
    // access element as v[i]

    // any code including continue, break, return
}

Advantages: familiar to anyone familiar with C-style code, can loop using different strides (e.g. i += 2).

Disadvantages: only for sequential random access containers (vector, array, deque), doesn't work for list, forward_list or the associative containers. Also the loop control is a little verbose (init, check, increment). People need to be aware of the 0-based indexing in C++.

2) iterator-based iteration

for (auto it = v.begin(); it != v.end(); ++it) {
    // if the current index is needed:
    auto i = std::distance(v.begin(), it); 

    // access element as *it

    // any code including continue, break, return
}

Advantages: more generic, works for all containers (even the new unordered associative containers, can also use different strides (e.g. std::advance(it, 2));

Disadvantages: need extra work to get the index of the current element (could be O(N) for list or forward_list). Again, the loop control is a little verbose (init, check, increment).

3) STL for_each algorithm + lambda

std::for_each(v.begin(), v.end(), [](T const& elem) {
     // if the current index is needed:
     auto i = &elem - &v[0];

     // cannot continue, break or return out of the loop
});

Advantages: same as 2) plus small reduction in loop control (no check and increment), this can greatly reduce your bug rate (wrong init, check or increment, off-by-one errors).

Disadvantages: same as explicit iterator-loop plus restricted possibilities for flow control in the loop (cannot use continue, break or return) and no option for different strides (unless you use an iterator adapter that overloads operator++).

4) range-for loop

for (auto& elem: v) {
     // if the current index is needed:
     auto i = &elem - &v[0];

    // any code including continue, break, return
}

Advantages: very compact loop control, direct access to the current element.

Disadvantages: extra statement to get the index. Cannot use different strides.

What to use?

For your particular example of iterating over std::vector: if you really need the index (e.g. access the previous or next element, printing/logging the index inside the loop etc.) or you need a stride different than 1, then I would go for the explicitly indexed-loop, otherwise I'd go for the range-for loop.

For generic algorithms on generic containers I'd go for the explicit iterator loop unless the code contained no flow control inside the loop and needed stride 1, in which case I'd go for the STL for_each + a lambda.

Spring Boot @autowired does not work, classes in different package

By default, in Spring boot applications, component scan is done inside the package where your main class resides. any bean which is outside the package will not the created and thus gives the above mentioned exception.

Solution: you could either move the beans to the main spring boot class(which is not a good approach) or create a seperate configutation file and import it:

@Import({CustomConfigutation1.class, CustomConfiguration2.class})
@SpringBootpplication
public class BirthdayApplication {

public static void main(String [] args) {
    springApplication.run(BirthdayApplication.class, args );
}

}

Add beans to these CustomConfiguration files.

Count number of occurrences for each unique value

If i am understanding your question, would this work? (you will have to replace with your actual column and table names)

SELECT time_col, COUNT(time_col) As Count
FROM time_table
GROUP BY time_col
WHERE activity_col = 3

How to change a package name in Eclipse?

com.myCompany.executabe is the path of executabe package. Here com,myCompany,executable are three different package. You have to manually rename individual package name you want to change.

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

I was getting this error when I tried to checkout new branch:

error: pathspec 'BRANCH-NAME' did not match any file(s) known to git.

When I tried git checkout origin/<BRANCH-NAME>, I got the detached HEAD:

(detached from origin/)

Finally, I did the following to resolve the issue:

git remote update
git fetch 
git checkout --track origin/<BRANCH-NAME>

Find if current time falls in a time range

You're very close, the problem is you're comparing a DateTime to a TimeOfDay. What you need to do is add the .TimeOfDay property to the end of your Convert.ToDateTime() functions.

Does Typescript support the ?. operator? (And, what's it called?)

As answered before, it's currently still being considered but it has been dead in the water for a few years by now.

Building on the existing answers, here's the most concise manual version I can think of:

jsfiddle

function val<T>(valueSupplier: () => T): T {
  try { return valueSupplier(); } catch (err) { return undefined; }
}

let obj1: { a?: { b?: string }} = { a: { b: 'c' } };
console.log(val(() => obj1.a.b)); // 'c'

obj1 = { a: {} };
console.log(val(() => obj1.a.b)); // undefined
console.log(val(() => obj1.a.b) || 'Nothing'); // 'Nothing'

obj1 = {};
console.log(val(() => obj1.a.b) || 'Nothing'); // 'Nothing'

obj1 = null;
console.log(val(() => obj1.a.b) || 'Nothing'); // 'Nothing'

It simply silently fails on missing property errors. It falls back to the standard syntax for determining default value, which can be omitted completely as well.


Although this works for simple cases, if you need more complex stuff such as calling a function and then access a property on the result, then any other errors are swallowed as well. Bad design.

In the above case, an optimized version of the other answer posted here is the better option:

jsfiddle

function o<T>(obj?: T, def: T = {} as T): T {
    return obj || def;
}

let obj1: { a?: { b?: string }} = { a: { b: 'c' } };
console.log(o(o(o(obj1).a)).b); // 'c'

obj1 = { a: {} };
console.log(o(o(o(obj1).a)).b); // undefined
console.log(o(o(o(obj1).a)).b || 'Nothing'); // 'Nothing'

obj1 = {};
console.log(o(o(o(obj1).a)).b || 'Nothing'); // 'Nothing'

obj1 = null;
console.log(o(o(o(obj1).a)).b || 'Nothing'); // 'Nothing'

A more complex example:

o(foo(), []).map((n) => n.id)

You can also go the other way and use something like Lodash' _.get(). It is concise, but the compiler won't be able to judge the validity of the properties used:

console.log(_.get(obj1, 'a.b.c'));

check if a number already exist in a list in python

You could probably use a set object instead. Just add numbers to the set. They inherently do not replicate.

Angular cli generate a service and include the provider in one step

Angular 6+ Singleton Services

The recommended approach for a singleton service for Angular 6 and beyond is :

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

@Injectable({
  providedIn: 'root',
})
export class UserService {
}

In fact the CLI --module switch doesn't even exist any more for registering a service at the app level because it doesn't need to modify app.module.ts anymore.

This will create the above code, without needing to specify a module.

ng g s services/user

So if you don't want your service to be a singleton you must remove the providedIn code yourself - and then add it manually to providers for a component or lazy loaded module. Doesn't look like there is currently a switch to not generate the providedIn: 'root' part so you need to manually remove it.

Could not load file or assembly '' or one of its dependencies

Another possible cause: make sure you haven't accidentally given both of the projects the same assembly name in project properties.

Scala list concatenation, ::: vs ++

Legacy. List was originally defined to be functional-languages-looking:

1 :: 2 :: Nil // a list
list1 ::: list2  // concatenation of two lists

list match {
  case head :: tail => "non-empty"
  case Nil          => "empty"
}

Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use ++ to concatenate any two collections -- and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.

Storing sex (gender) in database

I'd call the column "gender".

Data Type   Bytes Taken          Number/Range of Values
------------------------------------------------
TinyINT     1                    255 (zero to 255)
INT         4            -       2,147,483,648 to 2,147,483,647
BIT         1 (2 if 9+ columns)  2 (0 and 1)
CHAR(1)     1                    26 if case insensitive, 52 otherwise

The BIT data type can be ruled out because it only supports two possible genders which is inadequate. While INT supports more than two options, it takes 4 bytes -- performance will be better with a smaller/more narrow data type.

CHAR(1) has the edge over TinyINT - both take the same number of bytes, but CHAR provides a more narrow number of values. Using CHAR(1) would make using "m", "f",etc natural keys, vs the use of numeric data which are referred to as surrogate/artificial keys. CHAR(1) is also supported on any database, should there be a need to port.

Conclusion

I would use Option 2: CHAR(1).

Addendum

An index on the gender column likely would not help because there's no value in an index on a low cardinality column. Meaning, there's not enough variety in the values for the index to provide any value.

Why is Dictionary preferred over Hashtable in C#?

HashTable:

Key/value will be converted into an object (boxing) type while storing into the heap.

Key/value needs to be converted into the desired type while reading from the heap.

These operations are very costly. We need to avoid boxing/unboxing as much as possible.

Dictionary : Generic variant of HashTable.

No boxing/unboxing. No conversions required.

javascript close current window

I found this method by Jeff Clayton. It is working for me with Firefox 56 and Chrome (on Windows and Android).

Did not try all possibilities. On my side, I open a window with a target name in my A links, for example, target="mywindowname", so all my links open inside the same window name: mywindowname.

To open a new window:

<a href="example-link.html" target="mywindowname">New Window</a>

And then in the new window (inside example-link.html):

<a href="#" onclick="return quitBox('quit');"></a>

Javascript:

function quitBox(cmd) {   
    if (cmd=='quit') {
        open(location, '_self').close();
    }   
    return false;   
}

Hope this can help anyone else that is looking for a method to close a window. I tried a lot of other methods and this one is the best I found.

Why is access to the path denied?

First just check the path if the colon(:) character is missing or not after the drive letter. If colon is not missing then you can check if access/write permission is granted for that path. I had the same issue and i was only missing the colon, permission and everything else was fine.

C:\folderpath

will work fine but,

C\folderpath .........(missing colon)

will give you access denial error.

access key and value of object using *ngFor

Use index:

<div *ngFor="let value of Objects; index as key">

Usage:

{{key}} -> {{value}}

pip not working in Python Installation in Windows 10

instead of typing in "python". try using "py". for ex:

py -m pip install    packagename
py -m pip --install  packagename
py -m pip --upgrade  packagename
py -m pip upgrade    packagename

note: this should be done in the command prompt "cmd" and not in python idle. also FYI pip is installed with python 3.6 automatically.

Error: Cannot match any routes. URL Segment: - Angular 2

please modify your router.module.ts as:

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [
        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree',
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        },
        {
           path: '',
           redirectTo: 'two',
           pathMatch: 'full'
        }
    ]
},];

and in your component1.html

<h3>In One</h3>

<nav>
    <a routerLink="/two" class="dash-item">...Go to Two...</a>
    <a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
    <a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>

<router-outlet></router-outlet>                   // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet>  // Error: Cannot match any routes. URL Segment: 'three'

How to safely open/close files in python 2.4

In the above solution, repeated here:

f = open('file.txt', 'r')

try:
    # do stuff with f
finally:
   f.close()

if something bad happens (you never know ...) after opening the file successfully and before the try, the file will not be closed, so a safer solution is:

f = None
try:
    f = open('file.txt', 'r')

    # do stuff with f

finally:
    if f is not None:
       f.close()

XOR operation with two strings in java

the abs function is when the Strings are not the same length so the legth of the result will be the same as the min lenght of the two String a and b

public String xor(String a, String b){
    StringBuilder sb = new StringBuilder();
    for(int k=0; k < a.length(); k++)
       sb.append((a.charAt(k) ^ b.charAt(k + (Math.abs(a.length() - b.length()))))) ;
       return sb.toString();
}

How to make an AlertDialog in Flutter?

Here is a shorter, but complete code.

If you need a dialog with only one button:

await showDialog(
      context: context,
      builder: (context) => new AlertDialog(
        title: new Text('Message'),
        content: Text(
                'Your file is saved.'),
        actions: <Widget>[
          new FlatButton(
            onPressed: () {
              Navigator.of(context, rootNavigator: true)
                  .pop(); // dismisses only the dialog and returns nothing
            },
            child: new Text('OK'),
          ),
        ],
      ),
    );

If you need a dialog with Yes/No buttons:

onPressed: () async {
bool result = await showDialog(
  context: context,
  builder: (context) {
    return AlertDialog(
      title: Text('Confirmation'),
      content: Text('Do you want to save?'),
      actions: <Widget>[
        new FlatButton(
          onPressed: () {
            Navigator.of(context, rootNavigator: true)
                .pop(false); // dismisses only the dialog and returns false
          },
          child: Text('No'),
        ),
        FlatButton(
          onPressed: () {
            Navigator.of(context, rootNavigator: true)
                .pop(true); // dismisses only the dialog and returns true
          },
          child: Text('Yes'),
        ),
      ],
    );
  },
);

if (result) {
  if (missingvalue) {
    Scaffold.of(context).showSnackBar(new SnackBar(
      content: new Text('Missing Value'),
    ));
  } else {
    saveObject();
    Navigator.of(context).pop(_myObject); // dismisses the entire widget
  }
} else {
  Navigator.of(context).pop(_myObject); // dismisses the entire widget
}
}

What is meant by immutable?

Actually String is not immutable if you use the wikipedia definition suggested above.

String's state does change post construction. Take a look at the hashcode() method. String caches the hashcode value in a local field but does not calculate it until the first call of hashcode(). This lazy evaluation of hashcode places String in an interesting position as an immutable object whose state changes, but it cannot be observed to have changed without using reflection.

So maybe the definition of immutable should be an object that cannot be observed to have changed.

If the state changes in an immutable object after it has been created but no-one can see it (without reflection) is the object still immutable?

Go install fails with error: no install location for directory xxx outside GOPATH

In windows, my cmd window was already open when I set the GOPATH environment variable. First I had to close the cmd and then reopen for it to become effective.

Mongoimport of json file

this will work:

$  mongoimport --db databaseName --collection collectionName --file filePath/jsonFile.json 

2021-01-09T11:13:57.410+0530 connected to: mongodb://localhost/ 2021-01-09T11:13:58.176+0530 1 document(s) imported successfully. 0 document(s) failed to import.

Above I shared the query along with its response

How to make PyCharm always show line numbers

PyCharm Version 3.4.1(For all files in the project):

File -> Preferences -> Editor (IDE Settings) -> Appearance -> mark 'Show line numbers'

PyCharm Version 3.4.1(only for existing file in the project):

View -> Active Editor -> Show Line Numbers

image

Javascript/jQuery detect if input is focused

Using jQuery's .is( ":focus" )

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }

Read and write a text file in typescript

import * as fs from 'fs';
import * as path from 'path';

fs.readFile(path.join(__dirname, "filename.txt"), (err, data) => {
    if (err) throw err;
    console.log(data);
})

EDIT:

consider the project structure:

../readfile/
+-- filename.txt
+-- src
    +-- index.js
    +-- index.ts

consider the index.ts:

import * as fs from 'fs';
import * as path from 'path';

function lookFilesInDirectory(path_directory) {
    fs.stat(path_directory, (err, stat) => {
        if (!err) {
            if (stat.isDirectory()) {
                console.log(path_directory)
                fs.readdirSync(path_directory).forEach(file => {
                    console.log(`\t${file}`);
                });
                console.log();
            }
        }
    });
}

let path_view = './';
lookFilesInDirectory(path_view);
lookFilesInDirectory(path.join(__dirname, path_view));

if you have in the readfile folder and run tsc src/index.ts && node src/index.js, the output will be:

./
        filename.txt
        src

/home/andrei/scripts/readfile/src/
        index.js
        index.ts

that is, it depends on where you run the node.

the __dirname is directory name of the current module.

git - Server host key not cached

I too had the same issue when I was trying to clone a repository on my Windows 7 machine. I tried most of the answers mentioned here. None of them worked for me.

What worked for me was, running the Pageant (Putty authentication agent) program. Once the Pageant was running in the background I was able to clone, push & pull from/to the repository. This worked for me, may be because I've setup my public key such that whenever it is used for the first time a password is required & the Pageant starts up.

Connect to Active Directory via LDAP

ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.

OU=Your_OU,OU=other_ou,dc=example,dc=com

You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain

Now i miss a parameter to authenticate, this works the same as the path for the username

CN=username,OU=users,DC=example,DC=com

Introduction to LDAP

How to use relative paths without including the context root name?

This is a derivative of @Ralph suggestion that I've been using. Add the c:url to the top of your JSP.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:url value="/" var="root" />

Then just reference the root variable in your page:

<link rel="stylesheet" href="${root}templates/style/main.css">

SQL Server : Transpose rows to columns

One way to do it if tagID values are known upfront is to use conditional aggregation

SELECT TimeSeconds,
       COALESCE(MAX(CASE WHEN TagID = 'A1' THEN Value END), 'n/a') A1,
       COALESCE(MAX(CASE WHEN TagID = 'A2' THEN Value END), 'n/a') A2,
       COALESCE(MAX(CASE WHEN TagID = 'A3' THEN Value END), 'n/a') A3,
       COALESCE(MAX(CASE WHEN TagID = 'A4' THEN Value END), 'n/a') A4
  FROM table1
 GROUP BY TimeSeconds

or if you're OK with NULL values instead of 'n/a'

SELECT TimeSeconds,
       MAX(CASE WHEN TagID = 'A1' THEN Value END) A1,
       MAX(CASE WHEN TagID = 'A2' THEN Value END) A2,
       MAX(CASE WHEN TagID = 'A3' THEN Value END) A3,
       MAX(CASE WHEN TagID = 'A4' THEN Value END) A4
  FROM table1
 GROUP BY TimeSeconds

or with PIVOT

SELECT TimeSeconds, A1, A2, A3, A4
  FROM
(
  SELECT TimeSeconds, TagID, Value
    FROM table1
) s
PIVOT
(
  MAX(Value) FOR TagID IN (A1, A2, A3, A4)
) p

Output (with NULLs):

TimeSeconds A1      A2     A3    A4
----------- ------- ------ ----- -----
1378700244  3.75    NULL   NULL  NULL
1378700245  30.00   NULL   NULL  NULL
1378700304  1.20    NULL   NULL  NULL
1378700305  NULL    56.00  NULL  NULL
1378700344  NULL    11.00  NULL  NULL
1378700345  NULL    NULL   0.53  NULL
1378700364  4.00    NULL   NULL  NULL
1378700365  14.50   NULL   NULL  NULL
1378700384  144.00  NULL   NULL  10.00

If you have to figure TagID values out dynamically then use dynamic SQL

DECLARE @cols NVARCHAR(MAX), @sql NVARCHAR(MAX)

SET @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(TagID)
            FROM Table1
            ORDER BY 1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'),1,1,'')

SET @sql = 'SELECT TimeSeconds, ' + @cols + '
              FROM
            (
              SELECT TimeSeconds, TagID, Value
                FROM table1
            ) s
            PIVOT
            (
              MAX(Value) FOR TagID IN (' + @cols + ')
            ) p'

EXECUTE(@sql)

Adding an onclicklistener to listview (android)

You are doing

Object o = prestListView.getItemAtPosition(position);
String str=(String)o;//As you are using Default String Adapter

The o that you get back is not a String, but a prestationEco so you get a CCE when doing the (String)o

How to create a thread?

The following ways work.

// The old way of using ParameterizedThreadStart. This requires a
// method which takes ONE object as the parameter so you need to
// encapsulate the parameters inside one object.
Thread t = new Thread(new ParameterizedThreadStart(StartupA));
t.Start(new MyThreadParams(path, port));

// You can also use an anonymous delegate to do this.
Thread t2 = new Thread(delegate()
{
    StartupB(port, path);
});
t2.Start();

// Or lambda expressions if you are using C# 3.0
Thread t3 = new Thread(() => StartupB(port, path));
t3.Start();

The Startup methods have following signature for these examples.

public void StartupA(object parameters);

public void StartupB(int port, string path);

Flash CS4 refuses to let go

Do you have several swf-files? If your class is imported in one of the swf's, other swf's will also use the same version of the class. One old import with * in one swf will do it. Recompile everything and see if it works.

What is the difference between AF_INET and PF_INET in socket programming?

AF_INET = Address Format, Internet = IP Addresses

PF_INET = Packet Format, Internet = IP, TCP/IP or UDP/IP

AF_INET is the address family that is used for the socket you're creating (in this case an Internet Protocol address). The Linux kernel, for example, supports 29 other address families such as UNIX sockets and IPX, and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).

For the most part sticking with AF_INET for socket programming over a network is the safest option.

Meaning, AF_INET refers to addresses from the internet, IP addresses specifically.

PF_INET refers to anything in the protocol, usually sockets/ports.

Regular expression include and exclude special characters

[a-zA-Z0-9~@#\^\$&\*\(\)-_\+=\[\]\{\}\|\\,\.\?\s]*

This would do the matching, if you only want to allow that just wrap it in ^$ or any other delimiters that you see appropriate, if you do this no specific disallow logic is needed.

Resolving a Git conflict with binary files

I came across a similar problem (wanting to pull a commit that included some binary files which caused conflicts when merged), but came across a different solution that can be done entirely using git (i.e. not having to manually copy files over). I figured I'd include it here so at the very least I can remember it the next time I need it. :) The steps look like this:

% git fetch

This fetches the latest commit(s) from the remote repository (you may need to specify a remote branch name, depending on your setup), but doesn't try to merge them. It records the the commit in FETCH_HEAD

% git checkout FETCH_HEAD stuff/to/update

This takes the copy of the binary files I want and overwrites what's in the working tree with the version fetched from the remote branch. git doesn't try to do any merging, so you just end up with an exact copy of the binary file from the remote branch. Once that's done, you can add/commit the new copy just like normal.

HashMap to return default value for non-found keys?

/**
 * Extension of TreeMap to provide default value getter/creator.
 * 
 * NOTE: This class performs no null key or value checking.
 * 
 * @author N David Brown
 *
 * @param <K>   Key type
 * @param <V>   Value type
 */
public abstract class Hash<K, V> extends TreeMap<K, V> {

    private static final long serialVersionUID = 1905150272531272505L;

    /**
     * Same as {@link #get(Object)} but first stores result of
     * {@link #create(Object)} under given key if key doesn't exist.
     * 
     * @param k
     * @return
     */
    public V getOrCreate(final K k) {
        V v = get(k);
        if (v == null) {
            v = create(k);
            put(k, v);
        }
        return v;
    }

    /**
     * Same as {@link #get(Object)} but returns specified default value
     * if key doesn't exist. Note that default value isn't automatically
     * stored under the given key.
     * 
     * @param k
     * @param _default
     * @return
     */
    public V getDefault(final K k, final V _default) {
        V v = get(k);
        return v == null ? _default : v;
    }

    /**
     * Creates a default value for the specified key.
     * 
     * @param k
     * @return
     */
    abstract protected V create(final K k);
}

Example Usage:

protected class HashList extends Hash<String, ArrayList<String>> {
    private static final long serialVersionUID = 6658900478219817746L;

    @Override
        public ArrayList<Short> create(Short key) {
            return new ArrayList<Short>();
        }
}

final HashList haystack = new HashList();
final String needle = "hide and";
haystack.getOrCreate(needle).add("seek")
System.out.println(haystack.get(needle).get(0));

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

These are utf-8 encoded characters. Use utf8_decode() to convert them to normal ISO-8859-1 characters.

IPhone/IPad: How to get screen width programmatically?

As of iOS 9.0 there's no way to get the orientation reliably. This is the code I used for an app I design for only portrait mode, so if the app is opened in landscape mode it will still be accurate:

screenHeight = [[UIScreen mainScreen] bounds].size.height;
screenWidth = [[UIScreen mainScreen] bounds].size.width;
if (screenWidth > screenHeight) {
    float tempHeight = screenWidth;
    screenWidth = screenHeight;
    screenHeight = tempHeight;
}

Find methods calls in Eclipse project

Go to the method in X.java, and select Open Call Hierarchy from the context menu.

Accessing UI (Main) Thread safely in WPF

The best way to go about it would be to get a SynchronizationContext from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher directly). For example:

class MyViewModel
{
    private readonly SynchronizationContext _syncContext;

    public MyViewModel()
    {
        // we assume this ctor is called from the UI thread!
        _syncContext = SynchronizationContext.Current;
    }

    // ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
         _syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
    }
}

What is the fastest way to send 100,000 HTTP requests in Python?

Consider using Windmill , although Windmill probably cant do that many threads.

You could do it with a hand rolled Python script on 5 machines, each one connecting outbound using ports 40000-60000, opening 100,000 port connections.

Also, it might help to do a sample test with a nicely threaded QA app such as OpenSTA in order to get an idea of how much each server can handle.

Also, try looking into just using simple Perl with the LWP::ConnCache class. You'll probably get more performance (more connections) that way.

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

This can be done with a single dict comprehension:

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> { key: y[key] if key in y else x[key]
      for key in set(x) + set(y)
    }

In my view the best answer for the 'single expression' part as no extra functions are needed, and it is short.

How to convert image into byte array and byte array to base64 String in android?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Get current value when change select option - Angular2

Template:

<select class="randomClass" id="randomId" (change) = 
"filterSelected($event.target.value)">

<option *ngFor = 'let type of filterTypes' [value]='type.value'>{{type.display}} 
</option>

</select>

Component:

public filterTypes = [{
  value : 'New', display : 'Open'
},
{
  value : 'Closed', display : 'Closed'
}]


filterSelected(selectedValue:string){
  console.log('selected value= '+selectedValue)

}

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.

Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.

This is the same question as Failed to connect to mailserver at "localhost" port 25

also check this php mail function not working

Lock screen orientation (Android)

In the Manifest, you can set the screenOrientation to landscape. It would look something like this in the XML:

<activity android:name="MyActivity"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize">
...
</activity>

Where MyActivity is the one you want to stay in landscape.

The android:configChanges=... line prevents onResume(), onPause() from being called when the screen is rotated. Without this line, the rotation will stay as you requested but the calls will still be made.

Note: keyboardHidden and orientation are required for < Android 3.2 (API level 13), and all three options are required 3.2 or above, not just orientation.

Remove/ truncate leading zeros by javascript/jquery

You can use a regular expression that matches zeroes at the beginning of the string:

s = s.replace(/^0+/, '');

How would I run an async Task<T> method synchronously?

I have found that SpinWait works pretty well for this.

var task = Task.Run(()=>DoSomethingAsyncronous());

if(!SpinWait.SpinUntil(()=>task.IsComplete, TimeSpan.FromSeconds(30)))
{//Task didn't complete within 30 seconds, fail...
   return false;
}

return true;

The above approach doesn't need to use .Result or .Wait(). It also lets you specify a timeout so that you're not stuck forever in case the task never completes.

How do I check if a string is a number (float)?

Sorry for the Zombie thread post - just wanted to round out the code for completeness...

# is_number() function - Uses re = regex library
# Should handle all normal and complex numbers
# Does not accept trailing spaces. 
# Note: accepts both engineering "j" and math "i" but only the imaginary part "+bi" of a complex number a+bi
# Also accepts inf or NaN
# Thanks to the earlier responders for most the regex fu

import re

ISNUM_REGEXP = re.compile(r'^[-+]?([0-9]+|[0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?[ij]?$')

def is_number(str):
#change order if you have a lot of NaN or inf to parse
    if ISNUM_REGEXP.match(str) or str == "NaN" or str == "inf": 
        return True 
    else:
        return False
# A couple test numbers
# +42.42e-42j
# -42.42E+42i

print('Is it a number?', is_number(input('Gimme any number: ')))

Gimme any number: +42.42e-42j

Is it a number? True

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!! use close(fd) system call after you finished working on a file.

iOS app 'The application could not be verified' only on one device

Working & tested solution, which does not require to delete application:

It looks like AppStore Distribution Provisioning Profile or just iOS Distribution certificate have special permissions and "Could not be verified..." problem does not apply to them. They will always override previous certificate.

In other words: AppStore release will install successfully, even if already installed (testing, adhoc or enterprise) app has been signed by the certificate from different team.

If you are lucky and have previously uploaded app to the AppStore account owned by the same team as in certificate you have a problem with - then things are very simple: just download & install app from AppStore.

When it installs - app certificate will be the same as the one you want to test with and problem goes away.

If your app is not on the AppStore yet - iTunesConnect beta comes to the rescue:

Disclaimer: I did not tested this but since cert an prev are the same as AppStore release, I bet it works:

  1. Archive your app with AppStore provisioning profile (iOS Distribution cert) and upload to iTunesConnect (to the account owned by the same developer team as included in the provisioning profile not you want to run).
  2. Invite person with the device you want to run on (yourself?) to beta test.
  3. Download & install the app from iTunes connect beta.
  4. Now you are able to install your testing version.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

To inject an Object, its class must be known to the CDI mechanism. Usualy adding the @Named annotation will do the trick.

Remove and Replace Printed items

One way is to use ANSI escape sequences:

import sys
import time
for i in range(10):
    print("Loading" + "." * i)
    sys.stdout.write("\033[F") # Cursor up one line
    time.sleep(1)

Also sometimes useful (for example if you print something shorter than before):

sys.stdout.write("\033[K") # Clear to the end of line

How to track down access violation "at address 00000000"

Here is a real quick temporary fix, at least until you reboot again but it will get rid of a persistent access. I had installed a program that works fine but for some reason, there is a point that did not install correctly in the right file. So when it cannot access the file, it pops up the access denied but instead of just one, it keeps trying to start it up so even searching for the location to stop it permanently, it will continue to pop up more and more and more every 3 seconds. To stop that from happening at least temporarily, do the following...

  1. Ctl+Alt+Del
  2. Open your Task Manager
  3. Note down the name of the program that's requesting access (you may see it in your application's tab)
  4. Click on your Processes tab
  5. Scroll through until you find the Process matching the program name and click on it
  6. Click End Process

That will prevent the window from persistently popping up, at least until you reboot. I know that does not solve the problem but like anything, there is a process of elimination and this step here will at least make it a little less annoying.

How do you add an in-app purchase to an iOS application?

Swift Answer

This is meant to supplement my Objective-C answer for Swift users, to keep the Objective-C answer from getting too big.

Setup

First, set up the in-app purchase on appstoreconnect.apple.com. Follow the beginning part of my Objective-C answer (steps 1-13, under the App Store Connect header) for instructions on doing that.

It could take a few hours for your product ID to register in App Store Connect, so be patient.

Now that you've set up your in-app purchase information on App Store Connect, we need to add Apple's framework for in-app-purchases, StoreKit, to the app.

Go into your Xcode project, and go to the application manager (blue page-like icon at the top of the left bar where your app's files are). Click on your app under targets on the left (it should be the first option), then go to "Capabilities" at the top. On the list, you should see an option "In-App Purchase". Turn this capability ON, and Xcode will add StoreKit to your project.

Coding

Now, we're going to start coding!

First, make a new swift file that will manage all of your in-app-purchases. I'm going to call it IAPManager.swift.

In this file, we're going to create a new class, called IAPManager that is a SKProductsRequestDelegate and SKPaymentTransactionObserver. At the top, make sure you import Foundation and StoreKit

import Foundation
import StoreKit

public class IAPManager: NSObject, SKProductsRequestDelegate,
                         SKPaymentTransactionObserver {
}

Next, we're going to add a variable to define the identifier for our in-app purchase (you could also use an enum, which would be easier to maintain if you have multiple IAPs).

// This should the ID of the in-app-purchase you made on AppStore Connect.
// if you have multiple IAPs, you'll need to store their identifiers in
// other variables, too (or, preferably in an enum).
let removeAdsID = "com.skiplit.removeAds"

Let's add an initializer for our class next:

// This is the initializer for your IAPManager class
//
// A better, and more scaleable way of doing this
// is to also accept a callback in the initializer, and call
// that callback in places like the paymentQueue function, and
// in all functions in this class, in place of calls to functions
// in RemoveAdsManager (you'll see those calls in the code below).

let productID: String
init(productID: String){
    self.productID = productID
}

Now, we're going to add the required functions for SKProductsRequestDelegate and SKPaymentTransactionObserver to work:

We'll add the RemoveAdsManager class later

// This is called when a SKProductsRequest receives a response
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse){
    // Let's try to get the first product from the response
    // to the request
    if let product = response.products.first{
        // We were able to get the product! Make a new payment
        // using this product
        let payment = SKPayment(product: product)

        // add the new payment to the queue
        SKPaymentQueue.default().add(self)
        SKPaymentQueue.default().add(payment)
    }
    else{
        // Something went wrong! It is likely that either
        // the user doesn't have internet connection, or
        // your product ID is wrong!
        //
        // Tell the user in requestFailed() by sending an alert,
        // or something of the sort

        RemoveAdsManager.removeAdsFailure()
    }
}

// This is called when the user restores their IAP sucessfully
private func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue){
    // For every transaction in the transaction queue...
    for transaction in queue.transactions{
        // If that transaction was restored
        if transaction.transactionState == .restored{
            // get the producted ID from the transaction
            let productID = transaction.payment.productIdentifier

            // In this case, we have only one IAP, so we don't need to check
            // what IAP it is. However, this is useful if you have multiple IAPs!
            // You'll need to figure out which one was restored
            if(productID.lowercased() == IAPManager.removeAdsID.lowercased()){
                // Restore the user's purchases
                RemoveAdsManager.restoreRemoveAdsSuccess()
            }

            // finish the payment
            SKPaymentQueue.default().finishTransaction(transaction)
        }
    }
}

// This is called when the state of the IAP changes -- from purchasing to purchased, for example.
// This is where the magic happens :)
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]){
    for transaction in transactions{
        // get the producted ID from the transaction
        let productID = transaction.payment.productIdentifier

        // In this case, we have only one IAP, so we don't need to check
        // what IAP it is.
        // However, if you have multiple IAPs, you'll need to use productID
        // to check what functions you should run here!

        switch transaction.transactionState{
        case .purchasing:
            // if the user is currently purchasing the IAP,
            // we don't need to do anything.
            //
            // You could use this to show the user
            // an activity indicator, or something like that
            break
        case .purchased:
            // the user successfully purchased the IAP!
            RemoveAdsManager.removeAdsSuccess()
            SKPaymentQueue.default().finishTransaction(transaction)
        case .restored:
                // the user restored their IAP!
                IAPTestingHandler.restoreRemoveAdsSuccess()
                SKPaymentQueue.default().finishTransaction(transaction)
        case .failed:
                // The transaction failed!
                RemoveAdsManager.removeAdsFailure()
                // finish the transaction
                SKPaymentQueue.default().finishTransaction(transaction)
        case .deferred:
                // This happens when the IAP needs an external action
                // in order to proceeded, like Ask to Buy
                RemoveAdsManager.removeAdsDeferred()
                break
        }
    }
}

Now let's add some functions that can be used to start a purchase or a restore purchases:

// Call this when you want to begin a purchase
// for the productID you gave to the initializer
public func beginPurchase(){
    // If the user can make payments
    if SKPaymentQueue.canMakePayments(){
        // Create a new request
        let request = SKProductsRequest(productIdentifiers: [productID])
        // Set the request delegate to self, so we receive a response
        request.delegate = self
        // start the request
        request.start()
    }
    else{
        // Otherwise, tell the user that
        // they are not authorized to make payments,
        // due to parental controls, etc
    }
}

// Call this when you want to restore all purchases
// regardless of the productID you gave to the initializer
public func beginRestorePurchases(){
    // restore purchases, and give responses to self
    SKPaymentQueue.default().add(self)
    SKPaymentQueue.default().restoreCompletedTransactions()
}

Next, let's add a new utilities class to manage our IAPs. All of this code could be in one class, but having it multiple makes it a little cleaner. I'm going to make a new class called RemoveAdsManager, and in it, put a few functions

public class RemoveAdsManager{

    class func removeAds()
    class func restoreRemoveAds()

    class func areAdsRemoved() -> Bool

    class func removeAdsSuccess()
    class func restoreRemoveAdsSuccess()
    class func removeAdsDeferred()
    class func removeAdsFailure()
}

The first three functions, removeAds, restoreRemoveAds, and areAdsRemoved, are functions that you'll call to do certain actions. The last four are one that will be called by IAPManager.

Let's add some code to the first two functions, removeAds and restoreRemoveAds:

// Call this when the user wants
// to remove ads, like when they
// press a "remove ads" button
class func removeAds(){
    // Before starting the purchase, you could tell the
    // user that their purchase is happening, maybe with
    // an activity indicator

    let iap = IAPManager(productID: IAPManager.removeAdsID)
    iap.beginPurchase()
}

// Call this when the user wants
// to restore their IAP purchases,
// like when they press a "restore
// purchases" button.
class func restoreRemoveAds(){
    // Before starting the purchase, you could tell the
    // user that the restore action is happening, maybe with
    // an activity indicator

    let iap = IAPManager(productID: IAPManager.removeAdsID)
    iap.beginRestorePurchases()
}

And lastly, let's add some code to the last five functions.

// Call this to check whether or not
// ads are removed. You can use the
// result of this to hide or show
// ads
class func areAdsRemoved() -> Bool{
    // This is the code that is run to check
    // if the user has the IAP.

    return UserDefaults.standard.bool(forKey: "RemoveAdsPurchased")
}

// This will be called by IAPManager
// when the user sucessfully purchases
// the IAP
class func removeAdsSuccess(){
    // This is the code that is run to actually
    // give the IAP to the user!
    //
    // I'm using UserDefaults in this example,
    // but you may want to use Keychain,
    // or some other method, as UserDefaults
    // can be modified by users using their
    // computer, if they know how to, more
    // easily than Keychain

    UserDefaults.standard.set(true, forKey: "RemoveAdsPurchased")
    UserDefaults.standard.synchronize()
}

// This will be called by IAPManager
// when the user sucessfully restores
//  their purchases
class func restoreRemoveAdsSuccess(){
    // Give the user their IAP back! Likely all you'll need to
    // do is call the same function you call when a user
    // sucessfully completes their purchase. In this case, removeAdsSuccess()

    removeAdsSuccess()
}

// This will be called by IAPManager
// when the IAP failed
class func removeAdsFailure(){
    // Send the user a message explaining that the IAP
    // failed for some reason, and to try again later
}

// This will be called by IAPManager
// when the IAP gets deferred.
class func removeAdsDeferred(){
    // Send the user a message explaining that the IAP
    // was deferred, and pending an external action, like
    // Ask to Buy.
}

Putting it all together, we get something like this:

import Foundation
import StoreKit

public class RemoveAdsManager{

    // Call this when the user wants
    // to remove ads, like when they
    // press a "remove ads" button
    class func removeAds(){
        // Before starting the purchase, you could tell the
        // user that their purchase is happening, maybe with
        // an activity indicator

        let iap = IAPManager(productID: IAPManager.removeAdsID)
        iap.beginPurchase()
    }

    // Call this when the user wants
    // to restore their IAP purchases,
    // like when they press a "restore
    // purchases" button.
    class func restoreRemoveAds(){
        // Before starting the purchase, you could tell the
        // user that the restore action is happening, maybe with
        // an activity indicator

        let iap = IAPManager(productID: IAPManager.removeAdsID)
        iap.beginRestorePurchases()
    }

    // Call this to check whether or not
    // ads are removed. You can use the
    // result of this to hide or show
    // ads
    class func areAdsRemoved() -> Bool{
        // This is the code that is run to check
        // if the user has the IAP.

        return UserDefaults.standard.bool(forKey: "RemoveAdsPurchased")
    }

    // This will be called by IAPManager
    // when the user sucessfully purchases
    // the IAP
    class func removeAdsSuccess(){
        // This is the code that is run to actually
        // give the IAP to the user!
        //
        // I'm using UserDefaults in this example,
        // but you may want to use Keychain,
        // or some other method, as UserDefaults
        // can be modified by users using their
        // computer, if they know how to, more
        // easily than Keychain

        UserDefaults.standard.set(true, forKey: "RemoveAdsPurchased")
        UserDefaults.standard.synchronize()
    }

    // This will be called by IAPManager
    // when the user sucessfully restores
    //  their purchases
    class func restoreRemoveAdsSuccess(){
        // Give the user their IAP back! Likely all you'll need to
        // do is call the same function you call when a user
        // sucessfully completes their purchase. In this case, removeAdsSuccess()
        removeAdsSuccess()
    }

    // This will be called by IAPManager
    // when the IAP failed
    class func removeAdsFailure(){
        // Send the user a message explaining that the IAP
        // failed for some reason, and to try again later
    }

    // This will be called by IAPManager
    // when the IAP gets deferred.
    class func removeAdsDeferred(){
        // Send the user a message explaining that the IAP
        // was deferred, and pending an external action, like
        // Ask to Buy.
    }

}

public class IAPManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver{

    // This should the ID of the in-app-purchase you made on AppStore Connect.
    // if you have multiple IAPs, you'll need to store their identifiers in
    // other variables, too (or, preferably in an enum).
    static let removeAdsID = "com.skiplit.removeAds"

    // This is the initializer for your IAPManager class
    //
    // An alternative, and more scaleable way of doing this
    // is to also accept a callback in the initializer, and call
    // that callback in places like the paymentQueue function, and
    // in all functions in this class, in place of calls to functions
    // in RemoveAdsManager.
    let productID: String
    init(productID: String){
        self.productID = productID
    }

    // Call this when you want to begin a purchase
    // for the productID you gave to the initializer
    public func beginPurchase(){
        // If the user can make payments
        if SKPaymentQueue.canMakePayments(){
            // Create a new request
            let request = SKProductsRequest(productIdentifiers: [productID])
            request.delegate = self
            request.start()
        }
        else{
            // Otherwise, tell the user that
            // they are not authorized to make payments,
            // due to parental controls, etc
        }
    }

    // Call this when you want to restore all purchases
    // regardless of the productID you gave to the initializer
    public func beginRestorePurchases(){
        SKPaymentQueue.default().add(self)
        SKPaymentQueue.default().restoreCompletedTransactions()
    }

    // This is called when a SKProductsRequest receives a response
    public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse){
        // Let's try to get the first product from the response
        // to the request
        if let product = response.products.first{
            // We were able to get the product! Make a new payment
            // using this product
            let payment = SKPayment(product: product)

            // add the new payment to the queue
            SKPaymentQueue.default().add(self)
            SKPaymentQueue.default().add(payment)
        }
        else{
            // Something went wrong! It is likely that either
            // the user doesn't have internet connection, or
            // your product ID is wrong!
            //
            // Tell the user in requestFailed() by sending an alert,
            // or something of the sort

            RemoveAdsManager.removeAdsFailure()
        }
    }

    // This is called when the user restores their IAP sucessfully
    private func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue){
        // For every transaction in the transaction queue...
        for transaction in queue.transactions{
            // If that transaction was restored
            if transaction.transactionState == .restored{
                // get the producted ID from the transaction
                let productID = transaction.payment.productIdentifier

                // In this case, we have only one IAP, so we don't need to check
                // what IAP it is. However, this is useful if you have multiple IAPs!
                // You'll need to figure out which one was restored
                if(productID.lowercased() == IAPManager.removeAdsID.lowercased()){
                    // Restore the user's purchases
                    RemoveAdsManager.restoreRemoveAdsSuccess()
                }

                // finish the payment
                SKPaymentQueue.default().finishTransaction(transaction)
            }
        }
    }

    // This is called when the state of the IAP changes -- from purchasing to purchased, for example.
    // This is where the magic happens :)
    public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]){
        for transaction in transactions{
            // get the producted ID from the transaction
            let productID = transaction.payment.productIdentifier

            // In this case, we have only one IAP, so we don't need to check
            // what IAP it is.
            // However, if you have multiple IAPs, you'll need to use productID
            // to check what functions you should run here!

            switch transaction.transactionState{
            case .purchasing:
                // if the user is currently purchasing the IAP,
                // we don't need to do anything.
                //
                // You could use this to show the user
                // an activity indicator, or something like that
                break
            case .purchased:
                // the user sucessfully purchased the IAP!
                RemoveAdsManager.removeAdsSuccess()
                SKPaymentQueue.default().finishTransaction(transaction)
            case .restored:
                // the user restored their IAP!
                RemoveAdsManager.restoreRemoveAdsSuccess()
                SKPaymentQueue.default().finishTransaction(transaction)
            case .failed:
                // The transaction failed!
                RemoveAdsManager.removeAdsFailure()
                // finish the transaction
                SKPaymentQueue.default().finishTransaction(transaction)
            case .deferred:
                // This happens when the IAP needs an external action
                // in order to proceeded, like Ask to Buy
                RemoveAdsManager.removeAdsDeferred()
                break
            }
        }
    }

}

Lastly, you need to add some way for the user to start the purchase and call RemoveAdsManager.removeAds() and start a restore and call RemoveAdsManager.restoreRemoveAds(), like a button somewhere! Keep in mind that, per the App Store guidelines, you do need to provide a button to restore purchases somewhere.

Submitting for review

The last thing to do is submit your IAP for review on App Store Connect! For detailed instructions on doing that, you can follow the last part of my Objective-C answer, under the Submitting for review header.

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

I agree with some of the others' answers. The <head> and <header> tags have two unique and very unrelated functions. The <header> tag, if I'm not mistaken, was introduced in HTML5 and was created for increased accessibility, namely for screen readers. It's generally used to indicate the heading of your document and, in order to work appropriately and effectively, should be placed inside the <body> tag. The <head> tag, since it's origin, is used for SEO in that it constructs all of the necessary meta data and such. A valid HTML structure for your page with both tags included would be like something like this:

<!DOCTYPE html/>
<html lang="es">
    <head>
        <!--crazy meta stuff here-->
    </head>
    <body>
        <header>
            <!--Optional nav tag-->
            <nav>
            </nav>
        </header>
        <!--Body content-->
    </body>
</html>

Is it bad practice to use break to exit a loop in Java?

While its not bad practice to use break and there are many excellent uses for it, it should not be all you rely upon. Almost any use of a break can be written into the loop condition. Code is far more readable when real conditions are used, but in the case of a long-running or infinite loop, breaks make perfect sense. They also make sense when searching for data, as shown above.

[Vue warn]: Cannot find element

I get the same error. the solution is to put your script code before the end of body, not in the head section.

How to check if an element is off-screen

There's a jQuery plugin here which allows users to test whether an element falls within the visible viewport of the browser, taking the browsers scroll position into account.

$('#element').visible();

You can also check for partial visibility:

$('#element').visible( true);

One drawback is that it only works with vertical positioning / scrolling, although it should be easy enough to add horizontal positioning into the mix.

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

The server directive has to be in the http directive. It should not be outside of it.

Incase if you need detailed information, refer this.

How do I hide anchor text without hiding the anchor?

Another option is to hide based on bootstraps "sr-only" class. If you wrap the text in a span with the class "sr-only" then the text will not be displayed, but screen readers will still have access to it. So you would have:

<li><a href="somehwere"><span class="sr-only">Link text</span></a></li>

If you are not using bootstrap, still keep the above, but also add the below css to define the "sr-only" class:

.sr-only {position: absolute;  width: 1px;  height: 1px;  padding: 0;  margin: -1px;  overflow: hidden;  clip: rect(0 0 0 0);  border: 0; }

Loop through a comma-separated shell variable

Try this one.

#/bin/bash   
testpid="abc,def,ghij" 
count=`echo $testpid | grep -o ',' | wc -l` # this is not a good way
count=`expr $count + 1` 
while [ $count -gt 0 ]  ; do
     echo $testpid | cut -d ',' -f $i
     count=`expr $count - 1 `
done

How to Decode Json object in laravel and apply foreach loop on that in laravel

you can use json_decode function

foreach (json_decode($response) as $area)
{
 print_r($area); // this is your area from json response
}

See this fiddle

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

Declaring a boolean in JavaScript using just var

You can use and test uninitialized variables at least for their 'definedness'. Like this:

var iAmNotDefined;
alert(!iAmNotDefined); //true
//or
alert(!!iAmNotDefined); //false

Furthermore, there are many possibilites: if you're not interested in exact types use the '==' operator (or ![variable] / !![variable]) for comparison (that is what Douglas Crockford calls 'truthy' or 'falsy' I think). In that case assigning true or 1 or '1' to the unitialized variable always returns true when asked. Otherwise [if you need type safe comparison] use '===' for comparison.

var thisMayBeTrue;

thisMayBeTrue = 1;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false

thisMayBeTrue = '1';
alert(thisMayBeTrue == true); //=> true 
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, in this case, using == or !! '1' is implicitly 
// converted to 1 and 1 is implicitly converted to true)

thisMayBeTrue = true;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> true

thisMayBeTrue = 'true';
alert(thisMayBeTrue == true); //=> false
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, here's no implicit conversion of the string 'true'
// it's also a demonstration of the fact that the 
// ! or !! operator tests the 'definedness' of a variable.

PS: you can't test 'definedness' for nonexisting variables though. So:

alert(!!HelloWorld);

gives a reference Error ('HelloWorld is not defined')

(is there a better word for 'definedness'? Pardon my dutch anyway;~)

cv2.imshow command doesn't work properly in opencv-python

This is how I solved it:

import cv2
from matplotlib import pyplot
    
img = cv2.imread('path')
pyplot.imshow(img)
pyplot.show()

Declaring a variable and setting its value from a SELECT query in Oracle

For storing a single row output into a variable from the select into query :

declare v_username varchare(20); SELECT username into v_username FROM users WHERE user_id = '7';

this will store the value of a single record into the variable v_username.


For storing multiple rows output into a variable from the select into query :

you have to use listagg function. listagg concatenate the resultant rows of a coloumn into a single coloumn and also to differentiate them you can use a special symbol. use the query as below SELECT listagg(username || ',' ) within group (order by username) into v_username FROM users;

Accessing Imap in C#

There is no .NET framework support for IMAP. You'll need to use some 3rd party component.

Try https://www.limilabs.com/mail, it's very affordable and easy to use, it also supports SSL:

using(Imap imap = new Imap())
{
    imap.ConnectSSL("imap.company.com");
    imap.Login("user", "password");

    imap.SelectInbox();
    List<long> uids = imap.SearchFlag(Flag.Unseen);
    foreach (long uid in uids)
    {
        string eml = imap.GetMessageByUID(uid);
        IMail message = new MailBuilder()
            .CreateFromEml(eml);

        Console.WriteLine(message.Subject);
        Console.WriteLine(message.TextDataString);
    }
    imap.Close(true);
}

Please note that this is a commercial product I've created.

You can download it here: https://www.limilabs.com/mail.

AES Encryption for an NSString on the iPhone

Please use the below mentioned URL to encrypt string using AES excryption with 
key and IV values.

https://github.com/muneebahmad/AESiOSObjC

To compare two elements(string type) in XSLT?

First of all, the provided long code:

    <xsl:choose>
        <xsl:when test="OU_NAME='OU_ADDR1'">   --comparing two elements coming from XML             
            <!--remove if  adrees already contain  operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="OU_NAME"/>
            <fo:block/>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:otherwise>
    </xsl:choose>

is equivalent to this, much shorter code:

<xsl:if test="not(OU_NAME='OU_ADDR1)'">
              <xsl:value-of select="OU_NAME"/>
        </xsl:if>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>

Now, to your question:

how to compare two elements coming from xml as string

In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator = and the function not() together with the operator =.

$str1 = $str2

evaluates to true() exactly when the string $str1 is equal to the string $str2.

not($str1 = $str2)

evaluates to true() exactly when the string $str1 is not equal to the string $str2.

There is also the != operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.

Now, the rules for comparing two element nodes are similar:

$el1 = $el2

evaluates to true() exactly when the string value of $el1 is equal to the string value of $el2.

not($el1 = $el2)

evaluates to true() exactly when the string value of $el1 is not equal to the string value of $el2.

However, if one of the operands of = is a node-set, then

 $ns = $str

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string $str

$ns1 = $ns2

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string value of some node from $ns2

Therefore, the expression:

OU_NAME='OU_ADDR1'

evaluates to true() only when there is at least one element child of the current node that is named OU_NAME and whose string value is the string 'OU_ADDR1'.

This is obviously not what you want!

Most probably you want:

OU_NAME=OU_ADDR1

This expression evaluates to true exactly there is at least one OU_NAME child of the current node and one OU_ADDR1 child of the current node with the same string value.

Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt, le, eq, gt, ge and the inherited from XPath 1.0 general comparison operator =.

Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.

HTTP GET request in JavaScript?

A version without callback

var i = document.createElement("img");
i.src = "/your/GET/url?params=here";

Best PHP IDE for Mac? (Preferably free!)

PDT eclipse from ZEND has a mac version (PDT all-in-one).

I've been using it for about 3 months and it's pretty solid and has debugging capabilities with xdebug (debug howto) and zend debugger.

jquery if div id has children

You can also check whether div has specific children or not,

if($('#myDiv').has('select').length>0)
{
   // Do something here.
   console.log("you can log here");

}

jQuery counter to count up to a target number

Don't know about plugins but this shouldn't be too hard:

;(function($) {        
     $.fn.counter = function(options) {
        // Set default values
        var defaults = {
            start: 0,
            end: 10,
            time: 10,
            step: 1000,
            callback: function() { }
        }
        var options = $.extend(defaults, options);            
        // The actual function that does the counting
        var counterFunc = function(el, increment, end, step) {
            var value = parseInt(el.html(), 10) + increment;
            if(value >= end) {
                el.html(Math.round(end));
                options.callback();
            } else {
                el.html(Math.round(value));
                setTimeout(counterFunc, step, el, increment, end, step);
            }
        }            
        // Set initial value
        $(this).html(Math.round(options.start));
        // Calculate the increment on each step
        var increment = (options.end - options.start) / ((1000 / options.step) * options.time);            
        // Call the counter function in a closure to avoid conflicts
        (function(e, i, o, s) {
            setTimeout(counterFunc, s, e, i, o, s);
        })($(this), increment, options.end, options.step);
    }
})(jQuery);

Usage:

$('#foo').counter({
    start: 1000,
    end: 4500,
    time: 8,
    step: 500,
    callback: function() {
        alert("I'm done!");
    }
});

Example:

http://www.ulmanen.fi/stuff/counter.php

I guess the usage is self-explanatory; in this example, the counter will start from 1000 and count up to 4500 in 8 seconds in 500ms intervals, and will call the callback function when the counting is done.

VB.NET: how to prevent user input in a ComboBox

Using 'DropDownList' for the 'DropDownStyle' property of the combo box doesn't work as it changes the look and feel of the combo box. I am using Visual Studio 2019 Community Edition.

Using 'e.Handled = True' also doesn't work either as it still allows user input. Using 'False' for the 'Enabled' property of the combo box also doesn't work too because it stops the user from being able to use the combo box.

All of the "solutions" that have been proposed above are complete rubbish. What really works is this following code which restricts user input to certain keys such as up / down (for navigating through the list of all available choices in the combo box), suppressing all other key inputs:-

Private Sub ComboBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles 
  ComboBox1.KeyDown
    REM The following code is executed whenever the user has pressed
    REM a key.  Added on Wednesday 1st January 2020.

    REM Determine what key the user has pressed.  Added on Wednesday
    REM 1st January 2020.
    Select Case e.KeyCode
        Case Keys.Down, Keys.Up
            REM This section is for whenever the user has pressed either
            REM the arrow down key or arrow up key.  Added on Wednesday
            REM 1st January 2020.

        Case Else
            REM This section is for whenever the user has pressed any
            REM other key.  Added on Wednesday 1st January 2020.

            REM Cancelling the key that the user has pressed.  Added on
            REM Wednesday 1st January 2020.
            e.SuppressKeyPress = True

    End Select

End Sub

Remove end of line characters from Java string

public static void main(final String[] argv) 
{
    String str;

    str = "hello\r\n\tjava\r\nbook";
    str = str.replaceAll("(\\r|\\n|\\t)", "");
    System.out.println(str);
}

It would be useful to add the tabulation in regex too.

Directly export a query to CSV using SQL Developer

Click in the grid so it has focus.

Ctrl+End

This will force the rest of the records back into the grid.

All credit to http://www.thatjeffsmith.com/archive/2012/03/how-to-export-sql-developer-query-results-without-re-running-the-query/

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

Swift applications are supported on iOS 7 and above as stated in Beta 4 release notes. iOS 6.0, 6.1, 7.0, 7.1, 8.0 in Xcode 6 Beta

Swift applications are supported on platforms OS X 10.9 and above. OS X 10.4 to 10.10 in Deployment Target. I have tested on targeting 10.5 to 10.10, and running on 10.9.3

How do you pass view parameters when navigating from an action in JSF2?

Check out these:

You're gonna need something like:

<h:link outcome="success">
  <f:param name="foo" value="bar"/>
</h:link>

...and...

<f:metadata>
  <f:viewParam name="foo" value="#{bean.foo}"/>
</f:metadata>

Judging from this page, something like this might be easier:

 <managed-bean>
   <managed-bean-name>blog</managed-bean-name>
   <managed-bean-class>com.acme.Blog</managed-bean-class>
   <managed-property>
      <property-name>entryId</property-name>
      <value>#{param['id']}</value>
   </managed-property>
 </managed-bean>

How do I find files with a path length greater than 260 characters in Windows?

As a refinement of simplest solution, and if you can’t or don’t want to install Powershell, just run:

dir /s /b | sort /r /+261 > out.txt

or (faster):

dir /s /b | sort /r /+261 /o out.txt

And lines longer than 260 will get to the top of listing. Note that you must add 1 to SORT column parameter (/+n).

How to create a secure random AES key in Java?

I would use your suggested code, but with a slight simplification:

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // for example
SecretKey secretKey = keyGen.generateKey();

Let the provider select how it plans to obtain randomness - don't define something that may not be as good as what the provider has already selected.

This code example assumes (as Maarten points out below) that you've configured your java.security file to include your preferred provider at the top of the list. If you want to manually specify the provider, just call KeyGenerator.getInstance("AES", "providerName");.

For a truly secure key, you need to be using a hardware security module (HSM) to generate and protect the key. HSM manufacturers will typically supply a JCE provider that will do all the key generation for you, using the code above.

Difference between SelectedItem, SelectedValue and SelectedValuePath

SelectedItem is an object. SelectedValue and SelectedValuePath are strings.

for example using the ListBox:

if you say give me listbox1.SelectedValue it will return the text of the currently selected item.

string value = listbox1.SelectedValue;

if you say give me listbox1.SelectedItem it will give you the entire object.

ListItem item = listbox1.SelectedItem;
string value = item.value;

Cast from VARCHAR to INT - MySQL

For casting varchar fields/values to number format can be little hack used:

SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`

How do I kill background processes / jobs when my shell script exits?

I made an adaption of @tokland's answer combined with the knowledge from http://veithen.github.io/2014/11/16/sigterm-propagation.html when I noticed that trap doesn't trigger if I'm running a foreground process (not backgrounded with &):

#!/bin/bash

# killable-shell.sh: Kills itself and all children (the whole process group) when killed.
# Adapted from http://stackoverflow.com/a/2173421 and http://veithen.github.io/2014/11/16/sigterm-propagation.html
# Note: Does not work (and cannot work) when the shell itself is killed with SIGKILL, for then the trap is not triggered.
trap "trap - SIGTERM && echo 'Caught SIGTERM, sending SIGTERM to process group' && kill -- -$$" SIGINT SIGTERM EXIT

echo $@
"$@" &
PID=$!
wait $PID
trap - SIGINT SIGTERM EXIT
wait $PID

Example of it working:

$ bash killable-shell.sh sleep 100
sleep 100
^Z
[1]  + 31568 suspended  bash killable-shell.sh sleep 100

$ ps aux | grep "sleep"
niklas   31568  0.0  0.0  19640  1440 pts/18   T    01:30   0:00 bash killable-shell.sh sleep 100
niklas   31569  0.0  0.0  14404   616 pts/18   T    01:30   0:00 sleep 100
niklas   31605  0.0  0.0  18956   936 pts/18   S+   01:30   0:00 grep --color=auto sleep

$ bg
[1]  + 31568 continued  bash killable-shell.sh sleep 100

$ kill 31568
Caught SIGTERM, sending SIGTERM to process group
[1]  + 31568 terminated  bash killable-shell.sh sleep 100

$ ps aux | grep "sleep"
niklas   31717  0.0  0.0  18956   936 pts/18   S+   01:31   0:00 grep --color=auto sleep

equivalent to push() or pop() for arrays?

You can use Arrays.copyOf() with a little reflection to make a nice helper function.

public class ArrayHelper {
    public static <T> T[] push(T[] arr, T item) {
        T[] tmp = Arrays.copyOf(arr, arr.length + 1);
        tmp[tmp.length - 1] = item;
        return tmp;
    }

    public static <T> T[] pop(T[] arr) {
        T[] tmp = Arrays.copyOf(arr, arr.length - 1);
        return tmp;
    }
}

Usage:

String[] items = new String[]{"a", "b", "c"};

items = ArrayHelper.push(items, "d");
items = ArrayHelper.push(items, "e");

items = ArrayHelper.pop(items);

Results

Original: a,b,c

Array after push calls: a,b,c,d,e

Array after pop call: a,b,c,d

sh: react-scripts: command not found after running npm start

Just doing an Yarn install solved the problem for me

Import Certificate to Trusted Root but not to Personal [Command Line]

To print the content of Root store:

certutil -store Root

To output content to a file:

certutil -store Root > root_content.txt

To add certificate to Root store:

certutil -addstore -enterprise Root file.cer

return query based on date

Find with a specific date:

db.getCollection('CollectionName').find({"DepartureDate" : new ISODate("2019-06-21T00:00:00.000Z")})

Find with greater gte or little lt :

db.getCollection('CollectionName').find({"DepartureDate" : { $gte : new ISODate("2019-06-11T00:00:00.000Z") }})

Find by range:

db.getCollection('CollectionName').find({ 
    "DepartureDate": { 
        $lt: new Date(), 
        $gte: new Date(new Date().setDate(new Date().getDate()-15))
      } 
    })

Nuget connection attempt failed "Unable to load the service index for source"

I have resolved this issue using below steps

  1. Click on run search this %APPDATA%\NuGet\NuGet.config.

  2. Open the setting and add this http_proxy keyin NuGet.config.

  3. Then you will able install the BouncyCastle.Crypto.dll in your application.

Thank you! Responses are welcome if you help this answer.

How can I find out if I have Xcode commandline tools installed?

/usr/bin/xcodebuild -version

will give you the xcode version, run it via Terminal command

How to split one string into multiple strings separated by at least one space in bash shell?

Did you try just passing the string variable to a for loop? Bash, for one, will split on whitespace automatically.

sentence="This is   a sentence."
for word in $sentence
do
    echo $word
done

 

This
is
a
sentence.

How to Bulk Insert from XLSX file extension?

Create a linked server to your document

http://www.excel-sql-server.com/excel-import-to-sql-server-using-linked-servers.htm

Then use ordinary INSERT or SELECT INTO. If you want to get fancy, you can use ADO.NET's SqlBulkCopy, which takes just about any data source that you can get a DataReader from and is pretty quick on insert, although the reading of the data won't be esp fast.

You could also take the time to transform an excel spreadsheet into a text delimited file or other bcp supported format and then use BCP.

iOS - UIImageView - how to handle UIImage image orientation

This method first checks the current orientation of UIImage and then it changes the orientation in a clockwise way and return UIImage.You can show this image as

self.imageView.image = rotateImage(currentUIImage)

   func rotateImage(image:UIImage)->UIImage
    {
        var rotatedImage = UIImage();
        switch image.imageOrientation
        {
            case UIImageOrientation.Right:
            rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Down);

           case UIImageOrientation.Down:
            rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Left);

            case UIImageOrientation.Left:
            rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Up);

             default:
            rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Right);
        }
        return rotatedImage;
    }

Swift 4 version

func rotateImage(image:UIImage) -> UIImage
    {
        var rotatedImage = UIImage()
        switch image.imageOrientation
        {
        case .right:
            rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .down)

        case .down:
            rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .left)

        case .left:
            rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .up)

        default:
            rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .right)
        }

        return rotatedImage
    }

Android : change button text and background color

When you create an App, a file called styles.xml will be created in your res/values folder. If you change the styles, you can change the background, text color, etc for all your layouts. That way you don’t have to go into each individual layout and change the it manually.

styles.xml:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Theme.AppBaseTheme" parent="@android:style/Theme.Light">
    <item name="android:editTextColor">#295055</item> 
    <item name="android:textColorPrimary">#295055</item>
    <item name="android:textColorSecondary">#295055</item>
    <item name="android:textColorTertiary">#295055</item>
    <item name="android:textColorPrimaryInverse">#295055</item>
    <item name="android:textColorSecondaryInverse">#295055</item>
    <item name="android:textColorTertiaryInverse">#295055</item>

     <item name="android:windowBackground">@drawable/custom_background</item>        
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

parent="@android:style/Theme.Light" is Google’s native colors. Here is a reference of what the native styles are: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/themes.xml

name="Theme.AppBaseTheme" means that you are creating a style that inherits all the styles from parent="@android:style/Theme.Light". This part you can ignore unless you want to inherit from AppBaseTheme again. = <style name="AppTheme" parent="AppBaseTheme">

@drawable/custom_background is a custom image I put in the drawable’s folder. It is a 300x300 png image.

#295055 is a dark blue color.

My code changes the background and text color. For Button text, please look through Google’s native stlyes (the link I gave u above).

Then in Android Manifest, remember to include the code:

<application
android:theme="@style/Theme.AppBaseTheme">

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

I ran into the exact same problem under identical circumstances. I don't have the tnsnames.ora file, and I wanted to use SQL*Plus with Easy Connection Identifier format in command line. I solved this problem as follows.

The SQL*Plus® User's Guide and Reference gives an example:

sqlplus hr@\"sales-server:1521/sales.us.acme.com\"

Pay attention to two important points:

  1. The connection identifier is quoted. You have two options:
    1. You can use SQL*Plus CONNECT command and simply pass quoted string.
    2. If you want to specify connection parameters on the command line then you must add backslashes as shields before quotes. It instructs the bash to pass quotes into SQL*Plus.
  2. The service name must be specified in FQDN-form as it configured by your DBA.

I found these good questions to detect service name via existing connection: 1, 2. Try this query for example:

SELECT value FROM V$SYSTEM_PARAMETER WHERE UPPER(name) = 'SERVICE_NAMES'

How to install an APK file on an Android phone?

I quote Hello Android because I can't say it better ;-)

You need to enable USB debugging on the phone itself (by starting the Settings application and selecting Applications > Development > USB Debugging), install the Android USB device driver if you haven’t already (Windows only), and then plug the phone into your computer using the USB cable that came with the phone.

Close the emulator window if it’s already open. As long as the phone is plugged in, Eclipse will load and run applications on the phone instead. You need to right-click the project and select Run As > Android Application.

ajax jquery simple get request

It seems to me, this is a cross-domain issue since you're not allowed to make a request to a different domain.

You have to find solutions to this problem: - Use a proxy script, running on your server that will forward your request and will handle the response sending it to the browser Or - The service you're making the request should have JSONP support. This is a cross-domain technique. You might want to read this http://en.wikipedia.org/wiki/JSONP

How do I do an insert with DATETIME now inside of SQL server mgmt studioÜ

Just use GETDATE() or GETUTCDATE() (if you want to get the "universal" UTC time, instead of your local server's time-zone related time).

INSERT INTO [Business]
           ([IsDeleted]
           ,[FirstName]
           ,[LastName]
           ,[LastUpdated]
           ,[LastUpdatedBy])
     VALUES
           (0, 'Joe', 'Thomas', 
           GETDATE(),  <LastUpdatedBy, nvarchar(50),>)

How To Launch Git Bash from DOS Command Line?

You can add git path to environment variables

  • For x86

%SYSTEMDRIVE%\Program Files (x86)\Git\bin\

  • For x64

%PROGRAMFILES%\Git\bin\

Open cmd and write this command to open git bash

sh --login

OR

bash --login

OR

sh

OR

bash

You can see this GIF image for more details:

https://media1.giphy.com/media/WSxbZkPFY490wk3abN/giphy.gif

How to remove line breaks (no characters!) from the string?

It's because nl2br() doesn't remove new lines at all.

Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).

Use str_replace instead:

$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);

ALTER DATABASE failed because a lock could not be placed on database

Just to add my two cents. I've put myself into the same situation, while searching the minimum required privileges of a db login to run successfully the statement:

ALTER DATABASE ... SET SINGLE_USER WITH ROLLBACK IMMEDIATE

It seems that the ALTER statement completes successfully, when executed with a sysadmin login, but it requires the connections cleanup part, when executed under a login which has "only" limited permissions like:

ALTER ANY DATABASE

P.S. I've spent hours trying to figure out why the "ALTER DATABASE.." does not work when executed under a login that has dbcreator role + ALTER ANY DATABASE privileges. Here's my MSDN thread!

Create a simple HTTP server with Java?

If you are using the Sun JDK you can use this built in library
Look at this site on how to use.

If n ot there are several Open Source HTTP Servers here which you can embed into your software.

What is the purpose of the return statement?

return is part of a function definition, while print outputs text to the standard output (usually the console).

A function is a procedure accepting parameters and returning a value. return is for the latter, while the former is done with def.

Example:

def timestwo(x):
    return x*2

Read specific columns with pandas or other python module

Above answers are in python2. So for python 3 users I am giving this answer. You can use the bellow code:

import pandas as pd
fields = ['star_name', 'ra']

df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print(df.keys())
# See content in 'star_name'
print(df.star_name)

How to dynamically add a style for text-align using jQuery

$(this).css("text-align", "center"); should work, make sure 'this' is the element you're actually trying to set the text-align style to.

Partly JSON unmarshal into a map in Go

This can be accomplished by Unmarshaling into a map[string]json.RawMessage.

var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)

To further parse sendMsg, you could then do something like:

var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)

For say, you can do the same thing and unmarshal into a string:

var str string
err = json.Unmarshal(objmap["say"], &str)

EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:

type sendMsg struct {
    User string
    Msg  string
}

Example: https://play.golang.org/p/OrIjvqIsi4-

Automating the InvokeRequired code pattern

Here's the form I've been using in all my code.

private void DoGUISwitch()
{ 
    Invoke( ( MethodInvoker ) delegate {
        object1.Visible = true;
        object2.Visible = false;
    });
} 

I've based this on the blog entry here. I have not had this approach fail me, so I see no reason to complicate my code with a check of the InvokeRequired property.

Hope this helps.

undefined reference to 'vtable for class' constructor

You're declaring a virtual function and not defining it:

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table

SQL Case Sensitive String Compare

You can also convert that attribute as case sensitive using this syntax :

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CS_AS

Now your search will be case sensitive.

If you want to make that column case insensitive again, then use

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CI_AS

What does it mean to bind a multicast (UDP) socket?

It is also very important to distinguish a SENDING multicast socket from a RECEIVING multicast socket.

I agree with all the answers above regarding RECEIVING multicast sockets. The OP noted that binding a RECEIVING socket to an interface did not help. However, it is necessary to bind a multicast SENDING socket to an interface.

For a SENDING multicast socket on a multi-homed server, it is very important to create a separate socket for each interface you want to send to. A bound SENDING socket should be created for each interface.

  // This is a fix for that bug that causes Servers to pop offline/online.
  // Servers will intermittently pop offline/online for 10 seconds or so.
  // The bug only happens if the machine had a DHCP gateway, and the gateway is no longer accessible.
  // After several minutes, the route to the DHCP gateway may timeout, at which
  // point the pingponging stops.
  // You need 3 machines, Client machine, server A, and server B
  // Client has both ethernets connected, and both ethernets receiving CITP pings (machine A pinging to en0, machine B pinging to en1)
  // Now turn off the ping from machine B (en1), but leave the network connected.
  // You will notice that the machine transmitting on the interface with
  // the DHCP gateway will fail sendto() with errno 'No route to host'
  if ( theErr == 0 )
  {
     // inspired by 'ping -b' option in man page:      
     //      -b boundif
     //             Bind the socket to interface boundif for sending.
     struct sockaddr_in bindInterfaceAddr;
     bzero(&bindInterfaceAddr, sizeof(bindInterfaceAddr));
     bindInterfaceAddr.sin_len = sizeof(bindInterfaceAddr);
     bindInterfaceAddr.sin_family = AF_INET;
     bindInterfaceAddr.sin_addr.s_addr = htonl(interfaceipaddr);
     bindInterfaceAddr.sin_port = 0; // Allow the kernel to choose a random port number by passing in 0 for the port.
     theErr = bind(mSendSocketID, (struct sockaddr *)&bindInterfaceAddr, sizeof(bindInterfaceAddr));
     struct sockaddr_in serverAddress;
     int namelen = sizeof(serverAddress);  
     if (getsockname(mSendSocketID, (struct sockaddr *)&serverAddress, (socklen_t *)&namelen) < 0) {
        DLogErr(@"ERROR Publishing service... getsockname err");
     }
     else
     {
        DLog( @"socket %d bind, %@ port %d", mSendSocketID, [NSString stringFromIPAddress:htonl(serverAddress.sin_addr.s_addr)], htons(serverAddress.sin_port) );
     }

Without this fix, multicast sending will intermittently get sendto() errno 'No route to host'. If anyone can shed light on why unplugging a DHCP gateway causes Mac OS X multicast SENDING sockets to get confused, I would love to hear it.

How to find out if a Python object is a string?

For a nice duck-typing approach for string-likes that has the bonus of working with both Python 2.x and 3.x:

def is_string(obj):
    try:
        obj + ''
        return True
    except TypeError:
        return False

wisefish was close with the duck-typing before he switched to the isinstance approach, except that += has a different meaning for lists than + does.

Javascript onload not working

You can try use in javascript:

window.onload = function() {
 alert("let's go!");
}

Its a good practice separate javascript of html

Google Chrome redirecting localhost to https

Go to settings in Chrome and then to Advanced settings, under privacy and security section click Clear browsing data and then clear all data. I followed these steps and it worked for me. Hope it helps some one.

How to set JAVA_HOME path on Ubuntu?

add JAVA_HOME to the file:

/etc/environment

for it to be available to the entire system (you would need to restart Ubuntu though)

Difference between virtual and abstract methods

Abstract Method:

  • If an abstract method is defined in a class, then the class should declare as an abstract class.

  • An abstract method should contain only method definition, should not Contain the method body/implementation.

  • An abstract method must be over ride in the derived class.

Virtual Method:

  • Virtual methods can be over ride in the derived class but not mandatory.
  • Virtual methods must have the method body/implementation along with the definition.

Example:

public abstract class baseclass
        {
            public abstract decimal getarea(decimal Radius);

            public virtual decimal interestpermonth(decimal amount)
            {
                return amount*12/100;
            }

            public virtual decimal totalamount(decimal Amount,decimal principleAmount)
            {
                return Amount + principleAmount;
            }
        }

        public class derivedclass:baseclass
        {
            public override decimal getarea(decimal Radius)
            {
                return 2 * (22 / 7) * Radius;
            }

            public override decimal interestpermonth(decimal amount)
            {
                return amount * 14 / 100;
            }
        }

Maven compile: package does not exist

Not sure if there was file corruption or what, but after confirming proper pom configuration I was able to resolve this issue by deleting the jar from my local m2 repository, forcing Maven to download it again when I ran the tests.

How to convert list to string

By using ''.join

list1 = ['1', '2', '3']
str1 = ''.join(list1)

Or if the list is of integers, convert the elements before joining them.

list1 = [1, 2, 3]
str1 = ''.join(str(e) for e in list1)

Handling the null value from a resultset in JAVA

The String being null is a very good chance, but when you see values in your table, yet a null is printed by the ResultSet, it might mean that the connection was closed before the value of ResultSet was used.

Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:My_db.db");
String sql = ("select * from cust where cust_id='" + cus + "'");
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
con.close();
System.out.println(rs.getString(1));

Would print null even if there are values.

Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:My_db.db");
String sql = ("select * from cust where cust_id='" + cus + "'");
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
System.out.println(rs.getString(1));
con.close();

Wouldn't print null if there are values in the table.

CSS: Control space between bullet and <li>

To summarise the other answers here – if you want finer control over the space between bullets and the text in a <li> list item, your options are:

(1) Use a background image:

<style type="text/css">
li {
    list-style-type:none;
    background-image:url(bullet.png);
}
</style>

<ul>
    <li>Some text</li>
</ul>

Advantages:

  • You can use any image you want for the bullet
  • You can use CSS background-position to position the image pretty much anywhere you want in relation to the text, using pixels, ems or %

Disadvantages:

  • Adds an extra (albeit small) image file to your page, increasing the page weight
  • If a user increases the text size on their browser, the bullet will stay at the original size. It'll also likely get further out of position as the text size increases
  • If you're developing a 'responsive' layout using only percentages for widths, it could be difficult to get the bullet exactly where you want it over a range of screen widths

2. Use padding on the <li> tag

<style type="text/css">
ul {padding-left:1em}
li {padding-left:1em}
</style>

<ul>
    <li>Some text</li>
</ul>

Advantages:

  • No image = 1 less file to download
  • By adjusting the padding on the <li>, you can add as much extra horizontal space between the bullet and the text as you like
  • If the user increases the text size, the spacing and bullet size should scale proportionally

Disadvantages:

  • Can't move the bullet any closer to the text than the browser default
  • Limited to shapes and sizes of CSS's built-in bullet types
  • Bullet must be same colour as the text
  • No control over vertical positioning of the bullet

(3) Wrap the text in an extra <span> element

<style type="text/css">
li {
    padding-left:1em;
    color:#f00; /* red bullet */
}
li span {
    display:block;
    margin-left:-0.5em;
    color:#000; /* black text */
}
</style>

<ul>
    <li><span>Some text</span></li>
</ul>

Advantages:

  • No image = 1 less file to download
  • You get more control over the position of the bullet than with option (2) – you can move it closer to the text (although despite my best efforts it seems you can't alter the vertical position by adding padding-top to the <span>. Someone else may have a workaround for this, though...)
  • The bullet can be a different colour to the text
  • If the user increases their text size, the bullet should scale in proportion (providing you set the padding & margin in ems not px)

Disadvantages:

  • Requires an extra unsemantic element (this will probably lose you more friends on SO than it will in real life ;) but it's annoying for those who like their code to be as lean and efficient as possible, and it violates the separation of presentation and content that HTML / CSS is supposed to offer)
  • No control over the size and shape of the bullet

Here's hoping for some new list-style features in CSS4, so we can create smarter bullets without resorting to images or exta mark-up :)

jQuery Form Validation before Ajax submit

You need to trigger form validation before checking if it is valid. Field validation runs after you enter data in each field. Form validation is triggered by the submit event but at the document level. So your event handler is being triggered before jquery validates the whole form. But fret not, there's a simple solution to all of this.

You should validate the form:

if ($(this).validate().form()) {
  // do ajax stuff
}

https://jqueryvalidation.org/Validator.form/#validator-form()

How to use multiple databases in Laravel

Actually, DB::connection('name')->select(..) doesnt work for me, because 'name' has to be in double quotes: "name"

Still, the select query is executed on my default connection. Still trying to figure out, how to convince Laravel to work the way it is intended: change the connection.

Edit: I figured it out. After debugging Laravels DatabaseManager it turned out my database.php (config file) (inside $this->app) was wrong. In the section "connections" I had stuff like "database" with values of the one i copied it from. In clear terms, instead of

env('DB_DATABASE', 'name')

I needed to place something like

'myNewName'

since all connections were listed with the same values for the database, username, password, etc. which of course makes little sense if I want to access at least another database name

Therefore, every time I wanted to select something from another database I always ended up in my default database

How to create a GUID in Excel?

The formula for German Excel:

=KLEIN(
    VERKETTEN(
        DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;8));8);"-";
        DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;4));4);"-";"4";
        DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;3));3);"-";
        DEZINHEX(ZUFALLSBEREICH(8;11));
        DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;3));3);"-";
        DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;8));8);
        DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;4));
    )
)

Calculate time difference in minutes in SQL Server

Please try as below to get the time difference in hh:mm:ss format

Select StartTime, EndTime, CAST((EndTime - StartTime) as time(0)) 'TotalTime' from [TableName]

Composer update memory limit

<C:\>set COMPOSER_MEMORY_LIMIT=-1
<C:\>composer install exhausted/packages

The ScriptManager must appear before any controls that need it

You can add your Script Manager tags just below the <Form> tag of your page. Here is how you can place your Script Manager tag.

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

If you are using Master Pages, its recommended to use your Script Manager in your Master page so that you do not have to write it again and again on every page that contains AJAX controls.

Why is my toFixed() function not working?

document.getElementById("EDTVALOR").addEventListener("change", function() {
  this.value = this.value.replace(",", ".");
  this.value = parseFloat(this.value).toFixed(2);
  if (this.value < 0) {
    this.value = 0;
  }
  this.value = this.value.replace(".", ",");
  this.value = this.value.replace("NaN", "0");
});

SSRS Field Expression to change the background color of the Cell

=IIF(fields!column.value =Condition,"Red","Black")

How to find what code is run by a button or element in Chrome using Developer Tools

Alexander Pavlov's answer gets the closest to what you want.

Due to the extensiveness of jQuery's abstraction and functionality, a lot of hoops have to be jumped in order to get to the meat of the event. I have set up this jsFiddle to demonstrate the work.


1. Setting up the Event Listener Breakpoint

You were close on this one.

  1. Open the Chrome Dev Tools (F12), and go to the Sources tab.
  2. Drill down to Mouse -> Click
    Chrome Dev Tools -> Sources tab -> Mouse -> Click
    (click to zoom)

2. Click the button!

Chrome Dev Tools will pause script execution, and present you with this beautiful entanglement of minified code:

Chrome Dev Tools paused script execution (click to zoom)


3. Find the glorious code!

Now, the trick here is to not get carried away pressing the key, and keep an eye out on the screen.

  1. Press the F11 key (Step In) until desired source code appears
  2. Source code finally reached
    • In the jsFiddle sample provided above, I had to press F11 108 times before reaching the desired event handler/function
    • Your mileage may vary, depending on the version of jQuery (or framework library) used to bind the events
    • With enough dedication and time, you can find any event handler/function

Desired event handler/function


4. Explanation

I don't have the exact answer, or explanation as to why jQuery goes through the many layers of abstractions it does - all I can suggest is that it is because of the job it does to abstract away its usage from the browser executing the code.

Here is a jsFiddle with a debug version of jQuery (i.e., not minified). When you look at the code on the first (non-minified) breakpoint, you can see that the code is handling many things:

    // ...snip...

    if ( !(eventHandle = elemData.handle) ) {
        eventHandle = elemData.handle = function( e ) {
            // Discard the second event of a jQuery.event.trigger() and
            // when an event is called after a page has unloaded
            return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
                jQuery.event.dispatch.apply( elem, arguments ) : undefined;
        };
    }

    // ...snip...

The reason I think you missed it on your attempt when the "execution pauses and I jump line by line", is because you may have used the "Step Over" function, instead of Step In. Here is a StackOverflow answer explaining the differences.

Finally, the reason why your function is not directly bound to the click event handler is because jQuery returns a function that gets bound. jQuery's function in turn goes through some abstraction layers and checks, and somewhere in there, it executes your function.

What's the difference between "git reset" and "git checkout"?

  • git reset is specifically about updating the index, moving the HEAD.
  • git checkout is about updating the working tree (to the index or the specified tree). It will update the HEAD only if you checkout a branch (if not, you end up with a detached HEAD).
    (actually, with Git 2.23 Q3 2019, this will be git restore, not necessarily git checkout)

By comparison, since svn has no index, only a working tree, svn checkout will copy a given revision on a separate directory.
The closer equivalent for git checkout would:

  • svn update (if you are in the same branch, meaning the same SVN URL)
  • svn switch (if you checkout for instance the same branch, but from another SVN repo URL)

All those three working tree modifications (svn checkout, update, switch) have only one command in git: git checkout.
But since git has also the notion of index (that "staging area" between the repo and the working tree), you also have git reset.


Thinkeye mentions in the comments the article "Reset Demystified ".

For instance, if we have two branches, 'master' and 'develop' pointing at different commits, and we're currently on 'develop' (so HEAD points to it) and we run git reset master, 'develop' itself will now point to the same commit that 'master' does.

On the other hand, if we instead run git checkout master, 'develop' will not move, HEAD itself will. HEAD will now point to 'master'.

So, in both cases we're moving HEAD to point to commit A, but how we do so is very different. reset will move the branch HEAD points to, checkout moves HEAD itself to point to another branch.

http://git-scm.com/images/reset/reset-checkout.png

On those points, though:

LarsH adds in the comments:

The first paragraph of this answer, though, is misleading: "git checkout ... will update the HEAD only if you checkout a branch (if not, you end up with a detached HEAD)".
Not true: git checkout will update the HEAD even if you checkout a commit that's not a branch (and yes, you end up with a detached HEAD, but it still got updated).

git checkout a839e8f updates HEAD to point to commit a839e8f.

De Novo concurs in the comments:

@LarsH is correct.
The second bullet has a misconception about what HEAD is in will update the HEAD only if you checkout a branch.
HEAD goes wherever you are, like a shadow.
Checking out some non-branch ref (e.g., a tag), or a commit directly, will move HEAD. Detached head doesn't mean you've detached from the HEAD, it means the head is detached from a branch ref, which you can see from, e.g., git log --pretty=format:"%d" -1.

  • Attached head states will start with (HEAD ->,
  • detached will still show (HEAD, but will not have an arrow to a branch ref.

Is there a way to select sibling nodes?

Well... sure... just access the parent and then the children.

 node.parentNode.childNodes[]

or... using jQuery:

$('#innerId').siblings()

Edit: Cletus as always is inspiring. I dug further. This is how jQuery gets siblings essentially:

function getChildren(n, skipMe){
    var r = [];
    for ( ; n; n = n.nextSibling ) 
       if ( n.nodeType == 1 && n != skipMe)
          r.push( n );        
    return r;
};

function getSiblings(n) {
    return getChildren(n.parentNode.firstChild, n);
}

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

double doubleVal = 1.745;
double doubleVal1 = 0.745;
System.out.println(new BigDecimal(doubleVal));
System.out.println(new BigDecimal(doubleVal1));

outputs:

1.74500000000000010658141036401502788066864013671875
0.74499999999999999555910790149937383830547332763671875

Which shows the real value of the two doubles and explains the result you get. As pointed out by others, don't use the double constructor (apart from the specific case where you want to see the actual value of a double).

More about double precision:

Difference between HttpModule and HttpClientModule

Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):

  • Automatic conversion from JSON to an object
  • Response type definition
  • Event firing
  • Simplified syntax for headers
  • Interceptors

I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.

Simply about new HttpClient in Angular

RabbitMQ / AMQP: single queue, multiple consumers for same message?

Can I have each consumer receive the same messages? Ie, both consumers get message 1, 2, 3, 4, 5, 6? What is this called in AMQP/RabbitMQ speak? How is it normally configured?

No, not if the consumers are on the same queue. From RabbitMQ's AMQP Concepts guide:

it is important to understand that, in AMQP 0-9-1, messages are load balanced between consumers.

This seems to imply that round-robin behavior within a queue is a given, and not configurable. Ie, separate queues are required in order to have the same message ID be handled by multiple consumers.

Is this commonly done? Should I just have the exchange route the message into two separate queues, with a single consumer, instead?

No it's not, single queue/multiple consumers with each each consumer handling the same message ID isn't possible. Having the exchange route the message onto into two separate queues is indeed better.

As I don't require too complex routing, a fanout exchange will handle this nicely. I didn't focus too much on Exchanges earlier as node-amqp has the concept of a 'default exchange' allowing you to publish messages to a connection directly, however most AMQP messages are published to a specific exchange.

Here's my fanout exchange, both sending and receiving:

var amqp = require('amqp');
var connection = amqp.createConnection({ host: "localhost", port: 5672 });
var count = 1;

connection.on('ready', function () {
  connection.exchange("my_exchange", options={type:'fanout'}, function(exchange) {   

    var sendMessage = function(exchange, payload) {
      console.log('about to publish')
      var encoded_payload = JSON.stringify(payload);
      exchange.publish('', encoded_payload, {})
    }

    // Recieve messages
    connection.queue("my_queue_name", function(queue){
      console.log('Created queue')
      queue.bind(exchange, ''); 
      queue.subscribe(function (message) {
        console.log('subscribed to queue')
        var encoded_payload = unescape(message.data)
        var payload = JSON.parse(encoded_payload)
        console.log('Recieved a message:')
        console.log(payload)
      })
    })

    setInterval( function() {    
      var test_message = 'TEST '+count
      sendMessage(exchange, test_message)  
      count += 1;
    }, 2000) 
 })
})

How to make image hover in css?

Simply this, no extra div or JavaScript needed, just pure CSS (jsfiddle demo):

HTML

<a href="javascript:alert('Hello!')" class="changesImgOnHover">
    <img src="http://dummyimage.com/50x25/00f/ff0.png&text=Hello!" alt="Hello!">
</a>

CSS

.changesImgOnHover {
    display: inline-block; /* or just block */
    width: 50px;
    background: url('http://dummyimage.com/50x25/0f0/f00.png&text=Hello!') no-repeat;
}
.changesImgOnHover:hover img {
    visibility: hidden;
}

Pushing to Git returning Error Code 403 fatal: HTTP request failed

I was signed in as a different github user previously(say user1) . For my actual github account(say user2) I was able to clone a newly created repo in github but I was not able to push the changes.

I tried all the answers mentioned above including removing credential from Windows Credential manager but nothing worked.

In the end what worked was launching github Windows App. Navigate to Settings->Options and voila the logged in user was user1. Click Logout from that user and login as required user in this case user2

enter image description here

Does Django scale?

I don't think the issue is really about Django scaling.

I really suggest you look into your architecture that's what will help you with your scaling needs.If you get that wrong there is no point on how well Django performs. Performance != Scale. You can have a system that has amazing performance but does not scale and vice versa.

Is your application database bound? If it is then your scale issues lay there as well. How are you planning on interacting with the database from Django? What happens when you database cannot process requests as fast as Django accepts them? What happens when your data outgrows one physical machine. You need to account for how you plan on dealing with those circumstances.

Moreover, What happens when your traffic outgrows one app server? how you handle sessions in this case can be tricky, more often than not you would probably require a shared nothing architecture. Again that depends on your application.

In short languages is not what determines scale, a language is responsible for performance(again depending on your applications, different languages perform differently). It is your design and architecture that makes scaling a reality.

I hope it helps, would be glad to help further if you have questions.

Padding is invalid and cannot be removed?

Make sure that the keys you use to encrypt and decrypt are the same. The padding method even if not explicitly set should still allow for proper decryption/encryption (if not set they will be the same). However if you for some reason are using a different set of keys for decryption than used for encryption you will get this error:

Padding is invalid and cannot be removed

If you are using some algorithm to dynamically generate keys that will not work. They need to be the same for both encryption and decryption. One common way is to have the caller provide the keys in the constructor of the encryption methods class, to prevent the encryption/decryption process having any hand in creation of these items. It focuses on the task at hand (encrypting and decrypting data) and requires the iv and key to be supplied by the caller.

SQL Server query to find all current database names

I don't recommend this method... but if you want to go wacky and strange:

EXEC sp_MSForEachDB 'SELECT ''?'' AS DatabaseName'

or

EXEC sp_MSForEachDB 'Print ''?'''

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

java_home environment variable should point to the location of the proper version of java installation directory, so that tomcat starts with the right version. for example it you built the project with java 1.7 , then make sure that JAVA_HOME environment variable points to the jdk 1.7 installation directory in your machine.

I had same problem , when i deploy the war in tomcat and run, the link throws the error. But pointing the variable - JAVA_HOME to jdk 1.7 resolved the issue, as my war file was built in java 1.7 environment.

How to run a function in jquery

Is this the most obfuscated solution possible? I don't believe the idea of jQuery was to create code like this.There's also the presumption that we don't want to bubble events, which is probably wrong.

Simple moving doosomething() outside of $(function(){} will cause it to have global scope and keep the code simple/readable.

Check string for palindrome

And here a complete Java 8 streaming solution. An IntStream provides all indexes til strings half length and then a comparision from the start and from the end is done.

public static void main(String[] args) {
    for (String testStr : Arrays.asList("testset", "none", "andna", "haah", "habh", "haaah")) {
        System.out.println("testing " + testStr + " is palindrome=" + isPalindrome(testStr));
    }
}

public static boolean isPalindrome(String str) {
    return IntStream.range(0, str.length() / 2)
            .noneMatch(i -> str.charAt(i) != str.charAt(str.length() - i - 1));
}

Output is:

testing testset is palindrome=true
testing none is palindrome=false
testing andna is palindrome=true
testing haah is palindrome=true
testing habh is palindrome=false
testing haaah is palindrome=true

Should I use @EJB or @Inject

Update: This answer may be incorrect or out of date. Please see comments for details.

I switched from @Inject to @EJB because @EJB allows circular injection whereas @Inject pukes on it.

Details: I needed @PostConstruct to call an @Asynchronous method but it would do so synchronously. The only way to make the asynchronous call was to have the original call a method of another bean and have it call back the method of the original bean. To do this each bean needed a reference to the other -- thus circular. @Inject failed for this task whereas @EJB worked.

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

Your Event.hbm.xml says:

<set name="attendees" cascade="all">
    <key column="attendeeId" />
    <one-to-many class="Attendee" />
</set>

In plain english, this means that the column Attendee.attendeeId is the foreign key for the association attendees and points to the primary key of Event.

When you add those Attendees to the event, hibernate updates the foreign key to express the changed association. Since that same column is also the primary key of Attendee, this violates the primary key constraint.

Since an Attendee's identity and event participation are independent, you should use separate columns for the primary and foreign key.

Edit: The selects might be because you don't appear to have a version property configured, making it impossible for hibernate to know whether the attendees already exists in the database (they might have been loaded in a previous session), so hibernate emits selects to check. As for the update statements, it was probably easier to implement that way. If you want to get rid of these separate updates, I recommend mapping the association from both ends, and declare the Event-end as inverse.

Simple int to char[] conversion

Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.

char c[2];
int i=1;
sprintf(c, "%d", i);

jQuery hyperlinks - href value?

you shoud use <a href="javascript:void(0)" ></a> instead of <a href="#" ></a>

Get the Selected value from the Drop down box in PHP

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

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

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

What is a stack trace, and how can I use it to debug my application errors?

Just to add to the other examples, there are inner(nested) classes that appear with the $ sign. For example:

public class Test {

    private static void privateMethod() {
        throw new RuntimeException();
    }

    public static void main(String[] args) throws Exception {
        Runnable runnable = new Runnable() {
            @Override public void run() {
                privateMethod();
            }
        };
        runnable.run();
    }
}

Will result in this stack trace:

Exception in thread "main" java.lang.RuntimeException
        at Test.privateMethod(Test.java:4)
        at Test.access$000(Test.java:1)
        at Test$1.run(Test.java:10)
        at Test.main(Test.java:13)

Throughput and bandwidth difference?

Imagine it this way: a mail truck can carry 5000 sheets of paper each trip so It's bandwidth is 5000. Does that mean it can carry 5000 letter each trip? Well, theoretically, if each letter didn't need an envelope telling us where it was coming from, going too, and possessing proof of payment (Envelope = Protocol Headers and Footers). But they do, so each letter (1 sheet of paper) requires an envelope (= to about 1 sheet of paper) to get it to it's destination. So in the worst case scenario (all envelopes only have one page letters), the truck would carry only 2500 sheets Throughput (Data that we want to send from source>destination, THE LETTERS) and would have 2500 sheets Overhead (Headers/Footer that we need to get the letter from source>destination but that the recipient won't be reading, THE ENVELOPES). The Throughput, 2500 Letters + the Overhead, 2500 Envelopes = Bandwidth, 5000 sheets of paper. Bigger letters (4 pages) still only require 1 envelope so that would move the ratio of Throughput to Overhead higher (i.e. Jumbo Frames) and make it more efficient, so if all the letters were 4 page letters throughput would change to 4000, and overhead would reduce to 1000, together equaling the 5000 Bandwidth of the truck.

Adding Multiple Values in ArrayList at a single index

Use two dimensional array instead. For instance, int values[][] = new int[2][5]; Arrays are faster, when you are not manipulating much.

How to close off a Git Branch?

Yes, just delete the branch by running git push origin :branchname. To fix a new issue later, branch off from master again.

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

I had this problem because of a typo in the filename tsnames.ora instead of tnsnames.ora

jQuery replace one class with another

Create a class in your CSS file:

.active {
  z-index: 20;
  background: rgb(23,55,94)
  color: #fff;
}

Then in your jQuery

$(this).addClass("active");

Get only specific attributes with from Laravel Collection

I had a similar issue where I needed to select values from a large array, but I wanted the resulting collection to only contain values of a single value.

pluck() could be used for this purpose (if only 1 key item is required)

you could also use reduce(). Something like this with reduce:

$result = $items->reduce(function($carry, $item) {
    return $carry->push($item->getCode());
}, collect());

Optimal way to DELETE specified rows from Oracle

Store all the to be deleted ID's into a table. Then there are 3 ways. 1) loop through all the ID's in the table, then delete one row at a time for X commit interval. X can be a 100 or 1000. It works on OLTP environment and you can control the locks.

2) Use Oracle Bulk Delete

3) Use correlated delete query.

Single query is usually faster than multiple queries because of less context switching, and possibly less parsing.

Shell script to copy files from one location to another location and rename add the current date to every file

cp --archive home/webapps/project1/folder1/{aaa,bbb,ccc,ddd}.csv home/webapps/project1/folder2
rename 's/\.csv$/'$(date +%m%d%Y).csv'/' home/webapps/project1/folder2/{aaa,bbb,ccc,ddd}.csv

Explanation:

  • --archive ensures that the files are copied with the same ownership and permissions.
  • foo{bar,baz} is expanded into foobar foobaz.
  • rename is a commonly available program to do exactly this kind of substitution.

PS: don't use ls for this.

OnClickListener in Android Studio

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         int id = item.getItemId();
         if (id == R.id.standingsButton) {
            startActivity(new Intent(MainActivity.this,StandingsActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

Open S3 object as a string with Boto3

I had a problem to read/parse the object from S3 because of .get() using Python 2.7 inside an AWS Lambda.

I added json to the example to show it became parsable :)

import boto3
import json

s3 = boto3.client('s3')

obj = s3.get_object(Bucket=bucket, Key=key)
j = json.loads(obj['Body'].read())

NOTE (for python 2.7): My object is all ascii, so I don't need .decode('utf-8')

NOTE (for python 3.6+): We moved to python 3.6 and discovered that read() now returns bytes so if you want to get a string out of it, you must use:

j = json.loads(obj['Body'].read().decode('utf-8'))

Can't connect to docker from docker-compose

The following worked for me, I'm not sure what part did the trick:

julian:project$ sudo service docker status
julian:varys$ sudo service docker status                                                                                                                                                                                
? docker.service - Docker Application Container Engine
   Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
   Active: active (running) since Wed 2020-07-15 01:21:16 UTC; 24min ago
     Docs: https://docs.docker.com
 Main PID: 6762 (dockerd)
    Tasks: 25
   CGroup: /system.slice/docker.service
           +-6762 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock

julian:project$ export DOCKER_HOST=unix:///run/containerd/containerd.sock

julian:project$ sudo groupadd docker
groupadd: group 'docker' already exists
julian:project$ sudo gpasswd -a $USER docker
Adding user ubuntu to group docker
julian:project$ newgrp docker

julian:project$ ls -ln /var/run/ | grep docker
drwx------  5   0   0  120 Jul 15 01:10 docker
-rw-r--r--  1   0   0    4 Jul 15 01:10 docker.pid
srw-rw----  1   0 999    0 Jul 15 01:10 docker.sock

julian:project$ sudo rm /var/run/docker.sock                                                                                                                                                                                            
julian:project$ sudo rm /var/run/docker.pid

julian:project$ sudo service docker restart  

TypeScript hashmap/dictionary interface

var x : IHash = {};
x['key1'] = 'value1';
x['key2'] = 'value2';

console.log(x['key1']);
// outputs value1

console.log(x['key2']);
// outputs value2

If you would like to then iterate through your dictionary, you can use.

Object.keys(x).forEach((key) => {console.log(x[key])});

Object.keys returns all the properties of an object, so it works nicely for returning all the values from dictionary styled objects.

You also mentioned a hashmap in your question, the above definition is for a dictionary style interface. Therefore the keys will be unique, but the values will not.

You could use it like a hashset by just assigning the same value to the key and its value.

if you wanted the keys to be unique and with potentially different values, then you just have to check if the key exists on the object before adding to it.

var valueToAdd = 'one';
if(!x[valueToAdd])
   x[valueToAdd] = valueToAdd;

or you could build your own class to act as a hashset of sorts.

Class HashSet{
  private var keys: IHash = {};
  private var values: string[] = [];

  public Add(key: string){
    if(!keys[key]){
      values.push(key);
      keys[key] = key;
    }
  }

  public GetValues(){
    // slicing the array will return it by value so users cannot accidentally
    // start playing around with your array
    return values.slice();
  }
}

Check element exists in array

EAFP vs. LBYL

I understand your dilemma, but Python is not PHP and coding style known as Easier to Ask for Forgiveness than for Permission (or EAFP in short) is a common coding style in Python.

See the source (from documentation):

EAFP - Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

So, basically, using try-catch statements here is not a last resort; it is a common practice.

"Arrays" in Python

PHP has associative and non-associative arrays, Python has lists, tuples and dictionaries. Lists are similar to non-associative PHP arrays, dictionaries are similar to associative PHP arrays.

If you want to check whether "key" exists in "array", you must first tell what type in Python it is, because they throw different errors when the "key" is not present:

>>> l = [1,2,3]
>>> l[4]

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    l[4]
IndexError: list index out of range
>>> d = {0: '1', 1: '2', 2: '3'}
>>> d[4]

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    d[4]
KeyError: 4

And if you use EAFP coding style, you should just catch these errors appropriately.

LBYL coding style - checking indexes' existence

If you insist on using LBYL approach, these are solutions for you:

  • for lists just check the length and if possible_index < len(your_list), then your_list[possible_index] exists, otherwise it doesn't:

    >>> your_list = [0, 1, 2, 3]
    >>> 1 < len(your_list) # index exist
    True
    >>> 4 < len(your_list) # index does not exist
    False
    
  • for dictionaries you can use in keyword and if possible_index in your_dict, then your_dict[possible_index] exists, otherwise it doesn't:

    >>> your_dict = {0: 0, 1: 1, 2: 2, 3: 3}
    >>> 1 in your_dict # index exists
    True
    >>> 4 in your_dict # index does not exist
    False
    

Did it help?

How to get the date and time values in a C program?

time_t rawtime;   
time ( &rawtime );
struct tm *timeinfo = localtime ( &rawtime );

You can also use strftime to format the time into a string.

How to display a JSON representation and not [Object Object] on the screen

There are 2 ways in which you can get the values:-

  1. Access the property of the object using dot notation (obj.property) .
  2. Access the property of the object by passing in key value for example obj["property"]

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

mysql> use mysql;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'my-password-here';

Try it once, it worked for me.

SQL Server - Adding a string to a text column (concat equivalent)

To Join two string in SQL Query use function CONCAT(Express1,Express2,...)

Like....

SELECT CODE, CONCAT(Rtrim(FName), " " , TRrim(LName)) as Title FROM MyTable

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

It turns out Java does not accept a bare Date value as DateTime. Using LocalDate instead of LocalDateTime solves the issue:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate dt = LocalDate.parse("20140218", formatter);

Convert milliseconds to date (in Excel)

Converting your value in milliseconds to days is simply (MsValue / 86,400,000)

We can get 1/1/1970 as numeric value by DATE(1970,1,1)

= (MsValueCellReference / 86400000) + DATE(1970,1,1)

Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss gives me a date and time of 19/04/2010 08:16:11

Going from MM/DD/YYYY to DD-MMM-YYYY in java

Try this

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // Set your date format
        String currentData = sdf.format(new Date());
        Toast.makeText(getApplicationContext(), ""+currentData,Toast.LENGTH_SHORT ).show();

Invalid shorthand property initializer

Because it's an object, the way to assign value to its properties is using :.

Change the = to : to fix the error.

var options = {
  host: 'localhost',
  port: 8080,
  path: '/',
  method: 'POST'
 }

How to get the path of current worksheet in VBA?

The quickest way

path = ThisWorkbook.Path & "\"

How can I fetch all items from a DynamoDB table without specifying the primary key?

A simple code to list all the Items from DynamoDB Table by specifying the region of AWS Service.

import boto3

dynamodb = boto3.resource('dynamodb', region_name='ap-south-1')
table = dynamodb.Table('puppy_store')
response = table.scan()
items = response['Items']

# Prints All the Items at once
print(items)

# Prints Items line by line
for i, j in enumerate(items):
    print(f"Num: {i} --> {j}")

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

appHelper.validateDates = function (start, end) {
    var returnval = false;

    var fd = new Date(start);
    var fdms = fd.getTime();
    var ed = new Date(end);
    var edms = ed.getTime();
    var cd = new Date();
    var cdms = cd.getTime();

    if (fdms >= edms) {
        returnval = false;
        console.log("step 1");
    }
    else if (cdms >= edms) {
        returnval = false;
        console.log("step 2");
    }
    else {
        returnval = true;
        console.log("step 3");
    }
    console.log("vall", returnval)
    return returnval;
}

What does enctype='multipart/form-data' mean?

The enctype attribute specifies how the form-data should be encoded when submitting it to the server.

The enctype attribute can be used only if method="post".

No characters are encoded. This value is required when you are using forms that have a file upload control

From W3Schools

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

You say "I am not using a forms to manipulate the data." But you are doing a POST. Therefore, you are, in fact, using a form, even if it's empty.

$.ajax's dataType tells jQuery what type the server will return, not what you are passing. POST can only pass a form. jQuery will convert data to key/value pairs and pass it as a query string. From the docs:

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key i.e. {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.

Therefore:

  1. You aren't passing JSON to the server. You're passing JSON to jQuery.
  2. Model binding happens in the same way it happens in any other case.