Programs & Examples On #Dxgi

Microsoft DirectX Graphics Infrastructure (DXGI) is often used in combination with Direct3D and is responsible for enumerating graphics adapters and display modes, selecting buffer formats, sharing resources between processes and presenting rendered frames to the monitor.

Deploying Java webapp to Tomcat 8 running in Docker container

There's a oneliner for this one.

You can simply run,

docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat

This will copy the war file to webapps directory and get your app running in no time.

How do I do multiple CASE WHEN conditions using SQL Server 2008?

Something Like this, Two Conditions Two Columns

SELECT ITEMSREQ.ITEM AS ITEM,
       ITEMSREQ.CANTIDAD AS CANTIDAD,
       (CASE  WHEN ITEMSREQ.ITEMAPROBADO=1 THEN 'APROBADO'
              WHEN ITEMSREQ.ITEMAPROBADO=0 THEN 'NO APROBADO'
        END) AS ITEMS,
        (CASE 
              WHEN ITEMSREQ.ITEMAPROBADO = 0 
              THEN CASE WHEN REQUISICIONES.RECIBIDA IS NULL  THEN 'ITEM NO APROBADO PARA ENTREGA' END
              WHEN ITEMSREQ.ITEMAPROBADO = 1 
              THEN CASE WHEN REQUISICIONES.RECIBIDA IS NULL THEN 'ITEM AUN NO RECIBIDO' 
                        WHEN REQUISICIONES.RECIBIDA=1 THEN 'RECIBIDO' 
                        WHEN REQUISICIONES.RECIBIDA=0 THEN 'NO RECIBIDO' 
                       END
              END)
              AS RECIBIDA
 FROM ITEMSREQ
      INNER JOIN REQUISICIONES ON
      ITEMSREQ.CNSREQ = REQUISICIONES.CNSREQ

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

A great substitute for np.isnan() and pd.isnull() is

for i in range(0,a.shape[0]):
    if(a[i]!=a[i]):
       //do something here
       //a[i] is nan

since only nan is not equal to itself.

How to get longitude and latitude of any address?

You need to access a geocoding service (i.e. from Google), there is no simple formula to transfer addresses to geo coordinates.

How do you extract IP addresses from files using a regex in a linux shell?

I usually start with grep, to get the regexp right.

# [multiple failed attempts here]
grep    '[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*'                 file  # good?
grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' file  # good enough

Then I'd try and convert it to sed to filter out the rest of the line. (After reading this thread, you and I aren't going to do that anymore: we're going to use grep -o instead)

sed -ne 's/.*\([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\).*/\1/p  # FAIL

That's when I usually get annoyed with sed for not using the same regexes as anyone else. So I move to perl.

$ perl -nle '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/ and print $&'

Perl's good to know in any case. If you've got a teeny bit of CPAN installed, you can even make it more reliable at little cost:

$ perl -MRegexp::Common=net -nE '/$RE{net}{IPV4}/ and say $&' file(s)

How do I search for files in Visual Studio Code?

For windows. if Ctrl+p doesn't always work use Ctrl+shift+n instead.

What are the advantages and disadvantages of recursion?

To start:

Pros:

  • It is the unique way of implementing a variable number of nested loops (and the only elegant way of implementing a big constant number of nested loops).

Cons:

  • Recursive methods will often throw a StackOverflowException when processing big sets. Recursive loops don't have this problem though.

Could you explain STA and MTA?

Code that calls COM object dlls (for example, to read proprietary data files), may work fine in a user interface but hang mysteriously from a service. The reason is that as of .Net 2.0 user interfaces assume STA (thread-safe) while services assume MTA ((before that, services assumed STA). Having to create an STA thread for every COM call in a service can add significant overhead.

Cannot connect to repo with TortoiseSVN

Run ipconfig /flushdns from a command prompt. Apparently some people seem to think I posted this answer for sheer fun. That's why they down voted my answer. Perhaps an explanation would help them. When I used "SVN Update" it said it can't connect to the SVN repository although I could ping the server. After running ipconfig /flushdns the issue was fixed.

How to perform grep operation on all files in a directory?

Use find. Seriously, it is the best way because then you can really see what files it's operating on:

find . -name "*.sql" -exec grep -H "slow" {} \;

Note, the -H is mac-specific, it shows the filename in the results.

Origin null is not allowed by Access-Control-Allow-Origin

Chrome and Safari has a restriction on using ajax with local resources. That's why it's throwing an error like

Origin null is not allowed by Access-Control-Allow-Origin.

Solution: Use firefox or upload your data to a temporary server. If you still want to use Chrome, start it with the below option;

--allow-file-access-from-files

More info how to add the above parameter to your Chrome: Right click the Chrome icon on your task bar, right click the Google Chrome on the pop-up window and click properties and add the above parameter inside the Target textbox under Shortcut tab. It will like as below;

C:\Users\XXX_USER\AppData\Local\Google\Chrome\Application\chrome.exe --allow-file-access-from-files

Hope this will help!

What is the simplest and most robust way to get the user's current location on Android?

Actualy we can use the two providers(GPS & NETWORK). And they just share a public listener:

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10 * 1000, (float) 10.0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 90 * 1000, (float) 10.0, listener);

This is necessary because the OnLocationChanged() method always need to be called in time.

How to enable/disable bluetooth programmatically in android

I used the below code to disable BT when my app launches and works fine. Not sure if this the correct way to implement this as google recommends not using "bluetooth.disable();" without explicit user action to turn off Bluetooth.

    BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
    bluetooth.disable();

I only used the below permission.

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

How to put data containing double-quotes in string variable?

You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:

Dim MyVar as string = "some text ""hello"" "

This will give the MyVar variable a value of some text "hello".

How to get UTF-8 working in Java webapps?

Some time you can solve problem through MySQL Administrator wizard. In

Startup variables > Advanced >

and set Def. char Set:utf8

Maybe this config need restart MySQL.

How to retrieve absolute path given relative

realpath is probably best

But ...

The initial question was very confused to start with, with an example poorly related to the question as stated.

The selected answer actually answers the example given, and not at all the question in the title. The first command is that answer (is it really ? I doubt), and could do as well without the '/'. And I fail to see what the second command is doing.

Several issues are mixed :

  • changing a relative pathname into an absolute one, whatever it denotes, possibly nothing. (Typically, if you issue a command such as touch foo/bar, the pathname foo/bar must exist for you, and possibly be used in computation, before the file is actually created.)

  • there may be several absolute pathname that denote the same file (or potential file), notably because of symbolic links (symlinks) on the path, but possibly for other reasons (a device may be mounted twice as read-only). One may or may not want to resolve explicity such symlinks.

  • getting to the end of a chain of symbolic links to a non-symlink file or name. This may or may not yield an absolute path name, depending on how it is done. And one may, or may not want to resolve it into an absolute pathname.

The command readlink foo without option gives an answer only if its argument foo is a symbolic link, and that answer is the value of that symlink. No other link is followed. The answer may be a relative path: whatever was the value of the symlink argument.

However, readlink has options (-f -e or -m) that will work for all files, and give one absolute pathname (the one with no symlinks) to the file actually denoted by the argument.

This works fine for anything that is not a symlink, though one might desire to use an absolute pathname without resolving the intermediate symlinks on the path. This is done by the command realpath -s foo

In the case of a symlink argument, readlink with its options will again resolve all symlinks on the absolute path to the argument, but that will also include all symlinks that may be encountered by following the argument value. You may not want that if you desired an absolute path to the argument symlink itself, rather than to whatever it may link to. Again, if foo is a symlink, realpath -s foo will get an absolute path without resolving symlinks, including the one given as argument.

Without the -s option, realpath does pretty much the same as readlink, except for simply reading the value of a link, as well as several other things. It is just not clear to me why readlink has its options, creating apparently an undesirable redundancy with realpath.

Exploring the web does not say much more, except that there may be some variations across systems.

Conclusion : realpath is the best command to use, with the most flexibility, at least for the use requested here.

Read user input inside a loop

Try to change the loop like this:

for line in $(cat filename); do
    read input
    echo $input;
done

Unit test:

for line in $(cat /etc/passwd); do
    read input
    echo $input;
    echo "[$line]"
done

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

I'm the creator of Restangular.

You can take a look at this CRUD example to see how you can PUT/POST/GET elements without all that URL configuration and $resource configuration that you need to do. Besides it, you can then use nested resources without any configuration :).

Check out this plunkr example:

http://plnkr.co/edit/d6yDka?p=preview

You could also see the README and check the documentation here https://github.com/mgonto/restangular

If you need some feature that's not there, just create an issue. I usually add features asked within a week, as I also use this library for all my AngularJS projects :)

Hope it helps!

member names cannot be the same as their enclosing type C#

Method names which are same as the class name are called constructors. Constructors do not have a return type. So correct as:

private Flow()
{
   X = x;
   Y = y;
}

Or rename the function as:

private void DoFlow()
{
   X = x;
   Y = y;
}

Though the whole code does not make any sense to me.

What is an MvcHtmlString and when should I use it?

A nice practical use of this is if you want to make your own HtmlHelper extensions. For example, I hate trying to remember the <link> tag syntax, so I've created my own extension method to make a <link> tag:

<Extension()> _
Public Function CssBlock(ByVal html As HtmlHelper, ByVal src As String, ByVal Optional ByVal htmlAttributes As Object = Nothing) As MvcHtmlString
    Dim tag = New TagBuilder("link")
    tag.MergeAttribute("type", "text/css")
    tag.MergeAttribute("rel", "stylesheet")
    tag.MergeAttribute("href", src)
    tag.MergeAttributes(New RouteValueDictionary(htmlAttributes))
    Dim result = tag.ToString(TagRenderMode.Normal)
    Return MvcHtmlString.Create(result)
End Function

I could have returned String from this method, but if I had the following would break:

<%: Html.CssBlock(Url.Content("~/sytles/mysite.css")) %>

With MvcHtmlString, using either <%: ... %> or <%= ... %> will both work correctly.

Changing an element's ID with jQuery

Your syntax is incorrect, you should pass the value as the second parameter:

jQuery(this).prev("li").attr("id","newId");

How to resolve "Could not find schema information for the element/attribute <xxx>"?

I configured the app.config with the tool for EntLib configuration and set up my LoggingConfiguration block. Then I copied this into the DotNetConfig.xsd. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore.

<xs:element name="loggingConfiguration">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="listeners">
        <xs:complexType>
          <xs:sequence>
            <xs:element maxOccurs="unbounded" name="add">
              <xs:complexType>
                <xs:attribute name="fileName" type="xs:string" use="required" />
                <xs:attribute name="footer" type="xs:string" use="required" />
                <xs:attribute name="formatter" type="xs:string" use="required" />
                <xs:attribute name="header" type="xs:string" use="required" />
                <xs:attribute name="rollFileExistsBehavior" type="xs:string" use="required" />
                <xs:attribute name="rollInterval" type="xs:string" use="required" />
                <xs:attribute name="rollSizeKB" type="xs:unsignedByte" use="required" />
                <xs:attribute name="timeStampPattern" type="xs:string" use="required" />
                <xs:attribute name="listenerDataType" type="xs:string" use="required" />
                <xs:attribute name="traceOutputOptions" type="xs:string" use="required" />
                <xs:attribute name="filter" type="xs:string" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="formatters">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="add">
              <xs:complexType>
                <xs:attribute name="template" type="xs:string" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="logFilters">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="add">
              <xs:complexType>
                <xs:attribute name="enabled" type="xs:boolean" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="categorySources">
        <xs:complexType>
          <xs:sequence>
            <xs:element maxOccurs="unbounded" name="add">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="listeners">
                    <xs:complexType>
                      <xs:sequence>
                        <xs:element name="add">
                          <xs:complexType>
                            <xs:attribute name="name" type="xs:string" use="required" />
                          </xs:complexType>
                        </xs:element>
                      </xs:sequence>
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="specialSources">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="allEvents">
              <xs:complexType>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
            <xs:element name="notProcessed">
              <xs:complexType>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
            <xs:element name="errors">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="listeners">
                    <xs:complexType>
                      <xs:sequence>
                        <xs:element name="add">
                          <xs:complexType>
                            <xs:attribute name="name" type="xs:string" use="required" />
                          </xs:complexType>
                        </xs:element>
                      </xs:sequence>
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
    <xs:attribute name="name" type="xs:string" use="required" />
    <xs:attribute name="tracingEnabled" type="xs:boolean" use="required" />
    <xs:attribute name="defaultCategory" type="xs:string" use="required" />
    <xs:attribute name="logWarningsWhenNoCategoriesMatch" type="xs:boolean" use="required" />
  </xs:complexType>
</xs:element>

How to convert strings into integers in Python?

In Python 3.5.1 things like these work:

c = input('Enter number:')
print (int(float(c)))
print (round(float(c)))

and

Enter number:  4.7
4
5

George.

JQuery wait for page to finish loading before starting the slideshow?

If you pass jQuery a function, it will not run until the page has loaded:

<script type="text/javascript">
$(function() {
    //your header rotation code goes here
});
</script>

Convert js Array() to JSon object for use with JQuery .ajax

When using the data on the server, your characters can reach with the addition of slashes eg if string = {"hello"} comes as string = {\ "hello \"} to solve the following function can be used later to use json decode.

<?php
function stripslashes_deep($value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

    return $value;
}

$array = $_POST['jObject'];
$array = stripslashes_deep($array);

$data = json_decode($array, true);
print_r($data);
?>

The connection to adb is down, and a severe error has occurred

The connection to adb is down, and a severe error has occured.

[2011-12-19 11:45:09 - RayhReport] You must restart adb and Eclipse.
[2011-12-19 11:45:09 - RayhReport] Please ensure that adb is correctly located at 'D:\android-sdk-windows\tools\adb.exe' and can be executed.

When you go to D:\android-sdk-windows\tools\adb.exe path then you see the text file,the name of file is "adb_has_moved" thats means your adb.exe is moved to platform-tools copied down the adb.exe and paste in tools folder and run it. I'm sure it works.

Android get image from gallery into ImageView

Simple pass Intent first:

Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);

And you will get picture path on your onActivityResult:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }
    }

for full source code here

How to skip the OPTIONS preflight request?

setting the content-type to undefined would make javascript pass the header data As it is , and over writing the default angular $httpProvider header configurations. Angular $http Documentation

$http({url:url,method:"POST", headers:{'Content-Type':undefined}).then(success,failure);

How to create Custom Ratings bar in Android

Making the custom rating bar with layer list and selectors is complex, it is better to override the RatingBar class and create a custom RatingBar. createBackgroundDrawableShape() is the function where you should put your empty state png and createProgressDrawableShape() is the function where you should put your filled state png.

Note: This code will not work with svg for now.

public class CustomRatingBar extends RatingBar {

    @Nullable
    private Bitmap mSampleTile;

    public ShapeDrawableRatingBar(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        setProgressDrawable(createProgressDrawable());
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (mSampleTile != null) {
            final int width = mSampleTile.getWidth() * getNumStars();
            setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0), getMeasuredHeight());
        }
    }

    protected LayerDrawable createProgressDrawable() {
        final Drawable backgroundDrawable = createBackgroundDrawableShape();
        LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{
            backgroundDrawable,
            backgroundDrawable,
            createProgressDrawableShape()
        });

        layerDrawable.setId(0, android.R.id.background);
        layerDrawable.setId(1, android.R.id.secondaryProgress);
        layerDrawable.setId(2, android.R.id.progress);
        return layerDrawable;
    }

    protected Drawable createBackgroundDrawableShape() {
        final Bitmap tileBitmap = drawableToBitmap(getResources().getDrawable(R.drawable.ic_star_empty));
        if (mSampleTile == null) {
            mSampleTile = tileBitmap;
        }
        final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape());
        final BitmapShader bitmapShader = new BitmapShader(tileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
        shapeDrawable.getPaint().setShader(bitmapShader);
        return shapeDrawable;
    }

    protected Drawable createProgressDrawableShape() {
        final Bitmap tileBitmap = drawableToBitmap(getResources().getDrawable(R.drawable.ic_star_full));
        final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape());
        final BitmapShader bitmapShader = new BitmapShader(tileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
        shapeDrawable.getPaint().setShader(bitmapShader);
        return new ClipDrawable(shapeDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
    }

    Shape getDrawableShape() {
        final float[] roundedCorners = new float[]{5, 5, 5, 5, 5, 5, 5, 5};
        return new RoundRectShape(roundedCorners, null, null);
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        int width = drawable.getIntrinsicWidth();
        width = width > 0 ? width : 1;
        int height = drawable.getIntrinsicHeight();
        height = height > 0 ? height : 1;

        final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }
}

Statistics: combinations in Python

Why not write it yourself? It's a one-liner or such:

from operator import mul    # or mul=lambda x,y:x*y
from fractions import Fraction

def nCk(n,k): 
  return int( reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1) )

Test - printing Pascal's triangle:

>>> for n in range(17):
...     print ' '.join('%5d'%nCk(n,k) for k in range(n+1)).center(100)
...     
                                                   1                                                
                                                1     1                                             
                                             1     2     1                                          
                                          1     3     3     1                                       
                                       1     4     6     4     1                                    
                                    1     5    10    10     5     1                                 
                                 1     6    15    20    15     6     1                              
                              1     7    21    35    35    21     7     1                           
                           1     8    28    56    70    56    28     8     1                        
                        1     9    36    84   126   126    84    36     9     1                     
                     1    10    45   120   210   252   210   120    45    10     1                  
                  1    11    55   165   330   462   462   330   165    55    11     1               
               1    12    66   220   495   792   924   792   495   220    66    12     1            
            1    13    78   286   715  1287  1716  1716  1287   715   286    78    13     1         
         1    14    91   364  1001  2002  3003  3432  3003  2002  1001   364    91    14     1      
      1    15   105   455  1365  3003  5005  6435  6435  5005  3003  1365   455   105    15     1   
    1    16   120   560  1820  4368  8008 11440 12870 11440  8008  4368  1820   560   120    16     1
>>> 

PS. edited to replace int(round(reduce(mul, (float(n-i)/(i+1) for i in range(k)), 1))) with int(reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1)) so it won't err for big N/K

Redirect all to index.php using htaccess

Silly answer but if you can't figure out why its not redirecting check that the following is enabled for the web folder ..

AllowOverride All

This will enable you to run htaccess which must be running! (there are alternatives but not on will cause problems https://httpd.apache.org/docs/2.4/mod/core.html#allowoverride)

How to terminate a python subprocess launched with shell=True

As Sai said, the shell is the child, so signals are intercepted by it -- best way I've found is to use shell=False and use shlex to split the command line:

if isinstance(command, unicode):
    cmd = command.encode('utf8')
args = shlex.split(cmd)

p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

Then p.kill() and p.terminate() should work how you expect.

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

How to check if BigDecimal variable == 0 in java?

I usually use the following:

if (selectPrice.compareTo(BigDecimal.ZERO) == 0) { ... }

How to store and retrieve a dictionary with redis

you can pickle your dict and save as string.

import pickle
import redis

r = redis.StrictRedis('localhost')
mydict = {1:2,2:3,3:4}
p_mydict = pickle.dumps(mydict)
r.set('mydict',p_mydict)

read_dict = r.get('mydict')
yourdict = pickle.loads(read_dict)

How to install PostgreSQL's pg gem on Ubuntu?

If you have libpq-dev installed and are still having this problem it is likely due to conflicting versions of OpenSSL's libssl and friends - the Ubuntu system version in /usr/lib (which libpq is built against) and a second version RVM installed in $HOME/.rvm/usr/lib (or /usr/local/rvm/usr/lib if it's a system install). You can verify this by temporarily renaming $HOME/.rvm/usr/lib and seeing if "gem install pg" works.

To solve the problem have rvm rebuild using the system OpenSSL libraries (you may need to manually remove libssl.* and libcrypto.* from the rvm/usr/lib dir):

rvm reinstall 1.9.3 --with-openssl-dir=/usr

This finally solved the problem for me on Ubunto 12.04.

maven "cannot find symbol" message unhelpful

SOLUTION: @Before building your component (using mvn clean install). Build the entire project once and build your component again

WHY SO :
I get this error many times. Most of the times I will try to build my component alone (As I have not made changes elsewhere).

Right, But that extra jar which has been downloaded recently might have affected by changes done by a third party(inside their component). Making a full mvn clean install on entire project saved me many times

Is true == 1 and false == 0 in JavaScript?

It's true that true and false don't represent any numerical values in Javascript.

In some languages (e.g. C, VB), the boolean values are defined as actual numerical values, so they are just different names for 1 and 0 (or -1 and 0).

In some other languages (e.g. Pascal, C#), there is a distinct boolean type that is not numerical. It's possible to convert between boolean values and numerical values, but it doesn't happen automatically.

Javascript falls in the category that has a distinct boolean type, but on the other hand Javascript is quite keen to convert values between different data types.

For example, eventhough a number is not a boolean, you can use a numeric value where a boolean value is expected. Using if (1) {...} works just as well as if (true) {...}.

When comparing values, like in your example, there is a difference between the == operator and the === operator. The == equality operator happily converts between types to find a match, so 1 == true evaluates to true because true is converted to 1. The === type equality operator doesn't do type conversions, so 1 === true evaluates to false because the values are of different types.

Change URL without refresh the page

Update

Based on Manipulating the browser history, passing the empty string as second parameter of pushState method (aka title) should be safe against future changes to the method, so it's better to use pushState like this:

history.pushState(null, '', '/en/step2');    

You can read more about that in mentioned article

Original Answer

Use history.pushState like this:

history.pushState(null, null, '/en/step2');

Update 2 to answer Idan Dagan's comment:

Why not using history.replaceState()?

From MDN

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one

That means if you use replaceState, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState doesn't add new entry to history) and it's not recommended and provide bad UX.

Update 3 to add window.onpopstate

So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState, you can detect the back/forward button navigation by using window.onpopstate like this:

window.onpopstate = function(e) {
    // ... 
};

As the first argument of pushState is an object, if you passed an object instead of null, you can access that object in onpopstate which is very handy, here is how:

window.onpopstate = function(e) {
    if(e.state) {
        console.log(e.state);
    }
};

Update 4 to add Reading the current state:

When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate event using the history.state property like this:

console.log(history.state);

Bonus: Use following to check history.pushState support:

if (history.pushState) {
  // \o/
}

Chart creating dynamically. in .net, c#

You need to attach the Form1_Load handler to the Load event:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Diagnostics;

namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Random rnd = new Random();
            Chart mych = new Chart();
            mych.Height = 100;
            mych.Width = 100;
            mych.BackColor = SystemColors.Highlight;
            mych.Series.Add("duck");

            mych.Series["duck"].SetDefault(true);
            mych.Series["duck"].Enabled = true;
            mych.Visible = true;

            for (int q = 0; q < 10; q++)
            {
                int first = rnd.Next(0, 10);
                int second = rnd.Next(0, 10);
                mych.Series["duck"].Points.AddXY(first, second);
                Debug.WriteLine(first + "  " + second);
            }

            Controls.Add(mych);
        }
    }
}

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

This code worked for me

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserDetail>()
            .HasRequired(d => d.User)
            .WithOptional(u => u.UserDetail)
            .WillCascadeOnDelete(true);
    }

The migration code was:

public override void Up()
    {
        AddForeignKey("UserDetail", "UserId", "User", "UserId", cascadeDelete: true);
    }

And it worked fine. When I first used

modelBuilder.Entity<User>()
    .HasOptional(a => a.UserDetail)
    .WithOptionalDependent()
    .WillCascadeOnDelete(true);

The migration code was:

AddForeignKey("User", "UserDetail_UserId", "UserDetail", "UserId", cascadeDelete: true); 

but it does not match any of the two overloads available (in EntityFramework 6)

Embed image in a <button> element

try this

   <input type="button" style="background-image:url('your_url')"/>

Identify if a string is a number

I know this is an old thread, but none of the answers really did it for me - either inefficient, or not encapsulated for easy reuse. I also wanted to ensure it returned false if the string was empty or null. TryParse returns true in this case (an empty string does not cause an error when parsing as a number). So, here's my string extension method:

public static class Extensions
{
    /// <summary>
    /// Returns true if string is numeric and not empty or null or whitespace.
    /// Determines if string is numeric by parsing as Double
    /// </summary>
    /// <param name="str"></param>
    /// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
    /// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
    /// <returns></returns>
    public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
        CultureInfo culture = null)
    {
        double num;
        if (culture == null) culture = CultureInfo.InvariantCulture;
        return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
    }
}

Simple to use:

var mystring = "1234.56789";
var test = mystring.IsNumeric();

Or, if you want to test other types of number, you can specify the 'style'. So, to convert a number with an Exponent, you could use:

var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);

Or to test a potential Hex string, you could use:

var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)

The optional 'culture' parameter can be used in much the same way.

It is limited by not being able to convert strings that are too big to be contained in a double, but that is a limited requirement and I think if you are working with numbers larger than this, then you'll probably need additional specialised number handling functions anyway.

javascript regex - look behind alternative?

Below is a positive lookbehind JavaScript alternative showing how to capture the last name of people with 'Michael' as their first name.

1) Given this text:

const exampleText = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green Miller and Michael Wood?";

get an array of last names of people named Michael. The result should be: ["Jordan","Johnson","Green","Wood"]

2) Solution:

function getMichaelLastName2(text) {
  return text
    .match(/(?:Michael )([A-Z][a-z]+)/g)
    .map(person => person.slice(person.indexOf(' ')+1));
}

// or even
    .map(person => person.slice(8)); // since we know the length of "Michael "

3) Check solution

console.log(JSON.stringify(    getMichaelLastName(exampleText)    ));
// ["Jordan","Johnson","Green","Wood"]

Demo here: http://codepen.io/PiotrBerebecki/pen/GjwRoo

You can also try it out by running the snippet below.

_x000D_
_x000D_
const inputText = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green Miller and Michael Wood?";_x000D_
_x000D_
_x000D_
_x000D_
function getMichaelLastName(text) {_x000D_
  return text_x000D_
    .match(/(?:Michael )([A-Z][a-z]+)/g)_x000D_
    .map(person => person.slice(8));_x000D_
}_x000D_
_x000D_
console.log(JSON.stringify(    getMichaelLastName(inputText)    ));
_x000D_
_x000D_
_x000D_

How to change the name of a Django app?

Follow these steps to change an app's name in Django:

  1. Rename the folder which is in your project root
  2. Change any references to your app in their dependencies, i.e. the app's views.py, urls.py , 'manage.py' , and settings.py files.
  3. Edit the database table django_content_type with the following command: UPDATE django_content_type SET app_label='<NewAppName>' WHERE app_label='<OldAppName>'
  4. Also if you have models, you will have to rename the model tables. For postgres use ALTER TABLE <oldAppName>_modelName RENAME TO <newAppName>_modelName. For mysql too I think it is the same (as mentioned by @null_radix)
  5. (For Django >= 1.7) Update the django_migrations table to avoid having your previous migrations re-run: UPDATE django_migrations SET app='<NewAppName>' WHERE app='<OldAppName>'. Note: there is some debate (in comments) if this step is required for Django 1.8+; If someone knows for sure please update here.
  6. If your models.py 's Meta Class has app_name listed, make sure to rename that too (mentioned by @will).
  7. If you've namespaced your static or templates folders inside your app, you'll also need to rename those. For example, rename old_app/static/old_app to new_app/static/new_app.
  8. For renaming django models, you'll need to change django_content_type.name entry in DB. For postgreSQL use UPDATE django_content_type SET name='<newModelName>' where name='<oldModelName>' AND app_label='<OldAppName>'

Meta point (If using virtualenv): Worth noting, if you are renaming the directory that contains your virtualenv, there will likely be several files in your env that contain an absolute path and will also need to be updated. If you are getting errors such as ImportError: No module named ... this might be the culprit. (thanks to @danyamachine for providing this).

Other references: you might also want to refer the below links for a more complete picture

  1. Renaming an app with Django and South
  2. How do I migrate a model out of one django app and into a new one?
  3. How to change the name of a Django app?
  4. Backwards migration with Django South
  5. Easiest way to rename a model using Django/South?
  6. Python code (thanks to A.Raouf) to automate the above steps (Untested code. You have been warned!)
  7. Python code (thanks to rafaponieman) to automate the above steps (Untested code. You have been warned!)

Text overflow ellipsis on two lines

Restricting to few lines will work in almost all browsers, but an ellipsis(3 dots) will not be displayed in Firefox & IE. Demo - http://jsfiddle.net/ahzo4b91/1/

div {
width: 300px;
height: 2.8em;
line-height: 1.4em;
display: flex;
-webkit-line-clamp: 2;
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden; 
}

Moving up one directory in Python

Combine Kim's answer with os:

p=Path(os.getcwd())
os.chdir(p.parent)

HTML/CSS: how to put text both right and left aligned in a paragraph

enter image description here

If the texts has different sizes and they must be underlined this is the solution:

<table>
  <tr>
    <td class='left'>January</td>
    <td class='right'>2014</td>
  </tr>
</table>

css:

table{
    width: 100%;
    border-bottom: 2px solid black;
    /*this is the size of the small text's baseline over part  (˜25px*3/4)*/
    line-height: 19.5px; 
}
table td{
    vertical-align: baseline;
}
.left{
    font-family: Arial;
    font-size: 40px;
    text-align: left;

}
.right{
    font-size: 25px;
    text-align: right;
}

demo here

Convert a string date into datetime in Oracle

Hey I had the same problem. I tried to convert '2017-02-20 12:15:32' varchar to a date with TO_DATE('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') and all I received was 2017-02-20 the time disappeared

My solution was to use TO_TIMESTAMP('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') now the time doesn't disappear.

How to get file name from file path in android

The easiest solution is to use Uri.getLastPathSegment():

String filename = uri.getLastPathSegment();

useState set method not reflecting change immediately

Much like setState in Class components created by extending React.Component or React.PureComponent, the state update using the updater provided by useState hook is also asynchronous, and will not be reflected immediately.

Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their current closures, and state updates will reflect in the next re-render by which the existing closures are not affected, but new ones are created. Now in the current state, the values within hooks are obtained by existing closures, and when a re-render happens, the closures are updated based on whether the function is recreated again or not.

Even if you add a setTimeout the function, though the timeout will run after some time by which the re-render would have happened, the setTimeout will still use the value from its previous closure and not the updated one.

setMovies(result);
console.log(movies) // movies here will not be updated

If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate in class components since the setter returned by useState doesn't have a callback pattern

useEffect(() => {
    // action on update of movies
}, [movies]);

As far as the syntax to update state is concerned, setMovies(result) will replace the previous movies value in the state with those available from the async request.

However, if you want to merge the response with the previously existing values, you must use the callback syntax of state updation along with the correct use of spread syntax like

setMovies(prevMovies => ([...prevMovies, ...result]));

Escape regex special characters in a Python string

I'm surprised no one has mentioned using regular expressions via re.sub():

import re
print re.sub(r'([\"])',    r'\\\1', 'it\'s "this"')  # it's \"this\"
print re.sub(r"([\'])",    r'\\\1', 'it\'s "this"')  # it\'s "this"
print re.sub(r'([\" \'])', r'\\\1', 'it\'s "this"')  # it\'s\ \"this\"

Important things to note:

  • In the search pattern, include \ as well as the character(s) you're looking for. You're going to be using \ to escape your characters, so you need to escape that as well.
  • Put parentheses around the search pattern, e.g. ([\"]), so that the substitution pattern can use the found character when it adds \ in front of it. (That's what \1 does: uses the value of the first parenthesized group.)
  • The r in front of r'([\"])' means it's a raw string. Raw strings use different rules for escaping backslashes. To write ([\"]) as a plain string, you'd need to double all the backslashes and write '([\\"])'. Raw strings are friendlier when you're writing regular expressions.
  • In the substitution pattern, you need to escape \ to distinguish it from a backslash that precedes a substitution group, e.g. \1, hence r'\\\1'. To write that as a plain string, you'd need '\\\\\\1' — and nobody wants that.

What is the GAC in .NET?

GAC = Global Assembly Cache

Let's break it down:

  • global - applies to the entire machine
  • assembly - what .NET calls its code-libraries (DLLs)
  • cache - a place to store things for faster/common access

So the GAC must be a place to store code libraries so they're accessible to all applications running on the machine.

How can I tell if a Java integer is null?

This should help.

Integer startIn = null;

// (optional below but a good practice, to prevent errors.)
boolean dontContinue = false;
try {
  Integer.parseInt (startField.getText());
} catch (NumberFormatException e){
  e.printStackTrace();
}

// in java = assigns a boolean in if statements oddly.
// Thus double equal must be used. So if startIn is null, display the message
if (startIn == null) {
  JOptionPane.showMessageDialog(null,
       "You must enter a number between 0-16.","Input Error",
       JOptionPane.ERROR_MESSAGE);                            
}

// (again optional)
if (dontContinue == true) {
  //Do-some-error-fix
}

Difference between DOM parentNode and parentElement

parentElement is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.

In most cases, it is the same as parentNode. The only difference comes when a node's parentNode is not an element. If so, parentElement is null.

As an example:

document.body.parentNode; // the <html> element
document.body.parentElement; // the <html> element

document.documentElement.parentNode; // the document node
document.documentElement.parentElement; // null

(document.documentElement.parentNode === document);  // true
(document.documentElement.parentElement === document);  // false

Since the <html> element (document.documentElement) doesn't have a parent that is an element, parentElement is null. (There are other, more unlikely, cases where parentElement could be null, but you'll probably never come across them.)

Which is the correct C# infinite loop, for (;;) or while (true)?

Alternatively one could say having an infinite loop is normally bad practice anyway, since it needs an exit condition unless the app really runs forever. However, if this is for a cruise missile I will accept an explicit exit condition might not be required.

Though I do like this one:

for (float f = 16777216f; f < 16777217f; f++) { } 

ICommand MVVM implementation

@Carlo I really like your implementation of this, but I wanted to share my version and how to use it in my ViewModel

First implement ICommand

public class Command : ICommand
{
    public delegate void ICommandOnExecute();
    public delegate bool ICommandOnCanExecute();

    private ICommandOnExecute _execute;
    private ICommandOnCanExecute _canExecute;

    public Command(ICommandOnExecute onExecuteMethod, ICommandOnCanExecute onCanExecuteMethod = null)
    {
        _execute = onExecuteMethod;
        _canExecute = onCanExecuteMethod;
    }

    #region ICommand Members

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute?.Invoke() ?? true;
    }

    public void Execute(object parameter)
    {
        _execute?.Invoke();
    }

    #endregion
}

Notice I have removed the parameter from ICommandOnExecute and ICommandOnCanExecute and added a null to the constructor

Then to use in the ViewModel

public Command CommandToRun_WithCheck
{
    get
    {
        return new Command(() =>
        {
            // Code to run
        }, () =>
        {
            // Code to check to see if we can run 
            // Return true or false
        });
    }
}

public Command CommandToRun_NoCheck
{
    get
    {
        return new Command(() =>
        {
            // Code to run
        });
    }
}

I just find this way cleaner as I don't need to assign variables and then instantiate, it all done in one go.

How to exit a function in bash

Use return operator:

function FUNCT {
  if [ blah is false ]; then
    return 1 # or return 0, or even you can omit the argument.
  else
    keep running the function
  fi
}

How to re-create database for Entity Framework?

I would like to add that Lin's answer is correct.

If you improperly delete the MDF you will have to fix it. To fix the screwed up connections in the project to the MDF. Short answer; recreate and delete it properly.

  1. Create a new MDF and name it the same as the old MDF, put it in the same folder location. You can create a new project and create a new mdf. The mdf does not have to match your old tables, because were going to delete it. So create or copy an old one to the correct folder.
  2. Open it in server explorer [double click the mdf from solution explorer]
  3. Delete it in server explorer
  4. Delete it from solution explorer
  5. run update-database -force [Use force if necessary]

Done, enjoy your new db

UPDATE 11/12/14 - I use this all the time when I make a breaking db change. I found this is a great way to roll back your migrations to the original db:

  • Puts the db back to original
  • Run the normal migration to put it back to current

    1. Update-Database -TargetMigration:0 -force [This will destroy all tables and all data.]
    2. Update-Database -force [use force if necessary]

Pushing from local repository to GitHub hosted remote

This worked for my GIT version 1.8.4:

  1. From the local repository folder, right click and select 'Git Commit Tool'.
  2. There, select the files you want to upload, under 'Unstaged Changes' and click 'Stage Changed' button. (You can initially click on 'Rescan' button to check what files are modified and not uploaded yet.)
  3. Write a Commit Message and click 'Commit' button.
  4. Now right click in the folder again and select 'Git Bash'.
  5. Type: git push origin master and enter your credentials. Done.

How to fix: "HAX is not working and emulator runs in emulation mode"

My problem was that I could no longer run an emulator that had worked because I had quit the emulator application but the process wasn't fully ended, so I was trying to launch another emulator while the previous one was still running. On a mac, I had to use the Activity Monitor to see the other process and kill it. Steps:

  1. Open Activity Monitor (in Utilities or using Command+Space)
  2. Locate the process name, in my case, qemu-system...
  3. Select the process.
  4. Force the process to quit using the 'x' button in the top left.
  5. I didn't have to use 'Force Quit', just the plain 'Quit', but you can use either.

How to allow CORS in react.js?

on the server side in node.js I just added this and it worked. reactjs front end on my local machine can access api backend hosted on azure:

// Enables CORS
const cors = require('cors');
app.use(cors({ origin: true }));

Plot a bar using matplotlib using a dictionary

For future reference, the above code does not work with Python 3. For Python 3, the D.keys() needs to be converted to a list.

import matplotlib.pyplot as plt

D = {u'Label1':26, u'Label2': 17, u'Label3':30}

plt.bar(range(len(D)), D.values(), align='center')
plt.xticks(range(len(D)), list(D.keys()))

plt.show()

Error "initializer element is not constant" when trying to initialize variable with const

I had this error in code that looked like this:

int A = 1;
int B = A;

The fix is to change it to this

int A = 1;
#define B A

The compiler assigns a location in memory to a variable. The second is trying a assign a second variable to the same location as the first - which makes no sense. Using the macro preprocessor solves the problem.

How do I validate a date in rails?

Using the chronic gem:

class MyModel < ActiveRecord::Base
  validate :valid_date?

  def valid_date?
    unless Chronic.parse(from_date)
      errors.add(:from_date, "is missing or invalid")
    end
  end

end

Using IF ELSE in Oracle

You can use Decode as well:

SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
      AND A.ITEM_KEY = b.item_key
      AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
                         and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item

Get UTC time in seconds

I believe +%s is seconds since epoch. It's timezone invariant.

How do I setup the InternetExplorerDriver so it works

If you are using RemoteDriver things are different. From http://element34.ca/blog/iedriverserver-webdriver-and-python :

You will need to start the server using a line like

java -jar selenium-server-standalone-2.26.0.jar -Dwebdriver.ie.driver=C:\Temp\IEDriverServer.exe

I found that if the IEDriverServer.exe was in C:\Windows\System32\ or its subfolders, it couldn't be found automatically (even though System32 was in the %PATH%) or explicitly using the -D flag.

Using parameters in batch files at Windows command line

Using parameters in batch files: %0 and %9

Batch files can refer to the words passed in as parameters with the tokens: %0 to %9.

%0 is the program name as it was called.
%1 is the first command line parameter
%2 is the second command line parameter
and so on till %9.

parameters passed in on the commandline must be alphanumeric characters and delimited by spaces. Since %0 is the program name as it was called, in DOS %0 will be empty for AUTOEXEC.BAT if started at boot time.

Example:

Put the following command in a batch file called mybatch.bat:

@echo off
@echo hello %1 %2
pause

Invoking the batch file like this: mybatch john billy would output:

hello john billy

Get more than 9 parameters for a batch file, use: %*

The Percent Star token %* means "the rest of the parameters". You can use a for loop to grab them, as defined here:

http://www.robvanderwoude.com/parameters.php

Notes about delimiters for batch parameters

Some characters in the command line parameters are ignored by batch files, depending on the DOS version, whether they are "escaped" or not, and often depending on their location in the command line:

commas (",") are replaced by spaces, unless they are part of a string in 
double quotes

semicolons (";") are replaced by spaces, unless they are part of a string in 
double quotes

"=" characters are sometimes replaced by spaces, not if they are part of a 
string in double quotes

the first forward slash ("/") is replaced by a space only if it immediately 
follows the command, without a leading space

multiple spaces are replaced by a single space, unless they are part of a 
string in double quotes

tabs are replaced by a single space

leading spaces before the first command line argument are ignored

How to diff one file to an arbitrary version in Git?

git diff <revision> <path>

For example:

git diff b0d14a4 foobar.txt

Context.startForegroundService() did not then call Service.startForeground()

I have a widget which does relatively frequent updates when the device is awake and I was seeing thousands of crashes in just a few days.

The issue trigger

I even noticed the issue even on my Pixel 3 XL when I wouldn't have thought the device to have much load at all. And any and all code paths were covered with startForeground(). But then I realized that in many cases my service gets the job done really quickly. I believe the trigger for my app was that the service was finishing before the system actually got around to showing a notification.

The workaround/solution

I was able to get rid of all crashes. What I did was to remove the call to stopSelf(). (I was thinking about delaying the stop until I was pretty sure the notification was shown, but I don't want the user to see the notification if it isn't necessary.) When the service has been idle for a minute or the system destroys it normally without throwing any exceptions.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    stopForeground(true);
} else {
    stopSelf();
}

isset in jQuery?

function isset(element) {
    return element.length > 0;
}

http://jsfiddle.net/8KYxe/1/


Or, as a jQuery extension:

$.fn.exists = function() { return this.length > 0; };

// later ...
if ( $("#id").exists() ) {
  // do something
}

Laravel 5: Display HTML with Blade

You can do that using three ways first use if condition like below

{!! $text !!}

The is Second way

<td class="nowrap">
@if( $order->status == '0' )
    <button class="btn btn-danger">Inactive</button>
@else
    <button class="btn btn-success">Active</button>
@endif
</td>

The third and proper way for use ternary operator on blade

<td class="nowrap">
      {!! $order->status=='0' ? 
          '<button class="btn btn-danger">Inactive</button> : 
          '<button class="btn btn-success">Active</button> !!}
</td>

I hope the third way is perfect for used ternary operator on blade.

Getting HTTP headers with Node.js

I'm not sure how you might do this with Node, but the general idea would be to send an HTTP HEAD request to the URL you're interested in.

HEAD

Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.


Something like this, based it on this question:

var cli = require('cli');
var http = require('http');
var url = require('url');

cli.parse();

cli.main(function(args, opts) {
        this.debug(args[0]);

        var siteUrl = url.parse(args[0]);
        var site = http.createClient(80, siteUrl.host);
        console.log(siteUrl);

        var request = site.request('HEAD', siteUrl.pathname, {'host' : siteUrl.host})
        request.end();

        request.on('response', function(response) {
                response.setEncoding('utf8');
                console.log('STATUS: ' + response.statusCode);
                response.on('data', function(chunk) {
                        console.log("DATA: " + chunk);
                });
        });
});

CSS Equivalent of the "if" statement

CSS has become a very powerful tool over the years and it has hacks for a lot of things javaScript can do

There is a hack in CSS for using conditional statements/logic.

It involves using the symbol '~'

Let me further illustrate with an example.

Let's say you want a background to slide into the page when a button is clicked. All you need to do is use a radio checkbox. Style the label for the radio underneath the button so that when the button is pressed the checkbox is also pressed.

Then you use the code below

.checkbox:checked ~ .background{
opacity:1
width: 100%
}

This code simply states IF the checkbox is CHECKED then open up the background ELSE leave it as it is.

Set selected option of select box

My problem

get_courses(); //// To load the course list
$("#course").val(course); //// Setting default value of the list

I had the same issue . The Only difference from your code is that I was loading the select box through an ajax call and soon as the ajax call was executed I had set the default value of the select box

The Solution

get_courses();
   setTimeout(function() {
     $("#course").val(course);
  }, 10);

ie8 var w= window.open() - "Message: Invalid argument."

Actually a name can be used however it cannot have spaces so window.open("../myPage","MyWindows",...) should work with no problem (window.open).

How to restore default perspective settings in Eclipse IDE

The solution that worked for me. Delete this folder:

workspace/.metadata/.plugins/org.eclipse.e4.workbench

What is the use of hashCode in Java?

From the Javadoc:

Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.)

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.

Try as follows:

  1. Format > Conditional Formating...
  2. Select 'Formula Is' from drop down menu
  3. Enter the following formula:

    =ISERROR(MATCH(A1,$B$1:$B$10,0))

  4. Now select the format you want to highlight the values in col A that do not appear in col B

This will highlight any value in Col A that does not appear in Col B.

laravel select where and where condition

You either need to use first() or get() to fetch the results :

$userRecord = $this->where('email', $email)->where('password', $password)->first();

You most likely need to use first() as you want only one result returned.

If the record isn't found null will be returned. If you are building this query from inside an Eloquent class you could use self .

for example :

$userRecord = self::where('email', $email)->where('password', $password)->first();

More info here

is there a 'block until condition becomes true' function in java?

As nobody published a solution with CountDownLatch. What about:

public class Lockeable {
    private final CountDownLatch countDownLatch = new CountDownLatch(1);

    public void doAfterEvent(){
        countDownLatch.await();
        doSomething();
    }

    public void reportDetonatingEvent(){
        countDownLatch.countDown();
    }
}

How to quickly clear a JavaScript Object?

The short answer to your question, I think, is no (you can just create a new object).

  1. In this example, I believe setting the length to 0 still leaves all of the elements for garbage collection.

  2. You could add this to Object.prototype if it's something you'd frequently use. Yes it's linear in complexity, but anything that doesn't do garbage collection later will be.

  3. This is the best solution. I know it's not related to your question - but for how long do we need to continue supporting IE6? There are many campaigns to discontinue the usage of it.

Feel free to correct me if there's anything incorrect above.

Is there a way to rollback my last push to Git?

Since you are the only user:

git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}

( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )

Without doing any changes to your local repo, you can also do something like:

git push -f origin <sha_of_previous_commit>:master

Generally, in published repos, it is safer to do git revert and then git push

jQuery autoComplete view all on click?

I can't see an obvious way to do that in the docs, but you try triggering the focus (or click) event on the autocomplete enabled textbox:

$('#myButton').click(function() {
   $('#autocomplete').trigger("focus"); //or "click", at least one should work
});

"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

Sometimes opening old project in new version Xcode will get this message.

Go to Issue navigator and follow the warning hint 'Upate to reconmmented settings'.

Boom, magic!

Bootstrap trying to load map file. How to disable it? Do I need to do it?

Delete the line "/*# sourceMappingURL=bootstrap.min.css.map */ " in following files.

  • css/bootstrap.min.css
  • css/bootstrap.css

To fetch the file path in Linux use the command find / -name "\*bootstrap\*"

How to remove not null constraint in sql server using query

Remove column constraint: not null to null

ALTER TABLE test ALTER COLUMN column_01 DROP NOT NULL;

Best way to pretty print a hash

require 'pp'
pp my_hash

Use pp if you need a built-in solution and just want reasonable line breaks.

Use awesome_print if you can install a gem. (Depending on your users, you may wish to use the index:false option to turn off displaying array indices.)

jQuery and AJAX response header

 var geturl;
  geturl = $.ajax({
    type: "GET",
    url: 'http://....',
    success: function () {
      alert("done!"+ geturl.getAllResponseHeaders());
    }
  });

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

How do I convert an enum to a list in C#?

private List<SimpleLogType> GetLogType()
{
  List<SimpleLogType> logList = new List<SimpleLogType>();
  SimpleLogType internalLogType;
  foreach (var logtype in Enum.GetValues(typeof(Log)))
  {
    internalLogType = new SimpleLogType();
    internalLogType.Id = (int) (Log) Enum.Parse(typeof (Log), logtype.ToString(), true);
    internalLogType.Name = (Log)Enum.Parse(typeof(Log), logtype.ToString(), true);
    logList.Add(internalLogType);
  }
  return logList;
}

in top Code , Log is a Enum and SimpleLogType is a structure for logs .

public enum Log
{
  None = 0,
  Info = 1,
  Warning = 8,
  Error = 3
}

How to get Client location using Google Maps API v3?

Try this :)

    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
    function initialize() {
        var loc = {};
        var geocoder = new google.maps.Geocoder();
        if(google.loader.ClientLocation) {
            loc.lat = google.loader.ClientLocation.latitude;
            loc.lng = google.loader.ClientLocation.longitude;

            var latlng = new google.maps.LatLng(loc.lat, loc.lng);
            geocoder.geocode({'latLng': latlng}, function(results, status) {
                if(status == google.maps.GeocoderStatus.OK) {
                    alert(results[0]['formatted_address']);
                };
            });
        }
    }

    google.load("maps", "3.x", {other_params: "sensor=false", callback:initialize});

    </script>

How to align a div to the top of its parent but keeping its inline-block behaviour?

Use vertical-align:top; for the element you want at the top, as I have demonstrated on your jsfiddle.

http://www.brunildo.org/test/inline-block.html

How can I store HashMap<String, ArrayList<String>> inside a list?

Always try to use interface reference in Collection, this adds more flexibility.
What is the problem with the below code?

List<Map<String,List<String>>> list = new ArrayList<Map<String,List<String>>>();//This is the final list you need
Map<String, List<String>> map1 = new HashMap<String, List<String>>();//This is one instance of the  map you want to store in the above list.
List<String> arraylist1 = new ArrayList<String>();
arraylist1.add("Text1");//And so on..
map1.put("key1",arraylist1);
//And so on...
list.add(map1);//In this way you can add.

You can easily do it like the above.

Job for mysqld.service failed See "systemctl status mysqld.service"

I had the same error, the problem was because I no longer had disk space. to check the space run this:

$ df -h

disk space

Then delete some files that you didn't need.

After this commands:

service mysql start
systemctl status mysql.service
mysql -u root -p

After entering with the root password verify that the mysql service was active

Android new Bottom Navigation bar or BottomNavigationView

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation" />

navigation.xml(inside menu)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/title_home"
        app:showAsAction="always|withText"
        android:enabled="true"/>

Inside onCreate() method,

BottomNavigationView navigation = (BottomNavigationView)findViewById(R.id.navigation);
//Dont forgot this line     
BottomNavigationViewHelper.disableShiftMode(navigation);

And Create class as below.

public class BottomNavigationViewHelper {
    public static void disableShiftMode(BottomNavigationView view) {
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
        try {
            Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
            shiftingMode.setAccessible(true);
            shiftingMode.setBoolean(menuView, false);
            shiftingMode.setAccessible(false);
            for (int i = 0; i < menuView.getChildCount(); i++) {
                BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
                //noinspection RestrictedApi
                item.setShiftingMode(false);
                // set once again checked value, so view will be updated
                //noinspection RestrictedApi
                item.setChecked(item.getItemData().isChecked());
            }
        } catch (NoSuchFieldException e) {
            Log.e("BNVHelper", "Unable to get shift mode field", e);
        } catch (IllegalAccessException e) {
            Log.e("BNVHelper", "Unable to change value of shift mode", e);
        }
    }
}

Android - shadow on text?

If you want to achieve a shadow like the one that Android does in the Launcher, we're managing these values. They're useful if you want to create TextViews that will appear as a Widget, without a background.

android:shadowColor="#94000000"
android:shadowDy="2"
android:shadowRadius="4"

Scrolling a flexbox with overflowing content

You can use a position: absolute inside a position: relative

https://codepen.io/Iquixe/pen/RwRzGrM

Printing one character at a time from a string, using the while loop

Python allows you to use a string as an iterator:

for character in 'string':
    print(character)

I'm guessing it's your job to figure out how to turn that into a while loop.

How to prevent vim from creating (and leaving) temporary files?

On Windows add following lines to _vimrc

" store backup, undo, and swap files in temp directory
set directory=$HOME/temp//
set backupdir=$HOME/temp//
set undodir=$HOME/temp//

Java 8 stream's .min() and .max(): why does this compile?

This works because Integer::min resolves to an implementation of the Comparator<Integer> interface.

The method reference of Integer::min resolves to Integer.min(int a, int b), resolved to IntBinaryOperator, and presumably autoboxing occurs somewhere making it a BinaryOperator<Integer>.

And the min() resp max() methods of the Stream<Integer> ask the Comparator<Integer> interface to be implemented.
Now this resolves to the single method Integer compareTo(Integer o1, Integer o2). Which is of type BinaryOperator<Integer>.

And thus the magic has happened as both methods are a BinaryOperator<Integer>.

Editing in the Chrome debugger

This is what you are looking for:

1.- Navigate to the Source tab and open the javascript file

2.- Edit the file, right-click it and a menu will appear: click Save and save it locally.

In order to view the diff or revert your changes, right-click and select the option Local Modifications... from the menu. You will see your changes diff with respect to the original file if you expand the timestamp shown.

More detailed info here: http://www.sitepoint.com/edit-source-files-in-chrome/

Jquery: How to check if the element has certain css class/style

if($('#someElement').hasClass('test')) {
  ... do something ...
}
else {
  ... do something else ...
}

How can I revert a single file to a previous version?

Let's start with a qualitative description of what we want to do (much of this is said in Ben Straub's answer). We've made some number of commits, five of which changed a given file, and we want to revert the file to one of the previous versions. First of all, git doesn't keep version numbers for individual files. It just tracks content - a commit is essentially a snapshot of the work tree, along with some metadata (e.g. commit message). So, we have to know which commit has the version of the file we want. Once we know that, we'll need to make a new commit reverting the file to that state. (We can't just muck around with history, because we've already pushed this content, and editing history messes with everyone else.)

So let's start with finding the right commit. You can see the commits which have made modifications to given file(s) very easily:

git log path/to/file

If your commit messages aren't good enough, and you need to see what was done to the file in each commit, use the -p/--patch option:

git log -p path/to/file

Or, if you prefer the graphical view of gitk

gitk path/to/file

You can also do this once you've started gitk through the view menu; one of the options for a view is a list of paths to include.

Either way, you'll be able to find the SHA1 (hash) of the commit with the version of the file you want. Now, all you have to do is this:

# get the version of the file from the given commit
git checkout <commit> path/to/file
# and commit this modification
git commit

(The checkout command first reads the file into the index, then copies it into the work tree, so there's no need to use git add to add it to the index in preparation for committing.)

If your file may not have a simple history (e.g. renames and copies), see VonC's excellent comment. git can be directed to search more carefully for such things, at the expense of speed. If you're confident the history's simple, you needn't bother.

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

I had this problem. Reinstalling the latest version of Adobe Reader did nothing. Adobe Reader worked in Chrome but not in IE. This worked for me ...

1) Go to IE's Tools-->Compatibility View menu.
2) Enter a website that has the PDF you wish to see. Click OK.
3) Restart IE 4) Go to the website you entered and select the PDF. It should come up.
5) Go back to Compatibility View and delete the entry you made.
6) Adobe Reader works OK now in IE on all websites.

It's a strange fix, but it worked for me. I needed to go through an Adobe acceptance screen after reinstall that only appeared after I did the Compatibility View trick. Once accepted, it seemed to work everywhere. Pretty flaky stuff. Hope this helps someone.

How do I find Waldo with Mathematica?

I agree with @GregoryKlopper that the right way to solve the general problem of finding Waldo (or any object of interest) in an arbitrary image would be to train a supervised machine learning classifier. Using many positive and negative labeled examples, an algorithm such as Support Vector Machine, Boosted Decision Stump or Boltzmann Machine could likely be trained to achieve high accuracy on this problem. Mathematica even includes these algorithms in its Machine Learning Framework.

The two challenges with training a Waldo classifier would be:

  1. Determining the right image feature transform. This is where @Heike's answer would be useful: a red filter and a stripped pattern detector (e.g., wavelet or DCT decomposition) would be a good way to turn raw pixels into a format that the classification algorithm could learn from. A block-based decomposition that assesses all subsections of the image would also be required ... but this is made easier by the fact that Waldo is a) always roughly the same size and b) always present exactly once in each image.
  2. Obtaining enough training examples. SVMs work best with at least 100 examples of each class. Commercial applications of boosting (e.g., the face-focusing in digital cameras) are trained on millions of positive and negative examples.

A quick Google image search turns up some good data -- I'm going to have a go at collecting some training examples and coding this up right now!

However, even a machine learning approach (or the rule-based approach suggested by @iND) will struggle for an image like the Land of Waldos!

public static const in TypeScript

Thank you WiredPrairie!

Just to expand on your answer a bit, here is a complete example of defining a constants class.

// CYConstants.ts

class CYConstants {
    public static get NOT_FOUND(): number    { return -1; }
    public static get EMPTY_STRING(): string { return ""; }
}

export = CYConstants;

To use

// main.ts

import CYConstants = require("./CYConstants");

console.log(CYConstants.NOT_FOUND);    // Prints -1
console.log(CYConstants.EMPTY_STRING); // Prints "" (Nothing!)

Selecting a row in DataGridView programmatically

Not tested, but I think you can do the following:

dataGrid.Rows[index].Selected = true;

or you could do the following (but again: not tested):

dataGrid.SelectedRows.Clear();
foreach(DataGridViewRow row in dataGrid.Rows)
{
    if(YOUR CONDITION)
       row.Selected = true;
}

Is an empty href valid?

The current HTML5 draft also allows ommitting the href attribute completely.

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant.

To answer your question: Yes it's valid.

Converting float to char*

In Arduino:

//temporarily holds data from vals
char charVal[10];                

//4 is mininum width, 3 is precision; float value is copied onto buff
dtostrf(123.234, 4, 3, charVal);

monitor.print("charVal: ");
monitor.println(charVal);

How do I use InputFilter to limit characters in an EditText in Android?

For some reason the android.text.LoginFilter class's constructor is package-scoped, so you can't directly extend it (even though it would be identical to this code). But you can extend LoginFilter.UsernameFilterGeneric! Then you just have this:

class ABCFilter extends LoginFilter.UsernameFilterGeneric {
    public UsernameFilter() {
        super(false); // false prevents not-allowed characters from being appended
    }

    @Override
    public boolean isAllowed(char c) {
        if ('A' <= c && c <= 'C')
            return true;
        if ('a' <= c && c <= 'c')
            return true;

        return false;
    }
}

This isn't really documented, but it's part of the core lib, and the source is straightforward. I've been using it for a while now, so far no problems, though I admit I haven't tried doing anything complex involving spannables.

Pass Multiple Parameters to jQuery ajax call

    var valueOfTextBox=$("#result").val();
    var valueOfSelectedCheckbox=$("#radio:checked").val();

    $.ajax({
    url: 'result.php',
    type: 'POST',
    data: { forValue: valueOfTextBox, check : valueOfSelectedCheckbox } ,
    beforeSend: function() {

          $("#loader").show();
       },
    success: function (response) {
       $("#loader").hide();
       $("#answer").text(response);
    },
    error: function () {
        //$("#loader").show();
        alert("error occured");
    }
    }); 

What's wrong with overridable method calls in constructors?

I guess for Wicket it's better to call add method in the onInitialize() (see components lifecycle) :

public abstract class BasicPage extends WebPage {

    public BasicPage() {
    }

    @Override
    public void onInitialize() {
        add(new Label("title", getTitle()));
    }

    protected abstract String getTitle();
}

How to get Real IP from Visitor?

apply this code for get the ipaddress:

    if (getenv('HTTP_X_FORWARDED_FOR')) { $pipaddress = getenv('HTTP_X_FORWARDED_FOR');
 $ipaddress = getenv('REMOTE_ADDR'); 
    echo "Your Proxy IP address is : ".$pipaddress. "(via $ipaddress)" ; } 
    else { $ipaddress = getenv('REMOTE_ADDR'); echo "Your IP address is : $ipaddress"; }
    ------------------------------------------------------------------------

How to convert int to string on Arduino?

Serial.println(val) 
Serial.println(val, format)

for more you can visit to the site of arduino https://www.arduino.cc/en/Serial/Println

wish this will help you. thanks!

Decimal values in SQL for dividing results

There may be other ways to get your desired result.

Declare @a int
Declare @b int
SET @a = 3
SET @b=2
SELECT cast((cast(@a as float)/ cast(@b as float)) as float)

python numpy machine epsilon

An easier way to get the machine epsilon for a given float type is to use np.finfo():

print(np.finfo(float).eps)
# 2.22044604925e-16

print(np.finfo(np.float32).eps)
# 1.19209e-07

Sublime 3 - Set Key map for function Goto Definition

ctrl != super on windows and linux machines.

If the F12 version of "Goto Definition" produces results of several files, the "ctrl + shift + click" version might not work well. I found that bug when viewing golang project with GoSublime package.

Spring,Request method 'POST' not supported

You are missimg @ModelAttribute annotation for UserProfessionalForm professionalForm parameter in forgotPassword method.

@RequestMapping(value = "proffessional", method = RequestMethod.POST)
public @ResponseBody
String forgotPassword(@ModelAttribute UserProfessionalForm professionalForm,
        BindingResult result, Model model) {

    UserProfileVO userProfileVO = new UserProfileVO();
    userProfileVO.setUser(sessionData.getUser());
    userService.saveUserProfile(userProfileVO);
    model.addAttribute("professional", professionalForm);
    return "Your Professional Details Updated";
}

handling dbnull data in vb.net

This is BY FAR the easiest way to convert DBNull to a string. The trick is that you CANNOT use the TRIM function (which was my initial problem) when referring to the fields from the database:

BEFORE (produced error msg):

Me.txtProvNum.Text = IIf(Convert.IsDBNull(TRIM(myReader("Prov_Num"))), "", TRIM(myReader("Prov_Num")))

AFTER (no more error msg :-) ):

Me.txtProvNum.Text = IIf(Convert.IsDBNull(myReader("Prov_Num")), "", myReader("Prov_Num"))

How do I access ViewBag from JS

if you are using razor engine template then do the following

in your view write :

<script> var myJsVariable = '@ViewBag.MyVariable' </script>

UPDATE: A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```

<head>
 <script>
   var AppConfig = @Html.Raw(Json.Encode(new {
    baseUrl: Url.Content("~"),
    fbApi: "get it from db",
    awsUrl: "get it from db"
   }));
 </script>
</head>

And you can use it in your JavaScript code as follow:

<script>
  myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
  alert(myProduct.fullUrl);
</script>

PHP preg_match - only allow alphanumeric strings and - _ characters

\w\- is probably the best but here just another alternative
Use [:alnum:]

if(!preg_match("/[^[:alnum:]\-_]/",$str)) echo "valid";

demo1 | demo2

PHP foreach change original array values

In PHP, passing by reference (&) is ... controversial. I recommend not using it unless you know why you need it and test the results.

I would recommend doing the following:

foreach ($fields as $key => $field) {
    if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
        $fields[$key]['value'] = "Some error";
    }
}

So basically use $field when you need the values, and $fields[$key] when you need to change the data.

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

How do I animate constraint changes?

// Step 1, update your constraint
self.myOutletToConstraint.constant = 50; // New height (for example)

// Step 2, trigger animation
[UIView animateWithDuration:2.0 animations:^{

    // Step 3, call layoutIfNeeded on your animated view's parent
    [self.view layoutIfNeeded];
}];

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

Why is my Git Submodule HEAD detached from master?

Adding a branch option in .gitmodule is NOT related to the detached behavior of submodules at all. The old answer from @mkungla is incorrect, or obsolete.

From git submodule --help, HEAD detached is the default behavior of git submodule update --remote.

First, there's no need to specify a branch to be tracked. origin/master is the default branch to be tracked.

--remote

Instead of using the superproject's recorded SHA-1 to update the submodule, use the status of the submodule's remote-tracking branch. The remote used is branch's remote (branch.<name>.remote), defaulting to origin. The remote branch used defaults to master.

Why

So why is HEAD detached after update? This is caused by the default module update behavior: checkout.

--checkout

Checkout the commit recorded in the superproject on a detached HEAD in the submodule. This is the default behavior, the main use of this option is to override submodule.$name.update when set to a value other than checkout.

To explain this weird update behavior, we need to understand how do submodules work?

Quote from Starting with Submodules in book Pro Git

Although sbmodule DbConnector is a subdirectory in your working directory, Git sees it as a submodule and doesn’t track its contents when you’re not in that directory. Instead, Git sees it as a particular commit from that repository.

The main repo tracks the submodule with its state at a specific point, the commit id. So when you update modules, you're updating the commit id to a new one.

How

If you want the submodule merged with remote branch automatically, use --merge or --rebase.

--merge

This option is only valid for the update command. Merge the commit recorded in the superproject into the current branch of the submodule. If this option is given, the submodule's HEAD will not be detached.

--rebase

Rebase the current branch onto the commit recorded in the superproject. If this option is given, the submodule's HEAD will not be detached.

All you need to do is,

git submodule update --remote --merge
# or
git submodule update --remote --rebase

Recommended alias:

git config alias.supdate 'submodule update --remote --merge'

# do submodule update with
git supdate

There's also an option to make --merge or --rebase as the default behavior of git submodule update, by setting submodule.$name.update to merge or rebase.

Here's an example about how to config the default update behavior of submodule update in .gitmodule.

[submodule "bash/plugins/dircolors-solarized"]
    path = bash/plugins/dircolors-solarized
    url = https://github.com/seebi/dircolors-solarized.git
    update = merge # <-- this is what you need to add

Or configure it in command line,

# replace $name with a real submodule name
git config -f .gitmodules submodule.$name.update merge

References

Cloud Firestore collection count

Be careful counting number of documents for large collections. It is a little bit complex with firestore database if you want to have a precalculated counter for every collection.

Code like this doesn't work in this case:

export const customerCounterListener = 
    functions.firestore.document('customers/{customerId}')
    .onWrite((change, context) => {

    // on create
    if (!change.before.exists && change.after.exists) {
        return firestore
                 .collection('metadatas')
                 .doc('customers')
                 .get()
                 .then(docSnap =>
                     docSnap.ref.set({
                         count: docSnap.data().count + 1
                     }))
    // on delete
    } else if (change.before.exists && !change.after.exists) {
        return firestore
                 .collection('metadatas')
                 .doc('customers')
                 .get()
                 .then(docSnap =>
                     docSnap.ref.set({
                         count: docSnap.data().count - 1
                     }))
    }

    return null;
});

The reason is because every cloud firestore trigger has to be idempotent, as firestore documentation say: https://firebase.google.com/docs/functions/firestore-events#limitations_and_guarantees

Solution

So, in order to prevent multiple executions of your code, you need to manage with events and transactions. This is my particular way to handle large collection counters:

const executeOnce = (change, context, task) => {
    const eventRef = firestore.collection('events').doc(context.eventId);

    return firestore.runTransaction(t =>
        t
         .get(eventRef)
         .then(docSnap => (docSnap.exists ? null : task(t)))
         .then(() => t.set(eventRef, { processed: true }))
    );
};

const documentCounter = collectionName => (change, context) =>
    executeOnce(change, context, t => {
        // on create
        if (!change.before.exists && change.after.exists) {
            return t
                    .get(firestore.collection('metadatas')
                    .doc(collectionName))
                    .then(docSnap =>
                        t.set(docSnap.ref, {
                            count: ((docSnap.data() && docSnap.data().count) || 0) + 1
                        }));
        // on delete
        } else if (change.before.exists && !change.after.exists) {
            return t
                     .get(firestore.collection('metadatas')
                     .doc(collectionName))
                     .then(docSnap =>
                        t.set(docSnap.ref, {
                            count: docSnap.data().count - 1
                        }));
        }

        return null;
    });

Use cases here:

/**
 * Count documents in articles collection.
 */
exports.articlesCounter = functions.firestore
    .document('articles/{id}')
    .onWrite(documentCounter('articles'));

/**
 * Count documents in customers collection.
 */
exports.customersCounter = functions.firestore
    .document('customers/{id}')
    .onWrite(documentCounter('customers'));

As you can see, the key to prevent multiple execution is the property called eventId in the context object. If the function has been handled many times for the same event, the event id will be the same in all cases. Unfortunately, you must have "events" collection in your database.

Github Push Error: RPC failed; result=22, HTTP code = 413

I already had "HTTPS//" in the git URL yet faced this error.

All I did was to add option -u with push and it worked.

git push -u origin master

Difference between F5, Ctrl + F5 and click on refresh button?

F5 and the refresh button will look at your browser cache before asking the server for content.

Ctrl + F5 forces a load from the server.

You can set content expiration headers and/or meta tags to ensure the browser doesn't cache anything (perhaps something you can do only for the development environment).

Why do we need virtual functions in C++?

I would like to add another use of Virtual function though it uses the same concept as above stated answers but I guess its worth mentioning.

VIRTUAL DESTRUCTOR

Consider this program below, without declaring Base class destructor as virtual; memory for Cat may not be cleaned up.

class Animal {
    public:
    ~Animal() {
        cout << "Deleting an Animal" << endl;
    }
};
class Cat:public Animal {
    public:
    ~Cat() {
        cout << "Deleting an Animal name Cat" << endl;
    }
};

int main() {
    Animal *a = new Cat();
    delete a;
    return 0;
}

Output:

Deleting an Animal
class Animal {
    public:
    virtual ~Animal() {
        cout << "Deleting an Animal" << endl;
    }
};
class Cat:public Animal {
    public:
    ~Cat(){
        cout << "Deleting an Animal name Cat" << endl;
    }
};

int main() {
    Animal *a = new Cat();
    delete a;
    return 0;
}

Output:

Deleting an Animal name Cat
Deleting an Animal

Spring configure @ResponseBody JSON format

For Spring version 4.1.3+

I tried Jama's solution, but then all responses were returned with Content-type 'application/json', including the main, generated HTML page.

Overriding configureMessageConverters(...) prevents spring from setting up the default converters. Spring 4.1.3 allows modification of already configured converters by overriding extendMessageConverters(...):

@Configuration
public class ConverterConfig extends WebMvcConfigurerAdapter {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof AbstractJackson2HttpMessageConverter) {
                AbstractJackson2HttpMessageConverter c = (AbstractJackson2HttpMessageConverter) converter;
                ObjectMapper objectMapper = c.getObjectMapper();
                objectMapper.setSerializationInclusion(Include.NON_NULL);
            }
        }

        super.extendMessageConverters(converters);
    }
}

see org.springframework..WebMvcConfigurationSupport#getMessageConverters()

see org.springframework..WebMvcConfigurationSupport#addDefaultHttpMessageConverters(...)

Can I change the Android startActivity() transition animation?

Starting from API level 5 you can call overridePendingTransition immediately to specify an explicit transition animation:

startActivity();
overridePendingTransition(R.anim.hold, R.anim.fade_in);

or

finish();
overridePendingTransition(R.anim.hold, R.anim.fade_out);

Hide Show content-list with only CSS, no javascript used

A very easy solution from cssportal.com

If pressed [show], the text [show] will be hidden and other way around.

This example does not work in Chrome, I don't why...

_x000D_
_x000D_
.show {_x000D_
 display: none;_x000D_
}_x000D_
.hide:focus + .show {_x000D_
 display: inline;_x000D_
}_x000D_
.hide:focus {_x000D_
 display: none;_x000D_
}_x000D_
.hide:focus ~ #list { display:none; }_x000D_
@media print {_x000D_
.hide, .show {_x000D_
 display: none;_x000D_
}_x000D_
}
_x000D_
<div><a class="hide" href="#">[hide]</a> <a class="show" href="#">[show]</a>_x000D_
<ol id="list">_x000D_
<li>item 1</li>_x000D_
<li>item 2</li>_x000D_
<li>item 3</li>_x000D_
</ol>_x000D_
</div>
_x000D_
_x000D_
_x000D_

AmazonS3 putObject with InputStream length example

If all you are trying to do is solve the content length error from amazon then you could just read the bytes from the input stream to a Long and add that to the metadata.

/*
 * Obtain the Content length of the Input stream for S3 header
 */
try {
    InputStream is = event.getFile().getInputstream();
    contentBytes = IOUtils.toByteArray(is);
} catch (IOException e) {
    System.err.printf("Failed while reading bytes from %s", e.getMessage());
} 

Long contentLength = Long.valueOf(contentBytes.length);

ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(contentLength);

/*
 * Reobtain the tmp uploaded file as input stream
 */
InputStream inputStream = event.getFile().getInputstream();

/*
 * Put the object in S3
 */
try {

    s3client.putObject(new PutObjectRequest(bucketName, keyName, inputStream, metadata));

} catch (AmazonServiceException ase) {
    System.out.println("Error Message:    " + ase.getMessage());
    System.out.println("HTTP Status Code: " + ase.getStatusCode());
    System.out.println("AWS Error Code:   " + ase.getErrorCode());
    System.out.println("Error Type:       " + ase.getErrorType());
    System.out.println("Request ID:       " + ase.getRequestId());
} catch (AmazonClientException ace) {
    System.out.println("Error Message: " + ace.getMessage());
} finally {
    if (inputStream != null) {
        inputStream.close();
    }
}

You'll need to read the input stream twice using this exact method so if you are uploading a very large file you might need to look at reading it once into an array and then reading it from there.

Convert Unicode data to int in python

In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.

So to convert string limit="100" to a number, you need to do

limit = int(limit) # will return new object (integer) and assign to "limit"

If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:

def int_in_place(mutable):
    mutable[0] = int(mutable[0])

mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer

But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

There is another thread with more examples here: A recursive remove directory function for PHP?

If you are using Yii then you can leave it to the framework:

CFileHelper::removeDirectory($my_directory);

How to get calendar Quarter from a date in TSQL

To get the exact output you requested, you can use the below:

CAST(DATEPART(YEAR, @Date) AS NVARCHAR(10)) + ' - Q' + CAST(DATEPART(QUARTER, @Date) AS NVARCHAR(10))

This will give you an outputs like: "2015 - Q1", "2013 - Q3", etc.

Fixed digits after decimal with f-strings

a = 10.1234

print(f"{a:0.2f}")

in 0.2f:

  • 0 is telling python to put no limit on the total number of digits to display
  • .2 is saying that we want to take only 2 digits after decimal (the result will be same as a round() function)
  • f is telling that it's a float number. If you forget f then it will just print 1 less digit after the decimal. In this case, it will be only 1 digit after the decimal.

A detailed video on f-string for numbers https://youtu.be/RtKUsUTY6to?t=606

How to convert const char* to char* in C?

A const to a pointer indicates a "read-only" memory location. Whereas the ones without const are a read-write memory areas. So, you "cannot" convert a const(read-only location) to a normal(read-write) location.

The alternate is to copy the data to a different read-write location and pass this pointer to the required function. You may use strdup() to perform this action.

Laravel 5 - redirect to HTTPS

This worked out for me. I made a custom php code to force redirect it to https. Just include this code on the header.php

<?php
if (isset($_SERVER['HTTPS']) &&
    ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
    isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
    $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
  $protocol = 'https://';
}
else {
  $protocol = 'http://';
}
$notssl = 'http://';
if($protocol==$notssl){
    $url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";?>
    <script> 
    window.location.href ='<?php echo $url?>';
    </script> 
 <?php } ?>

CocoaPods Errors on Project Build

I had a similar problem when I did major changes to my Podfile. My solution was to remove the workspace file and run pod install again:

rm -rf MyProject.xcworkspace
pod install

How do I solve the "server DNS address could not be found" error on Windows 10?

There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.

  1. Go to Control Panel ? Network and Internet ? Network and Sharing Centre
  2. Click on Change Adapter settings.
  3. Right click on your connection icon (Wireless Network Connection or Local Area Connection) and select properties.
  4. Select Internet protocol version 4.
  5. Click on "Use the following DNS server address" and type either of the two DNS given below.

Google Public DNS

Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4

OpenDNS

Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220

Basic calculator in Java

import java.util.Scanner; import javax.swing.JOptionPane;

public class javaCalculator {

public static void main(String[] args) 
{
    int num1;
    int num2;
    String operation;


    Scanner input = new Scanner(System.in);

    System.out.println("please enter the first number");
    num1 = input.nextInt();

    System.out.println("please enter the second number");
    num2 = input.nextInt();

    Scanner op = new Scanner(System.in);

    System.out.println("Please enter operation");
    operation = op.next();

    if (operation.equals("+"))
    {
        System.out.println("your answer is" + (num1 + num2));
    }
   else if  (operation.equals("-"))
    {
        System.out.println("your answer is" + (num1 - num2));
    }

  else if (operation.equals("/"))
    {
        System.out.println("your answer is" + (num1 / num2));
    }
   else if (operation.equals("*"))
    {
        System.out.println("your answer is" + (num1 * num2));
    }
   else 
    {
       System.out.println("Wrong selection");
    }


}

}

How to change Navigation Bar color in iOS 7?

self.navigationBar.barTintColor = [UIColor blueColor];
self.navigationBar.tintColor = [UIColor whiteColor];
self.navigationBar.translucent = NO;

// *barTintColor* sets the background color
// *tintColor* sets the buttons color

What does MVW stand for?

It stands indeed for whatever, as in whatever works for you

MVC vs MVVM vs MVP. What a controversial topic that many developers can spend hours and hours debating and arguing about.

For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it's now closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller.

Being able to categorize a framework and put it into one of the MV* buckets has some advantages. It can help developers get more comfortable with its apis by making it easier to create a mental model that represents the application that is being built with the framework. It can also help to establish terminology that is used by developers.

Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".

Angular gives you a lot of flexibility to nicely separate presentation logic from business logic and presentation state. Please use it fuel your productivity and application maintainability rather than heated discussions about things that at the end of the day don't matter that much.

How can I convert String[] to ArrayList<String>

You can loop all of the array and add into ArrayList:

ArrayList<String> files = new ArrayList<String>(filesOrig.length);
for(String file: filesOrig) {
    files.add(file);
}

Or use Arrays.asList(T... a) to do as the comment posted.

Flutter: RenderBox was not laid out

Reading answers here, it seems that the error "RenderBox was not laid out" is caused when somehow the ListView size is limitless and this can happen in different scenarios.

Just aiming to help who may have the same case as mine. In my case, I was getting this error because my ListView was inside a a column whose parent was a SingleChildScrollView. I remove this parent and it worked.

Here is my working code:

 List _todoList = ["AAA", "BBB"];

 ...

    body: Column(
      children: [
        Container(...),
        Expanded(
            child: ListView.builder(
                itemCount: _todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(_todoList[index]));
                }))
      ],
    ));

Here how it was when I was getting the "not laid out" error:

     List _todoList = ["AAA", "BBB"];

     ...


     body: SingleChildScrollView(child: Column(
      children: [
        Container(...),
        Expanded(
            child: ListView.builder(
                itemCount: _todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(_todoList[index]));
                }))
      ],
    )));

I hope this may be useful for someone.

Tuples( or arrays ) as Dictionary keys in C#

If you're on C# 7, you should consider using value tuples as your composite key. Value tuples typically offer better performance than the traditional reference tuples (Tuple<T1, …>) since value tuples are value types (structs), not reference types, so they avoid the memory allocation and garbage collection costs. Also, they offer conciser and more intuitive syntax, allowing for their fields to be named if you so wish. They also implement the IEquatable<T> interface needed for the dictionary.

var dict = new Dictionary<(int PersonId, int LocationId, int SubjectId), string>();
dict.Add((3, 6, 9), "ABC");
dict.Add((PersonId: 4, LocationId: 9, SubjectId: 10), "XYZ");
var personIds = dict.Keys.Select(k => k.PersonId).Distinct().ToList();

TypeError: unsupported operand type(s) for -: 'str' and 'int'

For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str to int) so you must do this yourself. You'll like that in the long-run, trust me!

Why use HttpClient for Synchronous Connection

In my case the accepted answer did not work. I was calling the API from an MVC application which had no async actions.

This is how I managed to make it work:

private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
public static T RunSync<T>(Func<Task<T>> func)
    {           
        CultureInfo cultureUi = CultureInfo.CurrentUICulture;
        CultureInfo culture = CultureInfo.CurrentCulture;
        return _myTaskFactory.StartNew<Task<T>>(delegate
        {
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = cultureUi;
            return func();
        }).Unwrap<T>().GetAwaiter().GetResult();
    }

Then I called it like this:

Helper.RunSync(new Func<Task<ReturnTypeGoesHere>>(async () => await AsyncCallGoesHere(myparameter)));

How to get a unique device ID in Swift?

I've tried with

let UUID = UIDevice.currentDevice().identifierForVendor?.UUIDString

instead

let UUID = NSUUID().UUIDString

and it works.

LDAP server which is my base dn

Either you set LDAP_DOMAIN variable or you misconfigured it. Jump inside of ldap machine/container and run:

slapcat > backup.ldif

If it fails, check punctuation, quotes etc while you assigned variable "LDAP_DOMAIN" Otherwise you will find answer inside on backup.ldif file.

How do I compile and run a program in Java on my Mac?

You need to make sure that a mac compatible version of java exists on your computer. Do java -version from terminal to check that. If not, download the apple jdk from the apple website. (Sun doesn't make one for apple themselves, IIRC.)

From there, follow the same command line instructions from compiling your program that you would use for java on any other platform.

linux execute command remotely

 ssh user@machine 'bash -s' < local_script.sh

or you can just

 ssh user@machine "remote command to run" 

Check, using jQuery, if an element is 'display:none' or block on click

You can use :visible for visible elements and :hidden to find out hidden elements. This hidden elements have display attribute set to none.

hiddenElements = $(':hidden');
visibleElements = $(':visible');

To check particular element.

if($('#yourID:visible').length == 0)
{

}

Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero, Reference

You can also use is() with :visible

if(!$('#yourID').is(':visible'))
{

}

If you want to check value of display then you can use css()

if($('#yourID').css('display') == 'none')
{

}

If you are using display the following values display can have.

display: none

display: inline

display: block

display: list-item

display: inline-block

Check complete list of possible display values here.

To check the display property with JavaScript

var isVisible = document.getElementById("yourID").style.display == "block";
var isHidden = document.getElementById("yourID").style.display == "none"; 

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

There are situations where it matters.

If you pass AF_INET to socket() in Cygwin, your socket may or may not be randomly reset. Passing PF_INET ensures that the connection works right.

Cygwin is self-admittedly a huge mess for socket programming, but it is a real world case where AF_INET and PF_INET are not identical.

Python foreach equivalent

While the answers above are valid, if you are iterating over a dict {key:value} it this is the approach I like to use:

for key, value in Dictionary.items():
    print(key, value)

Therefore, if I wanted to do something like stringify all keys and values in my dictionary, I would do this:

stringified_dictionary = {}
for key, value in Dictionary.items():
    stringified_dictionary.update({str(key): str(value)})
return stringified_dictionary

This avoids any mutation issues when applying this type of iteration, which can cause erratic behavior (sometimes) in my experience.

Fatal error: Class 'ZipArchive' not found in

For the ZipArchive class to be present, PHP needs to have the zip extension installed.

See this page for installation instructions (both Linux and Windows).

How to merge lists into a list of tuples?

Youre looking for the builtin function zip.

Entity Framework code first unique column

In EF 6.2 using FluentAPI, you can use HasIndex()

modelBuilder.Entity<User>().HasIndex(u => u.UserName).IsUnique();

How to grep for two words existing on the same line?

you could use awk. like this...

cat <yourFile> | awk '/word1/ && /word2/'

Order is not important. So if you have a file and...

a file named , file1 contains:

word1 is in this file as well as word2
word2 is in this file as well as word1
word4 is in this file as well as word1
word5 is in this file as well as word2

then,

/tmp$ cat file1| awk '/word1/ && /word2/'

will result in,

word1 is in this file as well as word2
word2 is in this file as well as word1

yes, awk is slower.

How to change background Opacity when bootstrap modal is open

you could utilize bootstrap events:: as

//when modal opens
$('#yourModal').on('shown.bs.modal', function (e) {
  $("#pageContent").css({ opacity: 0.5 });
})

//when modal closes
$('#yourModal').on('hidden.bs.modal', function (e) {
  $("#pageContent").css({ opacity: 1 });
})

HQL Hibernate INNER JOIN

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="empTable")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String empName;

List<Address> addList=new ArrayList<Address>();


@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="emp_id")
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getEmpName() {
    return empName;
}
public void setEmpName(String empName) {
    this.empName = empName;
}

@OneToMany(mappedBy="employee",cascade=CascadeType.ALL)
public List<Address> getAddList() {
    return addList;
}

public void setAddList(List<Address> addList) {
    this.addList = addList;
}
}

We have two entities Employee and Address with One to Many relationship.

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="address")
public class Address implements Serializable{

private static final long serialVersionUID = 1L;

private int address_id;
private String address;
Employee employee;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getAddress_id() {
    return address_id;
}
public void setAddress_id(int address_id) {
    this.address_id = address_id;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

@ManyToOne
@JoinColumn(name="emp_id")
public Employee getEmployee() {
    return employee;
}
public void setEmployee(Employee employee) {
    this.employee = employee;
}
}

By this way we can implement inner join between two tables

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

public class Main {

public static void main(String[] args) {
    saveEmployee();

    retrieveEmployee();

}

private static void saveEmployee() {
    Employee employee=new Employee();
    Employee employee1=new Employee();
    Employee employee2=new Employee();
    Employee employee3=new Employee();

    Address address=new Address();
    Address address1=new Address();
    Address address2=new Address();
    Address address3=new Address();

    address.setAddress("1485,Sector 42 b");
    address1.setAddress("1485,Sector 42 c");
    address2.setAddress("1485,Sector 42 d");
    address3.setAddress("1485,Sector 42 a");

    employee.setEmpName("Varun");
    employee1.setEmpName("Krishan");
    employee2.setEmpName("Aasif");
    employee3.setEmpName("Dut");

    address.setEmployee(employee);
    address1.setEmployee(employee1);
    address2.setEmployee(employee2);
    address3.setEmployee(employee3);

    employee.getAddList().add(address);
    employee1.getAddList().add(address1);
    employee2.getAddList().add(address2);
    employee3.getAddList().add(address3);

    Session session=HibernateUtil.getSessionFactory().openSession();

    session.beginTransaction();

    session.save(employee);
    session.save(employee1);
    session.save(employee2);
    session.save(employee3);
    session.getTransaction().commit();
    session.close();
}

private static void retrieveEmployee() {
    try{

    String sqlQuery="select e from Employee e inner join e.addList";

    Session session=HibernateUtil.getSessionFactory().openSession();

    Query query=session.createQuery(sqlQuery);

    List<Employee> list=query.list();

     list.stream().forEach((p)->{System.out.println(p.getEmpName());});     
    session.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

I have used Java 8 for loop for priting the names. Make sure you have jdk 1.8 with tomcat 8. Also add some more records for better understanding.

 public class HibernateUtil {
 private static SessionFactory sessionFactory ;
 static {
    Configuration configuration = new Configuration();

    configuration.addAnnotatedClass(Employee.class);
    configuration.addAnnotatedClass(Address.class);
                  configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");                                
    configuration.setProperty("hibernate.connection.username", "root");     
    configuration.setProperty("hibernate.connection.password", "root");
    configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
    configuration.setProperty("hibernate.hbm2ddl.auto", "update");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty(" hibernate.connection.pool_size", "10");


   // configuration
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    sessionFactory = configuration.buildSessionFactory(builder.build());
 }
public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
} 

What does it mean: The serializable class does not declare a static final serialVersionUID field?

From the javadoc:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:

You can configure your IDE to:

  • ignore this, instead of giving a warning.
  • autogenerate an id

As per your additional question "Can it be that the discussed warning message is a reason why my GUI application freeze?":

No, it can't be. It can cause a problem only if you are serializing objects and deserializing them in a different place (or time) where (when) the class has changed, and it will not result in freezing, but in InvalidClassException.

Best practice for Django project working directory structure

You can use https://github.com/Mischback/django-project-skeleton repository.

Run below command:

$ django-admin startproject --template=https://github.com/Mischback/django-project-skeleton/archive/development.zip [projectname]

The structure is something like this:

[projectname]/                  <- project root
+-- [projectname]/              <- Django root
¦   +-- __init__.py
¦   +-- settings/
¦   ¦   +-- common.py
¦   ¦   +-- development.py
¦   ¦   +-- i18n.py
¦   ¦   +-- __init__.py
¦   ¦   +-- production.py
¦   +-- urls.py
¦   +-- wsgi.py
+-- apps/
¦   +-- __init__.py
+-- configs/
¦   +-- apache2_vhost.sample
¦   +-- README
+-- doc/
¦   +-- Makefile
¦   +-- source/
¦       +-- *snap*
+-- manage.py
+-- README.rst
+-- run/
¦   +-- media/
¦   ¦   +-- README
¦   +-- README
¦   +-- static/
¦       +-- README
+-- static/
¦   +-- README
+-- templates/
    +-- base.html
    +-- core
    ¦   +-- login.html
    +-- README

Excel Reference To Current Cell

EDIT: the following is wrong, because Cell("width") returns the width of the last modified cell.

Cell("width") returns the width of the current cell, so you don't need a reference to the current cell. If you need one, though, cell("address") returns the address of the current cell, so if you need a reference to the current cell, use indirect(cell("address")). See the documentation: http://www.techonthenet.com/excel/formulas/cell.php

Graph visualization library in JavaScript

JsVIS was pretty nice, but slow with larger graphs, and has been abandoned since 2007.

prefuse is a set of software tools for creating rich interactive data visualizations in Java. flare is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.

What is reflection and why is it useful?

Java Reflection is quite powerful and can be very useful. Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.

A quick Java Reflection example to show you what using reflection looks like:

Method[] methods = MyObject.class.getMethods();

    for(Method method : methods){
        System.out.println("method = " + method.getName());
    }

This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names.

Exactly how all this works is explained here

Edit: After almost 1 year I am editing this answer as while reading about reflection I got few more uses of Reflection.

  • Spring uses bean configuration such as:


<bean id="someID" class="com.example.Foo">
    <property name="someField" value="someValue" />
</bean>

When the Spring context processes this < bean > element, it will use Class.forName(String) with the argument "com.example.Foo" to instantiate that Class.

It will then again use reflection to get the appropriate setter for the < property > element and set its value to the specified value.

  • Junit uses Reflection especially for testing Private/Protected methods.

For Private methods,

Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);

For private fields,

Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);

Using FolderBrowserDialog in WPF application

If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

Also see this SO thread: Open directory dialog

Java better way to delete file if exists

Use the below statement to delete any files:

FileUtils.forceDelete(FilePath);

Note: Use exception handling codes if you want to use.

Python + Django page redirect

It's simple:

from django.http import HttpResponseRedirect

def myview(request):
    ...
    return HttpResponseRedirect("/path/")

More info in the official Django docs

Update: Django 1.0

There is apparently a better way of doing this in Django now using generic views.

Example -

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',   
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

There is more in the generic views documentation. Credit - Carles Barrobés.

Update #2: Django 1.3+

In Django 1.5 redirect_to no longer exists and has been replaced by RedirectView. Credit to Yonatan

from django.views.generic import RedirectView

urlpatterns = patterns('',
    (r'^one/$', RedirectView.as_view(url='/another/')),
)

SQL datetime format to date only

SELECT Subject, CONVERT(varchar(10),DeliveryDate) as DeliveryDate
from Email_Administration 
where MerchantId =@ MerchantID

Popup window in PHP?

if (isset($_POST['Register']))
    {
        $ErrorArrays = array (); //Empty array for input errors 

        $Input_Username = $_POST['Username'];
        $Input_Password = $_POST['Password'];
        $Input_Confirm = $_POST['ConfirmPass'];
        $Input_Email = $_POST['Email'];

        if (empty($Input_Username))
        {
            $ErrorArrays[] = "Username Is Empty";
        }
        if (empty($Input_Password))
        {
            $ErrorArrays[] = "Password Is Empty";
        }
        if ($Input_Password !== $Input_Confirm)
        {
            $ErrorArrays[] = "Passwords Do Not Match!";
        }
        if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
        {
            $ErrorArrays[] = "Incorrect Email Formatting";
        }

        if (count($ErrorArrays) == 0)
        {
            // No Errors
        }
        else
        {
            foreach ($ErrorArrays AS $Errors)
            {
                echo "<font color='red'><b>".$Errors."</font></b><br>";
            }
        }
    }

?>

    <form method="POST"> 
        Username: <input type='text' name='Username'> <br>
        Password: <input type='password' name='Password'><br>
        Confirm Password: <input type='password' name='ConfirmPass'><br>
        Email: <input type='text' name='Email'> <br><br>

        <input type='submit' name='Register' value='Register'>


    </form> 

This is a very basic PHP Form validation. This could be put in a try block, but for basic reference, I see this fit following our conversation in the comment box.

What this script will do, is process each of the post elements, and act accordingly, for example:

    if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
        {
            $ErrorArrays[] = "Incorrect Email Formatting";
        }

This will check:

if $Input_Email is not a valid email. If this is not a valid E-mail, then a message will get added to a empty array.

Further down the script, you will see:

    if (count($ErrorArrays) == 0)
    {
        // No Errors
    }
    else
    {
        foreach ($ErrorArrays AS $Errors)
        {
            echo "<font color='red'><b>".$Errors."</font></b><br>";
        }
    }

Basically. if the array count is not 0, errors have been found. Then the script will print out the errors.

Remember, this is a reference based on our conversation in the comment box, and should be used as such.

Conditional Logic on Pandas DataFrame

In [34]: import pandas as pd

In [35]: import numpy as np

In [36]:  df = pd.DataFrame([1,2,3,4], columns=["data"])

In [37]: df
Out[37]: 
   data
0     1
1     2
2     3
3     4

In [38]: df["desired_output"] = np.where(df["data"] <2.5, "False", "True")

In [39]: df
Out[39]: 
   data desired_output
0     1          False
1     2          False
2     3           True
3     4           True

how to make a specific text on TextView BOLD

I came here to provide a more up-to-date solution, because I wasn't satisfied with the existing answers. I needed something that would work for translated texts and does not have the performance hit of using Html.fromHtml(). If you're using Kotlin, here is an extension function which will easily set multiple parts of your text to bold. This works just like Markdown, and could be extended to support other Markdown tags, if need be.

val yourString = "**This** is your **string**.".makePartialTextsBold()
val anotherString = getString(R.string.something).makePartialTextsBold()

/**
 * This function requires that the parts of the string that need
 * to be bolded are wrapped in ** and ** tags
 */
fun String.makePartialTextsBold(): SpannableStringBuilder {
    var copy = this
    return SpannableStringBuilder().apply {
        var setSpan = true
        var next: String
        do {
            setSpan = !setSpan
            next = if (length == 0) copy.substringBefore("**", "") else copy.substringBefore("**")
            val start = length
            append(next)
            if (setSpan) {
                setSpan(StyleSpan(Typeface.BOLD), start, length,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }
            copy = copy.removePrefix(next).removePrefix("**")
        } while (copy.isNotEmpty())
    }
}

Repeat a task with a time delay?

For people using Kotlin, inazaruk's answer will not work, the IDE will require the variable to be initialized, so instead of using the postDelayed inside the Runnable, we'll use it in an separate method.

  • Initialize your Runnable like this :

    private var myRunnable = Runnable {
        //Do some work
        //Magic happens here ?
        runDelayedHandler(1000)   }
    
  • Initialize your runDelayedHandler method like this :

     private fun runDelayedHandler(timeToWait : Long) {
        if (!keepRunning) {
            //Stop your handler
            handler.removeCallbacksAndMessages(null)
            //Do something here, this acts like onHandlerStop
        }
        else {
            //Keep it running
            handler.postDelayed(myRunnable, timeToWait)
        }
    }
    
  • As you can see, this approach will make you able to control the lifetime of the task, keeping track of keepRunning and changing it during the lifetime of the application will do the job for you.

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

copy the below content to file tomcat-users.xml

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
<!--
  NOTE:  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary. It is
  strongly recommended that you do NOT use one of the users in the commented out
  section below since they are intended for use with the examples web
  application.
-->
<!--
  NOTE:  The sample user and role entries below are intended for use with the
  examples web application. They are wrapped in a comment and thus are ignored
  when reading this file. If you wish to configure these users for use with the
  examples web application, do not forget to remove the <!.. ..> that surrounds
  them. You will also need to set the passwords to something appropriate.
-->
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
  <user username="role1" password="<must-be-changed>" roles="role1"/>
-->
<role rolename="manager-gui"/>
<role rolename="manager-script"/>

<user username="notadmin" password="not_real_pass" roles="manager-gui"/>
<user username="cargo" password="not_real_pass" roles="manager-script"/>


</tomcat-users>

I have tested, it just works!

enter image description here

What is the difference between properties and attributes in HTML?

Difference HTML properties and attributes:

Let's first look at the definitions of these words before evaluating what the difference is in HTML:

English definition:

  • Attributes are referring to additional information of an object.
  • Properties are describing the characteristics of an object.

In HTML context:

When the browser parses the HTML, it creates a tree data structure wich basically is an in memory representation of the HTML. It the tree data structure contains nodes which are HTML elements and text. Attributes and properties relate to this is the following manner:

  • Attributes are additional information which we can put in the HTML to initialize certain DOM properties.
  • Properties are formed when the browser parses the HTML and generates the DOM. Each of the elements in the DOM have their own set of properties which are all set by the browser. Some of these properties can have their initial value set by HTML attributes. Whenever a DOM property changes which has influence on the rendered page, the page will be immediately re rendered

It is also important to realize that the mapping of these properties is not 1 to 1. In other words, not every attribute which we give on an HTML element will have a similar named DOM property.

Furthermore have different DOM elements different properties. For example, an <input> element has a value property which is not present on a <div> property.

Example:

Let's take the following HTML document:

 <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">  <!-- charset is a attribute -->
  <meta name="viewport" content="width=device-width"> <!-- name and content are attributes -->
  <title>JS Bin</title>
</head>
<body>
<div id="foo" class="bar foobar">hi</div> <!-- id and class are attributes -->
</body>
</html>

Then we inspect the <div>, in the JS console:

 console.dir(document.getElementById('foo'));

We see the following DOM properties (chrome devtools, not all properties shown):

html properties and attributes

  • We can see that the attribute id in the HTML is now also a id property in the DOM. The id has been initialized by the HTML (although we could change it with javascript).
  • We can see that the class attribute in the HTML has no corresponding class property (class is reserved keyword in JS). But actually 2 properties, classList and className.

SASS and @font-face

For those looking for an SCSS mixin instead, including woff2:

@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
  @font-face {
    font-family: $family;
    @if $svg == '' {
      // with OTF without SVG and EOT
      src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
    } @else {
      // traditional src inclusions
      src: url('#{$path}#{$type}.eot');
      src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
    }
    font-weight: $weight;
    font-style: $style;
  }
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);

$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
  font-family: Inter;
  font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
  font-family: AmaticSC;
  font-weight: 700; // default font is loaded
}

The $type parameter is useful for stacking related families with different weights.

The @if is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.

If you get a can't resolve error, remember to double check your fonts directory ($dir).

"Char cannot be dereferenced" error

The type char is a primitive -- not an object -- so it cannot be dereferenced

Dereferencing is the process of accessing the value referred to by a reference. Since a char is already a value (not a reference), it can not be dereferenced.

use Character class:

if(Character.isLetter(c)) {

Get Selected value from Multi-Value Select Boxes by jquery-select2?

This will get selected value from multi-value select boxes: $("#id option:selected").val()

In oracle, how do I change my session to display UTF8?

Okay, per http://www.oracle.com/technology/tech/globalization/htdocs/nls_lang%20faq.htm:

NLS_LANG cannot be changed by ALTER SESSION, NLS_LANGUAGE and NLS_TERRITORY can. However NLS_LANGUAGE and /or NLS_TERRITORY cannot be set as "standalone" parameters in the environment or registry on the client.

Evidently the "right" solution is, before logging into Oracle at all, setting the following environment variable:

export NLS_LANG=AMERICAN_AMERICA.UTF8

Oracle gets a big fat F for usability.

Sending XML data using HTTP POST with PHP

you can use cURL library for posting data: http://www.php.net/curl

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);

where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects

WSDL validator?

you might want to look at the online version of xsv

How to use multiple @RequestMapping annotations in spring?

Right now with using Spring-Boot 2.0.4 - { } won't work.

@RequestMapping

still has String[] as a value parameter, so declaration looks like this:

 @RequestMapping(value=["/","/index","/login","/home"], method = RequestMethod.GET)

** Update - Works With Spring-Boot 2.2**

 @RequestMapping(value={"/","/index","/login","/home"}, method = RequestMethod.GET)

How do I get the XML SOAP request of an WCF Web service request?

There is an another way to see XML SOAP - custom MessageEncoder. The main difference from IClientMessageInspector is that it works on lower level, so it captures original byte content including any malformed xml.

In order to implement tracing using this approach you need to wrap a standard textMessageEncoding with custom message encoder as new binding element and apply that custom binding to endpoint in your config.

Also you can see as example how I did it in my project - wrapping textMessageEncoding, logging encoder, custom binding element and config.

Enable remote connections for SQL Server Express 2012

I had the same issue with SQL Server 2014 locally installed named instance. Connecting using the FQDN\InstanceName would fail, while connecting using only my hostname\InstanceName worked. For example: connecting using mycomputername\sql2014 worked, but using mycomputername.mydomain.org\sql2014 did not. DNS resolved correctly, TCP/IP was enabled within SQL Configuration Manager, Windows Firewall rules added (and then turned the firewall off for testing to ensure it wasn't blocking anything), but none of those fixed the problem.

Finally, I had to start the "SQL Server Browser" service on the SQL Server and that fixed the connectivity issue.

I had never realized that the SQL Server Browser service actually assisted the SQL Server in making connections; I was under the impression that it simply helped populate the dropdowns when you clicked "browse for more" servers to connect to, but it actually helps align client requests with the correct port # to use, if the port # is not explicitly assigned (similar to how website bindings help alleviate the same issue on an IIS web server that hosts multiple websites).

This connect item is what gave me the clue about the SQL Server Browser service: https://connect.microsoft.com/SQLServer/feedback/details/589901/unable-to-connect-on-localhost-using-fqdn-machine-name

  • when you use wstst05\sqlexpress as a server name, the client code separates the machine name from the instance name and the wstst05 is compared against the netbios name. I see no problem for them to match and the connection is considered local. From there, we retrieve the needed information WITHOUT contacting SQL Browser and connect to the SQL instance via Shared Memory without any problem.
  • when you use wstst05.capatest.local\sqlexpress, the client code fails the comparison of the name (wstst05.capatest.local) to the netbios name (wstst05) and considers the connection "remote". This is by design and we will definitely consider improving this in the future. Anyway, due to considering the connection remote and the fact that it is a named instance, client decides that it needs to use SQLBrowser for name resolution. It attempts to contact SQL Browser on wstst05.capatest.local (UDP port 1434) and apparently that part fails. Hence the error you get.

The reason for the "SQL Server Browser" service from TechNet (emphasis added by me): https://technet.microsoft.com/en-us/library/ms181087(v=sql.120).aspx

From the "Using SQL Server Browser" section:

If the SQL Server Browser service is not running, you are still able to connect to SQL Server if you provide the correct port number or named pipe. For instance, you can connect to the default instance of SQL Server with TCP/IP if it is running on port 1433. However, if the SQL Server Browser service is not running, the following connections do not work:

  • Any component that tries to connect to a named instance without fully specifying all the parameters (such as the TCP/IP port or named pipe).
  • Any component that generates or passes server\instance information that could later be used by other components to reconnect.
  • Connecting to a named instance without providing the port number or pipe.
  • DAC to a named instance or the default instance if not using TCP/IP port 1433.
  • The OLAP redirector service.
  • Enumerating servers in SQL Server Management Studio, Enterprise Manager, or Query Analyzer.

If you are using SQL Server in a client-server scenario (for example, when your application is accessing SQL Server across a network), if you stop or disable the SQL Server Browser service, you must assign a specific port number to each instance and write your client application code to always use that port number. This approach has the following problems:

  • You must update and maintain client application code to ensure it is connecting to the proper port.
  • The port you choose for each instance may be used by another service or application on the server, causing the instance of SQL Server to be unavailable.

And more info from the same article from the "How SQL Server Browser Works" section:

Because only one instance of SQL Server can use a port or pipe, different port numbers and pipe names are assigned for named instances, including SQL Server Express. By default, when enabled, both named instances and SQL Server Express are configured to use dynamic ports, that is, an available port is assigned when SQL Server starts. If you want, a specific port can be assigned to an instance of SQL Server. When connecting, clients can specify a specific port; but if the port is dynamically assigned, the port number can change anytime SQL Server is restarted, so the correct port number is unknown to the client. ... When SQL Server clients request SQL Server resources, the client network library sends a UDP message to the server using port 1434. SQL Server Browser responds with the TCP/IP port or named pipe of the requested instance. The network library on the client application then completes the connection by sending a request to the server using the port or named pipe of the desired instance

How to change the text of a button in jQuery?

You can use something like this:

$('#your-button').text('New Value');

You can also add extra properties like this:

$(this).text('New Value').attr('disabled', true).addClass('bt-hud').unbind('click');

How to easily duplicate a Windows Form in Visual Studio?

  • Save the all project
  • Right click in the Solution Explorer (SE), "Copy"
  • Right click on the project name in the SE (this is the first line), "Paste". It will create a "Copy of .....vb" form
  • Right click on this new form in SE, "View code", and change its class name to the name, that you wanna use for the Form
  • Left click on the new form in SE and rewrite its name for the one, that you used in the class name (and .vb in the end)
  • Build - if it has no error, you win! :)

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

The file in question is not using the CP1252 encoding. It's using another encoding. Which one you have to figure out yourself. Common ones are Latin-1 and UTF-8. Since 0x90 doesn't actually mean anything in Latin-1, UTF-8 (where 0x90 is a continuation byte) is more likely.

You specify the encoding when you open the file:

file = open(filename, encoding="utf8")

How to generate unique IDs for form labels in React?

You could use a library such as node-uuid for this to make sure you get unique ids.

Install using:

npm install node-uuid --save

Then in your react component add the following:

import {default as UUID} from "node-uuid";
import {default as React} from "react";

export default class MyComponent extends React.Component {   
  componentWillMount() {
    this.id = UUID.v4();
  }, 
  render() {
    return (
      <div>
        <label htmlFor={this.id}>My label</label>
        <input id={this.id} type="text"/>
      </div>
    );
  }   
}

how to get yesterday's date in C#

DateTime.Today as it implies is todays date and you need to get the Date a day before so you subtract one day using AddDays(-1);

There are sufficient options available in DateTime to get the formatting like ToShortDateString depending on your culture and you have no need to concatenate them individually.

Also you can have a desirable format in the .ToString() version of the DateTime instance

How to extract text from an existing docx file using python-docx

You can use python-docx2txt which is adapted from python-docx but can also extract text from links, headers and footers. It can also extract images.

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

Put empty value if the value does not exist or null.

value={ this.state.value || "" }

How to add,set and get Header in request of HttpClient?

On apache page: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

You have something like this:

URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
    .setParameter("q", "httpclient")
    .setParameter("btnG", "Google Search")
    .setParameter("aq", "f")
    .setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());

gridview data export to excel in asp.net

I think it will help you

string filename = String.Format("Results_{0}_{1}.xls", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());
        if (!string.IsNullOrEmpty(GRIDVIEWNAME.Page.Title))
            filename = GRIDVIEWNAME.Page.Title + ".xls";

        HttpContext.Current.Response.Clear();

        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);


        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.Charset = "";

        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);



        System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
        GRIDVIEWNAME.Parent.Controls.Add(form);
        form.Controls.Add(GRIDVIEWNAME);
        form.RenderControl(htmlWriter);

        HttpContext.Current.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
        HttpContext.Current.Response.Write(stringWriter.ToString());
        HttpContext.Current.Response.End();

How can I wrap text in a label using WPF?

Instead of using a Label class, I would recommend using a TextBlock. This allows you to set the TextWrapping appropriately.

You can always do:

 label1.Content = new TextBlock() { Text = textBox1.Text, TextWrapping = TextWrapping.Wrap };

However, if all this "label" is for is to display text, use a TextBlock instead.