Programs & Examples On #Squeak

Squeak is a modern, open source implementation of the Smalltalk language, with a history of being very easy to port across platforms.

auto refresh for every 5 mins

Install an interval:

<script type="text/javascript">    
    setInterval(page_refresh, 5*60000); //NOTE: period is passed in milliseconds
</script>

Best ways to teach a beginner to program?

I recommend Logo (aka the turtle) to get the basic concepts down. It provides a good sandbox with immediate graphical feedback, and you can demostrate loops, variables, functions, conditionals, etc. This page provides an excellent tutorial.

After Logo, move to Python or Ruby. I recommend Python, as it's based on ABC, which was invented for the purpose of teaching programming.

When teaching programming, I must second EHaskins's suggestion of simple projects and then complex projects. The best way to learn is to start with a definite outcome and a measurable milestone. It keeps the lessons focused, allows the student to build skills and then build on those skills, and gives the student something to show off to friends. Don't underestimate the power of having something to show for one's work.

Theoretically, you can stick with Python, as Python can do almost anything. It's a good vehicle to teach object-oriented programming and (most) algorithms. You can run Python in interactive mode like a command line to get a feel for how it works, or run whole scripts at once. You can run your scripts interpreted on the fly, or compile them into binaries. There are thousands of modules to extend the functionality. You can make a graphical calculator like the one bundled with Windows, or you can make an IRC client, or anything else.

XKCD describes Python's power a little better: "You're flying! How?" "Python!"

You can move to C# or Java after that, though they don't offer much that Python doesn't already have. The benefit of these is that they use C-style syntax, which many (dare I say most?) languages use. You don't need to worry about memory management yet, but you can get used to having a bit more freedom and less handholding from the language interpreter. Python enforces whitespace and indenting, which is nice most of the time but not always. C# and Java let you manage your own whitespace while remaining strongly-typed.

From there, the standard is C or C++. The freedom in these languages is almost existential. You are now in charge of your own memory management. There is no garbage collection to help you. This is where you teach the really advanced algorithms (like mergesort and quicksort). This is where you learn why "segmentation fault" is a curse word. This is where you download the source code of the Linux kernel and gaze into the Abyss. Start by writing a circular buffer and a stack for string manipulation. Then work your way up.

How do I capture the output of a script if it is being ran by the task scheduler?

You can write to a log file on the lines that you want to output like this:

@echo off
echo Debugging started >C:\logfile.txt
echo More stuff
echo Debugging stuff >>C:\logfile.txt
echo Hope this helps! >>C:\logfile.txt

This way you can choose which commands to output if you don't want to trawl through everything, just get what you need to see. The > will output it to the file specified (creating the file if it doesn't exist and overwriting it if it does). The >> will append to the file specified (creating the file if it doesn't exist but appending to the contents if it does).

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

Calling stored procedure with return value

This is a very short sample of returning a single value from a procedure:

SQL:

CREATE PROCEDURE [dbo].[MakeDouble] @InpVal int AS BEGIN 
SELECT @InpVal * 2; RETURN 0; 
END

C#-code:

int inpVal = 11;
string retVal = "?";
using (var sqlCon = new SqlConnection(
    "Data Source = . ; Initial Catalog = SampleDb; Integrated Security = True;"))
{
    sqlCon.Open();
    retVal = new SqlCommand("Exec dbo.MakeDouble " + inpVal + ";", 
        sqlCon).ExecuteScalar().ToString();
    sqlCon.Close();
}
Debug.Print(inpVal + " * 2 = " + retVal); 
//> 11 * 2 = 22

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

If you are using Maven you may have both src/{main,test}/resources/META-INF/persistence.xml. This is a common setup: test your JPA code with h2 or Derby and deploy it with PostgreSQL or some other full DBMS. If you're using this pattern, do make sure the two files have different unit names, else some versions of the Persistence class will try to load BOTH (because of course your test-time CLASSPATH includes both classes and test-classes); this will cause conflicting definitions of the persistence unit, resulting in the dreaded annoying message that we all hate so much!

Worse: this may "work" with some older versions of e.g., Hibernate, but fail with current versions. Worth getting it right anyway...

What is a practical, real world example of the Linked List?

In the .NET BCL, the class System.Exception has a property called InnerException, which points to another exception or else is null. This forms a linked list.

In System.Type, the BaseType property points to another type in the same way.

Remove URL parameters without refreshing page

a simple way to do this, works on any page, requires HTML 5

// get the string following the ?
var query = window.location.search.substring(1)

// is there anything there ?
if(query.length) {
   // are the new history methods available ?
   if(window.history != undefined && window.history.pushState != undefined) {
        // if pushstate exists, add a new state to the history, this changes the url without reloading the page

        window.history.pushState({}, document.title, window.location.pathname);
   }
}

Reason to Pass a Pointer by Reference in C++?

One example is when you write a parser function and pass it a source pointer to read from, if the function is supposed to push that pointer forward behind the last character which has been correctly recognized by the parser. Using a reference to a pointer makes it clear then that the function will move the original pointer to update its position.

In general, you use references to pointers if you want to pass a pointer to a function and let it move that original pointer to some other position instead of just moving a copy of it without affecting the original.

Pass multiple parameters in Html.BeginForm MVC

Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.

public ActionResult ClientIdSearch(int cid)
{
  var action = String.Format("Details/{0}", cid);

  return RedirectToAction(action, "Accounts");
}

I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.

How to convert an int array to String with toString method in Java

Very much agreed with @Patrik M, but the thing with Arrays.toString is that it includes "[" and "]" and "," in the output. So I'll simply use a regex to remove them from outout like this

String strOfInts = Arrays.toString(intArray).replaceAll("\\[|\\]|,|\\s", "");

and now you have a String which can be parsed back to java.lang.Number, for example,

long veryLongNumber = Long.parseLong(intStr);

Or you can use the java 8 streams, if you hate regex,

String strOfInts = Arrays
            .stream(intArray)
            .mapToObj(String::valueOf)
            .reduce((a, b) -> a.concat(",").concat(b))
            .get();

Interface or an Abstract Class: which one to use?

Also, just would like to add here that just because any other OO language has some kind of interfaces and abstraction too doesn't mean they have the same meaning and purpose as in PHP. The use of abstraction/interfaces is slightly different while interfaces in PHP actually don't have a real function. They merely are used for semantic and scheme-related reasons. The point is to have a project as much flexible as possible, expandable and safe for future extensions regardless whether the developer later on has a totally different plan of use or not.

If your English is not native you might lookup what Abstraction and Interfaces actually are. And look for synonyms too.

And this might help you as a metaphor:

INTERFACE

Let's say, you bake a new sort of cake with strawberries and you made up a recipe describing the ingredients and steps. Only you know why it's tasting so well and your guests like it. Then you decide to publish your recipe so other people can try that cake as well.

The point here is

- to make it right
- to be careful
- to prevent things which could go bad (like too much strawberries or something)
- to keep it easy for the people who try it out
- to tell you how long is what to do (like stiring)
- to tell which things you CAN do but don't HAVE to

Exactly THIS is what describes interfaces. It is a guide, a set of instructions which observe the content of the recipe. Same as if you would create a project in PHP and you want to provide the code on GitHub or with your mates or whatever. An interface is what people can do and what you should not. Rules that hold it - if you disobey one, the entire construct will be broken.


ABSTRACTION

To continue with this metaphor here... imagine, you are the guest this time eating that cake. Then you are trying that cake using the recipe now. But you want to add new ingredients or change/skip the steps described in the recipe. So what comes next? Plan a different version of that cake. This time with black berries and not straw berries and more vanilla cream...yummy.

This is what you could consider an extension of the original cake. You basically do an abstraction of it by creating a new recipe because it's a lil different. It has a few new steps and other ingredients. However, the black berry version has some parts you took over from the original - these are the base steps that every kind of that cake must have. Like ingredients just as milk - That is what every derived class has.

Now you want to exchange ingredients and steps and these MUST be defined in the new version of that cake. These are abstract methods which have to be defined for the new cake, because there should be a fruit in the cake but which? So you take the black berries this time. Done.

There you go, you have extended the cake, followed the interface and abstracted steps and ingredients from it.

@ variables in Ruby on Rails

Use @title in your controllers when you want your variable to be available in your views.

The explanation is that @title is an instance variable while title is a local variable. Rails makes instance variables from controllers available to views because the template code (erb, haml, etc) is executed within the scope of the current controller instance.

How to remove origin from git repository

Fairly straightforward:

git remote rm origin

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

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

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

The difference between a shared project and a class library is that the latter is compiled and the unit of reuse is the assembly.

Whereas with the former, the unit of reuse is the source code, and the shared code is incorporated into each assembly that references the shared project.

This can be useful when you want to create separate assemblies that target specific platforms but still have code that should be shared.

See also here:

The shared project reference shows up under the References node in the Solution Explorer, but the code and assets in the shared project are treated as if they were files linked into the main project.


In previous versions of Visual Studio1, you could share source code between projects by Add -> Existing Item and then choosing to Link. But this was kind of clunky and each separate source file had to be selected individually. With the move to supporting multiple disparate platforms (iOS, Android, etc), they decided to make it easier to share source between projects by adding the concept of Shared Projects.


1 This question and my answer (up until now) suggest that Shared Projects was a new feature in Visual Studio 2015. In fact, they made their debut in Visual Studio 2013 Update 2

Increasing the Command Timeout for SQL command

Since it takes 2 mins to respond, you can increase the timeout to 3 mins by adding the below code

scGetruntotals.CommandTimeout = 180;

Note : the parameter value is in seconds.

Draw path between two points using Google Maps Android API v2

Try below solution to draw path with animation and also get time and distance between two points.

DirectionHelper.java

public class DirectionHelper {

    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;
        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {

                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString((list.get(l)).latitude));
                            hm.put("lng", Double.toString((list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }


        return routes;
    }

    //Method to decode polyline points
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

GetPathFromLocation.java

public class GetPathFromLocation extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {

    private Context context;
    private String TAG = "GetPathFromLocation";
    private LatLng source, destination;
    private ArrayList<LatLng> wayPoint;
    private GoogleMap mMap;
    private boolean animatePath, repeatDrawingPath;
    private DirectionPointListener resultCallback;
    private ProgressDialog progressDialog;

    //https://www.mytrendin.com/draw-route-two-locations-google-maps-android/
    //https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/

    public GetPathFromLocation(Context context, LatLng source, LatLng destination, ArrayList<LatLng> wayPoint, GoogleMap mMap, boolean animatePath, boolean repeatDrawingPath, DirectionPointListener resultCallback) {
        this.context = context;
        this.source = source;
        this.destination = destination;
        this.wayPoint = wayPoint;
        this.mMap = mMap;
        this.animatePath = animatePath;
        this.repeatDrawingPath = repeatDrawingPath;
        this.resultCallback = resultCallback;
    }

    synchronized public String getUrl(LatLng source, LatLng dest, ArrayList<LatLng> wayPoint) {

        String url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&origin="
                + source.latitude + "," + source.longitude + "&destination=" + dest.latitude + "," + dest.longitude;
        for (int centerPoint = 0; centerPoint < wayPoint.size(); centerPoint++) {
            if (centerPoint == 0) {
                url = url + "&waypoints=optimize:true|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            } else {
                url = url + "|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            }
        }
        url = url + "&key=" + context.getResources().getString(R.string.google_api_key);

        return url;
    }

    public int getRandomColor() {
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Please wait...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... url) {

        String data;

        try {
            InputStream inputStream = null;
            HttpURLConnection connection = null;
            try {
                URL directionUrl = new URL(getUrl(source, destination, wayPoint));
                connection = (HttpURLConnection) directionUrl.openConnection();
                connection.connect();
                inputStream = connection.getInputStream();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();

                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }

                data = stringBuffer.toString();
                bufferedReader.close();

            } catch (Exception e) {
                Log.e(TAG, "Exception : " + e.toString());
                return null;
            } finally {
                inputStream.close();
                connection.disconnect();
            }
            Log.e(TAG, "Background Task data : " + data);

            //Second AsyncTask

            JSONObject jsonObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jsonObject = new JSONObject(data);
                // Starts parsing data
                DirectionHelper helper = new DirectionHelper();
                routes = helper.parse(jsonObject);
                Log.e(TAG, "Executing Routes : "/*, routes.toString()*/);

                return routes;

            } catch (Exception e) {
                Log.e(TAG, "Exception in Executing Routes : " + e.toString());
                return null;
            }

        } catch (Exception e) {
            Log.e(TAG, "Background Task Exception : " + e.toString());
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        super.onPostExecute(result);

        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        ArrayList<LatLng> points;
        PolylineOptions lineOptions = null;
        String distance = "";
        String duration = "";

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                if (j == 0) {    // Get distance from the list
                    distance = (String) point.get("distance");
                    continue;
                } else if (j == 1) { // Get duration from the list
                    duration = (String) point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(8);
            lineOptions.color(Color.RED);
            //lineOptions.color(getRandomColor());

            if (animatePath) {
                final ArrayList<LatLng> finalPoints = points;
                ((AppCompatActivity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PolylineOptions polylineOptions;
                        final Polyline greyPolyLine, blackPolyline;
                        final ValueAnimator polylineAnimator;

                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (LatLng latLng : finalPoints) {
                            builder.include(latLng);
                        }
                        polylineOptions = new PolylineOptions();
                        polylineOptions.color(Color.RED);
                        polylineOptions.width(8);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.jointType(ROUND);
                        polylineOptions.addAll(finalPoints);
                        greyPolyLine = mMap.addPolyline(polylineOptions);

                        polylineOptions = new PolylineOptions();
                        polylineOptions.width(8);
                        polylineOptions.color(Color.WHITE);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.zIndex(5f);
                        polylineOptions.jointType(ROUND);

                        blackPolyline = mMap.addPolyline(polylineOptions);
                        polylineAnimator = ValueAnimator.ofInt(0, 100);
                        polylineAnimator.setDuration(5000);
                        polylineAnimator.setInterpolator(new LinearInterpolator());
                        polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                List<LatLng> points = greyPolyLine.getPoints();
                                int percentValue = (int) valueAnimator.getAnimatedValue();
                                int size = points.size();
                                int newPoints = (int) (size * (percentValue / 100.0f));
                                List<LatLng> p = points.subList(0, newPoints);
                                blackPolyline.setPoints(p);
                            }
                        });

                        polylineAnimator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                if (repeatDrawingPath) {
                                    List<LatLng> greyLatLng = greyPolyLine.getPoints();
                                    if (greyLatLng != null) {
                                        greyLatLng.clear();

                                    }
                                    polylineAnimator.start();
                                }
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {
                                polylineAnimator.cancel();
                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {
                            }
                        });
                        polylineAnimator.start();
                    }
                });
            }

            Log.e(TAG, "PolylineOptions Decoded");
        }

        // Drawing polyline in the Google Map for the i-th route
        if (resultCallback != null && lineOptions != null)
            resultCallback.onPath(lineOptions, distance, duration);
    }
}

DirectionPointListener

public interface DirectionPointListener {
    public void onPath(PolylineOptions polyLine,String distance,String duration);
}

Now draw path using below code in your Activity

private GoogleMap mMap;
private ArrayList<LatLng> wayPoint = new ArrayList<>();
private SupportMapFragment mapFragment;

mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();

                /*Add Source Marker*/
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(source);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                mMap.addMarker(markerOptions);
                builder.include(source);

                /*Add Destination Marker*/
                markerOptions = new MarkerOptions();
                markerOptions.position(destination);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                mMap.addMarker(markerOptions);
                builder.include(destination);

                LatLngBounds bounds = builder.build();

                int width = mapFragment.getView().getMeasuredWidth();
                int height = mapFragment.getView().getMeasuredHeight();
                int padding = (int) (width * 0.15); // offset from edges of the map 10% of screen

                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

                mMap.animateCamera(cu);

                new GetPathFromLocation(context, source, destination, wayPoint, mMap, true, false, new DirectionPointListener() {
                    @Override
                    public void onPath(PolylineOptions polyLine, String distance, String duration) {
                        mMap.addPolyline(polyLine);
                        Log.e(TAG, "onPath :: Distance :: " + distance + " Duration :: " + duration);

                        binding.txtDistance.setText(String.format(" %s", distance));
                        binding.txtDuration.setText(String.format(" %s", duration));
                    }
                }).execute();
            }
        });
    }

OutPut

enter image description here

I hope this can help you!

Thank You.

How to extract URL parameters from a URL with Ruby or Rails?

In your Controller, you should be able to access a dictionary (hash) called params. So, if you know what the names of each query parameter is, then just do params[:param1] to access it... If you don't know what the names of the parameters are, you could traverse the dictionary and get the keys.

Some simple examples here.

How to read request body in an asp.net core webapi controller?

Recently I came across a very elegant solution that take in random JSON that you have no idea the structure:

    [HttpPost]
    public JsonResult Test([FromBody] JsonElement json)
    {
        return Json(json);
    }

Just that easy.

How to convert float number to Binary?

The float value is stored in IEEE 754 format so we can't convert it directly like integer, char to binary.

But we can convert float to binary through a pointer.

#include <stdio.h>

int main()
{
    float a = 7.5;
    int i;
    int * p;

    p = &a;
    for (i = sizeof(int) * 8 - 1; i >= 0; i--)
    {   
        printf("%d", (*p) >> i & 1); 
    }   

    return 0;
}

Output

0 10000001 11100000000000000000000

Spaces added for clarification, they are not included as part of the program.

How to get the size of a varchar[n] field in one SQL statement?

On SQL Server specifically:

SELECT DATALENGTH(Remarks) AS FIELDSIZE FROM mytable

Documentation

LocalDate to java.util.Date and vice versa simplest conversion?

tl;dr

Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object? By 'simple', I mean simpler than this

Nope. You did it properly, and as concisely as possible.

java.util.Date.from(                     // Convert from modern java.time class to troublesome old legacy class.  DO NOT DO THIS unless you must, to inter operate with old code not yet updated for java.time.
    myLocalDate                          // `LocalDate` class represents a date-only, without time-of-day and without time zone nor offset-from-UTC. 
    .atStartOfDay(                       // Let java.time determine the first moment of the day on that date in that zone. Never assume the day starts at 00:00:00.
        ZoneId.of( "America/Montreal" )  // Specify time zone using proper name in `continent/region` format, never 3-4 letter pseudo-zones such as “PST”, “CST”, “IST”. 
    )                                    // Produce a `ZonedDateTime` object. 
    .toInstant()                         // Extract an `Instant` object, a moment always in UTC.
)

Read below for issues, and then think about it. How could it be simpler? If you ask me what time does a date start, how else could I respond but ask you “Where?”?. A new day dawns earlier in Paris FR than in Montréal CA, and still earlier in Kolkata IN, and even earlier in Auckland NZ, all different moments.

So in converting a date-only (LocalDate) to a date-time we must apply a time zone (ZoneId) to get a zoned value (ZonedDateTime), and then move into UTC (Instant) to match the definition of a java.util.Date.

Details

Firstly, avoid the old legacy date-time classes such as java.util.Date whenever possible. They are poorly designed, confusing, and troublesome. They were supplanted by the java.time classes for a reason, actually, for many reasons.

But if you must, you can convert to/from java.time types to the old. Look for new conversion methods added to the old classes.

Table of all date-time types in Java, both modern and legacy

java.util.Date ? java.time.LocalDate

Keep in mind that a java.util.Date is a misnomer as it represents a date plus a time-of-day, in UTC. In contrast, the LocalDate class represents a date-only value without time-of-day and without time zone.

Going from java.util.Date to java.time means converting to the equivalent class of java.time.Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myUtilDate.toInstant();

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

So we need to move that Instant into a time zone. We apply ZoneId to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

From there, ask for a date-only, a LocalDate.

LocalDate ld = zdt.toLocalDate();

java.time.LocalDate ? java.util.Date

To move the other direction, from a java.time.LocalDate to a java.util.Date means we are going from a date-only to a date-time. So we must specify a time-of-day. You probably want to go for the first moment of the day. Do not assume that is 00:00:00. Anomalies such as Daylight Saving Time (DST) means the first moment may be another time such as 01:00:00. Let java.time determine that value by calling atStartOfDay on the LocalDate.

ZonedDateTime zdt = myLocalDate.atStartOfDay( z );

Now extract an Instant.

Instant instant = zdt.toInstant();

Convert that Instant to java.util.Date by calling from( Instant ).

java.util.Date d = java.util.Date.from( instant );

More info


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Remove '\' char from string c#

line = line.Replace("\\", "");

Printing a 2D array in C

First you need to input the two numbers say num_rows and num_columns perhaps using argc and argv then do a for loop to print the dots.

int j=0;
int k=0;
for (k=0;k<num_columns;k++){
   for (j=0;j<num_rows;j++){
       printf(".");
   }
 printf("\n");
 }

you'd have to replace the dot with something else later.

Best way to pass parameters to jQuery's .load()

In the first case, the data are passed to the script via GET, in the second via POST.

http://docs.jquery.com/Ajax/load#urldatacallback

I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.

Datatable date sorting dd/mm/yyyy issue

To the column you want ordering keep "sType": "date-uk" for example:-"data": "OrderDate", "sType": "date-uk" After the completion of Datatable script in ajax keep the below code

 jQuery.extend(jQuery.fn.dataTableExt.oSort, {
            "date-uk-pre": function (a) {
                var ukDatea = a.split('/');
                return (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
            },

            "date-uk-asc": function (a, b) {
                return ((a < b) ? -1 : ((a > b) ? 1 : 0));
            },

            "date-uk-desc": function (a, b) {
                return ((a < b) ? 1 : ((a > b) ? -1 : 0));
            }
        });

Then You will get date as 22-10-2018 in this format

How to create a Calendar table for 100 years in Sql

Here is a generic script you can use in SQL server. just amend the start and end dates:

IF EXISTS (SELECT * FROM information_schema.tables WHERE Table_Name = 'Calendar' AND Table_Type = 'BASE TABLE')
BEGIN
DROP TABLE [Calendar]
END

CREATE TABLE [Calendar]
(
    [CalendarDate] DATETIME
)

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = GETDATE()
SET @EndDate = DATEADD(d, 365, @StartDate)

WHILE @StartDate <= @EndDate
      BEGIN
             INSERT INTO [Calendar]
             (
                   CalendarDate
             )
             SELECT
                   @StartDate

             SET @StartDate = DATEADD(dd, 1, @StartDate)
      END

If you want a more advanced calendar here is one I found on the net a while ago:

CREATE SCHEMA Auxiliary
-- We put our auxiliary tables and stuff in a separate schema
-- One of the great new things in SQL Server 2005
go

CREATE FUNCTION Auxiliary.Computus
-- Computus (Latin for computation) is the calculation of the date of
-- Easter in the Christian calendar
-- http://en.wikipedia.org/wiki/Computus
-- I'm using the Meeus/Jones/Butcher Gregorian algorithm
(
    @Y INT -- The year we are calculating easter sunday for
)
RETURNS DATETIME
AS
BEGIN
DECLARE
@a INT,
@b INT,
@c INT,
@d INT,
@e INT,
@f INT,
@g INT,
@h INT,
@i INT,
@k INT,
@L INT,
@m INT

SET @a = @Y % 19
SET @b = @Y / 100
SET @c = @Y % 100
SET @d = @b / 4
SET @e = @b % 4
SET @f = (@b + 8) / 25
SET @g = (@b - @f + 1) / 3
SET @h = (19 * @a + @b - @d - @g + 15) % 30
SET @i = @c / 4
SET @k = @c % 4
SET @L = (32 + 2 * @e + 2 * @i - @h - @k) % 7
SET @m = (@a + 11 * @h + 22 * @L) / 451
RETURN(DATEADD(month, ((@h + @L - 7 * @m + 114) / 31)-1, cast(cast(@Y AS VARCHAR) AS Datetime)) + ((@h + @L - 7 * @m + 114) % 31))
END
GO


CREATE TABLE [Auxiliary].[Calendar] (
-- This is the calendar table
  [Date] datetime NOT NULL,
  [Year] int NOT NULL,
  [Quarter] int NOT NULL,
  [Month] int NOT NULL,
  [Week] int NOT NULL,
  [Day] int NOT NULL,
  [DayOfYear] int NOT NULL,
  [Weekday] int NOT NULL,
  [Fiscal_Year] int NOT NULL,
  [Fiscal_Quarter] int NOT NULL,
  [Fiscal_Month] int NOT NULL,
  [KindOfDay] varchar(10) NOT NULL,
  [Description] varchar(50) NULL,
  PRIMARY KEY CLUSTERED ([Date])
)
GO

ALTER TABLE [Auxiliary].[Calendar]
-- In Celkoish style I'm manic about constraints (Never use em ;-))
-- http://www.celko.com/

ADD CONSTRAINT [Calendar_ck] CHECK (  ([Year] > 1900)
AND ([Quarter] BETWEEN 1 AND 4)
AND ([Month] BETWEEN 1 AND 12)
AND ([Week]  BETWEEN 1 AND 53)
AND ([Day] BETWEEN 1 AND 31)
AND ([DayOfYear] BETWEEN 1 AND 366)
AND ([Weekday] BETWEEN 1 AND 7)
AND ([Fiscal_Year] > 1900)
AND ([Fiscal_Quarter] BETWEEN 1 AND 4)
AND ([Fiscal_Month] BETWEEN 1 AND 12)
AND ([KindOfDay] IN ('HOLIDAY', 'SATURDAY', 'SUNDAY', 'BANKDAY')))
GO




SET DATEFIRST 1;
-- I want my table to contain datedata acording to ISO 8601
-- http://en.wikipedia.org/wiki/ISO_8601
-- thus first day of a week is monday
WITH Dates(Date)
-- A recursive CTE that produce all dates between 1999 and 2020-12-31
AS
(
SELECT cast('1999' AS DateTime) Date -- SQL Server supports the ISO 8601 format so this is an unambigious shortcut for 1999-01-01
UNION ALL                            -- http://msdn2.microsoft.com/en-us/library/ms190977.aspx
SELECT (Date + 1) AS Date
FROM Dates
WHERE
Date < cast('2021' AS DateTime) -1
),

DatesAndThursdayInWeek(Date, Thursday)
-- The weeks can be found by counting the thursdays in a year so we find
-- the thursday in the week for a particular date
AS
(
SELECT
Date,
CASE DATEPART(weekday,Date)
WHEN 1 THEN Date + 3
WHEN 2 THEN Date + 2
WHEN 3 THEN Date + 1
WHEN 4 THEN Date
WHEN 5 THEN Date - 1
WHEN 6 THEN Date - 2
WHEN 7 THEN Date - 3
END AS Thursday
FROM Dates
),

Weeks(Week, Thursday)
-- Now we produce the weeknumers for the thursdays
-- ROW_NUMBER is new to SQL Server 2005
AS
(
SELECT ROW_NUMBER() OVER(partition by year(Date) order by Date) Week, Thursday
FROM DatesAndThursdayInWeek
WHERE DATEPART(weekday,Date) = 4
)
INSERT INTO Auxiliary.Calendar
SELECT
d.Date,
YEAR(d.Date) AS Year,
DATEPART(Quarter, d.Date) AS Quarter,
MONTH(d.Date) AS Month,
w.Week,
DAY(d.Date) AS Day,
DATEPART(DayOfYear, d.Date) AS DayOfYear,
DATEPART(Weekday, d.Date) AS Weekday,

-- Fiscal year may be different to the actual year in Norway the are the same
-- http://en.wikipedia.org/wiki/Fiscal_year
YEAR(d.Date) AS Fiscal_Year,
DATEPART(Quarter, d.Date) AS Fiscal_Quarter,
MONTH(d.Date) AS Fiscal_Month,

CASE
-- Holidays in Norway
-- For other countries and states: Wikipedia - List of holidays by country
-- http://en.wikipedia.org/wiki/List_of_holidays_by_country
    WHEN (DATEPART(DayOfYear, d.Date) = 1)          -- New Year's Day
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-7)  -- Palm Sunday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-3)  -- Maundy Thursday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-2)  -- Good Friday
    OR (d.Date = Auxiliary.Computus(YEAR(Date)))    -- Easter Sunday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+39) -- Ascension Day
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+49) -- Pentecost
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+50) -- Whitmonday
    OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 1)      -- Labour day
    OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 17)     -- Constitution day
    OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 25)    -- Cristmas day
    OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 26)    -- Boxing day
    THEN 'HOLIDAY'
    WHEN DATEPART(Weekday, d.Date) = 6 THEN 'SATURDAY'
    WHEN DATEPART(Weekday, d.Date) = 7 THEN 'SUNDAY'
    ELSE 'BANKDAY'
END KindOfDay,
CASE
-- Description of holidays in Norway
    WHEN (DATEPART(DayOfYear, d.Date) = 1)            THEN 'New Year''s Day'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-7)  THEN 'Palm Sunday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-3)  THEN 'Maundy Thursday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-2)  THEN 'Good Friday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date)))    THEN 'Easter Sunday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+39) THEN 'Ascension Day'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+49) THEN 'Pentecost'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+50) THEN 'Whitmonday'
    WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 1)      THEN 'Labour day'
    WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 17)     THEN 'Constitution day'
    WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 25)    THEN 'Cristmas day'
    WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 26)    THEN 'Boxing day'
END Description

FROM DatesAndThursdayInWeek d
-- This join is for getting the week into the result set
     inner join Weeks w
     on d.Thursday = w.Thursday

OPTION(MAXRECURSION 0)
GO

CREATE FUNCTION Auxiliary.Numbers
(
@AFrom INT,
@ATo INT,
@AIncrement INT
)
RETURNS @RetNumbers TABLE
(
[Number] int PRIMARY KEY NOT NULL
)
AS
BEGIN
WITH Numbers(n)
AS
(
SELECT @AFrom AS n
UNION ALL
SELECT (n + @AIncrement) AS n
FROM Numbers
WHERE
n < @ATo
)
INSERT @RetNumbers
SELECT n from Numbers
OPTION(MAXRECURSION 0)
RETURN;
END
GO

CREATE FUNCTION Auxiliary.iNumbers
(
@AFrom INT,
@ATo INT,
@AIncrement INT
)
RETURNS TABLE
AS
RETURN(
WITH Numbers(n)
AS
(
SELECT @AFrom AS n
UNION ALL
SELECT (n + @AIncrement) AS n
FROM Numbers
WHERE
n < @ATo
)
SELECT n AS Number from Numbers
)
GO

Enable/Disable Anchor Tags using AngularJS

Make a toggle function in the respective scope to grey out the link.

First,create the following CSS classes in your .css file.

.disabled {
    pointer-events: none;
    cursor: default;
}

.enabled {
    pointer-events: visible;
    cursor: auto;
}

Add a $scope.state and $scope.toggle variable. Edit your controller in the JS file like:

    $scope.state='on';
    $scope.toggle='enabled';
    $scope.changeState = function () {
                $scope.state = $scope.state === 'on' ? 'off' : 'on';
                $scope.toggleEdit();
            };
    $scope.toggleEdit = function () {
            if ($scope.state === 'on')
                $scope.toggle = 'enabled';
            else
                $scope.toggle = 'disabled';
        };

Now,in the HTML a tags edit as:

<a href="#" ng-click="create()" class="{{toggle}}">CREATE</a><br/>
<a href="#" ng-click="edit()" class="{{toggle}}">EDIT</a><br/>
<a href="#" ng-click="delete()" class="{{toggle}}">DELETE</a>

To avoid the problem of the link disabling itself, change the DOM CSS class at the end of the function.

document.getElementById("create").className = "enabled";

How can I get the current date and time in UTC or GMT in Java?

public class CurrentUtcDate 
{
    public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println("UTC Time is: " + dateFormat.format(date));
    }
}

Output:

UTC Time is: 22-01-2018 13:14:35

You can change the date format as needed.

How do I fetch lines before/after the grep result in bash?

You can use the -B and -A to print lines before and after the match.

grep -i -B 10 'error' data

Will print the 10 lines before the match, including the matching line itself.

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Toolbar Navigation Hamburger Icon missing

in onCreate():

    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close) {
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            supportInvalidateOptionsMenu();
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            supportInvalidateOptionsMenu();
        }
    };
    drawerLayout.setDrawerListener(drawerToggle);


    drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Backstack.get(MainActivity.this).goBack();
        }
    });
    //actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
    //getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    actionBar.setDisplayHomeAsUpEnabled(false);
    actionBar.setHomeButtonEnabled(true);

And when setting up UP navigation:

private void setupViewsForKey(Key key) {
    if(key.shouldShowUp()) {
        drawerToggle.setDrawerIndicatorEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    else {
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        drawerToggle.setDrawerIndicatorEnabled(true);
    }
    drawerToggle.syncState();

Disable submit button when form invalid with AngularJS

We can create a simple directive and disable the button until all the mandatory fields are filled.

angular.module('sampleapp').directive('disableBtn',
function() {
 return {
  restrict : 'A',
  link : function(scope, element, attrs) {
   var $el = $(element);
   var submitBtn = $el.find('button[type="submit"]');
   var _name = attrs.name;
   scope.$watch(_name + '.$valid', function(val) {
    if (val) {
     submitBtn.removeAttr('disabled');
    } else {
     submitBtn.attr('disabled', 'disabled');
    }
   });
  }
 };
}
);

For More Info click here

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

In JPA 2.0 if you want to delete an address if you removed it from a User entity you can add orphanRemoval=true (instead of CascadeType.REMOVE) to your @OneToMany.

More explanation between orphanRemoval=true and CascadeType.REMOVE is here.

Java - No enclosing instance of type Foo is accessible

Declare the INNER class Thing as a static and it will work with no issues.

I remember I have the same issue with the inner class Dog when I declared it as class Dog { only. I got the same issue as you did. There were two solutions:

1- To declare the inner class Dog as static. Or

2- To move the inner class Dog to a new class by itself.

Here is the Example:

public class ReturnDemo {

public static void main(String[] args) {
    
    int z = ReturnDemo.calculate(10, 12);
    System.out.println("z = " + z);
    
    ReturnDemo.Dog dog = new Dog("Bosh", " Doggy");
    System.out.println( dog.getDog());
}


public static int calculate (int x, int y) {
    return x + y;
}

public void print( ) {
    System.out.println("void method");
    return;
}

public String getString() {
    return "Retrun String type value";
}


static class Dog {
    
private String breed;
private String name;

public Dog(String breed, String name) {
    super();
    this.breed = breed;
    this.name = name;
}

public Dog getDog() {
    // return Dog type;
    return this;
    
}

public String toString() {
    return "breed" + breed.concat("name: " + name);
}
}

}

Caesar Cipher Function in Python

according to me this answer is useful for you:

def casear(a,key):
str=""
if key>26:
    key%=26
for i in range(0,len(a)):
    if a[i].isalpha():
        b=ord(a[i])
        b+=key
        #if b>90:                   #if upper case letter ppear in your string
        #    c=b-90                 #if upper case letter ppear in your string
        #    str+=chr(64+c)         #if upper case letter ppear in your string
        if b>122:
            c=b-122
            str+=chr(96+c)
        else:
            str+=chr(b)
    else:
        str+=a[i]
print str

a=raw_input()
key=int(input())
casear(a,key)

This function shifts all letter to right according to given key.

How to delete all files from a specific folder?

System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(myDirPath);

foreach (FileInfo file in myDirInfo.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
{
    dir.Delete(true); 
}

How do I remove background-image in css?

div#a {
  background-image: none !important;
}

Although the "!important" might not be necessary, because "div#a" has a higher specificity than just "div".

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

An easy fix to this would be going to the SQL tab and just simply put in the code

ALTER TABLE `tablename`
ADD PRIMARY KEY (`id`);

Asuming that you have a row named id.

How to define partitioning of DataFrame?

So to start with some kind of answer : ) - You can't

I am not an expert, but as far as I understand DataFrames, they are not equal to rdd and DataFrame has no such thing as Partitioner.

Generally DataFrame's idea is to provide another level of abstraction that handles such problems itself. The queries on DataFrame are translated into logical plan that is further translated to operations on RDDs. The partitioning you suggested will probably be applied automatically or at least should be.

If you don't trust SparkSQL that it will provide some kind of optimal job, you can always transform DataFrame to RDD[Row] as suggested in of the comments.

JavaScript Chart.js - Custom data formatting to display on tooltip

You can give tooltipTemplate a function, and format the tooltip as you wish:

tooltipTemplate: function(v) {return someFunction(v.value);}
multiTooltipTemplate: function(v) {return someOtherFunction(v.value);}

Those given 'v' arguments contain lots of information besides the 'value' property. You can put a 'debugger' inside that function and inspect those yourself.

Saving images in Python at a very high quality

Just to add my results, also using Matplotlib.

.eps made all my text bold and removed transparency. .svg gave me high-resolution pictures that actually looked like my graph.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Do the plot code
fig.savefig('myimage.svg', format='svg', dpi=1200)

I used 1200 dpi because a lot of scientific journals require images in 1200 / 600 / 300 dpi, depending on what the image is of. Convert to desired dpi and format in GIMP or Inkscape.

Obviously the dpi doesn't matter since .svg are vector graphics and have "infinite resolution".

Convert regular Python string to raw string

s = "hel\nlo"
raws = '%r'%s #coversion to raw string
#print(raws) will print 'hel\nlo' with single quotes.
print(raws[1:-1]) # will print hel\nlo without single quotes.
#raws[1:-1] string slicing is performed

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

Maybe you should try using Starwind V2V Converter, you can get it from here - http://www.starwindsoftware.com/converter. It also supports IMG disk format and performs sector-by sector conversion between IMG, VMDK or VHD into and from any of them without making any changes to source image. This tool is free :)

basic authorization command for curl

Use the -H header again before the Authorization:Basic things. So it will be

curl -i \
    -H 'Accept:application/json' \
    -H 'Authorization:Basic BASE64_string' \
    http://example.com

Here, BASE64_string = Base64 of username:password

Does GPS require Internet?

As others have said, you do not need internet for GPS.

GPS is basically a satellite based positioning system that is designed to calculate geographic coordinates based on timing information received from multiple satellites in the GPS constellation. GPS has a relatively slow time to first fix (TTFF), and from a cold start (meaning without a last known position), it can take up to 15 minutes to download the data it needs from the satellites to calculate a position. A-GPS used by cellular networks shortens this time by using the cellular network to deliver the satellite data to the phone.

But regardless of whether it is an A-GPS or GPS location, all that is derived is Geographic Coordinates (latitude/longitude). It is impossible to obtain more from GPS only.

To be able to return anything other than coordinates (such as an address), you need some mechanism to do Reverse Geocoding. Typically this is done by querying a server or a web service (like using Google Maps or Bing Maps, but there are others). Some of the services will allow you to cache data locally, but it would still require an internet connection for periods of time to download the map information in the surrounding area.

While it requires a significant amount of effort, you can write your own tool to do the reverse geocoding, but you still need to be able to house the data somewhere as the amount of data required to do this is far more you can store on a phone, which means you still need an internet connection to do it. If you think of tools like Garmin GPS Navigation units, they do store the data locally, so it is possible, but you will need to optimize it for maximum storage and would probably need more than is generally available in a phone.

Bottom line:

The short answer to your question is, no you do not need an active internet connection to get coordinates, but unless you are building a specialized device or have unlimited storage, you will need an internet connection to turn those coordinates into anything else.

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

After a certain amount of time, your access token expires.

To prevent this, you can request the 'offline_access' permission during the authentication, as noted here: Do Facebook Oauth 2.0 Access Tokens Expire?

How to set default value for form field in Symfony2?

Just so I understand the problem.

You want to adjust the way the form is built based on data in your entity. If the entity is being created then use some default value. If the entity is existing use the database value.

Personally, I think @MolecularMans's solution is the way to go. I would actually set the default values in the constructor or in the property statement. But you don't seem to like that approach.

Instead you can follow this: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html

You hang a listener on your form type and you can then examine your entity and adjust the builder->add statements accordingly based on havine a new or existing entity. You still need to specify your default values somewhere though you could just code them in your listener. Or pass them into the form type.

Seems like a lot of work though. Better to just pass the entity to the form with it's default values already set.

datetime datatype in java

I used this import:

import java.util.Date;

And declared my variable like this:

Date studentEnrollementDate;

How do I refresh the page in ASP.NET? (Let it reload itself by code)

You can use 2 ways for solve this problem: 1) After the head tag

<head> 
<meta http-equiv="refresh" content="600">
</head>

2) If your page hasn't head tag you must use Javascript to implement

<script type="text/javascript">
  function RefreshPage()
  {
    window.location.reload()
  }
</script>

My contact:

http://gola.vn

How do I set the value property in AngularJS' ng-options?

Here is how I solve this problem in a legacy application:

In HTML:

ng-options="kitType.name for kitType in vm.kitTypes track by kitType.id" ng-model="vm.itemTypeId"

In JavaScript:

vm.kitTypes = [
    {"id": "1", "name": "Virtual"},
    {"id": "2", "name": "Physical"},
    {"id": "3", "name": "Hybrid"}
];

...

vm.itemTypeId = vm.kitTypes.filter(function(value, index, array){
    return value.id === (vm.itemTypeId || 1);
})[0];

My HTML displays the option value properly.

How to load image files with webpack file-loader

webpack.config.js

{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
    options: {
        name: '[name].[ext]',
    },
}

anyfile.html

<img src={image_name.jpg} />

json_decode returns NULL after webservice call

Well, i had a similar issue and the problems was the PHP magic quotes in the server... here is my solution:

if(get_magic_quotes_gpc()){
  $param = stripslashes($_POST['param']);
}else{
  $param = $_POST['param'];
}
$param = json_decode($param,true);

What do the icons in Eclipse mean?

In eclipse help documentation, we can all icons information as follows. Common path for all eclipse versions except eclipse version:

enter image description here

https://help.eclipse.org/2019-09/index.jsp?nav=%2F1

How to prevent column break within an element?

I faced same issue while using card-columns

i fixed it using

 display: inline-flex ;
 column-break-inside: avoid;
 width:100%;

Windows 8.1 gets Error 720 on connect VPN

I had the same problem. Most posted solutions would not work. I ran sfc /scannow and it reported that some errors could not be fixed. To address that problem I ran the command

Dism /Online /Cleanup-Image /RestoreHealth

Ironically, I later found the WAN errors had gone away, the 720 VPN error went away and my VPN worked.

Hard to believe that the WAN errors were corrected by this rather esoteric command, but it's worth a try.

Change :hover CSS properties with JavaScript

You can't change or alter the actual :hover selector through Javascript. You can, however, use mouseenter to change the style, and revert back on mouseleave (thanks, @Bryan).

How to add an image in the title bar using html?

I just tried with this code, and it worked for me: <link rel="icon" type="image/jpg" href="C:\Users\nrm05\Pictures\logo.jpg" /> Be sure to type type="image/jpg" for jpg files, and type="image/png" for PNG files. If you haven't downloaded the image, but you know the image URL, then you can type it in like this: href="image_url"

Hope this answered your question :-)

difference between new String[]{} and new String[] in java

String array=new String[]; and String array=new String[]{}; both are invalid statement in java.

It will gives you an error that you are trying to assign String array to String datatype. More specifically error is like this Type mismatch: cannot convert from String[] to String

Calculating distance between two geographic locations

distanceTo will give you the distance in meters between the two given location ej target.distanceTo(destination).

distanceBetween give you the distance also but it will store the distance in a array of float( results[0]). the doc says If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2]

hope that this helps

i've used distanceTo to get the distance from point A to B i think that is the way to go.

Angularjs $q.all

The issue seems to be that you are adding the deffered.promise when deffered is itself the promise you should be adding:

Try changing to promises.push(deffered); so you don't add the unwrapped promise to the array.

 UploadService.uploadQuestion = function(questions){

            var promises = [];

            for(var i = 0 ; i < questions.length ; i++){

                var deffered  = $q.defer();
                var question  = questions[i]; 

                $http({

                    url   : 'upload/question',
                    method: 'POST',
                    data  : question
                }).
                success(function(data){
                    deffered.resolve(data);
                }).
                error(function(error){
                    deffered.reject();
                });

                promises.push(deffered);
            }

            return $q.all(promises);
        }

how to use #ifdef with an OR condition?

Like this

#if defined(LINUX) || defined(ANDROID)

How to return a html page from a restful controller in spring boot?

You can try using ModelAndView:

@RequestMapping("/")
public ModelAndView index () {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("index");
    return modelAndView;
}

Best radio-button implementation for IOS

Try UISegmentedControl. It behaves similarly to radio buttons -- presents an array of choices and lets the user pick 1.

How to exit when back button is pressed?

you can simply use this

 startActivity(new Intent(this, Splash.class));
 moveTaskToBack(true);

The startActivity(new Intent(this, Splash.class)); is the first class that will be lauched when the application starts

moveTaskToBack(true); will minimize your application

How to use pagination on HTML tables?

There's a easy way to paginate a table using breedjs (jQuery plugin), see the example:

HTML

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Gender</th>
      <th>Age</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr b-scope="people" b-loop="person in people" b-paginate="5">
      <td>{{person.name}}</td>
      <td>{{person.gender}}</td>
      <td>{{person.age}}</td>
      <td>{{person.email}}</td>
    </tr>
  </tbody>
</table>
<ul></ul>

JS

var data={ people: [ {...}, {...}, ...] };

$(function() {
  breed.run({
    scope: 'people',
    input: data,
    runEnd: function(){ //This runEnd is just to mount the page buttons
        for(i=1 ; i<=breed.getPageCount('people') ; i++){
        $('ul').append(
            $('<li>',{
            html: i,
            onclick: "breed.paginate({scope: 'people', page: " + i + "});"
          })
        );
      }
    }
  });
});

Every time you want to change pages, just call:

breed.paginate({scope: 'people', page: pageNumber);

More info.

Working example.

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

The last argument of CONVERT seems to determine the format used for parsing. Consult MSDN docs for CONVERT.

111 - the one you are using is Japan yy/mm/dd.

I guess the one you are looking for is 103, that is dd/mm/yyyy.

So you should try:

 SELECT convert(datetime, '23/07/2009', 103)

Increment variable value by 1 ( shell programming)

These are the methods I know:

ichramm@NOTPARALLEL ~$ i=10; echo $i;
10
ichramm@NOTPARALLEL ~$ ((i+=1)); echo $i;
11
ichramm@NOTPARALLEL ~$ ((i=i+1)); echo $i;
12
ichramm@NOTPARALLEL ~$ i=`expr $i + 1`; echo $i;
13

Note the spaces in the last example, also note that's the only one that uses $i.

Can't find android device using "adb devices" command

If using adb devices on Mac OS X no device is displayed and, of course, you have enabled the USB debugging on your device (see http://developer.android.com/tools/device.html), then try with:

$ android update adb
adb has been updated. You must restart adb with the following commands
    adb kill-server
    adb start-server

Then:

$ adb kill-server
$ adb start-server
* daemon not running. starting it now on port ... *
* daemon started successfully *

And finally:

$ adb devices
List of devices attached 
......  device

Your device should be now in the list.

How can I copy network files using Robocopy?

I use the following format and works well.

robocopy \\SourceServer\Path \\TargetServer\Path filename.txt

to copy everything you can replace filename.txt with *.* and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html

Visual Studio Code: format is not using indent settings

The VSCode plugin Vetur; used for VueJS applications was overriding the setting for me.

Setting vetur.format.options.tabSize to my preferred number of spaces made it work.

Get human readable version of file size?

There's always got to be one of those guys. Well today it's me. Here's a one-liner -- or two lines if you count the function signature.

def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):
    """ Returns a human readable string representation of bytes """
    return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:])

>>> human_size(123)
123 bytes
>>> human_size(123456789)
117GB

If you need sizes bigger than an Exabyte, it's a little bit more gnarly:

def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):
    return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:]) if units[1:] else f'{bytes>>10}ZB'

how to re-format datetime string in php?

You can use date_parse_from_format() function ...

Check this link..you will get clear idea

Git submodule head 'reference is not a tree' error

Assuming the submodule's repository does contain a commit you want to use (unlike the commit that is referenced from current state of the super-project), there are two ways to do it.

The first requires you to already know the commit from the submodule that you want to use. It works from the “inside, out” by directly adjusting the submodule then updating the super-project. The second works from the “outside, in” by finding the super-project's commit that modified the submodule and then reseting the super-project's index to refer to a different submodule commit.

Inside, Out

If you already know which commit you want the submodule to use, cd to the submodule, check out the commit you want, then git add and git commit it back in the super-project.

Example:

$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'

Oops, someone made a super-project commit that refers to an unpublished commit in the submodule sub. Somehow, we already know that we want the submodule to be at commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c. Go there and check it out directly.

Checkout in the Submodule

$ cd sub
$ git checkout 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
Note: moving to '5d5a3ee314476701a20f2c6ec4a53f88d651df6c' which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
  git checkout -b <new_branch_name>
HEAD is now at 5d5a3ee... quux
$ cd ..

Since we are checking out a commit, this produces a detached HEAD in the submodule. If you want to make sure that the submodule is using a branch, then use git checkout -b newbranch <commit> to create and checkout a branch at the commit or checkout the branch that you want (e.g. one with the desired commit at the tip).

Update the Super-project

A checkout in the submodule is reflected in the super-project as a change to the working tree. So we need to stage the change in the super-project's index and verify the results.

$ git add sub

Check the Results

$ git submodule update
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

The submodule update was silent because the submodule is already at the specified commit. The first diff shows that the index and worktree are the same. The third diff shows that the only staged change is moving the sub submodule to a different commit.

Commit

git commit

This commits the fixed-up submodule entry.


Outside, In

If you are not sure which commit you should use from the submodule, you can look at the history in the superproject to guide you. You can also manage the reset directly from the super-project.

$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'

This is the same situation as above. But this time we will focus on fixing it from the super-project instead of dipping into the submodule.

Find the Super-project's Errant Commit

$ git log --oneline -p -- sub
ce5d37c local change in sub
diff --git a/sub b/sub
index 5d5a3ee..e47c0a1 160000
--- a/sub
+++ b/sub
@@ -1 +1 @@
-Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
+Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
bca4663 added sub
diff --git a/sub b/sub
new file mode 160000
index 0000000..5d5a3ee
--- /dev/null
+++ b/sub
@@ -0,0 +1 @@
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

OK, it looks like it went bad in ce5d37c, so we will restore the submodule from its parent (ce5d37c~).

Alternatively, you can take the submodule's commit from the patch text (5d5a3ee314476701a20f2c6ec4a53f88d651df6c) and use the above “inside, out” process instead.

Checkout in the Super-project

$ git checkout ce5d37c~ -- sub

This reset the submodule entry for sub to what it was at commit ce5d37c~ in the super-project.

Update the Submodule

$ git submodule update
Submodule path 'sub': checked out '5d5a3ee314476701a20f2c6ec4a53f88d651df6c'

The submodule update went OK (it indicates a detached HEAD).

Check the Results

$ git diff ce5d37c~ -- sub
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

The first diff shows that sub is now the same in ce5d37c~. The second diff shows that the index and worktree are the same. The third diff shows the only staged change is moving the sub submodule to a different commit.

Commit

git commit

This commits the fixed-up submodule entry.

Get values from a listbox on a sheet

Unfortunately for MSForms list box looping through the list items and checking their Selected property is the only way. However, here is an alternative. I am storing/removing the selected item in a variable, you can do this in some remote cell and keep track of it :)

Dim StrSelection As String

Private Sub ListBox1_Change()
    If ListBox1.Selected(ListBox1.ListIndex) Then
        If StrSelection = "" Then
            StrSelection = ListBox1.List(ListBox1.ListIndex)
        Else
            StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
        End If
    Else
        StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
    End If
End Sub

Angular window resize event

There's a ViewportRuler service in angular CDK. It runs outside of the zone, and works with server side rendering too.

File upload along with other object in Jersey restful web service

The request type is multipart/form-data and what you are sending is essentially form fields that go out as bytes with content boundaries separating different form fields.To send an object representation as form field (string), you can send a serialized form from the client that you can then deserialize on the server.

After all no programming environment object is actually ever traveling on the wire. The programming environment on both side are just doing automatic serialization and deserialization that you can also do. That is the cleanest and programming environment quirks free way to do it.

As an example, here is a javascript client posting to a Jersey example service,

submitFile(){

    let data = new FormData();
    let account = {
        "name": "test account",
        "location": "Bangalore"
    }

    data.append('file', this.file);
    data.append("accountKey", "44c85e59-afed-4fb2-884d-b3d85b051c44");
    data.append("device", "test001");
    data.append("account", JSON.stringify(account));
    
    let url = "http://localhost:9090/sensordb/test/file/multipart/upload";

    let config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }

    axios.post(url, data, config).then(function(data){
        console.log('SUCCESS!!');
        console.log(data.data);
    }).catch(function(){
        console.log('FAILURE!!');
    });
},

Here the client is sending a file, 2 form fields (strings) and an account object that has been stringified for transport. here is how the form fields look on the wire,

enter image description here

On the server, you can just deserialize the form fields the way you see fit. To finish this trivial example,

    @POST
@Path("/file/multipart/upload")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadMultiPart(@Context ContainerRequestContext requestContext,
        @FormDataParam("file") InputStream fileInputStream,
        @FormDataParam("file") FormDataContentDisposition cdh,
        @FormDataParam("accountKey") String accountKey,
        @FormDataParam("account") String json)  {
    

    
    System.out.println(cdh.getFileName());
    System.out.println(cdh.getName());
    System.out.println(accountKey);
    
    try {
        Account account = Account.deserialize(json);
        System.out.println(account.getLocation());
        System.out.println(account.getName());
        
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    return Response.ok().build();
    
}

How do I see if Wi-Fi is connected on Android?

Since the method NetworkInfo.isConnected() is now deprecated in API-23, here is a method which detects if the Wi-Fi adapter is on and also connected to an access point using WifiManager instead:

private boolean checkWifiOnAndConnected() {
    WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    if (wifiMgr.isWifiEnabled()) { // Wi-Fi adapter is ON

        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();

        if( wifiInfo.getNetworkId() == -1 ){
            return false; // Not connected to an access point
        }
        return true; // Connected to an access point
    }
    else {
        return false; // Wi-Fi adapter is OFF
    }
}

Why does flexbox stretch my image rather than retaining aspect ratio?

The key attribute is align-self: center:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
img {_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
img.align-self {_x000D_
  align-self: center;_x000D_
}
_x000D_
<div class="container">_x000D_
    <p>Without align-self:</p>_x000D_
    <img src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
    <p>With align-self:</p>_x000D_
    <img class="align-self" src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Detect when an image fails to load in Javascript

jQuery + CSS for img

With jQuery this is working for me :

$('img').error(function() {
    $(this).attr('src', '/no-img.png').addClass('no-img');
});

And I can use this picture everywhere on my website regardless of the size of it with the following CSS3 property :

img.no-img {
    object-fit: cover;
    object-position: 50% 50%;
}

TIP 1 : use a square image of at least 800 x 800 pixels.

TIP 2 : for use with portrait of people, use object-position: 20% 50%;

CSS only for background-img

For missing background images, I also added the following on each background-image declaration :

background-image: url('path-to-image.png'), url('no-img.png');

NOTE : not working for transparent images.

Apache server side

Another solution is to detect missing image with Apache before to send to browser and remplace it by the default no-img.png content.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} /images/.*\.(gif|jpg|jpeg|png)$
RewriteRule .* /images/no-img.png [L,R=307]

How to display length of filtered ng-repeat data

Here is worked example See on Plunker

  <body ng-controller="MainCtrl">
    <input ng-model="search" type="text">
    <br>
    Showing {{data.length}} Persons; <br>
    Filtered {{counted}}
    <ul>
      <li ng-repeat="person in data | filter:search">
        {{person.name}}
      </li>
    </ul>
  </body>

<script> 
var app = angular.module('angularjs-starter', [])

app.controller('MainCtrl', function($scope, $filter) {
  $scope.data = [
    {
      "name": "Jim", "age" : 21
    }, {
      "name": "Jerry", "age": 26
    }, {
      "name": "Alex",  "age" : 25
    }, {
      "name": "Max", "age": 22
    }
  ];

  $scope.counted = $scope.data.length; 
  $scope.$watch("search", function(query){
    $scope.counted = $filter("filter")($scope.data, query).length;
  });
});

How do I create a comma-separated list using a SQL query?

Assuming SQL Server:

Table structure:

CREATE TABLE [dbo].[item_dept](
    [ItemName] char(20) NULL,
    [DepartmentID] int NULL   
)

Query:

SELECT ItemName,
       STUFF((SELECT ',' + rtrim(convert(char(10),DepartmentID))
        FROM   item_dept b
        WHERE  a.ItemName = b.ItemName
        FOR XML PATH('')),1,1,'') DepartmentID
FROM   item_dept a
GROUP BY ItemName

Results:

ItemName    DepartmentID
item1       21,13,9,36
item2       4,9,44

Bootstrap select dropdown list placeholder

Add hidden attribute:

<select>
    <option value="" selected disabled hidden>Please select</option>
    <option value="">A</option>
    <option value="">B</option>
    <option value="">C</option>
</select>

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

For swift 3.0 and above

public static func getTopViewController() -> UIViewController?{
if var topController = UIApplication.shared.keyWindow?.rootViewController
{
  while (topController.presentedViewController != nil)
  {
    topController = topController.presentedViewController!
  }
  return topController
}
return nil}

How can I search sub-folders using glob.glob module?

If you can install glob2 package...

import glob2
filenames = glob2.glob("C:\\top_directory\\**\\*.ext")  # Where ext is a specific file extension
folders = glob2.glob("C:\\top_directory\\**\\")

All filenames and folders:

all_ff = glob2.glob("C:\\top_directory\\**\\**")  

What's the best way to check if a file exists in C?

Look up the access() function, found in unistd.h. You can replace your function with

if( access( fname, F_OK ) == 0 ) {
    // file exists
} else {
    // file doesn't exist
}

You can also use R_OK, W_OK, and X_OK in place of F_OK to check for read permission, write permission, and execute permission (respectively) rather than existence, and you can OR any of them together (i.e. check for both read and write permission using R_OK|W_OK)

Update: Note that on Windows, you can't use W_OK to reliably test for write permission, since the access function does not take DACLs into account. access( fname, W_OK ) may return 0 (success) because the file does not have the read-only attribute set, but you still may not have permission to write to the file.

How to detect a loop in a linked list?

public boolean hasLoop(Node start){   
   TreeSet<Node> set = new TreeSet<Node>();
   Node lookingAt = start;

   while (lookingAt.peek() != null){
       lookingAt = lookingAt.next;

       if (set.contains(lookingAt){
           return false;
        } else {
        set.put(lookingAt);
        }

        return true;
}   
// Inside our Node class:        
public Node peek(){
   return this.next;
}

Forgive me my ignorance (I'm still fairly new to Java and programming), but why wouldn't the above work?

I guess this doesn't solve the constant space issue... but it does at least get there in a reasonable time, correct? It will only take the space of the linked list plus the space of a set with n elements (where n is the number of elements in the linked list, or the number of elements until it reaches a loop). And for time, worst-case analysis, I think, would suggest O(nlog(n)). SortedSet look-ups for contains() are log(n) (check the javadoc, but I'm pretty sure TreeSet's underlying structure is TreeMap, whose in turn is a red-black tree), and in the worst case (no loops, or loop at very end), it will have to do n look-ups.

What is the difference between Document style and RPC style communication?

Document
Document style messages can be validated against predefined schema. In document style, SOAP message is sent as a single document. Example of schema:

  <types>  
   <xsd:schema> <xsd:import namespace="http://example.com/" 
    schemaLocation="http://localhost:8080/ws/hello?xsd=1"/>  
   </xsd:schema>  
  </types>

Example of document style soap body message

  <message name="getHelloWorldAsString">   
     <part name="parameters" element="tns:getHelloWorldAsString"/>   
  </message> 
  <message name="getHelloWorldAsStringResponse">  
     <part name="parameters"> element="tns:getHelloWorldAsStringResponse"/>   
  </message>

Document style message is loosely coupled.

RPC RPC style messages use method name and parameters to generate XML structure. messages are difficult to be validated against schema. In RPC style, SOAP message is sent as many elements.

  <message name="getHelloWorldAsString">
    <part name="arg0"> type="xsd:string"/>   
   </message> 
  <message name="getHelloWorldAsStringResponse">   
    <part name="return"
   > type="xsd:string"/>   
  </message>

Here each parameters are discretely specified, RPC style message is tightly coupled, is typically static, requiring changes to the client when the method signature changes The rpc style is limited to very simple XSD types such as String and Integer, and the resulting WSDL will not even have a types section to define and constrain the parameters

Literal By default style. Data is serialized according to a schema, data type not specified in messages but a reference to schema(namespace) is used to build soap messages.

   <soap:body>
     <myMethod>
        <x>5</x>
        <y>5.0</y>
     </myMethod>
   </soap:body>

Encoded Datatype specified in each parameter

   <soap:body>
     <myMethod>
         <x xsi:type="xsd:int">5</x>
         <y xsi:type="xsd:float">5.0</y>
     </myMethod>
   </soap:body>

Schema free

Cannot access a disposed object - How to fix?

If this happens sporadically then my guess is that it has something to do with the timer.

I'm guessing (and this is only a guess since I have no access to your code) that the timer is firing while the form is being closed. The dbiSchedule object has been disposed but the timer somehow still manages to try to call it. This shouldn't happen, because if the timer has a reference to the schedule object then the garbage collector should see this and not dispose of it.

This leads me to ask: are you calling Dispose() on the schedule object manually? If so, are you doing that before disposing of the timer? Be sure that you release all references to the schedule object before Disposing it (i.e. dispose of the timer beforehand).

Now I realize that a few months have passed between the time you posted this and when I am answering, so hopefully, you have resolved this issue. I'm writing this for the benefit of others who may come along later with a similar issue.

Hope this helps.

How do I read the contents of a Node.js stream into a string variable?

(This answer is from years ago, when it was the best answer. There is now a better answer below this. I haven't kept up with node.js, and I cannot delete this answer because it is marked "correct on this question". If you are thinking of down clicking, what do you want me to do?)

The key is to use the data and end events of a Readable Stream. Listen to these events:

stream.on('data', (chunk) => { ... });
stream.on('end', () => { ... });

When you receive the data event, add the new chunk of data to a Buffer created to collect the data.

When you receive the end event, convert the completed Buffer into a string, if necessary. Then do what you need to do with it.

Spring Data JPA find by embedded object property

If you are using BookId as an combined primary key, then remember to change your interface from:

public interface QueuedBookRepo extends JpaRepository<QueuedBook, Long> {

to:

public interface QueuedBookRepo extends JpaRepository<QueuedBook, BookId> {

And change the annotation @Embedded to @EmbeddedId, in your QueuedBook class like this:

public class QueuedBook implements Serializable {

@EmbeddedId
@NotNull
private BookId bookId;

...

running php script (php function) in linux bash

php test.php

should do it, or

php -f test.php

to be explicit.

Formatting numbers (decimal places, thousands separators, etc) with CSS

Unfortunately, it's not possible with CSS currently, but you can use Number.prototype.toLocaleString(). It can also format for other number formats, e.g. latin, arabic, etc.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

How to get Bitmap from an Uri?

private fun setImage(view: ImageView, uri: Uri) {
        val stream = contentResolver.openInputStream(uri)
        val bitmap = BitmapFactory.decodeStream(stream)
        view.setImageBitmap(bitmap)
}

Switching users inside Docker image to a non-root user

As a different approach to the other answer, instead of indicating the user upon image creation on the Dockerfile, you can do so via command-line on a particular container as a per-command basis.

With docker exec, use --user to specify which user account the interactive terminal will use (the container should be running and the user has to exist in the containerized system):

docker exec -it --user [username] [container] bash

See https://docs.docker.com/engine/reference/commandline/exec/

Get Character value from KeyCode in JavaScript... then trim

I recently wrote a module called keysight that translates keypress, keydown, and keyup events into characters and keys respectively.

Example:

 element.addEventListener("keydown", function(event) {
    var character = keysight(event).char
 })

add commas to a number in jQuery

Take a look at recently released Globalization plugin to jQuery by Microsoft

Laravel Migration table already exists, but I want to add new not the older

EDIT: (for laravel)

Just Came across this issue while working on a project in laravel. My tables were messed up, needed to frequent changes on columns. Once the tables were there I wasn't able to run php artisan migrate anymore.

I've done following to get rid of the issue-

  1. Drop the tables in the database [every one, including the migration table]
  2. $ composer dump-autoload -o
  3. php artisan migrate

Previous Comment, regarding lumen

[Well, pretty late to the party (and possibly a different party than what I was looking for). I banged my head, screamed out loud and by the grace of gray skull just found a solution.]

I'm developing an restful app using lumen and I'm new to it. This is my first project/experiment using laraval and lumen. My dependencies-

"require": {
    "php": ">=5.6.4",
    "laravel/lumen-framework": "5.4.*",
    "vlucas/phpdotenv": "~2.2",
    "barryvdh/laravel-cors": "^0.8.6",
    "league/fractal": "^0.13.0"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "phpunit/phpunit": "~5.0",
    "mockery/mockery": "~0.9.4"
}

Anyway, everything was fine until yesterday night but suddenly phpunit started complaining about an already existed table.

Caused by
PDOException: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'items' already exists

Duh! Items table should exist in the database, or else how am i supposed to save items!

Anyway the problem only persisted in the test classes, but strangely not in the browser (I checked with chrome, firefox and postman altering headers). I was getting JSON responses with data as expected.

I dropped the database and recreated it with lots of migrate, refresh, rollback. Everything was fine but in phpunit.

Out of desperation I removed my migration files (of course I took a backup first ) then hit phpunit in the terminal. Same thing all over again.

Suddenly I remembered that I put a different database name in the phpunit.xml file for testing purpose only. I checked that database and guess what! There was a table named items. I removed this table manually, run phpunit, everything started working just fine.

I'm documenting my experience for future references only and with hope this might help someone in future.

How to print in C

printf is a fair bit more complicated than that. You have to supply a format string, and then the variables to apply to the format string. If you just supply one variable, C will assume that is the format string and try to print out all the bytes it finds in it until it hits a terminating nul (0x0).

So if you just give it an integer, it will merrily march through memory at the location your integer is stored, dumping whatever garbage is there to the screen, until it happens to come across a byte containing 0.

For a Java programmer, I'd imagine this is a rather rude introduction to C's lack of type checking. Believe me, this is only the tip of the iceberg. This is why, while I applaud your desire to expand your horizons by learning C, I highly suggest you do whatever you can to avoid writing real programs in it.

(This goes for everyone else reading this too.)

No value accessor for form control with name: 'recipient'

You should add the ngDefaultControl attribute to your input like this:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

See https://material.angular.io/components/input/overview

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

Carousel with Thumbnails in Bootstrap 3.0

Just found out a great plugin for this:

http://flexslider.woothemes.com/

Regards

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

The difference between Classes, Objects, and Instances

Honestly, I feel more comfortable with Alfred blog definitions:

Object: real world objects shares 2 main characteristics, state and behavior. Human have state (name, age) and behavior (running, sleeping). Car have state (current speed, current gear) and behavior (applying brake, changing gear). Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods.

Class: is a “template” / “blueprint” that is used to create objects. Basically, a class will consists of field, static field, method, static method and constructor. Field is used to hold the state of the class (eg: name of Student object). Method is used to represent the behavior of the class (eg: how a Student object going to stand-up). Constructor is used to create a new Instance of the Class.

Instance: An instance is a unique copy of a Class that representing an Object. When a new instance of a class is created, the JVM will allocate a room of memory for that class instance.

Given the next example:

public class Person {
    private int id;
    private String name;
    private int age;

    public Person (int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        return result;
    }

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (id != other.id)
            return false;
        return true;
    }

    public static void main(String[] args) {
        //case 1
        Person p1 = new Person(1, "Carlos", 20);
        Person p2 = new Person(1, "Carlos", 20);

        //case 2
        Person p3 = new Person(2, "John", 15);
        Person p4 = new Person(3, "Mary", 17);
    }
}

For case 1, there are two instances of the class Person, but both instances represent the same object.

For case 2, there are two instances of the class Person, but each instance represent a different object.

So class, object and instance are different things. Object and instance are not synonyms as is suggested in the answer selected as right answer.

Replacing H1 text with a logo image: best method for SEO and accessibility?

For SEO reason:

<div itemscope itemtype="https://schema.org/Organization">
 <p id="logo"><a href="/"><span itemprop="Brand">Your business</span> <span class="icon fa-stg"></span> - <span itemprop="makesOffer">sell staff</span></a></p>
 </div>
   <h1>Your awesome title</h1>

How to add anchor tags dynamically to a div in Javascript?

One more variation wrapped up nicely where setAttribute isn't needed.

There are 3 lines that wouldn't be needed if Wetfox could dry off.

var saveAs = function (filename, content) {
    if(filename === undefined) filename = "Unknown.txt";
    if(content === undefined) content = "Empty?!";
    let link = document.createElement('a');
    link.style.display = "none"; // because Firefox sux
    document.body.appendChild(link); // because Firefox sux
    link.href = "data:application/octet-stream," + encodeURIComponent(content);
    link.download = filename;
    link.click();
    document.body.removeChild(link); // because Firefox sux
};

Thanks for the help.

How to find out which JavaScript events fired?

Regarding Chrome, checkout the monitorEvents() via the command line API.

  • Open the console via Menu > Tools > JavaScript Console.

  • Enter monitorEvents(window);

  • View the console flooded with events

     ...
     mousemove MouseEvent {dataTransfer: ...}
     mouseout MouseEvent {dataTransfer: ...}
     mouseover MouseEvent {dataTransfer: ...}
     change Event {clipboardData: ...}
     ...
    

There are other examples in the documentation. I'm guessing this feature was added after the previous answer.

Javascript validation: Block special characters

Try this one, this function allows alphanumeric and spaces:

function alpha(e) {
    var k;
    document.all ? k = e.keyCode : k = e.which;
    return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}

in your html:

<input type="text" name="name"  onkeypress="return alpha(event)"/>

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

Indentation Error in Python

For Sublime Text Editor

Indentation Error generally occurs when the code contains a mix of both tabs and spaces for indentation. I have got a very nice solution to correct it, just open your code in a sublime text editor and find 'Tab Size' in the bottom right corner of Sublime Text Editor and click it. Now select either

'Convert Indentation to Spaces'

OR

'Convert Indentation to Tabs'

Your code will work in either case.

Additionally, if you want Sublime text to do it automatically for you for every code you can update the Preference settings as below:-

Sublime Text menu > Preferences > Settings - Syntax Specific :

Python.sublime-settings

{
    "tab_size": 4,
    "translate_tabs_to_spaces": true
}

How to create duplicate table with new name in SQL Server 2008

My SQL Server Management Studio keeps asking me how I can make it better, I have an idea! The ability to highlight a table and then, ctrl C, ctrl V! would be great and the answer to this question at the same time!

How to disable mouse right click on a web page?

There are plenty of examples of this which can be found via Google

However, users can turn off Javascript to stop this highly annoying "feature". I think you should really think about this before implementing it. It isn't really going to protect your content (if that is what you are trying achieve).

There is an article here that illustrates just how annoying and pointless it is.

Understanding __get__ and __set__ and Python descriptors

Why do I need the descriptor class?

Inspired by Fluent Python by Buciano Ramalho

Imaging you have a class like this

class LineItem:
     price = 10.9
     weight = 2.1
     def __init__(self, name, price, weight):
          self.name = name
          self.price = price
          self.weight = weight

item = LineItem("apple", 2.9, 2.1)
item.price = -0.9  # it's price is negative, you need to refund to your customer even you delivered the apple :(
item.weight = -0.8 # negative weight, it doesn't make sense

We should validate the weight and price in avoid to assign them a negative number, we can write less code if we use descriptor as a proxy as this

class Quantity(object):
    __index = 0

    def __init__(self):
        self.__index = self.__class__.__index
        self._storage_name = "quantity#{}".format(self.__index)
        self.__class__.__index += 1

    def __set__(self, instance, value):
        if value > 0:
            setattr(instance, self._storage_name, value)
        else:
           raise ValueError('value should >0')

   def __get__(self, instance, owner):
        return getattr(instance, self._storage_name)

then define class LineItem like this:

class LineItem(object):
     weight = Quantity()
     price = Quantity()

     def __init__(self, name, weight, price):
         self.name = name
         self.weight = weight
         self.price = price

and we can extend the Quantity class to do more common validating

How to set value of input text using jQuery

this is for classes

$('.nameofdiv').val('we are developers');

for ids

$('#nameofdiv').val('we are developers');

now if u have an iput in a form u can use

$("#form li.name input.name_val").val('we are awsome developers');

Length of the String without using length() method

Hidden length() usage:

    String s = "foobar";

    int i = 0;
    for(char c: s.toCharArray())
    {
        i++;
    }

What do two question marks together mean in C#?

It's the null coalescing operator.

http://msdn.microsoft.com/en-us/library/ms173224.aspx

Yes, nearly impossible to search for unless you know what it's called! :-)

EDIT: And this is a cool feature from another question. You can chain them.

Hidden Features of C#?

Android: show/hide a view using an animation

This can reasonably be achieved in a single line statement in API 12 and above. Below is an example where v is the view you wish to animate;

v.animate().translationXBy(-1000).start();

This will slide the View in question off to the left by 1000px. To slide the view back onto the UI we can simply do the following.

v.animate().translationXBy(1000).start();

I hope someone finds this useful.

Counting array elements in Python

len is a built-in function that calls the given container object's __len__ member function to get the number of elements in the object.

Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.).

Using obj.__len__() wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.

php refresh current page?

header('Location: '.$_SERVER['PHP_SELF']);  

will also work

Object passed as parameter to another class, by value or reference?

I found the other examples unclear, so I did my own test which confirmed that a class instance is passed by reference and as such actions done to the class will affect the source instance.

In other words, my Increment method modifies its parameter myClass everytime its called.

class Program
{
    static void Main(string[] args)
    {
        MyClass myClass = new MyClass();
        Console.WriteLine(myClass.Value);  // Displays 1
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 2
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 3           
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 4
        Console.WriteLine("Hit Enter to exit.");
        Console.ReadLine();
    }

    public static void Increment(MyClass myClassRef)
    {
        myClassRef.Value++;
    }
}

public class MyClass
{
    public int Value {get;set;}
    public MyClass()
    {
        Value = 1;
    }
}

Check if a Bash array contains a value

Although there were several great and helpful answers here, I didn't find one that seemed to be the right combination of performant, cross-platform, and robust; so I wanted to share the solution I wrote for my code:

#!/bin/bash

# array_contains "$needle" "${haystack[@]}"
#
# Returns 0 if an item ($1) is contained in an array ($@).
#
# Developer note:
#    The use of a delimiter here leaves something to be desired. The ideal
#    method seems to be to use `grep` with --line-regexp and --null-data, but
#    Mac/BSD grep doesn't support --line-regexp.
function array_contains()
{
    # Extract and remove the needle from $@.
    local needle="$1"
    shift

    # Separates strings in the array for matching. Must be extremely-unlikely
    # to appear in the input array or the needle.
    local delimiter='#!-\8/-!#'

    # Create a string with containing every (delimited) element in the array,
    # and search it for the needle with grep in fixed-string mode.
    if printf "${delimiter}%s${delimiter}" "$@" | \
        grep --fixed-strings --quiet "${delimiter}${needle}${delimiter}"; then
        return 0
    fi

    return 1
}

Stretch background image css?

This works flawlessly @ 2019

.marketing-panel  {
    background-image: url("../images/background.jpg");
    background-repeat: no-repeat;
    background-size: auto;
    background-position: center;
}

How to get HTTP Response Code using Selenium WebDriver

I was also having same issue and stuck for some days, but after some research i figured out that we can actually use chrome's "--remote-debugging-port" to intercept requests in conjunction with selenium web driver. Use following Pseudocode as a reference:-

create instance of chrome driver with remote debugging

int freePort = findFreePort();

chromeOptions.addArguments("--remote-debugging-port=" + freePort);

ChromeDriver driver = new ChromeDriver(chromeOptions);`

make a get call to http://127.0.0.1:freePort

String response = makeGetCall( "http://127.0.0.1" + freePort  + "/json" );

Extract chrome's webSocket Url to listen, you can see response and figure out how to extract

String webSocketUrl = response.substring(response.indexOf("ws://127.0.0.1"), response.length() - 4);

Connect to this socket, u can use asyncHttp

socket = maketSocketConnection( webSocketUrl );

Enable network capture

socket.send( { "id" : 1, "method" : "Network.enable" } );

Now chrome will send all network related events and captures them as follows

socket.onMessageReceived( String message ){

    Json responseJson = toJson(message);
    if( responseJson.method == "Network.responseReceived" ){
       //extract status code
    }
}

driver.get("http://stackoverflow.com");

you can do everything mentioned in dev tools site. see https://chromedevtools.github.io/devtools-protocol/ Note:- use chromedriver 2.39 or above.

I hope it helps someone.

reference : Using Google Chrome remote debugging protocol

Numpy matrix to array

ravel() and flatten() functions from numpy are two techniques that I would try here. I will like to add to the posts made by Joe, Siraj, bubble and Kevad.

Ravel:

A = M.ravel()
print A, A.shape
>>> [1 2 3 4] (4,)

Flatten:

M = np.array([[1], [2], [3], [4]])
A = M.flatten()
print A, A.shape
>>> [1 2 3 4] (4,)

numpy.ravel() is faster, since it is a library level function which does not make any copy of the array. However, any change in array A will carry itself over to the original array M if you are using numpy.ravel().

numpy.flatten() is slower than numpy.ravel(). But if you are using numpy.flatten() to create A, then changes in A will not get carried over to the original array M.

numpy.squeeze() and M.reshape(-1) are slower than numpy.flatten() and numpy.ravel().

%timeit M.ravel()
>>> 1000000 loops, best of 3: 309 ns per loop

%timeit M.flatten()
>>> 1000000 loops, best of 3: 650 ns per loop

%timeit M.reshape(-1)
>>> 1000000 loops, best of 3: 755 ns per loop

%timeit np.squeeze(M)
>>> 1000000 loops, best of 3: 886 ns per loop

javax.net.ssl.SSLException: Received fatal alert: protocol_version

Not sure if you found an answer but I had this problem and needed to upgrade TLS version to 1.2

private HttpsURLConnection getSSlConnection(String url, String username, String password){
    SSLContext sc = SSLContext.getInstance("TLSv1.2")
    // Create a trust manager that accepts all SSL sites
    TrustManager[] trustAllCerts = new TrustManager[1]
    def tm = new X509TrustManager(){
        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0]
        }
    }
    trustAllCerts[0] = tm

    sc.init(null, trustAllCerts, new SecureRandom())
    HttpsURLConnection connection = (HttpsURLConnection) getConnection(url, username, password)
    connection.setSSLSocketFactory(sc.getSocketFactory())
    return connection
}

How to apply !important using .css()?

FYI, it doesn't work because jQuery doesn't support it. There was a ticket filed on 2012 (#11173 $(elem).css("property", "value !important") fails) that was eventually closed as WONTFIX.

How prevent CPU usage 100% because of worker process in iis

There are a lot of reasons that you can be seeing w3wp.exe high CPU usage. I have selected six common causes to cover.

  1. High error rates within your ASP.NET web application
  2. Increase in web traffic causing high CPU
  3. Problems with application dependencies
  4. Garbage collection
  5. Requests getting blocked or hung somewhere in the ASP.NET pipeline
  6. Inefficient .NET code that needs to be optimized

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

I think this will work even though this was forever ago.

SELECT employee_number, Row_Number()  
   OVER (PARTITION BY course_code ORDER BY course_completion_date DESC ) as rownum
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
   AND rownum = 1

If you want to get the last Id if the date is the same then you can use this assuming your primary key is Id.

SELECT employee_number, Row_Number()  
   OVER (PARTITION BY course_code ORDER BY course_completion_date DESC, Id Desc) as rownum    FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
   AND rownum = 1

How to Count Duplicates in List with LINQ

Slightly shorter version using methods chain:

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = list.GroupBy(x => x)
            .Select(g => new {Value = g.Key, Count = g.Count()})
            .OrderByDescending(x=>x.Count);

foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

Android RelativeLayout programmatically Set "centerInParent"

Just to add another flavor from the Reuben response, I use it like this to add or remove this rule according to a condition:

    RelativeLayout.LayoutParams layoutParams =
            (RelativeLayout.LayoutParams) holder.txtGuestName.getLayoutParams();

    if (SOMETHING_THAT_WOULD_LIKE_YOU_TO_CHECK) {
        // if true center text:
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        holder.txtGuestName.setLayoutParams(layoutParams);
    } else {
        // if false remove center:
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
        holder.txtGuestName.setLayoutParams(layoutParams);
    }

What does O(log n) mean exactly?

What's logb(n)?

It is the number of times you can cut a log of length n repeatedly into b equal parts before reaching a section of size 1.

how can I enable scrollbars on the WPF Datagrid?

Add grid with defined height and width for columns and rows. Then add ScrollViewer and inside it add the dataGrid.

HTML5 Audio stop function

I believe it would be good to check if the audio is playing state and reset the currentTime property.

if (sound.currentTime !== 0 && (sound.currentTime > 0 && sound.currentTime < sound.duration) {
    sound.currentTime = 0;
}
sound.play();

How to perform runtime type checking in Dart?

As others have mentioned, Dart's is operator is the equivalent of Javascript's instanceof operator. However, I haven't found a direct analogue of the typeof operator in Dart.

Thankfully the dart:mirrors reflection API has recently been added to the SDK, and is now available for download in the latest Editor+SDK package. Here's a short demo:

import 'dart:mirrors'; 

getTypeName(dynamic obj) {
  return reflect(obj).type.reflectedType.toString();
}

void main() {
  var val = "\"Dart is dynamically typed (with optional type annotations.)\"";
  if (val is String) {
    print("The value is a String, but I needed "
        "to check with an explicit condition.");
  }
  var typeName = getTypeName(val);
  print("\nThe mirrored type of the value is $typeName.");
}

Tomcat is web server or application server?

Tomcat is a web server and a Servlet/JavaServer Pages container. It is often used as an application server for strictly web-based applications but does not include the entire suite of capabilities that a Java EE application server would supply.

Links:

What is the MySQL JDBC driver connection string?

update for mySQL 8 :

String jdbcUrl="jdbc:mysql://localhost:3306/youdatabase?useSSL=false&serverTimezone=UTC";

Check whether your Jdbc configurations and URL correct or wrong using the following code snippet.

import java.sql.Connection;
import java.sql.DriverManager;

public class TestJdbc {

    public static void main(String[] args) {

        //db name:testdb_version001
        //useSSL=false (get rid of MySQL SSL warnings)

        String jdbcUrl = "jdbc:mysql://localhost:3306/testdb_version001?useSSL=false";
        String username="testdb";
        String password ="testdb";

        try{

            System.out.println("Connecting to database :" +jdbcUrl);
            Connection myConn =
                    DriverManager.getConnection(jdbcUrl,username,password);

            System.out.println("Connection Successful...!");


        }catch (Exception e){
            e.printStackTrace();
            //e.printStackTrace();
        }

    }


}

How do I properly compare strings in C?

You can't (usefully) compare strings using != or ==, you need to use strcmp:

while (strcmp(check,input) != 0)

The reason for this is because != and == will only compare the base addresses of those strings. Not the contents of the strings themselves.

Redirect to new Page in AngularJS using $location

this worked for me inside a directive and works without refreshing the baseurl (just adds the endpoint).Good for Single Page Apps with routing mechanism.

  $(location).attr('href', 'http://localhost:10005/#/endpoint') 

Clear dropdown using jQuery Select2

I found the answer (compliments to user780178) I was looking for in this other question:

Reset select2 value and show placeholdler

$("#customers_select").select2("val", "");

How to drop all tables from a database with one SQL query?

If you don't want to type, you can create the statements with this:

USE Databasename

SELECT  'DROP TABLE [' + name + '];'
FROM    sys.tables

Then copy and paste into a new SSMS window to run it.

What does the question mark in Java generics' type parameter mean?

In English:

It's a List of some type that extends the class HasWord, including HasWord

In general the ? in generics means any class. And the extends SomeClass specifies that that object must extend SomeClass (or be that class).

How can I strip all punctuation from a string in JavaScript using regex?

If you want to retain only alphabets and spaces, you can do:

str.replace(/[^a-zA-Z ]+/g, '').replace('/ {2,}/',' ')

Filter an array using a formula (without VBA)

Today, in Office 365, Excel has so called 'array functions'. The filter function does exactly what you want. No need to use CTRL+SHIFT+ENTER anymore, a simple enter will suffice.

In Office 365, your problem would be simply solved by using:

=VLOOKUP(A3, FILTER(A2:C6, B2:B6="B"), 3, FALSE)

Java AES encryption and decryption

Here is the implementation that was mentioned above:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;

try
{
    String passEncrypt = "my password";
    byte[] saltEncrypt = "choose a better salt".getBytes();
    int iterationsEncrypt = 10000;
    SecretKeyFactory factoryKeyEncrypt = SecretKeyFactory
            .getInstance("PBKDF2WithHmacSHA1");
    SecretKey tmp = factoryKeyEncrypt.generateSecret(new PBEKeySpec(
            passEncrypt.toCharArray(), saltEncrypt, iterationsEncrypt,
            128));
    SecretKeySpec encryptKey = new SecretKeySpec(tmp.getEncoded(),
            "AES");

    Cipher aesCipherEncrypt = Cipher
            .getInstance("AES/ECB/PKCS5Padding");
    aesCipherEncrypt.init(Cipher.ENCRYPT_MODE, encryptKey);

    // get the bytes
    byte[] bytes = StringUtils.getBytesUtf8(toEncodeEncryptString);

    // encrypt the bytes
    byte[] encryptBytes = aesCipherEncrypt.doFinal(bytes);

    // encode 64 the encrypted bytes
    String encoded = Base64.encodeBase64URLSafeString(encryptBytes);

    System.out.println("e: " + encoded);

    // assume some transport happens here

    // create a new string, to make sure we are not pointing to the same
    // string as the one above
    String encodedEncrypted = new String(encoded);

    //we recreate the same salt/encrypt as if its a separate system
    String passDecrypt = "my password";
    byte[] saltDecrypt = "choose a better salt".getBytes();
    int iterationsDecrypt = 10000;
    SecretKeyFactory factoryKeyDecrypt = SecretKeyFactory
            .getInstance("PBKDF2WithHmacSHA1");
    SecretKey tmp2 = factoryKeyDecrypt.generateSecret(new PBEKeySpec(passDecrypt
            .toCharArray(), saltDecrypt, iterationsDecrypt, 128));
    SecretKeySpec decryptKey = new SecretKeySpec(tmp2.getEncoded(), "AES");

    Cipher aesCipherDecrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
            aesCipherDecrypt.init(Cipher.DECRYPT_MODE, decryptKey);

    //basically we reverse the process we did earlier

    // get the bytes from encodedEncrypted string
    byte[] e64bytes = StringUtils.getBytesUtf8(encodedEncrypted);

    // decode 64, now the bytes should be encrypted
    byte[] eBytes = Base64.decodeBase64(e64bytes);

    // decrypt the bytes
    byte[] cipherDecode = aesCipherDecrypt.doFinal(eBytes);

    // to string
    String decoded = StringUtils.newStringUtf8(cipherDecode);

    System.out.println("d: " + decoded);

}
catch (Exception e)
{
    e.printStackTrace();
}

SQL to search objects, including stored procedures, in Oracle

I would use DBA_SOURCE (if you have access to it) because if the object you require is not owned by the schema under which you are logged in you will not see it.

If you need to know the functions and Procs inside the packages try something like this:

select * from all_source
 where type = 'PACKAGE'
   and (upper(text) like '%FUNCTION%' or upper(text) like '%PROCEDURE%')
   and owner != 'SYS';

The last line prevents all the sys stuff (DBMS_ et al) from being returned. This will work in user_source if you just want your own schema stuff.

Count number of tables in Oracle

Use this query which will give you the actual no of counts in respect to the table owners

SELECT COUNT(*),tablespace_name  FROM USER_TABLES group by tablespace_name;

overlay opaque div over youtube iframe

Note that the wmode=transparent fix only works if it's first so

http://www.youtube.com/embed/K3j9taoTd0E?wmode=transparent&rel=0

Not

http://www.youtube.com/embed/K3j9taoTd0E?rel=0&wmode=transparent

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You can just use the Select() extension method:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());

Or in LINQ syntax:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };

var strings = from i in integers
              select i.ToString();

How to print HTML content on click of a button, but not the page?

According to this SO link you can print a specific div with

w=window.open();
w.document.write(document.getElementsByClassName('report_left_inner')[0].innerH??TML);
w.print();
w.close();

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

How can I import Swift code to Objective-C?

Instructions from the Apple website:

To import Swift code into Objective-C from the same framework

Under Build Settings, in Packaging, make sure the Defines Module setting for that framework target is set to Yes. Import the Swift code from that framework target into any Objective-C .m file within that framework target using this syntax and substituting the appropriate names:

#import "ProductName-Swift.h"

Revision:

You can only import "ProductName-Swift.h" in .m files.

The Swift files in your target will be visible in Objective-C .m files containing this import statement.

To avoid cyclical references, don’t import Swift into an Objective-C header file. Instead, you can forward declare a Swift class to use it in an Objective-C header. Note that you cannot subclass a Swift class in Objective-C.

enter image description here

Convert xlsx to csv in Linux with command line

You can do this with LibreOffice:

libreoffice --headless --convert-to csv $filename --outdir $outdir

For reasons not clear to me, you might need to run this with sudo. You can make LibreOffice work with sudo without requiring a password by adding this line to you sudoers file:

users ALL=(ALL) NOPASSWD: libreoffice

How to substring in jquery

Using .split(). (Second version uses .slice() and .join() on the Array.)

var result = name.split('name')[1];
var result = name.split('name').slice( 1 ).join(''); // May be a little safer

Using .replace().

var result = name.replace('name','');

Using .slice() on a String.

var result = name.slice( 4 );

"webxml attribute is required" error in Maven

Make sure to run mvn install before you compile your war.

Java: Retrieving an element from a HashSet

It sounds like you're essentially trying to use the hash code as a key in a map (which is what HashSets do behind the scenes). You could just do it explicitly, by declaring HashMap<Integer, MyHashObject>.

There is no get for HashSets because typically the object you would supply to the get method as a parameter is the same object you would get back.

How to assign a select result to a variable?

Try This

SELECT @PrimaryContactKey = c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey 
    AND i.invckey = @tmp_key

UPDATE tarinvoice SET confirmtocntctkey = @PrimaryContactKey 
WHERE invckey = @tmp_key
FETCH NEXT FROM @get_invckey INTO @tmp_key

You would declare this variable outside of your loop as just a standard TSQL variable.

I should also note that this is how you would do it for any type of select into a variable, not just when dealing with cursors.

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

Retrofit 2.3.0

    // Load CAs from an InputStream
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

    InputStream inputStream = context.getResources().openRawResource(R.raw.ssl_certificate); //(.crt)
    Certificate certificate = certificateFactory.generateCertificate(inputStream);
    inputStream.close();

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", certificate);

    // Create a TrustManager that trusts the CAs in our KeyStore.
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
    trustManagerFactory.init(keyStore);

    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    X509TrustManager x509TrustManager = (X509TrustManager) trustManagers[0];


    // Create an SSLSocketFactory that uses our TrustManager
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, new TrustManager[]{x509TrustManager}, null);
    sslSocketFactory = sslContext.getSocketFactory();

    //create Okhttp client
    OkHttpClient client = new OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory,x509TrustManager)
                .build();

    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(client)
                    .build();

Pandas DataFrame: replace all values in a column, based on condition

We can update the First Season column in df with the following syntax:

df['First Season'] = expression_for_new_values

To map the values in First Season we can use pandas‘ .map() method with the below syntax:

data_frame(['column']).map({'initial_value_1':'updated_value_1','initial_value_2':'updated_value_2'})

Equivalent of explode() to work with strings in MySQL

Use this function. It works like a charm. replace "|" with the char to explode/split and the values 1,2,3,etc are based on the number of entries in the data-set: Value_ONE|Value_TWO|Value_THREE.

SUBSTRING_INDEX(SUBSTRING_INDEX(`tblNAME`.`tblFIELD`, '|', 1), '|', -1) AS PSI,
SUBSTRING_INDEX(SUBSTRING_INDEX(`tblNAME`.`tblFIELD`, '|', 2), '|', -1) AS GPM,
SUBSTRING_INDEX(SUBSTRING_INDEX(`tblNAME`.`tblFIELD`, '|', 3), '|', -1) AS LIQUID

I hope this helps.

How do I use reflection to invoke a private method?

Simply change your code to use the overloaded version of GetMethod that accepts BindingFlags:

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, 
    BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(this, new object[] { methodParams });

Here's the BindingFlags enumeration documentation.

Java - Relative path of a file in a java web application

there is another way, if you are using a container like Tomcat :

String textPath = "http://localhost:8080/NameOfWebapp/resources/images/file.txt";

How to create a file name with the current date & time in Python?

This prints in an easy to read format -

import datetime

time_now  = datetime.datetime.now().strftime('%m_%d_%Y_%H_%M_%S') 

print(time_now)

Output: 02_03_2021_22_44_50

What does the red exclamation point icon in Eclipse mean?

Make sure you don't have any undefined classpath variables (like M2_REPO).

laravel collection to array

Use collect($comments_collection).

Else, try json_encode($comments_collection) to convert to json.

How can we run a test method with multiple parameters in MSTest?

This feature is in pre-release now and works with Visual Studio 2015.

For example:

[TestClass]
public class UnitTest1
{
    [TestMethod]
    [DataRow(1, 2, 2)]
    [DataRow(2, 3, 5)]
    [DataRow(3, 5, 8)]
    public void AdditionTest(int a, int b, int result)
    {
        Assert.AreEqual(result, a + b);
    }
}

What are the differences between struct and class in C++?

Quoting The C++ FAQ,

[7.8] What's the difference between the keywords struct and class?

The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults.

Struct and class are otherwise functionally equivalent.

OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.

Execute combine multiple Linux commands in one line

If you want to execute all the commands, whether the previous one executes or not, you can use semicolon (;) to separate the commands.

cd /my_folder; rm *.jar; svn co path to repo; mvn compile package install

If you want to execute the next command only if the previous command succeeds, then you can use && to separate the commands.

cd /my_folder && rm *.jar && svn co path to repo && mvn compile package install

In your case, the execution of consecutive commands seems to depend upon the previous commands, so use the second example i.e. use && to join the commands.

Comparison of DES, Triple DES, AES, blowfish encryption for data

enter image description here

DES is the old "data encryption standard" from the seventies.

How to add 'libs' folder in Android Studio?

Click the left side dropdown menu "android" and choose "project" to see libs folders

enter image description here

*after choosing project you will see the libs directory

What's the difference between align-content and align-items?

Well I have examined them on my browser.

align-content can change a line's height for row direction or width for column when it's value is stretch, or add empty space between or around the lines for space-between, space-around, flex-start, flex-end values.

align-items can change items height or position inside the line's area. When items are not wrapped they have only one line which it's area is always stretched to the flex-box area (even if the items overflow), and align-content has no effect on a single line. So it has no effect on items that are not wrapped and only align-items can change items position or stretch them when all of them are on a single line.

However, if they are wrapped you have multiple lines and items inside each line. And if all items of each line have the same height (for row direction) that line's height will be equal to those items height and you don't see any effect by changing align-items value.

So if you want to affect items by align-items when your items are wrapped and have the same height (for row direction) first you have to use align-content with stretch value in order to expand the lines area.

encapsulation vs abstraction real world example

Abstraction Means We focus on the essential qualities of some thing rather than one specific example and we automatically discard what is unimportant or irrelevant.

Example We are writing a bank account class,essential qualities of bank account are Opening date, Account title,Account number,Balance etc...

Encapsulation Means the idea of capsulation or surrounding some thing not just to keep the content together but also to protect and restrict form accessing out side.Along with secrecy It's about reducing dependencies between different parts of the application.

Example In our Bank account class Someone accessing the attribute of Balance and trying to change it ,Attempt can be successful if there is no encapsulation.

PHP: How to check if image file exists?

If the file is on your local domain, you don't need to put the full URL. Only the path to the file. If the file is in a different directory, then you need to preface the path with "."

$file = './images/image.jpg';
if (file_exists($file)) {}

Often times the "." is left off which will cause the file to be shown as not existing, when it in fact does.

PadLeft function in T-SQL

declare @T table(id int)
insert into @T values
(1),
(2),
(12),
(123),
(1234)

select right('0000'+convert(varchar(4), id), 4)
from @T

Result

----
0001
0002
0012
0123
1234

Storing and retrieving datatable from session

this is just as a side note, but generally what you want to do is keep size on the Session and ViewState small. I generally just store IDs and small amounts of packets in Session and ViewState.

for instance if you want to pass large chunks of data from one page to another, you can store an ID in the querystring and use that ID to either get data from a database or a file.

PS: but like I said, this might be totally unrelated to your query :)

What is the equivalent of 'describe table' in SQL Server?

Just double click on the table name and press Alt+F1

How do I execute cmd commands through a batch file?

@echo off
title Command Executer
color 1b

echo Command Executer by: YourNameHere
echo #################################
: execute
echo Please Type A Command Here:
set /p cmd=Command:
%cmd%
goto execute

Filtering collections in C#

You can use the FindAll method of the List, providing a delegate to filter on. Though, I agree with @IainMH that it's not worth worrying yourself too much unless it's a huge list.

Stop absolutely positioned div from overlapping text

Thank you for all your answers, Whilst all were correct, none actually solved my problem. The solution for me was to create a second invisible div at the end of the content of unknown length, this invisible div is the same size as my absolutely positioned div, this ensures that there is always a space at the end of my content for the absolutely positioned div.

This answer was previously provided here: Prevent absolutely-positioned elements from overlapping with text However I didn't see (until now) how to apply it to a bottom right positioned div.

New structure is as follows:

_x000D_
_x000D_
<div id="outer" style="position: relative; width:450px; background-color:yellow;">
        <p>Content of unknown length</p>
        <div>Content of unknown height </div>
        <div id="spacer" style="width: 200px; height: 25px; margin-right:0px;"></div>
        <div style="position: absolute; right: 0; bottom: 0px; width: 200px; height: 20px; background-color:red;">bottom right</div>
    </div>
_x000D_
_x000D_
_x000D_

This seems to solve the issue.

How to convert a huge list-of-vector to a matrix more efficiently?

you can use as.matrix as below:

output <- as.matrix(z)

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

If you are on a mac keyboard using with UNIX OS;

control + alt + command + left or right should work for sure.

Does my application "contain encryption"?

As of September 20th, 2016, registering is no longer required for apps that use https (or perhaps other forms of encryption): https://web.archive.org/web/20170312060607/https://www.bis.doc.gov/index.php/informationsecurity2016-updates

In fact, on SNAP-R you can no longer choose 'encryption registration': enter image description here

Specifically, they note:

Encryption Registrations no longer required – some of the information from the registration now goes into the Supp. No. 8 to Part 742 report.

This means you may need to send an annual report to BIS, but you don't need to register and you can note when submitting your app that it is exempt.

How to use UIPanGestureRecognizer to move object? iPhone/iPad

-(IBAction)Method
{
      UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
      [panRecognizer setMinimumNumberOfTouches:1];
      [panRecognizer setMaximumNumberOfTouches:1];
      [ViewMain addGestureRecognizer:panRecognizer];
      [panRecognizer release];
}
- (Void)handlePan:(UIPanGestureRecognizer *)recognizer
{

     CGPoint translation = [recognizer translationInView:self.view];
     recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, 
                                     recognizer.view.center.y + translation.y);
     [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];

     if (recognizer.state == UIGestureRecognizerStateEnded) {

         CGPoint velocity = [recognizer velocityInView:self.view];
         CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
         CGFloat slideMult = magnitude / 200;
         NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);

         float slideFactor = 0.1 * slideMult; // Increase for more of a slide
         CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor), 
                                     recognizer.view.center.y + (velocity.y * slideFactor));
         finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
         finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);

         [UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
             recognizer.view.center = finalPoint;
         } completion:nil];

    }

}

How to download file in swift?

After trying a few of the above suggestions without success (Swift versions...) I ended up using the official documentation: https://developer.apple.com/documentation/foundation/url_loading_system/downloading_files_from_websites

let downloadTask = URLSession.shared.downloadTask(with: url) {
    urlOrNil, responseOrNil, errorOrNil in
    // check for and handle errors:
    // * errorOrNil should be nil
    // * responseOrNil should be an HTTPURLResponse with statusCode in 200..<299
    
    guard let fileURL = urlOrNil else { return }
    do {
        let documentsURL = try
            FileManager.default.url(for: .documentDirectory,
                                    in: .userDomainMask,
                                    appropriateFor: nil,
                                    create: false)
        let savedURL = documentsURL.appendingPathComponent(fileURL.lastPathComponent)
        try FileManager.default.moveItem(at: fileURL, to: savedURL)
    } catch {
        print ("file error: \(error)")
    }
}
downloadTask.resume()

Override default Spring-Boot application.properties settings in Junit Test

I just configured min as the following :

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console


# changing the name of my data base for testing
spring.datasource.url= jdbc:h2:mem:mockedDB
spring.datasource.username=sa
spring.datasource.password=sa



# in testing i don`t need to know the port

#Feature that determines what happens when no accessors are found for a type
#(and there are no annotations to indicate it is meant to be serialized).
spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false`enter code here`

How do you create a temporary table in an Oracle database?

Just a tip.. Temporary tables in Oracle are different to SQL Server. You create it ONCE and only ONCE, not every session. The rows you insert into it are visible only to your session, and are automatically deleted (i.e., TRUNCATE, not DROP) when you end you session ( or end of the transaction, depending on which "ON COMMIT" clause you use).

How to find the most recent file in a directory using .NET, and without looping?

how about something like this...

var directory = new DirectoryInfo("C:\\MyDirectory");
var myFile = (from f in directory.GetFiles()
             orderby f.LastWriteTime descending
             select f).First();

// or...
var myFile = directory.GetFiles()
             .OrderByDescending(f => f.LastWriteTime)
             .First();

MySQL - how to front pad zip code with "0"?

I know this is well after the OP. One way you can go with that keeps the table storing the zipcode data as an unsigned INT but displayed with zeros is as follows.

select LPAD(cast(zipcode_int as char), 5, '0') as zipcode from table;

While this preserves the original data as INT and can save some space in storage you will be having the server perform the INT to CHAR conversion for you. This can be thrown into a view and the person who needs this data can be directed there vs the table itself.

Setting Windows PowerShell environment variables

do not make headaches for yourself, want a simple, one line solution to add a permanent environment variable (open powershell in elevated mode):

[Environment]::SetEnvironmentVariable("NewEnvVar", "NewEnvValue", "Machine")

close the session and open it again to make things done


in case that u want to modify/change that:

[Environment]::SetEnvironmentVariable("oldEnvVar", "NewEnvValue", "Machine")


in case that u want to delete/remove that:

[Environment]::SetEnvironmentVariable("oldEnvVar", "", "Machine")

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

const times = 4;
new Array(times).fill().map(() => console.log('test'));

This snippet will console.log test 4 times.

IF EXISTS before INSERT, UPDATE, DELETE for optimization

The performance of an IF EXISTS statement:

IF EXISTS(SELECT 1 FROM mytable WHERE someColumn = someValue)

depends on the indexes present to satisfy the query.

How to select element using XPATH syntax on Selenium for Python?

Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.

> def get_browser():
>     """Get the browser (a "driver")."""
>     # find the path with 'which chromedriver'
>     path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
>                             'venv/bin/chromedriver')
>     download_dir = "/home/moose/selenium-download/"
>     print("Is directory: {}".format(os.path.isdir(download_dir)))
> 
>     from selenium.webdriver.chrome.options import Options
>     chrome_options = Options()
>     chrome_options.add_experimental_option('prefs', {
>         "plugins.plugins_list": [{"enabled": False,
>                                   "name": "Chrome PDF Viewer"}],
>         "download": {
>             "prompt_for_download": False,
>             "default_directory": download_dir
>         }
>     })
> 
>     browser = webdriver.Chrome(path_to_chromedriver,
>                                chrome_options=chrome_options)
>     return browser

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

import string 

sentence = "I     am having  a   very  nice  23!@$      day. "
# Remove all punctuations
sentence = sentence.translate(str.maketrans('', '', string.punctuation))
# Remove all numbers"
sentence = ''.join([word for word in sentence if not word.isdigit()])
count = 0;
for index in range(len(sentence)-1) :
    if sentence[index+1].isspace() and not sentence[index].isspace():
        count += 1 
print(count)

What does void do in java?

When the return type is void, your method doesn't return anything.

Look again at your code: There's no return in that method. You print to the console and exit.

Create Excel file in Java

Changing the extension of a file does not in any way change its contents. The extension is just a label.

If you want to work with Excel spreadsheets using Java, read up on the Apache POI library.

MySQL - Selecting data from multiple tables all with same structure but different data

I think you're looking for the UNION clause, a la

(SELECT * from us_music where `genre` = 'punk')
UNION
(SELECT * from de_music where `genre` = 'punk')