Programs & Examples On #Service

A Service is a long-running executable that performs specific functions and which is designed not to require user intervention.

startForeground fail after upgrade to Android 8.1

This worked for me. In my service class, I created the notification channel for android 8.1 as below:

public class Service extends Service {

    public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.package.MyService";
    public static final String NOTIFICATION_CHANNEL_ID_INFO = "com.package.download_info";

    @Override
    public void onCreate() {

        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
            nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
        } else {
            Notification notification = new Notification();
            startForeground(1, notification);
        }
    }
}

Note: Create the channel where you are creating the Notification for Build.VERSION.SDK_INT >= Build.VERSION_CODES.O

Using Service to run background and create notification

The question is relatively old, but I hope this post still might be relevant for others.

TL;DR: use AlarmManager to schedule a task, use IntentService, see the sample code here;

What this test-application(and instruction) is about:

Simple helloworld app, which sends you notification every 2 hours. Clicking on notification - opens secondary Activity in the app; deleting notification tracks.

When should you use it:

Once you need to run some task on a scheduled basis. My own case: once a day, I want to fetch new content from server, compose a notification based on the content I got and show it to user.

What to do:

  1. First, let's create 2 activities: MainActivity, which starts notification-service and NotificationActivity, which will be started by clicking notification:

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp">
        <Button
            android:id="@+id/sendNotifications"
            android:onClick="onSendNotificationsButtonClick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Start Sending Notifications Every 2 Hours!" />
    </RelativeLayout>
    

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        public void onSendNotificationsButtonClick(View view) {
            NotificationEventReceiver.setupAlarm(getApplicationContext());
        }   
    }
    

    and NotificationActivity is any random activity you can come up with. NB! Don't forget to add both activities into AndroidManifest.

  2. Then let's create WakefulBroadcastReceiver broadcast receiver, I called NotificationEventReceiver in code above.

    Here, we'll set up AlarmManager to fire PendingIntent every 2 hours (or with any other frequency), and specify the handled actions for this intent in onReceive() method. In our case - wakefully start IntentService, which we'll specify in the later steps. This IntentService would generate notifications for us.

    Also, this receiver would contain some helper-methods like creating PendintIntents, which we'll use later

    NB1! As I'm using WakefulBroadcastReceiver, I need to add extra-permission into my manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />

    NB2! I use it wakeful version of broadcast receiver, as I want to ensure, that the device does not go back to sleep during my IntentService's operation. In the hello-world it's not that important (we have no long-running operation in our service, but imagine, if you have to fetch some relatively huge files from server during this operation). Read more about Device Awake here.

    NotificationEventReceiver.java

    public class NotificationEventReceiver extends WakefulBroadcastReceiver {
    
        private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
        private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
        private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
    
        public static void setupAlarm(Context context) {
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            PendingIntent alarmIntent = getStartPendingIntent(context);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    getTriggerAt(new Date()),
                    NOTIFICATIONS_INTERVAL_IN_HOURS * AlarmManager.INTERVAL_HOUR,
                    alarmIntent);
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Intent serviceIntent = null;
            if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
                serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
            } else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
                serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
            }
    
            if (serviceIntent != null) {
                startWakefulService(context, serviceIntent);
            }
        }
    
        private static long getTriggerAt(Date now) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            //calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
            return calendar.getTimeInMillis();
        }
    
        private static PendingIntent getStartPendingIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    
        public static PendingIntent getDeleteIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_DELETE_NOTIFICATION);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    }
    
  3. Now let's create an IntentService to actually create notifications.

    There, we specify onHandleIntent() which is responses on NotificationEventReceiver's intent we passed in startWakefulService method.

    If it's Delete action - we can log it to our analytics, for example. If it's Start notification intent - then by using NotificationCompat.Builder we're composing new notification and showing it by NotificationManager.notify. While composing notification, we are also setting pending intents for click and remove actions. Fairly Easy.

    NotificationIntentService.java

    public class NotificationIntentService extends IntentService {
    
        private static final int NOTIFICATION_ID = 1;
        private static final String ACTION_START = "ACTION_START";
        private static final String ACTION_DELETE = "ACTION_DELETE";
    
        public NotificationIntentService() {
            super(NotificationIntentService.class.getSimpleName());
        }
    
        public static Intent createIntentStartNotificationService(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_START);
            return intent;
        }
    
        public static Intent createIntentDeleteNotification(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_DELETE);
            return intent;
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
            try {
                String action = intent.getAction();
                if (ACTION_START.equals(action)) {
                    processStartNotification();
                }
                if (ACTION_DELETE.equals(action)) {
                    processDeleteNotification(intent);
                }
            } finally {
                WakefulBroadcastReceiver.completeWakefulIntent(intent);
            }
        }
    
        private void processDeleteNotification(Intent intent) {
            // Log something?
        }
    
        private void processStartNotification() {
            // Do something. For example, fetch fresh data from backend to create a rich notification?
    
            final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            builder.setContentTitle("Scheduled Notification")
                    .setAutoCancel(true)
                    .setColor(getResources().getColor(R.color.colorAccent))
                    .setContentText("This notification has been triggered by Notification Service")
                    .setSmallIcon(R.drawable.notification_icon);
    
            PendingIntent pendingIntent = PendingIntent.getActivity(this,
                    NOTIFICATION_ID,
                    new Intent(this, NotificationActivity.class),
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);
            builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));
    
            final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(NOTIFICATION_ID, builder.build());
        }
    }
    
  4. Almost done. Now I also add broadcast receiver for BOOT_COMPLETED, TIMEZONE_CHANGED, and TIME_SET events to re-setup my AlarmManager, once device has been rebooted or timezone has changed (For example, user flown from USA to Europe and you don't want notification to pop up in the middle of the night, but was sticky to the local time :-) ).

    NotificationServiceStarterReceiver.java

    public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            NotificationEventReceiver.setupAlarm(context);
        }
    }
    
  5. We need to also register all our services, broadcast receivers in AndroidManifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="klogi.com.notificationbyschedule">
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <service
                android:name=".notifications.NotificationIntentService"
                android:enabled="true"
                android:exported="false" />
    
            <receiver android:name=".broadcast_receivers.NotificationEventReceiver" />
            <receiver android:name=".broadcast_receivers.NotificationServiceStarterReceiver">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                    <action android:name="android.intent.action.TIMEZONE_CHANGED" />
                    <action android:name="android.intent.action.TIME_SET" />
                </intent-filter>
            </receiver>
    
            <activity
                android:name=".NotificationActivity"
                android:label="@string/title_activity_notification"
                android:theme="@style/AppTheme.NoActionBar"/>
        </application>
    
    </manifest>
    

That's it!

The source code for this project you can find here. I hope, you will find this post helpful.

How to start and stop android service from a adb shell?

If you want to run the script in adb shell, then I am trying to do the same, but with an application. I think you can use "am start" command

usage: am [subcommand] [options]

start an Activity: am start [-D] [-W] <INTENT>
    -D: enable debugging
    -W: wait for launch to complete

**start a Service: am startservice <INTENT>**

send a broadcast Intent: am broadcast <INTENT>

start an Instrumentation: am instrument [flags] <COMPONENT>
    -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)
    -e <NAME> <VALUE>: set argument <NAME> to <VALUE>
    -p <FILE>: write profiling data to <FILE>
    -w: wait for instrumentation to finish before returning

start profiling: am profile <PROCESS> start <FILE>
stop profiling: am profile <PROCESS> stop

start monitoring: am monitor [--gdb <port>]
    --gdb: start gdbserv on the given port at crash/ANR

<INTENT> specifications include these flags:
    [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
    [-c <CATEGORY> [-c <CATEGORY>] ...]
    [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]
    [--esn <EXTRA_KEY> ...]
    [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]
    [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]
    [-n <COMPONENT>] [-f <FLAGS>]
    [--grant-read-uri-permission] [--grant-write-uri-permission]
    [--debug-log-resolution]
    [--activity-brought-to-front] [--activity-clear-top]
    [--activity-clear-when-task-reset] [--activity-exclude-from-recents]
    [--activity-launched-from-history] [--activity-multiple-task]
    [--activity-no-animation] [--activity-no-history]
    [--activity-no-user-action] [--activity-previous-is-top]
    [--activity-reorder-to-front] [--activity-reset-task-if-needed]
    [--activity-single-top]
    [--receiver-registered-only] [--receiver-replace-pending]
    [<URI>]

The VMware Authorization Service is not running

1.Click Start and then type Run (or Windows button + R)

2.Type services.msc and click OK

3.Find all VMware services.

4.For each, click Start the service, unless the service is showing a status of Started.

  • If "Start the service" is disappear, please do these things before:

    1. Click Start and then type Run (or Windows button + R)
    2. Type msconfig and click OK
    3. In Services tab, find then check all VMware services checkboxes.
    4. Click Apply then OK.

stop service in android

To stop the service we must use the method stopService():

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  //startService(myService);
  stopService(myService);

then the method onDestroy() in the service is called:

  @Override
    public void onDestroy() {

        Log.i(TAG, "onCreate() , service stopped...");
    }

Here is a complete example including how to stop the service.

bind/unbind service example (android)

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

Thanks for sharing this. It helped a lot. The one difference in my applicationHost.config was

            <add name="SharePoint14Module" image="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\isapi\owssvr.dll" preCondition="appPoolName=SharePoint Central Administration v4,bitness64;SharePoint - 80" />

Note the multiple semicolon seperated entries. This is probably because I have a single box install of SPS.

.aspx vs .ashx MAIN difference

Page is a special case handler.

Generic Web handler (*.ashx, extension based processor) is the default HTTP handler for all Web handlers that do not have a UI and that include the @WebHandler directive.

ASP.NET page handler (*.aspx) is the default HTTP handler for all ASP.NET pages.

Among the built-in HTTP handlers there are also Web service handler (*.asmx) and Trace handler (trace.axd)

MSDN says:

An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.

The image below illustrates this: request pipe line

As to your second question:

Does ashx handle more connections than aspx?

Don't think so (but for sure, at least not less than).

Start systemd service after specific service?

In the .service file under the [Unit] section:

[Unit]
Description=My Website
After=syslog.target network.target mongodb.service

The important part is the mongodb.service

The manpage describes it however due to formatting it's not as clear on first sight

systemd.unit - well formatted

systemd.unit - not so well formatted

Install Windows Service created in Visual Studio

You need to open the Service.cs file in the designer, right click it and choose the menu-option "Add Installer".

It won't install right out of the box... you need to create the installer class first.

Some reference on service installer:

How to: Add Installers to Your Service Application

Quite old... but this is what I am talking about:

Windows Services in C#: Adding the Installer (part 3)

By doing this, a ProjectInstaller.cs will be automaticaly created. Then you can double click this, enter the designer, and configure the components:

  • serviceInstaller1 has the properties of the service itself: Description, DisplayName, ServiceName and StartType are the most important.

  • serviceProcessInstaller1 has this important property: Account that is the account in which the service will run.

For example:

this.serviceProcessInstaller1.Account = ServiceAccount.LocalSystem;

How to check if a particular service is running on Ubuntu

For Ubuntu (checked with 12.04)

You can get list of all services and select by color one of them with 'grep':

sudo service --status-all | grep postgres

Or you may use another way if you know correct name of service:

sudo service postgresql status

Unable to start Service Intent

In my case the 1 MB maximum cap for data transport by Intent. I'll just use Cache or Storage.

Mongodb service won't start

Delete the .lock file from the C:\mongodb\data\ path and then restart the mongodb service.

Should a RESTful 'PUT' operation return something

I think it is possible for the server to return content in response to a PUT. If you are using a response envelop format that allows for sideloaded data (such as the format consumed by ember-data), then you can also include other objects that may have been modified via database triggers, etc. (Sideloaded data is explicitly to reduce # of requests, and this seems like a fine place to optimize.)

If I just accept the PUT and have nothing to report back, I use status code 204 with no body. If I have something to report, I use status code 200, and include a body.

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

I found this answer on another site but it definitely worked for me so I thought I would share it.

In Windows Explorer: Right Click on the folder OfficeSoftwareProtection Platform from C:\Program Files\Common Files\Microsoft Shared and Microsoft from C:\Program data(this is a hidden folder) Properties > Security > Edit > Add > Type Network Service > OK > Check the Full control box > Apply and OK.

In Registry Editor (regedit.exe): Go to HKEY_CLASSES_ROOT\AppID registry >Right Click on the folder > Permissions > Add > Type = NETWORK SERVICE > OK > Check Full Control > Apply > OK

I found this response here::: https://social.technet.microsoft.com/Forums/windows/en-US/5dda9b0b-636f-4f2f-8e50-ad05e98ab22d/error-1920-service-office-software-protection-platform-osppsvc-failed-to-start-verify-that-you?forum=officesetupdeployprevious

Which was originally a method discovered by Jennifer Zhan

Android: keep Service running when app is killed

All the answers seem correct so I'll go ahead and give a complete answer here.

Firstly, the easiest way to do what you are trying to do is launch a Broadcast in Android when the app is killed manually, and define a custom BroadcastReceiver to trigger a service restart following that.

Now lets jump into code.


Create your Service in YourService.java

Note the onCreate() method, where we are starting a foreground service differently for Build versions greater than Android Oreo. This because of the strict notification policies introduced recently where we have to define our own notification channel to display them correctly.

The this.sendBroadcast(broadcastIntent); in the onDestroy() method is the statement which asynchronously sends a broadcast with the action name "restartservice". We'll be using this later as a trigger to restart our service.

Here we have defined a simple Timer task, which prints a counter value every 1 second in the Log while incrementing itself every time it prints.

public class YourService extends Service {
public int counter=0;

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
            startMyOwnForeground();
        else
            startForeground(1, new Notification());
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private void startMyOwnForeground()
    {
        String NOTIFICATION_CHANNEL_ID = "example.permanence";
        String channelName = "Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder.setOngoing(true)
                .setContentTitle("App is running in background")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(2, notification);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        startTimer();
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        stoptimertask();

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("restartservice");
        broadcastIntent.setClass(this, Restarter.class);
        this.sendBroadcast(broadcastIntent);
    }



    private Timer timer;
    private TimerTask timerTask;
    public void startTimer() {
        timer = new Timer();
        timerTask = new TimerTask() {
            public void run() {
                Log.i("Count", "=========  "+ (counter++));
            }
        };
        timer.schedule(timerTask, 1000, 1000); //
    }

    public void stoptimertask() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Create a Broadcast Receiver to respond to your custom defined broadcasts in Restarter.java

The broadcast with the action name "restartservice" which you just defined in YourService.java is now supposed to trigger a method which will restart your service. This is done using BroadcastReceiver in Android.

We override the built-in onRecieve() method in BroadcastReceiver to add the statement which will restart the service. The startService() will not work as intended in and above Android Oreo 8.1, as strict background policies will soon terminate the service after restart once the app is killed. Therefore we use the startForegroundService() for higher versions and show a continuous notification to keep the service running.

public class Restarter extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Broadcast Listened", "Service tried to stop");
        Toast.makeText(context, "Service restarted", Toast.LENGTH_SHORT).show();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(new Intent(context, YourService.class));
        } else {
            context.startService(new Intent(context, YourService.class));
        }
    }
}

Define your MainActivity.java to call the service on app start.

Here we define a separate isMyServiceRunning() method to check the current status of the background service. If the service is not running, we start it by using startService().

Since the app is already running in foreground, we need not launch the service as a foreground service to prevent itself from being terminated.

Note that in onDestroy() we are dedicatedly calling stopService(), so that our overridden method gets invoked. If this was not done, then the service would have ended automatically after app is killed without invoking our modified onDestroy() method in YourService.java

public class MainActivity extends AppCompatActivity {
    Intent mServiceIntent;
    private YourService mYourService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mYourService = new YourService();
        mServiceIntent = new Intent(this, mYourService.getClass());
        if (!isMyServiceRunning(mYourService.getClass())) {
            startService(mServiceIntent);
        }
    }

    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                Log.i ("Service status", "Running");
                return true;
            }
        }
        Log.i ("Service status", "Not running");
        return false;
    }


    @Override
    protected void onDestroy() {
        //stopService(mServiceIntent);
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("restartservice");
        broadcastIntent.setClass(this, Restarter.class);
        this.sendBroadcast(broadcastIntent);
        super.onDestroy();
    }
}

Finally register them in your AndroidManifest.xml

All of the above three classes need to be separately registered in AndroidManifest.xml.

Note that we define an intent-filter with the action name as "restartservice" where the Restarter.java is registered as a receiver. This ensures that our custom BroadcastReciever is called whenever the system encounters a broadcast with the given action name.

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <receiver
        android:name="Restarter"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="restartservice" />
        </intent-filter>
    </receiver>

    <activity android:name="MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="YourService"
        android:enabled="true" >
    </service>
</application>

This should now restart your service again if the app was killed from the task-manager. This service will keep on running in background as long as the user doesn't Force Stop the app from Application Settings.

UPDATE: Kudos to Dr.jacky for pointing it out. The above mentioned way will only work if the onDestroy() of the service is called, which might not be the case certain times, which I was unaware of. Thanks.

How to run a Python script in the background even after I logout SSH?

Try this:

nohup python -u <your file name>.py >> <your log file>.log &

You can run above command in screen and come out of screen.

Now you can tail logs of your python script by: tail -f <your log file>.log

To kill you script, you can use ps -aux and kill commands.

How to check if Location Services are enabled?

On Android 8.1 or lower the user can enable "Battery saving" mode from
Settings > Location > Mode > Battery Saving.
This mode only uses WiFi, Bluetooth or mobile data instead of GPS to determine the user location.

That's why you have to check if the network provider is enabled and locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) is not enough.

If you are using androidx this code will check which SDK version you are running and call the corresponding provider:

public boolean isLocationEnabled(Context context) {
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    return manager != null ? LocationManagerCompat.isLocationEnabled(manager) : false;
}

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

i faced this issue where i was using SQL it is different from MYSQL the solution was puting in this format: =date('m-d-y h:m:s'); rather than =date('y-m-d h:m:s');

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

I get the same error in Cygwin. I had to install the openssh package in Cygwin Setup.

(The strange thing was that all ssh-* commands were valid, (bash could execute as program) but the openssh package wasn't installed.)

Start service in Android

startService(new Intent(this, MyService.class));

Just writing this line was not sufficient for me. Service still did not work. Everything had worked only after registering service at manifest

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >

    ...

    <service
        android:name=".MyService"
        android:label="My Service" >
    </service>
</application>

How to create a service running a .exe file on Windows 2012 Server?

You can just do that too, it seems to work well too. sc create "Servicename" binPath= "Path\To\your\App.exe" DisplayName= "My Custom Service"

You can open the registry and add a string named Description in your service's registry key to add a little more descriptive information about it. It will be shown in services.msc.

How SID is different from Service name in Oracle tnsnames.ora

Please see: http://www.sap-img.com/oracle-database/finding-oracle-sid-of-a-database.htm

What is the difference between Oracle SIDs and Oracle SERVICE NAMES. One config tool looks for SERVICE NAME and then the next looks for SIDs! What's going on?!

Oracle SID is the unique name that uniquely identifies your instance/database where as Service name is the TNS alias that you give when you remotely connect to your database and this Service name is recorded in Tnsnames.ora file on your clients and it can be the same as SID and you can also give it any other name you want.

SERVICE_NAME is the new feature from oracle 8i onwards in which database can register itself with listener. If database is registered with listener in this way then you can use SERVICE_NAME parameter in tnsnames.ora otherwise - use SID in tnsnames.ora.

Also if you have OPS (RAC) you will have different SERVICE_NAME for each instance.

SERVICE_NAMES specifies one or more names for the database service to which this instance connects. You can specify multiple services names in order to distinguish among different uses of the same database. For example:

SERVICE_NAMES = sales.acme.com, widgetsales.acme.com

You can also use service names to identify a single service that is available from two different databases through the use of replication.

In an Oracle Parallel Server environment, you must set this parameter for every instance.

In short: SID = the unique name of your DB instance, ServiceName = the alias used when connecting

Android WSDL/SOAP service client

I’ve created a new SOAP client for the Android platform, it is use a JAX-WS generated interfaces, but it is only a proof-of-concept yet.

If you are interested, please try the example and/or watch the source: http://wiki.javaforum.hu/display/ANDROIDSOAP/Home

Update: the version 0.0.4 is out with tutorial:

http://wiki.javaforum.hu/display/ANDROIDSOAP/2012/04/16/Version+0.0.4+released

http://wiki.javaforum.hu/display/ANDROIDSOAP/Step+by+step+tutorial

how to set windows service username and password through commandline

In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:

sc.exe config Service obj= user password= pass

Specyfying the .exe extension, PowerShell bypasses the alias lookup.

HTH

Android Service Stops When App Is Closed

Why not use an IntentService?

IntentService opens a new Thread apart from the main Thread and works there, that way closing the app wont effect it

Be advised that IntentService runs the onHandleIntent() and when its done the service closes, see if it fits your needs. http://developer.android.com/reference/android/app/IntentService.html

Android: How can I get the current foreground activity (from a service)?

Here is my answer that works just fine...

You should be able to get current Activity in this way... If you structure your app with a few Activities with many fragments and you want to keep track of what is your current Activity, it would take a lot of work though. My senario was I do have one Activity with multiple Fragments. So I can keep track of Current Activity through Application Object, which can store all of the current state of Global variables.

Here is a way. When you start your Activity, you store that Activity by Application.setCurrentActivity(getIntent()); This Application will store it. On your service class, you can simply do like Intent currentIntent = Application.getCurrentActivity(); getApplication().startActivity(currentIntent);

Call to getLayoutInflater() in places not in activity

LayoutInflater.from(context).inflate(R.layout.row_payment_gateway_item, null);

IIS w3svc error

Run cmd as administrator. Type iisreset. That's it.

Spring Boot application as a Service

If you want to use Spring Boot 1.2.5 with Spring Boot Maven Plugin 1.3.0.M2, here's out solution:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>1.3.0.M2</version>
            <configuration>
                <executable>true</executable>
            </configuration>
        </plugin>
    </plugins>
</build>

<pluginRepositories>
    <pluginRepository>
        <id>spring-libs-milestones</id>
        <url>http://repo.spring.io/libs-milestone</url>
    </pluginRepository> 
</pluginRepositories>

Then compile as ususal: mvn clean package, make a symlink ln -s /.../myapp.jar /etc/init.d/myapp, make it executable chmod +x /etc/init.d/myapp and start it service myapp start (with Ubuntu Server)

Installing Tomcat 7 as Service on Windows Server 2008

Looks like now they have the bat in the zip as well

note that you can use windows sc command to do more

e.g.

sc config tomcat7 start= auto

yes the space before auto is NEEDED

the MySQL service on local computer started and then stopped

Also remember to give NETWORK SERVICE permission to the folder:

  1. Right-click Data folder
  2. Select Properties
  3. Select Security tab
  4. Click Advanced
  5. Click Change Permissions...
  6. Click Add...
  7. Type NETWORK SERVICE
  8. Click Check Names
  9. Click OK
  10. Select Full Control
  11. Click OK – four times
  12. Start MySQL service

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

Details

http://msdn.microsoft.com/en-us/library/hh169179(v=nav.71).aspx

"This error can occur when there are multiple versions of the .NET Framework on the computer that is running IIS..."

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

SSRS expression to format two decimal places does not show zeros

If you want it as a string use:

=Format(Fields!CUL1.Value, "F2")

As a number use:

=FormatNumber(Fields!CUL1.Value, 2)

This will ensure it exports out to excel correctly as a number.

Android: keeping a background service alive (preventing process death)

For Android 2.0 or later you can use the startForeground() method to start your Service in the foreground.

The documentation says the following:

A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)

The is primarily intended for when killing the service would be disruptive to the user, e.g. killing a music player service would stop music playing.

You'll need to supply a Notification to the method which is displayed in the Notifications Bar in the Ongoing section.

Bind service to activity in Android

I tried to call

startService(oIntent);
bindService(oIntent, mConnection, Context.BIND_AUTO_CREATE);

consequently and I could create a sticky service and bind to it. Detailed tutorial for Bound Service Example.

Android - implementing startForeground for a service?

Solution for Oreo 8.1

I've encountered some problems such as RemoteServiceException because of invalid channel id with most recent versions of Android. This is how i solved it:

Activity:

override fun onCreate(savedInstanceState: Bundle?) {
    val intent = Intent(this, BackgroundService::class.java)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(intent)
    } else {
        startService(intent)
    }
}

BackgroundService:

override fun onCreate() {
    super.onCreate()
    startForeground()
}

private fun startForeground() {

    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val channelId =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                createNotificationChannel()
            } else {
                // If earlier version channel ID is not used
                // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
                ""
            }

    val notificationBuilder = NotificationCompat.Builder(this, channelId )
    val notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(PRIORITY_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build()
    startForeground(101, notification)
}


@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(): String{
    val channelId = "my_service"
    val channelName = "My Background Service"
    val chan = NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_HIGH)
    chan.lightColor = Color.BLUE
    chan.importance = NotificationManager.IMPORTANCE_NONE
    chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    service.createNotificationChannel(chan)
    return channelId
}

JAVA EQUIVALENT

public class YourService extends Service {

    // Constants
    private static final int ID_SERVICE = 101;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // do stuff like register for BroadcastReceiver, etc.

        // Create the Foreground Service
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(PRIORITY_MIN)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .build();

        startForeground(ID_SERVICE, notification);
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(NotificationManager notificationManager){
        String channelId = "my_service_channelid";
        String channelName = "My Foreground Service";
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        // omitted the LED color
        channel.setImportance(NotificationManager.IMPORTANCE_NONE);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        notificationManager.createNotificationChannel(channel);
        return channelId;
    }
}

Pass data from Activity to Service using an Intent

If you are using kotlin you can try the following code,

In the sending activity,

  val intent = Intent(context, RecorderService::class.java);
  intent.putExtra("filename", filename);
  context.startService(intent)

In the service,

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    super.onStartCommand(intent, flags, startId)

    if (intent != null && intent.extras != null)
       val filename = intent.getStringExtra("filename")

}

Microsoft SQL Server 2005 service fails to start

We had a similar problem recently withour running SQL 2005 servers (more specifically: The reporting services). The windows services didn't start anymore with no real error message whatsoever.

I found out that this problem was related to some KB hotfixes that have been deployed lately. For some reason those hotfixes resulted in the services taking longer than usually for starting up.

Since by default, there is a timeout that kills the service after 30 seconds when it was not able to go beyond the start methods, this was the reason why it simply terminated.

Maybe this is what you are experiencing.

Theres a work around described on Microsoft Connect (link). Although the hotfixes listed in this article didn't match the ones that have been deployed to our systems, the workaround worked for us.

What is the correct way to start a mongod service on linux / OS X?

I did a bit of looking around on the Mac side. You may want to use the installer here as it looks like it does all the setup for you to automatically launch on Mac OS. The only downside is it looks like it's using a pretty old mongo version.

This link here also explains the setup to get mongo automatically launching as a background service on the Mac.

Get GPS location via a service in Android

Here is my solution

Step1 Register Serice in manifest

<receiver
    android:name=".MySMSBroadcastReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
    </intent-filter>
</receiver>

Step2 Code Of Service

public class FusedLocationService extends Service {

    private String mLastUpdateTime = null;

    // bunch of location related apis
    private FusedLocationProviderClient mFusedLocationClient;
    private SettingsClient mSettingsClient;
    private LocationRequest mLocationRequest;
    private LocationSettingsRequest mLocationSettingsRequest;
    private LocationCallback mLocationCallback;
    private Location lastLocation;

    // location updates interval - 10sec
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 5000;

    // fastest updates interval - 5 sec
    // location updates will be received if another app is requesting the locations
    // than your app can handle
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 500;
    private DatabaseReference locationRef;
    private int notificationBuilder = 0;
    private boolean isInitRef;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.log("LOCATION GET DURATION", "start in service");
        init();
        return START_STICKY;
    }

    /**
     * Initilize Location Apis
     * Create Builder if Share location true
     */
    private void init() {
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mSettingsClient = LocationServices.getSettingsClient(this);
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                receiveLocation(locationResult);
            }
        };

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        mLocationSettingsRequest = builder.build();
        startLocationUpdates();
    }

    /**
     * Request Location Update
     */
    @SuppressLint("MissingPermission")
    private void startLocationUpdates() {
        mSettingsClient
                .checkLocationSettings(mLocationSettingsRequest)
                .addOnSuccessListener(locationSettingsResponse -> {
                    Log.log(TAG, "All location settings are satisfied. No MissingPermission");

                    //noinspection MissingPermission
                    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                })
                .addOnFailureListener(e -> {
                    int statusCode = ((ApiException) e).getStatusCode();
                    switch (statusCode) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            Log.loge("Location settings are not satisfied. Attempting to upgrade " + "location settings ");
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            Log.loge("Location settings are inadequate, and cannot be " + "fixed here. Fix in Settings.");
                    }
                });
    }

    /**
     * onLocationResult
     * on Receive Location  share to other activity and save if save true
     *
     * @param locationResult
     */
    private void receiveLocation(LocationResult locationResult) {
        lastLocation = locationResult.getLastLocation();

        LocationInstance.getInstance().changeState(lastLocation);

        saveLocation();
    }

    private void saveLocation() {
        String saveLocation = getsaveLocationStatus(this);

        if (saveLocation.equalsIgnoreCase("true") && notificationBuilder == 0) {
            notificationBuilder();
            notificationBuilder = 1;
        } else if (saveLocation.equalsIgnoreCase("false") && notificationBuilder == 1) {
            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1);
            notificationBuilder = 0;
        }

        Log.logd("receiveLocation : Share :- " + saveLocation + ", [Lat " + lastLocation.getLatitude() + ", Lng" + lastLocation.getLongitude() + "], Time :- " + mLastUpdateTime);

        if (saveLocation.equalsIgnoreCase("true") || getPreviousMin() < getCurrentMin()) {
            setLatLng(this, lastLocation);

            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());

            if (isOnline(this) && !getUserId(this).equalsIgnoreCase("")) {
                if (!isInitRef) {
                    locationRef = getFirebaseInstance().child(getUserId(this)).child("location");
                    isInitRef = true;
                }
                if (isInitRef) {
                    locationRef.setValue(new LocationModel(lastLocation.getLatitude(), lastLocation.getLongitude(), mLastUpdateTime));
                }
            }
        }
    }

    private int getPreviousMin() {
        int previous_min = 0;
        if (mLastUpdateTime != null) {
            String[] pretime = mLastUpdateTime.split(":");
            previous_min = Integer.parseInt(pretime[1].trim()) + 1;

            if (previous_min > 59) {
                previous_min = 0;
            }
        }
        return previous_min;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopLocationUpdates();
    }

    /**
     * Remove Location Update
     */
    public void stopLocationUpdates() {
        mFusedLocationClient
                .removeLocationUpdates(mLocationCallback)
                .addOnCompleteListener(task -> Log.logd("stopLocationUpdates : "));
    }

    private void notificationBuilder() {
        if (Build.VERSION.SDK_INT >= 26) {
            String CHANNEL_ID = "my_channel_01";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);

            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("")
                    .setContentText("").build();

            startForeground(1, notification);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Step 3

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

Step 4

implementation 'com.google.android.gms:play-services-location:16.0.0'

Succeeded installing but could not start apache 2.4 on my windows 7 system

I was also facing the same issue, then i tried restarting my system after every change and it worked for me:

  1. Uninstall Apache2.4 in cmd prompt (run administrator) with the command: httpd -k uninstall.
  2. Restart the system.
  3. open cmd prompt (run administrator) with the command: httpd -k install.
  4. Then httpd -k install.

Hope you find useful.

Android Service needs to run always (Never pause or stop)

If you already have a service and want it to work all the time, you need to add 2 things:

  1. in the service itself:

    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    
  2. In the manifest:

    android:launchMode="singleTop"
    

No need to add bind unless you need it in the service.

AngularJS : Initialize service with asynchronous data

I had the same problem: I love the resolve object, but that only works for the content of ng-view. What if you have controllers (for top-level nav, let's say) that exist outside of ng-view and which need to be initialized with data before the routing even begins to happen? How do we avoid mucking around on the server-side just to make that work?

Use manual bootstrap and an angular constant. A naiive XHR gets you your data, and you bootstrap angular in its callback, which deals with your async issues. In the example below, you don't even need to create a global variable. The returned data exists only in angular scope as an injectable, and isn't even present inside of controllers, services, etc. unless you inject it. (Much as you would inject the output of your resolve object into the controller for a routed view.) If you prefer to thereafter interact with that data as a service, you can create a service, inject the data, and nobody will ever be the wiser.

Example:

//First, we have to create the angular module, because all the other JS files are going to load while we're getting data and bootstrapping, and they need to be able to attach to it.
var MyApp = angular.module('MyApp', ['dependency1', 'dependency2']);

// Use angular's version of document.ready() just to make extra-sure DOM is fully 
// loaded before you bootstrap. This is probably optional, given that the async 
// data call will probably take significantly longer than DOM load. YMMV.
// Has the added virtue of keeping your XHR junk out of global scope. 
angular.element(document).ready(function() {

    //first, we create the callback that will fire after the data is down
    function xhrCallback() {
        var myData = this.responseText; // the XHR output

        // here's where we attach a constant containing the API data to our app 
        // module. Don't forget to parse JSON, which `$http` normally does for you.
        MyApp.constant('NavData', JSON.parse(myData));

        // now, perform any other final configuration of your angular module.
        MyApp.config(['$routeProvider', function ($routeProvider) {
            $routeProvider
              .when('/someroute', {configs})
              .otherwise({redirectTo: '/someroute'});
          }]);

        // And last, bootstrap the app. Be sure to remove `ng-app` from your index.html.
        angular.bootstrap(document, ['NYSP']);
    };

    //here, the basic mechanics of the XHR, which you can customize.
    var oReq = new XMLHttpRequest();
    oReq.onload = xhrCallback;
    oReq.open("get", "/api/overview", true); // your specific API URL
    oReq.send();
})

Now, your NavData constant exists. Go ahead and inject it into a controller or service:

angular.module('MyApp')
    .controller('NavCtrl', ['NavData', function (NavData) {
        $scope.localObject = NavData; //now it's addressable in your templates 
}]);

Of course, using a bare XHR object strips away a number of the niceties that $http or JQuery would take care of for you, but this example works with no special dependencies, at least for a simple get. If you want a little more power for your request, load up an external library to help you out. But I don't think it's possible to access angular's $http or other tools in this context.

(SO related post)

Is Spring annotation @Controller same as @Service?

@Service vs @Controller

@Service : class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar.

@Controller : Indicates that an annotated class is a "Controller" (e.g. a web controller).

----------Find Usefull notes on Major Stereotypes http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Component.html

@interface Component

  @Target(value=TYPE)
     @Retention(value=RUNTIME)
     @Documented
    public @interface Component

Indicates that an annotated class is a component. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

Other class-level annotations may be considered as identifying a component as well, typically a special kind of component: e.g. the @Repository annotation or AspectJ's @Aspect annotation.

@interface Controller

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Component
public @interface Controller

Indicates that an annotated class is a "Controller" (e.g. a web controller).

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the RequestMapping annotation.

@interface Service

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Component
public @interface Service

Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design (Evans, 2003) as "an operation offered as an interface that stands alone in the model, with no encapsulated state." May also indicate that a class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

@interface Repository

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Component
public @interface Repository

Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects". Teams implementing traditional J2EE patterns such as "Data Access Object" may also apply this stereotype to DAO classes, though care should be taken to understand the distinction between Data Access Object and DDD-style repositories before doing so. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.

A class thus annotated is eligible for Spring DataAccessException translation when used in conjunction with a PersistenceExceptionTranslationPostProcessor. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tooling, aspects, etc.

As of Spring 2.5, this annotation also serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

Run a Java Application as a Service on Linux

Linux service init script are stored into /etc/init.d. You can copy and customize /etc/init.d/skeleton file, and then call

service [yourservice] start|stop|restart

see http://www.ralfebert.de/blog/java/debian_daemon/. Its for Debian (so, Ubuntu as well) but fit more distribution.

Sending a notification from a service in Android

Well, I'm not sure if my solution is best practice. Using the NotificationBuilder my code looks like that:

private void showNotification() {
    Intent notificationIntent = new Intent(this, MainActivity.class);

    PendingIntent contentIntent = PendingIntent.getActivity(
                this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, builder.build());
    }

Manifest:

    <activity
        android:name=".MainActivity"
        android:launchMode="singleInstance"
    </activity>

and here the Service:

    <service
        android:name=".services.ProtectionService"
        android:launchMode="singleTask">
    </service>

I don't know if there really is a singleTask at Service but this works properly at my application...

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

I just check the PendingIntent null or nor not before calling the context.startForegroundService(service_intent) function.

this works for me

PendingIntent pendingIntent=PendingIntent.getBroadcast(context,0,intent,PendingIntent.FLAG_NO_CREATE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && pendingIntent==null){
            context.startForegroundService(service_intent);
        }
        else
        {
            context.startService(service_intent);
        }
}

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Pls check JobScheduler for apis above 26

WakeLock was the best option for this but it is deprecated in api level 26 Pls check this link if you consider api levels above 26
https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html#startWakefulService(android.content.Context,%20android.content.Intent)

It says

As of Android O, background check restrictions make this class no longer generally useful. (It is generally not safe to start a service from the receipt of a broadcast, because you don't have any guarantees that your app is in the foreground at this point and thus allowed to do so.) Instead, developers should use android.app.job.JobScheduler to schedule a job, and this does not require that the app hold a wake lock while doing so (the system will take care of holding a wake lock for the job).

so as it says cosider JobScheduler
https://developer.android.com/reference/android/app/job/JobScheduler

if it is to do something than to start and to keep it you can receive the broadcast ACTION_BOOT_COMPLETED

If it isn't about foreground pls check if an Accessibility service could do

another option is to start an activity from broadcast receiver and finish it after starting the service within onCreate() , since newer android versions doesnot allows starting services from receivers

Mysql service is missing

If you wish to have your config file on a different path you have to give your service a name:

mysqld --install NAME --defaults-file=C:\my-opts2.cnf

You can also use the name to install multiple mysql services listening on different sockets if you need that for some reason. You can see why it's failing by copying the execution path and adding --console to the end in the terminal. Finally, you can modify the starting path of a service by regediting:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\NAME

That works well but it isn't as useful because the windows service mechanism provides little logging capabilities.

Detect rotation of Android phone in the browser with JavaScript

I had the same problem. I am using Phonegap and Jquery mobile, for Adroid devices. To resize properly I had to set a timeout:

$(window).bind('orientationchange',function(e) {
  fixOrientation();
});

$(window).bind('resize',function(e) {
  fixOrientation();
});

function fixOrientation() {

    setTimeout(function() {

        var windowWidth = window.innerWidth;

        $('div[data-role="page"]').width(windowWidth);
        $('div[data-role="header"]').width(windowWidth);
        $('div[data-role="content"]').width(windowWidth-30);
        $('div[data-role="footer"]').width(windowWidth);

    },500);
}

How can I make a multipart/form-data POST request using Java?

These are the Maven dependencies I have.

Java Code:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

FileBody uploadFilePart = new FileBody(uploadFile);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("upload-file", uploadFilePart);
httpPost.setEntity(reqEntity);

HttpResponse response = httpclient.execute(httpPost);

Maven Dependencies in pom.xml:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.0.1</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.0.1</version>
  <scope>compile</scope>
</dependency>

Combining a class selector and an attribute selector with jQuery

I think you just need to remove the space. i.e.

$(".myclass[reference=12345]").css('border', '#000 solid 1px');

There is a fiddle here http://jsfiddle.net/xXEHY/

How to create a simple checkbox in iOS?

On iOS there is the switch UI component instead of a checkbox, look into the UISwitch class. The property on (boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.

Upgrade python without breaking yum

Put /opt/python2.7/bin in your PATH environment variable in front of /usr/bin...or just get used to typing python2.7.

Copy/duplicate database without using mysqldump

I can see you said you didn't want to use mysqldump, but I reached this page while looking for a similar solution and others might find it as well. With that in mind, here is a simple way to duplicate a database from the command line of a windows server:

  1. Create the target database using MySQLAdmin or your preferred method. In this example, db2 is the target database, where the source database db1 will be copied.
  2. Execute the following statement on a command line:

mysqldump -h [server] -u [user] -p[password] db1 | mysql -h [server] -u [user] -p[password] db2

Note: There is NO space between -p and [password]

Remove attribute "checked" of checkbox

You could try $(this):

$("#captureAudio").live("change", function() {
    if($(this).val() !== undefined) { /* IF THIS VALUE IS NOT UNDEFINED */
            navigator.device.capture.captureAudio(function(mediaFiles) {
            console.log("audio");
        }, function() {
            $(this).removeAttr('checked'); /* REMOVE checked ATTRIBUTE; */
            /* YOU CAN USE `$(this).prop("checked", false);` ALSO */
            _callback.error;
        }, {limit: 1});
    }
});

How to build minified and uncompressed bundle with webpack?

You should export an array like this:

const path = require('path');
const webpack = require('webpack');

const libName = 'YourLibraryName';

function getConfig(env) {
  const config = {
    mode: env,
    output: {
      path: path.resolve('dist'),
      library: libName,
      libraryTarget: 'umd',
      filename: env === 'production' ? `${libName}.min.js` : `${libName}.js`
    },
    target: 'web',
    .... your shared options ...
  };

  return config;
}

module.exports = [
  getConfig('development'),
  getConfig('production'),
];

How to pass List from Controller to View in MVC 3

Passing data to view is simple as passing object to method. Take a look at Controller.View Method

protected internal ViewResult View(
    Object model
)

Something like this

//controller

List<MyObject> list = new List<MyObject>();

return View(list);


//view

@model List<MyObject>

// and property Model is type of List<MyObject>

@foreach(var item in Model)
{
    <span>@item.Name</span>
}

Can a local variable's memory be accessed outside its scope?

Pay attention to all warnings . Do not only solve errors.
GCC shows this Warning

warning: address of local variable 'a' returned

This is power of C++. You should care about memory. With the -Werror flag, this warning becames an error and now you have to debug it.

Executing a stored procedure within a stored procedure

Thats how it works stored procedures run in order, you don't need begin just something like

exec dbo.sp1
exec dbo.sp2

Insert content into iFrame

Wait, are you really needing to render it using javascript?

Be aware that in HTML5 there is srcdoc, which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)

See here [srcdoc]: https://www.w3schools.com/tags/att_iframe_srcdoc.asp

Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox mode.

See here [sandbox]: https://www.w3schools.com/tags/att_iframe_sandbox.asp

Mocking methods of local scope objects with Mockito

You can do this by creating a factory method in MyObject:

class MyObject {
    public static MyObject create() {
      return new MyObject();
    }
}

then mock that with PowerMock.

However, by mocking the methods of a local scope object, you are depending on that part of the implementation of the method staying the same. So you lose the ability to refactor that part of the method without breaking the test. In addition, if you are stubbing return values in the mock, then your unit test may pass, but the method may behave unexpectedly when using the real object.

In sum, you should probably not try to do this. Rather, letting the test drive your code (aka TDD), you would arrive at a solution like:

void method1(MyObject obj1) {
   obj1.method1();
}

passing in the dependency, which you can easily mock for the unit test.

What is __init__.py for?

__init__.py will treat the directory it is in as a loadable module.

For people who prefer reading code, I put Two-Bit Alchemist's comment here.

$ find /tmp/mydir/
/tmp/mydir/
/tmp/mydir//spam
/tmp/mydir//spam/__init__.py
/tmp/mydir//spam/module.py
$ cd ~
$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
>>> module.myfun(3)
9
>>> exit()
$ 
$ rm /tmp/mydir/spam/__init__.py*
$ 
$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named spam
>>> 

How to use the ConfigurationManager.AppSettings

\if what you have posted is exactly what you are using then your problem is a bit obvious. Now assuming in your web.config you have you connection string defined like this

 <add name="SiteSqlServer" connectionString="Data Source=(local);Initial Catalog=some_db;User ID=sa;Password=uvx8Pytec" providerName="System.Data.SqlClient" />

In your code you should use the value in the name attribute to refer to the connection string you want (you could actually define several connection strings to different databases), so you would have

 con.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;

How to view Plugin Manager in Notepad++

Latest version of Notepad++ got a new built-in plugin manager which works nicely.

How do I remove a key from a JavaScript object?

It's as easy as:

delete object.keyname;

or

delete object["keyname"];

Any way to exit bash script, but not quitting the terminal

I think that this happens because you are running it on source mode with the dot

. myscript.sh

You should run that in a subshell:

/full/path/to/script/myscript.sh

'source' http://ss64.com/bash/source.html

What is Ruby's double-colon `::`?

What good is scope (private, protected) if you can just use :: to expose anything?

In Ruby, everything is exposed and everything can be modified from anywhere else.

If you're worried about the fact that classes can be changed from outside the "class definition", then Ruby probably isn't for you.

On the other hand, if you're frustrated by Java's classes being locked down, then Ruby is probably what you're looking for.

How to rename a pane in tmux?

For those who want to easily rename their panes, this is what I have in my .tmux.conf

set -g default-command '                      \
function renamePane () {                      \
  read -p "Enter Pane Name: " pane_name;      \
  printf "\033]2;%s\033\\r:r" "${pane_name}"; \
};                                            \
export -f renamePane;                         \
bash -i'
set -g pane-border-status top
set -g pane-border-format "#{pane_index} #T #{pane_current_command}"
bind-key -T prefix R send-keys "renamePane" C-m

Panes are automatically named with their index, machine name and current command. To change the machine name you can run <C-b>R which will prompt you to enter a new name.

*Pane renaming only works when you are in a shell.

is there a function in lodash to replace matched item

Immutable, suitable for ReactJS:

Assume:

cosnt arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];

The updated item is the second and name is changed to Special Person:

const updatedItem = {id:2, name:"Special Person"};

Hint: the lodash has useful tools but now we have some of them on Ecmascript6+, so I just use map function that is existed on both of lodash and ecmascript6+:

const newArr = arr.map(item => item.id === 2 ? updatedItem : item);

How to download Google Play Services in an Android emulator?

The key is to select the target of your emulator to, for example: Google APIs (ver 18). If you select, for example, just Jellybean 18 (without API) you will not be able to test apps that require Google services such as map. Keep in mind that you must first download the Google API of your favorite version with the Android SDK Manager.

This is a good practice and it is far better than juggling with most workarounds.

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

getActivity() returns null in Fragment function

You can using onAttach or if you do not want to put onAttach everywhere then you can put a method that returns ApplicationContext on the main App class :

public class App {
    ...  
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
    }

    public static Context getContext() {
        return context;
    }
    ...
}

After that you can re-use it everywhere in all over your project, like this :

App.getContext().getString(id)

Please let me know if this does not work for you.

Importing json file in TypeScript

Enable "resolveJsonModule": true in tsconfig.json file and implement as below code, it's work for me:

const config = require('./config.json');

Can I have H2 autocreate a schema in an in-memory database?

Yes, H2 supports executing SQL statements when connecting. You could run a script, or just a statement or two:

String url = "jdbc:h2:mem:test;" + 
             "INIT=CREATE SCHEMA IF NOT EXISTS TEST"
String url = "jdbc:h2:mem:test;" + 
             "INIT=CREATE SCHEMA IF NOT EXISTS TEST\\;" + 
                  "SET SCHEMA TEST";
String url = "jdbc:h2:mem;" + 
             "INIT=RUNSCRIPT FROM '~/create.sql'\\;" + 
                  "RUNSCRIPT FROM '~/populate.sql'";

Please note the double backslash (\\) is only required within Java. The backslash(es) before ; within the INIT is required.

Handle JSON Decode Error when nothing returned

There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.

Thus, try the following:

try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except ValueError:  # includes simplejson.decoder.JSONDecodeError
    print 'Decoding JSON has failed'

EDIT: Since simplejson.decoder.JSONDecodeError actually inherits from ValueError (proof here), I simplified the catch statement by just using ValueError.

smooth scroll to top

I just customized BootPc Deutschland's answer

You can simply use

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $('body,html').animate({
            scrollTop: 0
        }, 800);
    $('#btn-go-to-top').click(function () {
        $('body,html').animate({
            scrollTop: 0
        }, 800);
        return false;
    });
}); 
</script>

this will help you to smoothly scroll to the top of the page.

and for styling

#btn-go-to-top {
opacity: .5;
width:4%;
height:8%;
display: none;
position: fixed;
bottom: 5%;
right: 3%;
z-index: 99;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 10px;
 border-radius: 50%;
}

#btn-go-to-top:hover {
opacity: 1;
}
.top {
transition: all 0.5s ease 0s;
-moz-transition: all 0.5s ease 0s;
-webkit-transition: all 0.5s ease 0s;
-o-transition: all 0.5s ease 0s;
}

this styling makes the button arrive at the bottom-right of the page.

and in your page you can add the button to go to top like this

<div id="btn-go-to-top" class="text-center top">
<img src="uploads/Arrow.png" style="margin: 7px;" width="50%" height="50%">
</div>

hope this help you.if you have any doubts you are always free to ask me

What is in your .vimrc?

I didn't realize how many of my 3200 .vimrc lines were just for my quirky needs and would be pretty uninspiring to list here. But maybe that's why Vim is so useful...

iab AlP ABCDEFGHIJKLMNOPQRSTUVWXYZ
iab MoN January February March April May June July August September October November December
iab MoO Jan Feb Mar Apr May Jun Jul Aug Sep Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
iab NuM 12345678901234567890123456789012345678901234567890123456789012345678901234567890 
iab RuL ----+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0

" Highlight every other line
map ,<Tab> :set hls<CR>/\\n.*\\n/<CR>

" This is for working across multiple xterms and/or gvims
" Transfer/read and write one block of text between vim sessions (capture whole line):
" Write
nmap ;w :. w! ~/.vimxfer<CR>
" Read
nmap ;r :r ~/.vimxfer<CR>
" Append 
nmap ;a :. w! >>~/.vimxfer<CR>

How to catch a click event on a button?

Just declare a method,e.g:if ur button id is button1 then,

button1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(Context, "Hello", Toast.LENGTH_SHORT).show();
        }
    });

If you want to make the imageview1 visible then in that method write:

imageview1.setVisibility(ImageView.VISIBLE);

Bigger Glyphicons

_x000D_
_x000D_
<button class="btn btn-default glyphicon glyphicon-plus fa-2x" type="button">_x000D_
</button>_x000D_
_x000D_
<!--fa-2x , fa-3x , fa-4x ... -->_x000D_
<button class="btn btn-default glyphicon glyphicon-plus fa-3x" type="button">_x000D_
</button>
_x000D_
_x000D_
_x000D_

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

SELECT st1.*
FROM some_table st1
inner join 
(
    SELECT relevant_field
    FROM some_table
    GROUP BY relevant_field
    HAVING COUNT(*) > 1
)st2 on st2.relevant_field = st1.relevant_field;

I've tried your query on one of my databases, and also tried it rewritten as a join to a sub-query.

This worked a lot faster, try it!

How to ping a server only once from within a batch file?

For bash (OSX) ping google.com -c 1 (incase search brought you here)

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

The percent sign means all ip's so localhost is superfluous ... There is no need of the second record with the localhost .

Actually there is, 'localhost' is special in mysql, it means a connection over a unix socket (or named pipes on windows I believe) as opposed to a TCP/IP socket. using % as the host does not include 'localhost'

MySQL user accounts have two components: a user name and a host name. The user name identifies the user, and the host name specifies what hosts that user can connect from. The user name and host name are combined to create a user account:

'<user_name>'@'<host_name>' You can specify a specific IP address or address range for host name, or use the percent character ("%") to enable that user to log in from any host.

Note that user accounts are defined by both the user name and the host name. For example, 'root'@'%' is a different user account than 'root'@'localhost'.

Git command to display HEAD commit id?

Use the command:

git rev-parse HEAD

For the short version:

git rev-parse --short HEAD

Reading/Writing a MS Word file in PHP

Reading binary Word documents would involve creating a parser according to the published file format specifications for the DOC format. I think this is no real feasible solution.

You could use the Microsoft Office XML formats for reading and writing Word files - this is compatible with the 2003 and 2007 version of Word. For reading you have to ensure that the Word documents are saved in the correct format (it's called Word 2003 XML-Document in Word 2007). For writing you just have to follow the openly available XML schema. I've never used this format for writing out Office documents from PHP, but I'm using it for reading in an Excel worksheet (naturally saved as XML-Spreadsheet 2003) and displaying its data on a web page. As the files are plainly XML data it's no problem to navigate within and figure out how to extract the data you need.

The other option - a Word 2007 only option (if the OpenXML file formats are not installed in your Word 2003) - would be to ressort to OpenXML. As databyss pointed out here the DOCX file format is just a ZIP archive with XML files included. There are a lot of resources on MSDN regarding the OpenXML file format, so you should be able to figure out how to read the data you want. Writing will be much more complicated I think - it just depends on how much time you'll invest.

Perhaps you can have a look at PHPExcel which is a library able to write to Excel 2007 files and read from Excel 2007 files using the OpenXML standard. You could get an idea of the work involved when trying to read and write OpenXML Word documents.

jquery : focus to div is not working

a <div> can be focused if it has a tabindex attribute. (the value can be set to -1)

For example:

$("#focus_point").attr("tabindex",-1).focus();

In addition, consider setting outline: none !important; so it displayed without a focus rectangle.

var element = $("#focus_point");
element.css('outline', 'none !important')
       .attr("tabindex", -1)
       .focus();

Can I animate absolute positioned element with CSS transition?

You forgot to define the default value for left so it doesn't know how to animate.

.test {
    left: 0;
    transition:left 1s linear;
}

See here: http://jsfiddle.net/shomz/yFy5n/5/

How to manually trigger click event in ReactJS?

Try this and let me know if it does not work on your end:

<input type="checkbox" name='agree' ref={input => this.inputElement = input}/>
<div onClick={() => this.inputElement.click()}>Click</div>

Clicking on the div should simulate a click on the input element

How can I make git show a list of the files that are being tracked?

The files managed by git are shown by git ls-files. Check out its manual page.

Get the Application Context In Fragment In Android?

In Kotlin we can get application context in fragment using this

requireActivity().application

Excel VBA, How to select rows based on data in a column?

The easiest way to do it is to use the End method, which is gives you the cell that you reach by pressing the end key and then a direction when you're on a cell (in this case B6). This won't give you what you expect if B6 or B7 is empty, though.

Dim start_cell As Range
Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Range(start_cell, start_cell.End(xlDown)).Copy Range("[Workbook2.xlsx]Sheet1!A2")

If you can't use End, then you would have to use a loop.

Dim start_cell As Range, end_cell As Range

Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Set end_cell = start_cell

Do Until IsEmpty(end_cell.Offset(1, 0))
    Set end_cell = end_cell.Offset(1, 0)
Loop

Range(start_cell, end_cell).Copy Range("[Workbook2.xlsx]Sheet1!A2")

how to use substr() function in jquery?

Extract characters from a string:

var str = "Hello world!";
var res = str.substring(1,4);

The result of res will be:

ell

http://www.w3schools.com/jsref/jsref_substring.asp

$('.dep_buttons').mouseover(function(){
    $(this).text().substring(0,25);
    if($(this).text().length > 30) {
        $(this).stop().animate({height:"150px"},150);
    }
    $(".dep_buttons").mouseout(function(){
        $(this).stop().animate({height:"40px"},150);
    });
});

c++ and opencv get and set pixel color to Mat

I would not use .at for performance reasons.

Define a struct:

//#pragma pack(push, 2) //not useful (see comments below)
struct RGB {
    uchar blue;
    uchar green;
    uchar red;  };

And then use it like this on your cv::Mat image:

RGB& rgb = image.ptr<RGB>(y)[x];

image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y

How to preventDefault on anchor tags?

if still relevant:

<a ng-click="unselect($event)" />

...

scope.unselect = function( event ) {
 event.preventDefault();
 event.stopPropagation();
}

...

Javascript getElementsByName.value not working

Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.

_x000D_
_x000D_
function myFunction() {_x000D_
  var selchbox = [];_x000D_
  var inputfields = document.getElementsByName("myCheck");_x000D_
  var ar_inputflds = inputfields.length;_x000D_
_x000D_
  for (var i = 0; i < ar_inputflds; i++) {_x000D_
    if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
      selchbox.push(inputfields[i].value);_x000D_
  }_x000D_
  return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
  var selchb = myFunction();_x000D_
  console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
_x000D_
_x000D_

Adding Git-Bash to the new Windows Terminal

Adding "%PROGRAMFILES%\\Git\\bin\\bash.exe -l -i" doesn't work for me. Because of space symbol (which is separator in cmd) in %PROGRAMFILES% terminal executes command "C:\Program" instead of "C:\Program Files\Git\bin\bash.exe -l -i". The solution should be something like adding quotation marks in json file, but I didn't figure out how. The only solution is to add "C:\Program Files\Git\bin" to %PATH% and write "commandline": "bash.exe" in profiles.json

Rounding a double to turn it into an int (java)

public static int round(double d) {
    if (d > 0) {
        return (int) (d + 0.5);
    } else {
        return (int) (d - 0.5);
    }
}

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

SQLite supports replacing a row if it already exists:

INSERT OR REPLACE INTO [...blah...]

You can shorten this to

REPLACE INTO [...blah...]

This shortcut was added to be compatible with the MySQL REPLACE INTO expression.

Split (explode) pandas dataframe string entry to separate rows

Another solution that uses python copy package

import copy
new_observations = list()
def pandas_explode(df, column_to_explode):
    new_observations = list()
    for row in df.to_dict(orient='records'):
        explode_values = row[column_to_explode]
        del row[column_to_explode]
        if type(explode_values) is list or type(explode_values) is tuple:
            for explode_value in explode_values:
                new_observation = copy.deepcopy(row)
                new_observation[column_to_explode] = explode_value
                new_observations.append(new_observation) 
        else:
            new_observation = copy.deepcopy(row)
            new_observation[column_to_explode] = explode_values
            new_observations.append(new_observation) 
    return_df = pd.DataFrame(new_observations)
    return return_df

df = pandas_explode(df, column_name)

Python: PIP install path, what is the correct location for this and other addons?

Modules go in site-packages and executables go in your system's executable path. For your environment, this path is /usr/local/bin/.

To avoid having to deal with this, simply use easy_install, distribute or pip. These tools know which files need to go where.

Java 8 stream map to list of keys sorted by values

You have to sort with a custom comparator based on the value of the entry. Then select all the keys before collecting

countByType.entrySet()
           .stream()
           .sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue())) // custom Comparator
           .map(e -> e.getKey())
           .collect(Collectors.toList());

How to send email to multiple recipients with addresses stored in Excel?

Both answers are correct. If you user .TO -method then the semicolumn is OK - but not for the addrecipients-method. There you need to split, e.g. :

                Dim Splitter() As String
                Splitter = Split(AddrMail, ";")
                For Each Dest In Splitter
                    .Recipients.Add (Trim(Dest))
                Next

In Python, how do I determine if an object is iterable?

The isiterable func at the following code returns True if object is iterable. if it's not iterable returns False

def isiterable(object_):
    return hasattr(type(object_), "__iter__")

example

fruits = ("apple", "banana", "peach")
isiterable(fruits) # returns True

num = 345
isiterable(num) # returns False

isiterable(str) # returns False because str type is type class and it's not iterable.

hello = "hello dude !"
isiterable(hello) # returns True because as you know string objects are iterable

How to fix ReferenceError: primordials is not defined in node

I have tried a lot of suggestions to fix this problem for an existing project on my Windows 10 machine and ended up following these steps to fix it;

  • Uninstall Node.js from "Add or remove programs". Fire up a new Command prompt and type gulp -v and then node -v to check that it has been uninstalled completely.
  • Download and install Node.js v10.16.0 - not the latest as latest node & gulp combination is causing the problem as far as I see. During installation I didn't change the installation path which I normally do(C:\Program Files\nodejs).
  • Open up a new Command prompt, go to your project's directory where you have got your gulpfile.js and start gulp as shown in the image.

Please note sometimes when I switch between git branches I might need to close my Visual Studio and run it as Admin again in order to see this solution working again.

As far as I see this problem started to happen after I installed the latest recommended version(12.18.4) of Node.js for a new project and I only realised this when some FE changes weren't reflected on the existing web project.

enter image description here

Laravel Request::all() Should Not Be Called Statically

The error message is due to the call not going through the Request facade.

Change

use Illuminate\Http\Request;

To

use Request;

and it should start working.

In the config/app.php file, you can find a list of the class aliases. There, you will see that the base class Request has been aliased to the Illuminate\Support\Facades\Request class. Because of this, to use the Request facade in a namespaced file, you need to specify to use the base class: use Request;.

Edit

Since this question seems to get some traffic, I wanted to update the answer a little bit since Laravel 5 was officially released.

While the above is still technically correct and will work, the use Illuminate\Http\Request; statement is included in the new Controller template to help push developers in the direction of using dependency injection versus relying on the Facade.

When injecting the Request object into the constructor (or methods, as available in Laravel 5), it is the Illuminate\Http\Request object that should be injected, and not the Request facade.

So, instead of changing the Controller template to work with the Request facade, it is better recommended to work with the given Controller template and move towards using dependency injection (via constructor or methods).

Example via method

<?php namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class UserController extends Controller {

    /**
     * Store a newly created resource in storage.
     *
     * @param  Illuminate\Http\Request  $request
     * @return Response
     */
    public function store(Request $request) {
        $name = $request->input('name');
    }
}

Example via constructor

<?php namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class UserController extends Controller {

    protected $request;

    public function __construct(Request $request) {
        $this->request = $request;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store() {
        $name = $this->request->input('name');
    }
}

Slide div left/right using jQuery

The easiest way to do so is using jQuery and animate.css animation library.

Javascript

/* --- Show DIV --- */
$( '.example' ).removeClass( 'fadeOutRight' ).show().addClass( 'fadeInRight' );

/* --- Hide DIV --- */
$( '.example' ).removeClass( 'fadeInRight' ).addClass( 'fadeOutRight' );


HTML

<div class="example">Some text over here.</div>


Easy enough to implement. Just don't forget to include the animate.css file in the header :)

How to get selected value from Dropdown list in JavaScript

I would say change var sv = sel.options[sel.selectedIndex].value; to var sv = sel.options[sel.selectedIndex].text;

It worked for me. Directing you to where I found my solution Getting the selected value dropdown jstl

pow (x,y) in Java

In Java x ^ y is an XOR operation.

How can I scale an image in a CSS sprite

It took me a while to create a solution to this problem I was happy with:

Problem:

  • An SVG sprite of icons - say 80px x 3200px

  • We want to scale each use of them in content selectors (:before/:after) in various places over various sizes without re-defining the co-ords of each sprite based on the size used.

So this solution allows you to use the same sprite co-ords in a <button> as a <menuitem> whilst still scaling it.

[data-command]::before {
    content: '';
    position: absolute;
    background-image: url("images/sprite.svgz");
    background-repeat: no-repeat;
    background-size: cover;
}

button[data-command]::before {
  width: 32px;
  height: 32px;
}

menuitem[data-command]::before {
  width: 24px;
  height: 24px;
}

[data-command="cancel"]::before {
  background-position: 0% 35%;
}

[data-command="logoff"]::before {
  background-position: 0% 37.5%;
}

By using percentages (to 2 decimal places) in background-position rather than background-size as suggested by others here, you can scale the same icon declaration to any size, without needing to redeclare it.

The position-y percentage is the original sprite height/icon height as a % - in our case here 80px*100/3200px == each sprite is represented by a y-position of 2.5%.

If you have hover/mouseover states you can double the width of the sprite and specify in the position-x coordinate.

The disadvantage of this approach is that adding more icons at a later date will change the sprite height and so y-position %, but if you don't do that then your sprite co-ordinates will need change for each scaled resolution you require.

ASP.NET MVC Razor pass model to layout

Why dont you just add a new Partial View with i's own specific controller passing the required model to the partial view and finally Render the mentioned partial view on your Layout.cshtml using RenderPartial or RenderAction ?

I use this method for showing the logged in user's info like name , profile picture and etc.

In Mongoose, how do I sort by date? (node.js)

ES6 solution with Koa.

  async recent() {
    data = await ReadSchema.find({}, { sort: 'created_at' });
    ctx.body = data;
  }

How can I list ALL DNS records?

  1. A zone transfer is the only way to be sure you have all the subdomain records. If the DNS is correctly configured you should not normally be able to perform an external zone transfer.

  2. The scans.io project has a database of DNS records that can be downloaded and searched for subdomains. This requires downloading the 87GB of DNS data, alternatively you can try the online search of the data at https://hackertarget.com/find-dns-host-records/

How to use mod operator in bash?

You must put your mathematical expressions inside $(( )).

One-liner:

for i in {1..600}; do wget http://example.com/search/link$(($i % 5)); done;

Multiple lines:

for i in {1..600}; do
    wget http://example.com/search/link$(($i % 5))
done

Why is json_encode adding backslashes?

Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).

json_encode($array,JSON_UNESCAPED_SLASHES);

importing pyspark in python shell

dont run your py file as: python filename.py instead use: spark-submit filename.py

How to pass a URI to an intent?

In Intent, you can directly put Uri. You don't need to convert the Uri to string and convert back again to Uri.

Look at this simple approach.

// put uri to intent 
intent.setData(imageUri);

And to get Uri back from intent:

// Get Uri from Intent
Uri imageUri=getIntent().getData();

A warning - comparison between signed and unsigned integer expressions

The important difference between signed and unsigned ints is the interpretation of the last bit. The last bit in signed types represent the sign of the number, meaning: e.g:

0001 is 1 signed and unsigned 1001 is -1 signed and 9 unsigned

(I avoided the whole complement issue for clarity of explanation! This is not exactly how ints are represented in memory!)

You can imagine that it makes a difference to know if you compare with -1 or with +9. In many cases, programmers are just too lazy to declare counting ints as unsigned (bloating the for loop head f.i.) It is usually not an issue because with ints you have to count to 2^31 until your sign bit bites you. That's why it is only a warning. Because we are too lazy to write 'unsigned' instead of 'int'.

What is console.log in jQuery?

jQuery and console.log are unrelated entities, although useful when used together.

If you use a browser's built-in dev tools, console.log will log information about the object being passed to the log function.

If the console is not active, logging will not work, and may break your script. Be certain to check that the console exists before logging:

if (window.console) console.log('foo');

The shortcut form of this might be seen instead:

window.console&&console.log('foo');

There are other useful debugging functions as well, such as debug, dir and error. Firebug's wiki lists the available functions in the console api.

ngModel cannot be used to register form controls with a parent formGroup directive

when you write formcontrolname Angular 2 do not accept. You have to write formControlName . it is about uppercase second words.

<input type="number" [(ngModel)]="myObject.name" formcontrolname="nameFormControl"/>

if the error still conitnue try to set form control for all of object(myObject) field.

between start <form> </form> for example: <form [formGroup]="myForm" (ngSubmit)="submitForm(myForm.value)"> set form control for all input field </form>.

How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

On linux, /etc/apache2/mods-enabled/php5.conf dans php5.load exists. If not, enables this modules (may require to sudo apt-get install libapache2-mod-php5).

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

You can use wc -l to figure out the total # of lines.

You can then combine head and tail to get at the range you want. Let's assume the log is 40,000 lines, you want the last 1562 lines, then of those you want the first 838. So:

tail -1562 MyHugeLogFile.log | head -838 | ....

Or there's probably an easier way using sed or awk.

Twitter bootstrap modal-backdrop doesn't disappear

Try this

$('#something_clickable').on('click', function () {
  $("#my_modal").modal("hide");
  $("body").removeClass("modal-open");
  $('.modal-backdrop').remove();
 });

It works fine for me.

Convert string to date in Swift

Swift 5. To see IF A DATE HAS PASSED:

let expiryDate = "2020-01-10" // Jan 10 2020

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

if Date() < dateFormatter.date(from: expiryDate) ?? Date() {
    print("Not Yet expiryDate")
} else {
    print("expiryDate has passed")
}

Change onclick action with a Javascript function

For anyone, like me, trying to set a query string on the action and wondering why it's not working-

You cannot set a query string for a GET form submission, but I have found you can for a POST.

For a GET submission you must set the values in hidden inputs e.g.

an action of: "/handleformsubmission?foo=bar" would have be added as the hidden field like: <input type="hidden" name="foo" value="bar" />

This can be done add dynamically in JavaScript as (where clickedButton is the submitted button that was clicked:

var form = clickedButton.form;
var hidden = document.createElement("input");
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "foo");
hidden.setAttribute("value", "bar");
form.appendChild(hidden);

See this question for more info submitting a GET form with query string params and hidden params disappear

Can we overload the main method in Java?

Yes According to my point of view, we are able to overload the main method but method overloading that's it. For Example

class main_overload {
    public static void main(int a) {
        System.out.println(a);
    }
    public static void main(String args[]) {
        System.out.println("That's My Main Function");
        main(100);
    }
}

In This Double Back slash Step, I am just calling the main method....

How can I get zoom functionality for images?

I just integrated Robert Foss's TouchImageView: it worked perfectly out of the box! Thanks!

I just modified a bit the code so I could be able to instantiate it from my layout.xml.

Just add two constructors

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

public TouchImageView(Context context) {
    super(context);
    init(context);
}

and transform the old constructor into an init method:

private void init(Context context){
    //...old code ofconstructor of Robert Moss's code
}

C# Get a control's position on a form

In my testing, both Hans Kesting's and Fredrik Mörk's solutions gave the same answer. But:

I found an interesting discrepancy in the answer using the methods of Raj More and Hans Kesting, and thought I'd share. Thanks to both though for their help; I can't believe such a method is not built into the framework.

Please note that Raj didn't write code and therefore my implementation could be different than he meant.

The difference I found was that the method from Raj More would often be two pixels greater (in both X and Y) than the method from Hans Kesting. I have not yet determined why this occurs. I'm pretty sure it has something to do with the fact that there seems to be a two-pixel border around the contents of a Windows form (as in, inside the form's outermost borders). In my testing, which was certainly not exhaustive to any extent, I've only come across it on controls that were nested. However, not all nested controls exhibit it. For example, I have a TextBox inside a GroupBox which exhibits the discrepancy, but a Button inside the same GroupBox does not. I cannot explain why.

Note that when the answers are equivalent, they consider the point (0, 0) to be inside the content border I mentioned above. Therefore I believe I'll consider the solutions from Hans Kesting and Fredrik Mörk to be correct but don't think I'll trust the solution I've implemented of Raj More's.

I also wondered exactly what code Raj More would have written, since he gave an idea but didn't provide code. I didn't fully understand the PointToScreen() method until I read this post: http://social.msdn.microsoft.com/Forums/en-US/netfxcompact/thread/aa91d4d8-e106-48d1-8e8a-59579e14f495

Here's my method for testing. Note that 'Method 1' mentioned in the comments is slightly different than Hans Kesting's.

private Point GetLocationRelativeToForm(Control c)
{
  // Method 1: walk up the control tree
  Point controlLocationRelativeToForm1 = new Point();
  Control currentControl = c;
  while (currentControl.Parent != null)
  {
    controlLocationRelativeToForm1.Offset(currentControl.Left, currentControl.Top);
    currentControl = currentControl.Parent;
  }

  // Method 2: determine absolute position on screen of control and form, and calculate difference
  Point controlScreenPoint = c.PointToScreen(Point.Empty);
  Point formScreenPoint = PointToScreen(Point.Empty);
  Point controlLocationRelativeToForm2 = controlScreenPoint - new Size(formScreenPoint);

  // Method 3: combine PointToScreen() and PointToClient()
  Point locationOnForm = c.FindForm().PointToClient(c.Parent.PointToScreen(c.Location));

  // Theoretically they should be the same
  Debug.Assert(controlLocationRelativeToForm1 == controlLocationRelativeToForm2);
  Debug.Assert(locationOnForm == controlLocationRelativeToForm1);
  Debug.Assert(locationOnForm == controlLocationRelativeToForm2);

  return controlLocationRelativeToForm1;
}

How to merge remote master to local branch

git rebase didn't seem to work for me. After git rebase, when I try to push changes to my local branch, I kept getting an error ("hint: Updates were rejected because the tip of your current branch is behind its remote counterpart. Integrate the remote changes (e.g. 'git pull ...') before pushing again.") even after git pull. What finally worked for me was git merge.

git checkout <local_branch>
git merge <master> 

If you are a beginner like me, here is a good article on git merge vs git rebase. https://www.atlassian.com/git/tutorials/merging-vs-rebasing

JSON find in JavaScript

If you are doing this in more than one place in your application it would make sense to use a client-side JSON database because creating custom search functions is messy and less maintainable than the alternative.

Check out ForerunnerDB which provides you with a very powerful client-side JSON database system and includes a very simple query language to help you do exactly what you are looking for:

// Create a new instance of ForerunnerDB and then ask for a database
var fdb = new ForerunnerDB(),
    db = fdb.db('myTestDatabase'),
    coll;

// Create our new collection (like a MySQL table) and change the default
// primary key from "_id" to "id"
coll = db.collection('myCollection', {primaryKey: 'id'});

// Insert our records into the collection
coll.insert([
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]);

// Search the collection for the string "my nam" as a case insensitive
// regular expression - this search will match all records because every
// name field has the text "my Nam" in it
var searchResultArray = coll.find({
    name: /my nam/i
});

console.log(searchResultArray);

/* Outputs
[
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]
*/

Disclaimer: I am the developer of ForerunnerDB.

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

if anybody unable to update windows online, I suggest you go to http://download.wsusoffline.net/ and download Most recent version.

Then install update generator -> select your operating system. and hit START, just wait few minutes let him download updates and complete all it's process. hope this help.

Image of Offline update generator

jQuery check if attr = value

Just remove the .val(). Like:

if ( $('html').attr('lang') == 'fr-FR' ) {
    // do this
} else {
    // do that
}

How to get the clicked link's href with jquery?

You're looking for $(this).attr("href");

How can I confirm a database is Oracle & what version it is using SQL?

You can either use

SELECT * FROM v$version;

or

SET SERVEROUTPUT ON
EXEC dbms_output.put_line( dbms_db_version.version );

if you don't want to parse the output of v$version.

Laravel - Return json along with http status code

There are multiple ways

return \Response::json(['hello' => $value], STATUS_CODE);

return response()->json(['hello' => $value], STATUS_CODE);

where STATUS_CODE is your HTTP status code you want to send. Both are identical.

if you are using Eloquent model, then simple return will also be auto converted in JSON by default like,

return User::all();

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

How to save a plot into a PDF file without a large margin around

The function export_fig on the MATLAB file exchange will crop the whitespace around an output PDF/EPS file by default when it exports a figure.

How can I remove 3 characters at the end of a string in php?

<?php echo substr("abcabcabc", 0, -3); ?>

string in namespace std does not name a type

You need to

#include <string>

<iostream> declares cout, cin, not string.

Cannot find module '@angular/compiler'

Try to delete that "angular/cli": "1.0.0-beta.28.3", in the devDependencies it is useless , and add instead of it "@angular/compiler-cli": "^2.3.1", (since it is the current version, else add it by npm i --save-dev @angular/compiler-cli ), then in your root app folder run those commands:

  1. rm -r node_modules (or delete your node_modules folder manually)
  2. npm cache clean (npm > v5 add --force so: npm cache clean --force)
  3. npm install

What are intent-filters in Android?

The Activity which you want it to be the very first screen if your app is opened, then mention it as LAUNCHER in the intent category and remaining activities mention Default in intent category.

For example :- There is 2 activity A and B
The activity A is LAUNCHER so make it as LAUNCHER in the intent Category and B is child for Activity A so make it as DEFAULT.

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".ListAllActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".AddNewActivity" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</application>

Test if element is present using Selenium WebDriver?

Try this: Call this method and pass 3 arguments:

  1. WebDriver variable. // assuming driver_variable as driver.
  2. The element which you are going to check. Should provide from By method. // ex: By.id("id")
  3. Time limit in seconds.

Example: waitForElementPresent(driver, By.id("id"), 10 );

public static WebElement waitForElementPresent(WebDriver driver, final By by, int timeOutInSeconds) {

        WebElement element; 

        try{
            driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //nullify implicitlyWait() 

            WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds); 
            element = wait.until(ExpectedConditions.presenceOfElementLocated(by));

            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //reset implicitlyWait
            return element; //return the element
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return null; 
    }

MySQL: how to get the difference between two timestamps in seconds

UNIX_TIMESTAMP(ts1) - UNIX_TIMESTAMP(ts2)

If you want an unsigned difference, add an ABS() around the expression.

Alternatively, you can use TIMEDIFF(ts1, ts2) and then convert the time result to seconds with TIME_TO_SEC().

How to increase application heap size in Eclipse?

Open eclipse.ini

Search for -Xmx512m or maybe more size it is.

Just change it to a required size such as I changed it to -Xmx1024m

What does "implements" do on a class?

An interface can be thought of as just a list of method definitions (without any body). If a class wants to implement and interface, it is entering into a contract, saying that it will provide an implementation for all of the methods listed in the interface. For more information, see http://download.oracle.com/javase/tutorial/java/concepts/

How to edit log message already committed in Subversion?

The Subversion FAQ covers this, but uses a bunch of confusing undefined terms like REPOS_PATH without giving any actual examples.

It might take a few tries to get it to work, so save your updated commit message in a file. Unlike with svn-commit.tmp files, Subversion won’t preserve your typing if there’s a problem.

In your working directory, run

svn propedit -r N --revprop svn:log

to edit the commit message. If that works, great! But it probably won’t, because the svn:log revision property is unversioned and Subversion by default will stop you from overwriting it, either with the hook script pre-revprop-change, or an error message that you don’t have such a hook.

To change the hooks, you need access to the filesystem on which the repository is hosted. svn info will tell you the Repository Root. Suppose it’s ~/svnrepo.

  1. cd to ~/svnrepo/hooks
  2. Is there a pre-revprop-change or pre-revprop-change.bat script? If so, temporarily comment out the part of it that aborts if you try to change svn:log.
  3. Otherwise, on Windows, create a blank file called pre-revprop-change.bat. Here’s one way to do that:

    copy con pre-revprop-change.bat
    ^Z
    
  4. Otherwise, on Unix, run

    echo '#!/bin/sh' > pre-revprop-change
    chmod +x pre-revprop-change
    
  5. In the working copy, run svn propedit -r N --revprop svn:log again

  6. Undo your changes to ~/svnrepo/hooks/svn-revprop-change(.bat)

matching query does not exist Error in Django

As mentioned in Django docs, when get method finds no entry or finds multiple entries, it raises an exception, this is the expected behavior:

get() raises MultipleObjectsReturned if more than one object was found. The MultipleObjectsReturned exception is an attribute of the model class.

get() raises a DoesNotExist exception if an object wasn’t found for the given parameters. This exception is an attribute of the model class.

Using exceptions is a way to handle this problem, but I actually don't like the ugly try-except block. An alternative solution, and cleaner to me, is to use the combination of filter + first.

user = UniversityDetails.objects.filter(email=email).first()

When you do .first() to an empty queryset it returns None. This way you can have the same effect in a single line.

The only difference between catching the exception and using this method occurs when you have multiple entries, the former will raise an exception while the latter will set the first element, but as you are using get I may assume we won't fall on this situation.

Note that first method was added on Django 1.6.

Setting default permissions for newly created files and sub-directories under a directory in Linux?

It's ugly, but you can use the setfacl command to achieve exactly what you want.

On a Solaris machine, I have a file that contains the acls for users and groups. Unfortunately, you have to list all of the users (at least I couldn't find a way to make this work otherwise):

user::rwx
user:user_a:rwx
user:user_b:rwx
...
group::rwx
mask:rwx
other:r-x
default:user:user_a:rwx
default:user:user_b:rwx
....
default:group::rwx
default:user::rwx
default:mask:rwx
default:other:r-x

Name the file acl.lst and fill in your real user names instead of user_X.

You can now set those acls on your directory by issuing the following command:

setfacl -f acl.lst /your/dir/here

How do I add a new column to a Spark DataFrame (using PySpark)?

There are multiple ways we can add a new column in pySpark.

Let's first create a simple DataFrame.

date = [27, 28, 29, None, 30, 31]
df = spark.createDataFrame(date, IntegerType())

Now let's try to double the column value and store it in a new column. PFB few different approaches to achieve the same.

# Approach - 1 : using withColumn function
df.withColumn("double", df.value * 2).show()

# Approach - 2 : using select with alias function.
df.select("*", (df.value * 2).alias("double")).show()

# Approach - 3 : using selectExpr function with as clause.
df.selectExpr("*", "value * 2 as double").show()

# Approach - 4 : Using as clause in SQL statement.
df.createTempView("temp")
spark.sql("select *, value * 2 as double from temp").show()

For more examples and explanation on spark DataFrame functions, you can visit my blog.

I hope this helps.

What are callee and caller saved registers?

Callee vs caller saved is a convention for who is responsible for saving and restoring the value in a register across a call. ALL registers are "global" in that any code anywhere can see (or modify) a register and those modifications will be seen by any later code anywhere. The point of register saving conventions is that code is not supposed to modify certain registers, as other code assumes that the value is not modified.

In your example code, NONE of the registers are callee save, as it makes no attempt to save or restore the register values. However, it would seem to not be an entire procedure, as it contains a branch to an undefined label (l$loop). So it might be a fragment of code from the middle of a procedure that treats some registers as callee save; you're just missing the save/restore instructions.

Python Requests and persistent sessions

Save only required cookies and reuse them.

import os
import pickle
from urllib.parse import urljoin, urlparse

login = '[email protected]'
password = 'secret'
# Assuming two cookies are used for persistent login.
# (Find it by tracing the login process)
persistentCookieNames = ['sessionId', 'profileId']
URL = 'http://example.com'
urlData = urlparse(URL)
cookieFile = urlData.netloc + '.cookie'
signinUrl = urljoin(URL, "/signin")
with requests.Session() as session:
    try:
        with open(cookieFile, 'rb') as f:
            print("Loading cookies...")
            session.cookies.update(pickle.load(f))
    except Exception:
        # If could not load cookies from file, get the new ones by login in
        print("Login in...")
        post = session.post(
            signinUrl,
            data={
                'email': login,
                'password': password,
            }
        )
        try:
            with open(cookieFile, 'wb') as f:
                jar = requests.cookies.RequestsCookieJar()
                for cookie in session.cookies:
                    if cookie.name in persistentCookieNames:
                        jar.set_cookie(cookie)
                pickle.dump(jar, f)
        except Exception as e:
            os.remove(cookieFile)
            raise(e)
    MyPage = urljoin(URL, "/mypage")
    page = session.get(MyPage)

SQL Server Profiler - How to filter trace to only display events from one database?

In SQL 2005, you first need to show the Database Name column in your trace. The easiest thing to do is to pick the Tuning template, which has that column added already.

Assuming you have the Tuning template selected, to filter:

  • Click the "Events Selection" tab
  • Click the "Column Filters" button
  • Check Show all Columns (Right Side Down)
  • Select "DatabaseName", click the plus next to Like in the right-hand pane, and type your database name.

I always save the trace to a table too so I can do LIKE queries on the trace data after the fact.

What is NODE_ENV and how to use it in Express?

Typically, you'd use the NODE_ENV variable to take special actions when you develop, test and debug your code. For example to produce detailed logging and debug output which you don't want in production. Express itself behaves differently depending on whether NODE_ENV is set to production or not. You can see this if you put these lines in an Express app, and then make a HTTP GET request to /error:

app.get('/error', function(req, res) {
  if ('production' !== app.get('env')) {
    console.log("Forcing an error!");
  }
  throw new Error('TestError');
});

app.use(function (req, res, next) {
  res.status(501).send("Error!")
})

Note that the latter app.use() must be last, after all other method handlers!

If you set NODE_ENV to production before you start your server, and then send a GET /error request to it, you should not see the text Forcing an error! in the console, and the response should not contain a stack trace in the HTML body (which origins from Express). If, instead, you set NODE_ENV to something else before starting your server, the opposite should happen.

In Linux, set the environment variable NODE_ENV like this:

export NODE_ENV='value'

Passing arguments to JavaScript function from code-behind

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call java script function on Code behind</title>
    <script  type="text/javascript">
    function abc()
    {
        var a=20;
        var b=30;
        alert("you enter"+a+":"+b);
    }
    </script>
</head>

cs code

protected void Page_Load(object sender, EventArgs e)
{
    TextBox2.Attributes.Add("onkeypress", "return abc();");
}

try this

Java escape JSON String?

If you want to simply escape a string, not an object or array, use this:

String escaped = JSONObject.valueToString(" Quotes \" ' ' \" ");

http://www.json.org/javadoc/org/json/JSONObject.html#valueToString(java.lang.Object)

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

Erik, You can just kill all the other node processes by

pkill -f node

and then restart your server again. It'll work just fine then.

Determine if map contains a value for a key?

You can create your getValue function with the following code:

bool getValue(const std::map<int, Bar>& input, int key, Bar& out)
{
   std::map<int, Bar>::iterator foundIter = input.find(key);
   if (foundIter != input.end())
   {
      out = foundIter->second;
      return true;
   }
   return false;
}

Finding the max value of an attribute in an array of objects

I'd like to explain the terse accepted answer step-by-step:

_x000D_
_x000D_
var objects = [{ x: 3 }, { x: 1 }, { x: 2 }];_x000D_
_x000D_
// array.map lets you extract an array of attribute values_x000D_
var xValues = objects.map(function(o) { return o.x; });_x000D_
// es6_x000D_
xValues = Array.from(objects, o => o.x);_x000D_
_x000D_
// function.apply lets you expand an array argument as individual arguments_x000D_
// So the following is equivalent to Math.max(3, 1, 2)_x000D_
// The first argument is "this" but since Math.max doesn't need it, null is fine_x000D_
var xMax = Math.max.apply(null, xValues);_x000D_
// es6_x000D_
xMax = Math.max(...xValues);_x000D_
_x000D_
// Finally, to find the object that has the maximum x value (note that result is array):_x000D_
var maxXObjects = objects.filter(function(o) { return o.x === xMax; });_x000D_
_x000D_
// Altogether_x000D_
xMax = Math.max.apply(null, objects.map(function(o) { return o.x; }));_x000D_
var maxXObject = objects.filter(function(o) { return o.x === xMax; })[0];_x000D_
// es6_x000D_
xMax = Math.max(...Array.from(objects, o => o.x));_x000D_
maxXObject = objects.find(o => o.x === xMax);_x000D_
_x000D_
_x000D_
document.write('<p>objects: ' + JSON.stringify(objects) + '</p>');_x000D_
document.write('<p>xValues: ' + JSON.stringify(xValues) + '</p>');_x000D_
document.write('<p>xMax: ' + JSON.stringify(xMax) + '</p>');_x000D_
document.write('<p>maxXObjects: ' + JSON.stringify(maxXObjects) + '</p>');_x000D_
document.write('<p>maxXObject: ' + JSON.stringify(maxXObject) + '</p>');
_x000D_
_x000D_
_x000D_

Further information:

Javascript equivalent of php's strtotime()?

Yes, it is. And it is supported in all major browser:

var ts = Date.parse("date string");

The only difference is that this function returns milliseconds instead of seconds, so you need to divide the result by 1000.

Check what valid formats can JavaScript parse.

How to sort an STL vector?

Overload less than operator, then sort. This is an example I found off the web...

class MyData
{
public:
  int m_iData;
  string m_strSomeOtherData;
  bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; }
};

std::sort(myvector.begin(), myvector.end());

Source: here

Is there a kind of Firebug or JavaScript console debug for Android?

If you're using Cordova 3.3 or higher and your device is running Android 4.4 or higher you can use 'Remote Debugging on Android with Chrome'. Full instructions are here:

https://developer.chrome.com/devtools/docs/remote-debugging

In summary:

  • Plug the device into your desktop computer using a USB cable
  • Enable USB debugging on your device (on my device this is under Settings > More > Developer options > USB debugging)

Or, if you're using Cordova 3.3+ and don't have a physical device with 4.4, you can use an emulator that uses Android 4.4+ to run the application through the emulator, on your desktop computer.

  • Run your Cordova application on the device or emulator
  • In Chrome on your desktop computer, enter chrome://inspect/#devices in the address bar
  • Your device/emulator will be displayed along with any other recognised devices that are connected to your computer, and under your device there will be details of the Cordova 'WebView' (basically your Cordova app), which is running on the device/emulator (the way Cordova works is that it basically creates a 'browser' window on your device/emulator, within which there is a 'WebView' which is your running HTML/JavaScript app)
  • Click the 'inspect' link under the 'WebView' section where you see your device/emulator listed. This brings up the Chrome developer tools that now allow you to debug your application.
  • Select the 'sources' tab of the Chrome developer tools to view JavaScript that your Cordova app on the device/emulator is currently running. You can add breakpoints in the JavaScript that allow you to debug your code.
  • Also, you can use the 'console' tab to view any errors (which will be shown in red), or at the bottom of the console you'll see a '>' prompt. Here you can type in any variables or objects (e.g. DOM objects) that you want to inspect the current value of, and the value will be displayed.

What are Makefile.am and Makefile.in?

DEVELOPER runs autoconf and automake:

  1. autoconf -- creates shippable configure script
    (which the installer will later run to make the Makefile)
  1. automake - creates shippable Makefile.in data file
    (which configure will later read to make the Makefile)

INSTALLER runs configure, make and sudo make install:

./configure       # Creates  Makefile        (from     Makefile.in).  
make              # Creates  the application (from the Makefile just created).  

sudo make install # Installs the application 
                  #   Often, by default its files are installed into /usr/local


INPUT/OUTPUT MAP

Notation below is roughly: inputs --> programs --> outputs

DEVELOPER runs these:

configure.ac -> autoconf -> configure (script) --- (*.ac = autoconf)
configure.in --> autoconf -> configure (script) --- (configure.in depreciated. Use configure.ac)

Makefile.am -> automake -> Makefile.in ----------- (*.am = automake)

INSTALLER runs these:

Makefile.in -> configure -> Makefile (*.in = input file)

Makefile -> make ----------> (puts new software in your downloads or temporary directory)
Makefile -> make install -> (puts new software in system directories)


"autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. These scripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for a package from a template file that lists the operating system features that the package can use, in the form of M4 macro calls."

"automake is a tool for automatically generating Makefile.in files compliant with the GNU Coding Standards. Automake requires the use of Autoconf."

Manuals:

Free online tutorials:


Example:

The main configure.ac used to build LibreOffice is over 12k lines of code, (but there are also 57 other configure.ac files in subfolders.)

From this my generated configure is over 41k lines of code.

And while the Makefile.in and Makefile are both only 493 lines of code. (But, there are also 768 more Makefile.in's in subfolders.)

Maven with Eclipse Juno

From Eclipse

  • Go to Help
  • Eclipse Marketplace
  • Search for m2e or maven integration for eclipse
  • click on Install against - 'Maven Integration for Eclipse (Juno and newer) 1.4'
  • Restart and Enjoy!!!

Is generator.next() visible in Python 3?

g.next() has been renamed to g.__next__(). The reason for this is consistency: special methods like __init__() and __del__() all have double underscores (or "dunder" in the current vernacular), and .next() was one of the few exceptions to that rule. This was fixed in Python 3.0. [*]

But instead of calling g.__next__(), use next(g).

[*] There are other special attributes that have gotten this fix; func_name, is now __name__, etc.

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

These are really two questions.

The first one is answered here: Calling a Sub in VBA

To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.

How to create named and latest tag in Docker?

Here is my bash script

docker build -t ${IMAGE}:${VERSION} .
docker tag ${IMAGE}:${VERSION} ${IMAGE}:latest

You can then remove untagged images if you rebuilt the same version with

docker rmi $(docker images | grep "^<none>" | awk "{print $3}")

link

or

docker rmi $(docker images | grep "^<none>" | tr -s " " | cut -d' ' -f3 | tr '\n' ' ')

or

Clean up commands:

Docker 1.13 introduces clean-up commands. To remove all unused containers, images, networks and volumes:

docker system prune

or individually:

docker container prune
docker image prune
docker network prune
docker volume prune

Merge or combine by rownames

Using merge and renaming your t vector as tt (see the PS of Andrie) :

merge(tt,z,by="row.names",all.x=TRUE)[,-(5:8)]

Now if you would work with dataframes instead of matrices, this would even become a whole lot easier :

z <- as.data.frame(z)
tt <- as.data.frame(tt)
merge(tt,z["symbol"],by="row.names",all.x=TRUE)

Event listener for when element becomes visible?

Going forward, the new HTML Intersection Observer API is the thing you're looking for. It allows you to configure a callback that is called whenever one element, called the target, intersects either the device viewport or a specified element. It's available in latest versions of Chrome, Firefox and Edge. See https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API for more info.

Simple code example for observing display:none switching:

// Start observing visbility of element. On change, the
//   the callback is called with Boolean visibility as
//   argument:

function respondToVisibility(element, callback) {
  var options = {
    root: document.documentElement,
  };

  var observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      callback(entry.intersectionRatio > 0);
    });
  }, options);

  observer.observe(element);
}

In action: https://jsfiddle.net/elmarj/u35tez5n/5/

Reading CSV files using C#

My experience is that there are many different csv formats. Specially how they handle escaping of quotes and delimiters within a field.

These are the variants I have ran into:

  • quotes are quoted and doubled (excel) i.e. 15" -> field1,"15""",field3
  • quotes are not changed unless the field is quoted for some other reason. i.e. 15" -> field1,15",fields3
  • quotes are escaped with \. i.e. 15" -> field1,"15\"",field3
  • quotes are not changed at all (this is not always possible to parse correctly)
  • delimiter is quoted (excel). i.e. a,b -> field1,"a,b",field3
  • delimiter is escaped with \. i.e. a,b -> field1,a\,b,field3

I have tried many of the existing csv parsers but there is not a single one that can handle the variants I have ran into. It is also difficult to find out from the documentation which escaping variants the parsers support.

In my projects I now use either the VB TextFieldParser or a custom splitter.

Get IFrame's document, from JavaScript in main document

The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:

function GetDoc(x) {
    return x.contentDocument || x.contentWindow.document;
}

Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.

Filter dict to contain only certain keys?

This one liner lambda should work:

dictfilt = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])

Here's an example:

my_dict = {"a":1,"b":2,"c":3,"d":4}
wanted_keys = ("c","d")

# run it
In [10]: dictfilt(my_dict, wanted_keys)
Out[10]: {'c': 3, 'd': 4}

It's a basic list comprehension iterating over your dict keys (i in x) and outputs a list of tuple (key,value) pairs if the key lives in your desired key list (y). A dict() wraps the whole thing to output as a dict object.

Writing an Excel file in EPPlus

If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection.

using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");

    worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);

    package.Save();
}

What does the "at" (@) symbol do in Python?

In Python 3.5 you can overload @ as an operator. It is named as __matmul__, because it is designed to do matrix multiplication, but it can be anything you want. See PEP465 for details.

This is a simple implementation of matrix multiplication.

class Mat(list):
    def __matmul__(self, B):
        A = self
        return Mat([[sum(A[i][k]*B[k][j] for k in range(len(B)))
                    for j in range(len(B[0])) ] for i in range(len(A))])

A = Mat([[1,3],[7,5]])
B = Mat([[6,8],[4,2]])

print(A @ B)

This code yields:

[[18, 14], [62, 66]]

How to create/read/write JSON files in Qt5

Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.

So I tried jsoncpp from the gSOAP tools on the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:

value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;

and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VAL as needed):

value x(ctx);
std::cin >> x;
if (x.soap->error)
  exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
  if (x["appDesc"].has("description"))
    USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
  if (x["appDesc"].has("message"))
    USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
  if (x["appName"].has("description"))
    USE_VAL("$.appName.description", x["appName"]["description"]);
  if (x["appName"].has("message"))
    USE_VAL("$.appName.message", x["appName"]["message"]);
  if (x["appName"].has("imp"))
  {
    for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
      USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
  }
}

This code uses the JSON C++ API of gSOAP 2.8.28. I don't expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.

Why is there no SortedList in Java?

Because the concept of a List is incompatible with the concept of an automatically sorted collection. The point of a List is that after calling list.add(7, elem), a call to list.get(7) will return elem. With an auto-sorted list, the element could end up in an arbitrary position.

How do I make a fully statically linked .exe with Visual Studio Express 2005?

I've had this same dependency problem and I also know that you can include the VS 8.0 DLLs (release only! not debug!---and your program has to be release, too) in a folder of the appropriate name, in the parent folder with your .exe:

How to: Deploy using XCopy (MSDN)

Also note that things are guaranteed to go awry if you need to have C++ and C code in the same statically linked .exe because you will get linker conflicts that can only be resolved by ignoring the correct libXXX.lib and then linking dynamically (DLLs).

Lastly, with a different toolset (VC++ 6.0) things "just work", since Windows 2000 and above have the correct DLLs installed.

Include headers when using SELECT INTO OUTFILE?

For complex select with ORDER BY I use the following:

SELECT * FROM (
    SELECT 'Column name #1', 'Column name #2', 'Column name ##'
    UNION ALL
    (
        // complex SELECT statement with WHERE, ORDER BY, GROUP BY etc.
    )
) resulting_set
INTO OUTFILE '/path/to/file';

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

The error says "The index is out of range". That means you were trying to index an object with a value that was not valid. If you have two books, and I ask you to give me your third book, you will look at me funny. This is the computer looking at you funny. You said - "create a collection". So it did. But initially the collection is empty: not only is there nothing in it - it has no space to hold anything. "It has no hands".

Then you said "the first element of the collection is now 'ItemID'". And the computer says "I never was asked to create space for a 'first item'." I have no hands to hold this item you are giving me.

In terms of your code, you created a view, but never specified the size. You need a

dataGridView1.ColumnCount = 5;

Before trying to access any columns. Modify

DataGridView dataGridView1 = new DataGridView();

dataGridView1.Columns[0].Name = "ItemID";

to

DataGridView dataGridView1 = new DataGridView();
dataGridView1.ColumnCount = 5;
dataGridView1.Columns[0].Name = "ItemID";

See http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columncount.aspx

Creating a ZIP archive in memory using System.IO.Compression

Just another version of zipping without writing any file.

string fileName = "export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx";
byte[] fileBytes = here is your file in bytes
byte[] compressedBytes;
string fileNameZip = "Export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";

using (var outStream = new MemoryStream())
{
    using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
    {
        var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);
        using (var entryStream = fileInArchive.Open())
        using (var fileToCompressStream = new MemoryStream(fileBytes))
        {
            fileToCompressStream.CopyTo(entryStream);
        }
    }
    compressedBytes = outStream.ToArray();
}

How do I add 24 hours to a unix timestamp in php?

A Unix timestamp is simply the number of seconds since January the first 1970, so to add 24 hours to a Unix timestamp we just add the number of seconds in 24 hours. (24 * 60 *60)

time() + 24*60*60;

Iterating over and deleting from Hashtable in Java

You need to use an explicit java.util.Iterator to iterate over the Map's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map of Integer, String pairs, removing any entry whose Integer key is null or equals 0.

Map<Integer, String> map = ...

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

while (it.hasNext()) {
  Map.Entry<Integer, String> entry = it.next();

  // Remove entry if key is null or equals 0.
  if (entry.getKey() == null || entry.getKey() == 0) {
    it.remove();
  }
}

ASP.NET Core Web API exception handling

There is a built-in middleware that makes it easier than writing a custom one.

Asp.Net Core 5 version:

app.UseExceptionHandler(a => a.Run(async context =>
{
    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
    var exception = exceptionHandlerPathFeature.Error;
    
    await context.Response.WriteAsJsonAsync(new { error = exception.Message });
}));

Older versions (they did not have WriteAsJsonAsync extension):

app.UseExceptionHandler(a => a.Run(async context =>
{
    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
    var exception = exceptionHandlerPathFeature.Error;
    
    var result = JsonConvert.SerializeObject(new { error = exception.Message });
    context.Response.ContentType = "application/json";
    await context.Response.WriteAsync(result);
}));

It should do pretty much the same, just a bit less code to write.

Important: Remember to add it before UseMvc (or UseRouting in .Net Core 3) as order is important.

How to append multiple items in one line in Python

No.

First off, append is a function, so you can't write append[i+1:i+4] because you're trying to get a slice of a thing that isn't a sequence. (You can't get an element of it, either: append[i+1] is wrong for the same reason.) When you call a function, the argument goes in parentheses, i.e. the round ones: ().

Second, what you're trying to do is "take a sequence, and put every element in it at the end of this other sequence, in the original order". That's spelled extend. append is "take this thing, and put it at the end of the list, as a single item, even if it's also a list". (Recall that a list is a kind of sequence.)

But then, you need to be aware that i+1:i+4 is a special construct that appears only inside square brackets (to get a slice from a sequence) and braces (to create a dict object). You cannot pass it to a function. So you can't extend with that. You need to make a sequence of those values, and the natural way to do this is with the range function.

Getting only Month and Year from SQL DATE

There are two SQL function to do it:

Refer to the linked documentation for details.

Does return stop a loop?

The answer is yes, if you write return statement the controls goes back to to the caller method immediately. With an exception of finally block, which gets executed after the return statement.

and finally can also override the value you have returned, if you return inside of finally block. LINK: Try-catch-finally-return clarification

Return Statement definition as per:

Java Docs:

a return statement can be used to branch out of a control flow block and exit the method

MSDN Documentation:

The return statement terminates the execution of a function and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call.

Wikipedia:

A return statement causes execution to leave the current subroutine and resume at the point in the code immediately after where the subroutine was called, known as its return address. The return address is saved, usually on the process's call stack, as part of the operation of making the subroutine call. Return statements in many languages allow a function to specify a return value to be passed back to the code that called the function.

Yes or No confirm box using jQuery

Try This... It's very simple just use confirm dialog box for alert with YES|NO.

if(confirm("Do you want to upgrade?")){ Your code }

How to exit from the application and show the home screen?

(I tried previous answers but they lacks in some points. For example if you don't do a return; after finishing activity, remaining activity code runs. Also you need to edit onCreate with return. If you doesn't run super.onCreate() you will get a runtime error)

Say you have MainActivity and ChildActivity.

Inside ChildActivity add this:

Intent intent = new Intent(ChildActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
return true;

Inside MainActivity's onCreate add this:

@Override
public void onCreate(Bundle savedInstanceState) {

    mContext = getApplicationContext();

    super.onCreate(savedInstanceState);

    if (getIntent().getBooleanExtra("EXIT", false)) {
        finish();
        return;
    }
    // your current codes
    // your current codes
}

How to create a DataTable in C# and how to add rows?

Question 1: How do create a DataTable in C#?

Answer 1:

DataTable dt = new DataTable(); // DataTable created

// Add columns in your DataTable
dt.Columns.Add("Name");
dt.Columns.Add("Marks");

Note: There is no need to Clear() the DataTable after creating it.

Question 2: How to add row(s)?

Answer 2: Add one row:

dt.Rows.Add("Ravi","500");

Add multiple rows: use ForEach loop

DataTable dt2 = (DataTable)Session["CartData"]; // This DataTable contains multiple records
foreach (DataRow dr in dt2.Rows)
{
    dt.Rows.Add(dr["Name"], dr["Marks"]);
}

JavaScript blob filename without link

Late, but since I had the same problem I add my solution:

function newFile(data, fileName) {
    var json = JSON.stringify(data);
    //IE11 support
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        let blob = new Blob([json], {type: "application/json"});
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {// other browsers
        let file = new File([json], fileName, {type: "application/json"});
        let exportUrl = URL.createObjectURL(file);
        window.location.assign(exportUrl);
        URL.revokeObjectURL(exportUrl);
    }
}

POST Multipart Form Data using Retrofit 2.0 including image

There is a correct way of uploading a file with its name with Retrofit 2, without any hack:

Define API interface:

@Multipart
@POST("uploadAttachment")
Call<MyResponse> uploadAttachment(@Part MultipartBody.Part filePart); 
                                   // You can add other parameters too

Upload file like this:

File file = // initialize file here

MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));

Call<MyResponse> call = api.uploadAttachment(filePart);

This demonstrates only file uploading, you can also add other parameters in the same method with @Part annotation.

How do I pre-populate a jQuery Datepicker textbox with today's date?

$('input[name*="date"]').datepicker({
        dateFormat: 'dd-mm-yy',
        changeMonth: true,
        changeYear: true,
        beforeShow: function(input, instance) { 
            $(input).datepicker('setDate', new Date());
        }
    });

What are the best JVM settings for Eclipse?

You can also try running with JRockit. It's a JVM optimized for servers, but many long running client applications, like IDE's, run very well on JRockit. Eclipse is no exception. JRockit doesn't have a perm-space so you don't need to configure it.

It's possible set a pause time target(ms) to avoid long gc pauses stalling the UI.

-showsplash
org.eclipse.platform
-vm
 C:\jrmc-3.1.2-1.6.0\bin\javaw.exe 
-vmargs
-XgcPrio:deterministic
-XpauseTarget:20

I usually don't bother setting -Xmx and -Xms and let JRockit grow the heap as it sees necessary. If you launch your Eclipse application with JRockit you can also monitor, profile and find memory leaks in your application using the JRockit Mission Control tools suite. You download the plugins from this update site. Note, only works for Eclipse 3.3 and Eclipse 3.4

open resource with relative path in Java

Doe the following work?

resourcesloader.class.getClass().getResource("/package1/resources/repository/SSL-Key/cert.jks")

Is there a reason you can't specify the full path including the package?

Printing out a linked list using toString

A very simple solution is to override the toString() method in the Node. Then, you can call print by passing LinkedList's head. You don't need to implement any kind of loop.

Code:

public class LinkedListNode {
    ...

    //New
    @Override
    public String toString() {
        return String.format("Node(%d, next = %s)", data, next);
    }
} 


public class LinkedList {

    public static void main(String[] args) {

        LinkedList l = new LinkedList();
        l.insertFront(0);
        l.insertFront(1);
        l.insertFront(2);
        l.insertFront(3);

        //New
        System.out.println(l.head);
    }
}

Full-screen responsive background image

This worked for me, so posting this.

.my-container {
  position: relative;
  background: #696969;
  overflow: hidden;
}
.my-container:before {
  content: ' ';
  display: block;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  opacity: 0.6;
  background-image: url('https://images.pexels.com/photos/1084542/pexels-photo-1084542.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260');
  background-repeat: no-repeat;
  background-position: 50% 0;
  -ms-background-size: cover;
  -o-background-size: cover;
  -moz-background-size: cover;
  -webkit-background-size: cover;
  background-size: cover;
}

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

Run given below command on terminal ( for linux only )

ps aux | grep rails

and then

kill -9 [pid]

Another way

lsof -wni tcp:3000

and then

kill -9 [PID]

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }
}

The simplest way to resize an UIImage?

Swift 3.0 with failsafe option (returns the original image in case of error):

func resize(image: UIImage, toSize size: CGSize) -> UIImage{
    UIGraphicsBeginImageContextWithOptions(size,false,1.0)
    image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
    if let resizedImage = UIGraphicsGetImageFromCurrentImageContext() {
        UIGraphicsEndImageContext()
        return resizedImage
    }
    UIGraphicsEndImageContext()
    return image
}

Console.log(); How to & Debugging javascript

Breakpoints and especially conditional breakpoints are your friends.

Also you can write small assert like function which will check values and throw exceptions if needed in debug version of site (some variable is set to true or url has some parameter)

get everything between <tag> and </tag> with php

You can also try:

function getTagValue($string, $tag)
{
    $pattern = "/<{$tag}>(.*?)<\/{$tag}>/s";
    preg_match($pattern, $string, $matches);
    return isset($matches[1]) ? $matches[1] : '';
}

It returns empty string in case of no match.

How to solve error message: "Failed to map the path '/'."

Changing pool from ASP.NET v4.0 to Framework4 worked for me.

fatal: bad default revision 'HEAD'

This seems to occur when .git/HEAD refers to a branch which does not exist. I ran into this error in a repo that had nothing in .git/refs/heads. I have no idea how the repo got into that state, I inherited from someone that left the company.

How do I check that a number is float or integer?

There is a method called Number.isInteger() which is currently implemented in everything but IE. MDN also provides a polyfill for other browsers:

Number.isInteger = Number.isInteger || function(value) {
  return typeof value === 'number' && 
    isFinite(value) && 
    Math.floor(value) === value;
};

However, for most uses cases, you are better off using Number.isSafeInteger which also checks if the value is so high/low that any decimal places would have been lost anyway. MDN has a polyfil for this as well. (You also need the isInteger pollyfill above.)

if (!Number.MAX_SAFE_INTEGER) {
    Number.MAX_SAFE_INTEGER = 9007199254740991; // Math.pow(2, 53) - 1;
}
Number.isSafeInteger = Number.isSafeInteger || function (value) {
   return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
};

How to make ng-repeat filter out duplicate results

Or you can write your own filter using lodash.

app.filter('unique', function() {
    return function (arr, field) {
        return _.uniq(arr, function(a) { return a[field]; });
    };
});

Spring Data JPA find by embedded object property

The above - findByBookIdRegion() did not work for me. The following works with the latest release of String Data JPA:

Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);

How to fix a header on scroll

If you are using React I recently published a custom hook which enables you to do this. You need to supply a ref to the sticky element as well as a ref to the element you want it to stick to the top of. It handles the screen "jump" (as mentioned in other responses) for you as well.

const sticky = useRef<HTMLDivElement>(null)
const container = useRef<HTMLDivElement>(null)

useStickyScroll({
    element: sticky,
    container: container
})

What are WSDL, SOAP and REST?

SOAP stands for Simple (sic) Object Access Protocol. It was intended to be a way to do Remote Procedure Calls to remote objects by sending XML over HTTP.

WSDL is Web Service Description Language. A request ending in '.wsdl' to an endpoint will result in an XML message describing request and response that a use can expect. It descibes the contract between service & client.

REST uses HTTP to send messages to services.

SOAP is a spec, REST is a style.

How to implement a custom AlertDialog View

AlertDialog.setView(View view) does add the given view to the R.id.custom FrameLayout. The following is a snippet of Android source code from AlertController.setupView() which finally handles this (mView is the view given to AlertDialog.setView method).

...
FrameLayout custom = (FrameLayout) mWindow.findViewById(R.id.**custom**);
custom.addView(**mView**, new LayoutParams(FILL_PARENT, FILL_PARENT));
...

What is the use of the square brackets [] in sql statements?

The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column [First Name] (with a space)--but then you'd need to use brackets every time you referred to that column.

The newer tools add them everywhere just in case or for consistency.

Running Jupyter via command line on Windows

I have two python version installed: 1. Python 3.8.2: This was installed independently 2. Python 3.7.6: This was installed along with Anaconda 3

Multiple versions caused conflict even after setting the path variables correctly.

I have uninstalled the Python 3.8.2 and after restart, the command

jupyter notebook

Worked perfectly :)

How to get full path of a file?

You can save this in your shell.rc or just put in console

function absolute_path { echo "$PWD/$1"; }
alias ap="absolute_path"

example:

ap somefile.txt

will output

/home/user/somefile.txt

@Autowired - No qualifying bean of type found for dependency

Faced the same issue in my spring boot application even though I had my package specific scans enabled like

@SpringBootApplication(scanBasePackages={"com.*"})

But, the issue was resolved by providing @ComponentScan({"com.*"}) in my Application class.

show/hide a div on hover and hover out

You could use jQuery to show the div, and set it at wherever your mouse is:

html:

<!DOCTYPE html>
<html>

  <head>
    <link href="style.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  </head>

  <body>
    <div id="trigger">
      <h1>Hover me!</h1>
      <p>Ill show you wonderful things</p>
    </div>
    <div id="secret">
     shhhh
    </div>
    <script src="script.js"></script>
  </body>

</html>

styles:

#trigger {
  border: 1px solid black;
}
#secret {
  display:none;
  top:0;  
  position:absolute;
  background: grey;
  color:white;
  width: 50%;
}

js:

$("#trigger").hover(function(e){
    $("#secret").show().css('top', e.pageY + "px").css('left', e.pageX + "px");
  },function(e){
    $("#secret").hide()
})

You can find the example here Cheers! http://plnkr.co/edit/LAhs8X9F8N3ft7qFvjzy?p=preview

How do I draw a grid onto a plot in Python?

Here is a small example how to add a matplotlib grid in Gtk3 with Python 2 (not working in Python 3):

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_title("Embedding in GTK3")

f = Figure(figsize=(1, 1), dpi=100)
ax = f.add_subplot(111)
ax.grid()

canvas = FigureCanvas(f)
canvas.set_size_request(400, 400)
win.add(canvas)

win.show_all()
Gtk.main()

enter image description here

Getting byte array through input type = file

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    (function (document) {_x000D_
  var input = document.getElementById("files"),_x000D_
  output = document.getElementById("result"),_x000D_
  fileData; // We need fileData to be visible to getBuffer._x000D_
_x000D_
  // Eventhandler for file input. _x000D_
  function openfile(evt) {_x000D_
    var files = input.files;_x000D_
    // Pass the file to the blob, not the input[0]._x000D_
    fileData = new Blob([files[0]]);_x000D_
    // Pass getBuffer to promise._x000D_
    var promise = new Promise(getBuffer);_x000D_
    // Wait for promise to be resolved, or log error._x000D_
    promise.then(function(data) {_x000D_
      // Here you can pass the bytes to another function._x000D_
      output.innerHTML = data.toString();_x000D_
      console.log(data);_x000D_
    }).catch(function(err) {_x000D_
      console.log('Error: ',err);_x000D_
    });_x000D_
  }_x000D_
_x000D_
  /* _x000D_
    Create a function which will be passed to the promise_x000D_
    and resolve it when FileReader has finished loading the file._x000D_
  */_x000D_
  function getBuffer(resolve) {_x000D_
    var reader = new FileReader();_x000D_
    reader.readAsArrayBuffer(fileData);_x000D_
    reader.onload = function() {_x000D_
      var arrayBuffer = reader.result_x000D_
      var bytes = new Uint8Array(arrayBuffer);_x000D_
      resolve(bytes);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  // Eventlistener for file input._x000D_
  input.addEventListener('change', openfile, false);_x000D_
}(document));_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<input type="file" id="files"/>_x000D_
<div id="result"></div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

@Scope("prototype") bean scope not creating new bean

Using ApplicationContextAware is tying you to Spring (which may or may not be an issue). I would recommend passing in a LoginActionFactory, which you can ask for a new instance of a LoginAction each time you need one.

How to search file text for a pattern and replace it with a given value

Keep in mind that, when you do this, the filesystem could be out of space and you may create a zero-length file. This is catastrophic if you're doing something like writing out /etc/passwd files as part of system configuration management.

Note that in-place file editing like in the accepted answer will always truncate the file and write out the new file sequentially. There will always be a race condition where concurrent readers will see a truncated file. If the process is aborted for any reason (ctrl-c, OOM killer, system crash, power outage, etc) during the write then the truncated file will also be left over, which can be catastrophic. This is the kind of dataloss scenario which developers MUST consider because it will happen. For that reason, I think the accepted answer should most likely not be the accepted answer. At a bare minimum write to a tempfile and move/rename the file into place like the "simple" solution at the end of this answer.

You need to use an algorithm that:

  1. Reads the old file and writes out to the new file. (You need to be careful about slurping entire files into memory).

  2. Explicitly closes the new temporary file, which is where you may throw an exception because the file buffers cannot be written to disk because there is no space. (Catch this and cleanup the temporary file if you like, but you need to rethrow something or fail fairly hard at this point.

  3. Fixes the file permissions and modes on the new file.

  4. Renames the new file and drops it into place.

With ext3 filesystems you are guaranteed that the metadata write to move the file into place will not get rearranged by the filesystem and written before the data buffers for the new file are written, so this should either succeed or fail. The ext4 filesystem has also been patched to support this kind of behavior. If you are very paranoid you should call the fdatasync() system call as a step 3.5 before moving the file into place.

Regardless of language, this is best practice. In languages where calling close() does not throw an exception (Perl or C) you must explicitly check the return of close() and throw an exception if it fails.

The suggestion above to simply slurp the file into memory, manipulate it and write it out to the file will be guaranteed to produce zero-length files on a full filesystem. You need to always use FileUtils.mv to move a fully-written temporary file into place.

A final consideration is the placement of the temporary file. If you open a file in /tmp then you have to consider a few problems:

  • If /tmp is mounted on a different file system you may run /tmp out of space before you've written out the file that would otherwise be deployable to the destination of the old file.

  • Probably more importantly, when you try to mv the file across a device mount you will transparently get converted to cp behavior. The old file will be opened, the old files inode will be preserved and reopened and the file contents will be copied. This is most likely not what you want, and you may run into "text file busy" errors if you try to edit the contents of a running file. This also defeats the purpose of using the filesystem mv commands and you may run the destination filesystem out of space with only a partially written file.

    This also has nothing to do with Ruby's implementation. The system mv and cp commands behave similarly.

What is more preferable is to open a Tempfile in the same directory as the old file. This ensures that there will be no cross-device move issues. The mv itself should never fail, and you should always get a complete and untruncated file. Any failures, such as device out of space, permission errors, etc., should be encountered during writing the Tempfile out.

The only downsides to the approach of creating the Tempfile in the destination directory are:

  • Sometimes you may not be able to open a Tempfile there, such as if you are trying to 'edit' a file in /proc for example. For that reason you might want to fall back and try /tmp if opening the file in the destination directory fails.
  • You must have enough space on the destination partition in order to hold both the complete old file and the new file. However, if you have insufficient space to hold both copies then you are probably short on disk space and the actual risk of writing a truncated file is much higher, so I would argue this is a very poor tradeoff outside of some exceedingly narrow (and well-monitored) edge cases.

Here's some code that implements the full-algorithm (windows code is untested and unfinished):

#!/usr/bin/env ruby

require 'tempfile'

def file_edit(filename, regexp, replacement)
  tempdir = File.dirname(filename)
  tempprefix = File.basename(filename)
  tempprefix.prepend('.') unless RUBY_PLATFORM =~ /mswin|mingw|windows/
  tempfile =
    begin
      Tempfile.new(tempprefix, tempdir)
    rescue
      Tempfile.new(tempprefix)
    end
  File.open(filename).each do |line|
    tempfile.puts line.gsub(regexp, replacement)
  end
  tempfile.fdatasync unless RUBY_PLATFORM =~ /mswin|mingw|windows/
  tempfile.close
  unless RUBY_PLATFORM =~ /mswin|mingw|windows/
    stat = File.stat(filename)
    FileUtils.chown stat.uid, stat.gid, tempfile.path
    FileUtils.chmod stat.mode, tempfile.path
  else
    # FIXME: apply perms on windows
  end
  FileUtils.mv tempfile.path, filename
end

file_edit('/tmp/foo', /foo/, "baz")

And here is a slightly tighter version that doesn't worry about every possible edge case (if you are on Unix and don't care about writing to /proc):

#!/usr/bin/env ruby

require 'tempfile'

def file_edit(filename, regexp, replacement)
  Tempfile.open(".#{File.basename(filename)}", File.dirname(filename)) do |tempfile|
    File.open(filename).each do |line|
      tempfile.puts line.gsub(regexp, replacement)
    end
    tempfile.fdatasync
    tempfile.close
    stat = File.stat(filename)
    FileUtils.chown stat.uid, stat.gid, tempfile.path
    FileUtils.chmod stat.mode, tempfile.path
    FileUtils.mv tempfile.path, filename
  end
end

file_edit('/tmp/foo', /foo/, "baz")

The really simple use-case, for when you don't care about file system permissions (either you're not running as root, or you're running as root and the file is root owned):

#!/usr/bin/env ruby

require 'tempfile'

def file_edit(filename, regexp, replacement)
  Tempfile.open(".#{File.basename(filename)}", File.dirname(filename)) do |tempfile|
    File.open(filename).each do |line|
      tempfile.puts line.gsub(regexp, replacement)
    end
    tempfile.close
    FileUtils.mv tempfile.path, filename
  end
end

file_edit('/tmp/foo', /foo/, "baz")

TL;DR: That should be used instead of the accepted answer at a minimum, in all cases, in order to ensure the update is atomic and concurrent readers will not see truncated files. As I mentioned above, creating the Tempfile in the same directory as the edited file is important here to avoid cross device mv operations being translated into cp operations if /tmp is mounted on a different device. Calling fdatasync is an added layer of paranoia, but it will incur a performance hit, so I omitted it from this example since it is not commonly practiced.

Pass arguments into C program from command line

Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.

How to revert the last migration?

Don't delete the migration file until after the reversion. I made this mistake and without the migration file, the database didn't know what things to remove.

python manage.py showmigrations
python manage.py migrate {app name from show migrations} {00##_migration file.py}

Delete the migration file. Once the desired migration is in your models...

python manage.py makemigrations
python manage.py migrate

How do I hide the bullets on my list for the sidebar?

its on you ul in the file http://ratest4.com/wp-content/themes/HarnettArts-BP-2010/style.css on line 252

add this to your css

ul{
     list-style:none;
}

How to add 'libs' folder in Android Studio?

You can create lib folder inside app you press right click and select directory you named as libs its will be worked

How to change environment's font size?

In Visual Studio Code, the font-size can be easily changed from the Settings tab.

The simplest way to do this is to press Ctrl + Shift + P and then type 'Settings'. This will show you a few results. Choose 'Settings(UI)'. The Settings tab will get opened in the editor. Now you can change the font settings from here. This will only affect the editor's font.

Or, you can also click on the settings icon on the left bottom of the window and search for font from there.

enter image description here

In order to change the font size of the entire environment, you may consider pressing ctrl++. This will work like zooming into the whole environment, resulting in an increased font-size.

Select Settings(UI)

How to bring view in front of everything?

You can set visibility to false of other views.

view1.setVisibility(View.GONE);
view2.setVisibility(View.GONE);
...

or

view1.setVisibility(View.INVISIBLE);
view2.setVisibility(View.INVISIBLE);
...

and set

viewN.setVisibility(View.VISIBLE);

Real world use of JMS/message queues?

I've used it to send intraday trades between different fund management systems. If you want to learn more about what a great technology messaging is, I can thoroughly recommend the book "Enterprise Integration Patterns". There are some JMS examples for things like request/reply and publish/subscribe.

Messaging is an excellent tool for integration.

How to handle back button in activity

For both hardware device back button and soft home (back) button e.g. " <- " this is what works for me. (*Note I have an app bar / toolbar in the activity)

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            //finish();
            onBackPressed();
            break;
    }
    return true;
}



@Override
public void onBackPressed() {
   //Execute your code here
   finish();

}

Cheers!

How to convert milliseconds into a readable date?

I just tested this and it works fine

var d = new Date(1441121836000);

The data object has a constructor which takes milliseconds as an argument.

What is trunk, branch and tag in Subversion?

To use Subversion in Visual Studio 2008, install TortoiseSVN and AnkhSVN.

TortoiseSVN is a really easy to use Revision control / version control / source control software for Windows. Since it's not an integration for a specific IDE you can use it with whatever development tools you like. TortoiseSVN is free to use. You don't need to get a loan or pay a full years salary to use it.

AnkhSVN is a Subversion SourceControl Provider for Visual Studio. The software allows you to perform the most common version control operations directly from inside the Microsoft Visual Studio IDE. With AnkhSVN you no longer need to leave your IDE to perform tasks like viewing the status of your source code, updating your Subversion working copy and committing changes. You can even browse your repository and you can plug-in your favorite diff tool.

java.net.BindException: Address already in use: JVM_Bind <null>:80

Make sure /webapps/ROOT file is there and it has all the icons, WEB-INF, and index.jsp is in the folder.

When you startup Tomcat, it will run this code in <Tomcat-Directory>/conf/web.xml directory:

<welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

The location of index.jsp is in <Tomcat-Directory>/webapps/ROOT/index.jsp

Also, try running tomcat from the /bin directory using ./catalina.sh start instead of ./startup.sh. For some reason, ./startup.sh isn't as reliable.

How can I remove the top and right axis in matplotlib?

This is the suggested Matplotlib 3 solution from the official website HERE:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)

ax = plt.subplot(111)
ax.plot(x, y)

# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')

plt.show()

enter image description here

Function vs. Stored Procedure in SQL Server

  • It is mandatory for Function to return a value while it is not for stored procedure.
  • Select statements only accepted in UDF while DML statements not required.
  • Stored procedure accepts any statements as well as DML statements.
  • UDF only allows inputs and not outputs.
  • Stored procedure allows for both inputs and outputs.
  • Catch blocks cannot be used in UDF but can be used in stored procedure.
  • No transactions allowed in functions in UDF but in stored procedure they are allowed.
  • Only table variables can be used in UDF and not temporary tables.
  • Stored procedure allows for both table variables and temporary tables.
  • UDF does not allow stored procedures to be called from functions while stored procedures allow calling of functions.
  • UDF is used in join clause while stored procedures cannot be used in join clause.
  • Stored procedure will always allow for return to zero. UDF, on the contrary, has values that must come - back to a predetermined point.

java howto ArrayList push, pop, shift, and unshift

Great Answer by Jon.

I'm lazy though and I hate typing, so I created a simple cut and paste example for all the other people who are like me. Enjoy!

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        List<String> animals = new ArrayList<>();

        animals.add("Lion");
        animals.add("Tiger");
        animals.add("Cat");
        animals.add("Dog");

        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

        // add() -> push(): Add items to the end of an array
        animals.add("Elephant");
        System.out.println(animals);  // [Lion, Tiger, Cat, Dog, Elephant]

        // remove() -> pop(): Remove an item from the end of an array
        animals.remove(animals.size() - 1);
        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

        // add(0,"xyz") -> unshift(): Add items to the beginning of an array
        animals.add(0, "Penguin");
        System.out.println(animals); // [Penguin, Lion, Tiger, Cat, Dog]

        // remove(0) -> shift(): Remove an item from the beginning of an array
        animals.remove(0);
        System.out.println(animals); // [Lion, Tiger, Cat, Dog]

    }

}

javac option to compile all java files under a given directory recursively

I would advice you to learn using ant, which is very-well suited for this task and is very easy to grasp and well documented.

You would just have to define a target like this in the build.xml file:

<target name="compile">
    <javac srcdir="your/source/directory"
           destdir="your/output/directory"
           classpath="xyz.jar" />
</target>

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

Oracle database: How to read a BLOB?

SQL Developer can show the blob as an image (at least it works for jpegs). In the Data view, double click on the BLOB field to get the "pencil" icon. Click on the pencil to get a dialog that will allow you to select a "View As Image" checkbox.

Pandas: Setting no. of max rows

Set display.max_rows:

pd.set_option('display.max_rows', 500)

For older versions of pandas (<=0.11.0) you need to change both display.height and display.max_rows.

pd.set_option('display.height', 500)
pd.set_option('display.max_rows', 500)

See also pd.describe_option('display').

You can set an option only temporarily for this one time like this:

from IPython.display import display
with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
    display(df) #need display to show the dataframe when using with in jupyter
    #some pandas stuff

You can also reset an option back to its default value like this:

pd.reset_option('display.max_rows')

And reset all of them back:

pd.reset_option('all')

jQuery remove selected option from this

This is a simpler one

$('#some_select_box').find('option:selected').remove().end();

In reactJS, how to copy text to clipboard?

<input
value={get(data, "api_key")}
styleName="input-wrap"
title={get(data, "api_key")}
ref={apikeyObjRef}
/>
  <div
onClick={() => {
  apikeyObjRef.current.select();
  if (document.execCommand("copy")) {
    document.execCommand("copy");
  }
}}
styleName="copy"
>
  ??
</div>

What is the default Jenkins password?

Well, Even I tried to log in with the admin/password which was failed. So I created my own user like this.

  1. Go to Jenkins home folder (C:\User.jenkins or you can find this in Jenkins server startup logs)
  2. Go to Config file config.xml
  3. set disableSignup to false false if at all you want to disable login security 4.set ser security to false. true

Overriding a JavaScript function while referencing the original

In my opinion the top answers are not readable/maintainable, and the other answers do not properly bind context. Here's a readable solution using ES6 syntax to solve both these problems.

const orginial = someObject.foo;
someObject.foo = function() {
  if (condition) orginial.bind(this)(...arguments);
};

R barplot Y-axis scale too short

I see you try to set ylim but you give bad values. This will change the scale of the plot (like a zoom). For example see this:

par(mfrow=c(2,1))
tN <- table(Ni <- stats::rpois(100, lambda = 5))
r <- barplot(tN, col = rainbow(20),ylim=c(0,50),main='long y-axis')
r <- barplot(tN, col = rainbow(20),main='short y axis')

enter image description here Another option is to plot without axes and set them manually using axis and usr:

require(grDevices) # for colours
par(mfrow=c(1,1))
r <- barplot(tN, col = rainbow(20),main='short y axis',ann=FALSE,axes=FALSE)
usr <- par("usr")
par(usr=c(usr[1:2], 0, 20))
axis(2,at=seq(0,20,5))

enter image description here

How to unzip a file using the command line?

Grab an executable from info-zip.

Info-ZIP supports hardware from microcomputers all the way up to Cray supercomputers, running on almost all versions of Unix, VMS, OS/2, Windows 9x/NT/etc. (a.k.a. Win32), Windows 3.x, Windows CE, MS-DOS, AmigaDOS, Atari TOS, Acorn RISC OS, BeOS, Mac OS, SMS/QDOS, MVS and OS/390 OE, VM/CMS, FlexOS, Tandem NSK and Human68K (Japanese). There is also some (old) support for LynxOS, TOPS-20, AOS/VS and Novell NLMs. Shared libraries (DLLs) are available for Unix, OS/2, Win32 and Win16, and graphical interfaces are available for Win32, Win16, WinCE and Mac OS.

Clearing _POST array fully

To unset the $_POST variable, redeclare it as an empty array:

$_POST = array();

Is there a way to define a min and max value for EditText in Android?

I extended @Pratik Sharmas code to use BigDecimal objects instead of ints so that it can accept larger numbers, and account for any formatting in the EditText that isn't a number (like currency formatting i.e. spaces, commas and periods)

EDIT: note that this implementation has 2 as the minimum significant figures set on the BigDecimal (see the MIN_SIG_FIG constant) as I used it for currency, so there was always 2 leading numbers before the decimal point. Alter the MIN_SIG_FIG constant as necessary for your own implementation.

public class InputFilterMinMax implements InputFilter {
private static final int MIN_SIG_FIG = 2;
private BigDecimal min, max;

public InputFilterMinMax(BigDecimal min, BigDecimal max) {
    this.min = min;
    this.max = max;
}

public InputFilterMinMax(String min, String max) {
    this.min = new BigDecimal(min);
    this.max = new BigDecimal(max);
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
        int dend) {
    try {
        BigDecimal input = formatStringToBigDecimal(dest.toString()
                + source.toString());

        if (isInRange(min, max, input)) {

            return null;
        }
    } catch (NumberFormatException nfe) {

    }
    return "";
}

private boolean isInRange(BigDecimal a, BigDecimal b, BigDecimal c) {
    return b.compareTo(a) > 0 ? c.compareTo(a) >= 0 && c.compareTo(b) <= 0
            : c.compareTo(b) >= 0 && c.compareTo(a) <= 0;
}

public static BigDecimal formatStringToBigDecimal(String n) {

    Number number = null;
    try {
        number = getDefaultNumberFormat().parse(n.replaceAll("[^\\d]", ""));

        BigDecimal parsed = new BigDecimal(number.doubleValue()).divide(new BigDecimal(100), 2,
                BigDecimal.ROUND_UNNECESSARY);
        return parsed;
    } catch (ParseException e) {
        return new BigDecimal(0);
    }
}

private static NumberFormat getDefaultNumberFormat() {
    NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
    nf.setMinimumFractionDigits(MIN_SIG_FIG);
    return nf;
}

Get list of filenames in folder with Javascript

No, Javascript doesn't have access to the filesystem. Server side Javascript is a whole different story but I guess you don't mean that.

How to add option to select list in jQuery

Your code fails because you are executing a method (addOption) on the jQuery object (and this object does not support the method)

You can use the standard Javascript function like this:

$("#dropListBuilding")[0].options.add( new Option("My Text","My Value") )

Best practice for Django project working directory structure

Here is what I follow on My system.

  1. All Projects: There is a projects directory in my home folder i.e. ~/projects. All the projects rest inside it.

  2. Individual Project: I follow a standardized structure template used by many developers called django-skel for individual projects. It basically takes care of all your static file and media files and all.

  3. Virtual environment: I have a virtualenvs folder inside my home to store all virtual environments in the system i.e. ~/virtualenvs . This gives me flexibility that I know what all virtual environments I have and can look use easily

The above 3 are the main partitions of My working environment.

All the other parts you mentioned are mostly dependent on project to project basis (i.e. you might use different databases for different projects). So they should reside in their individual projects.

Switch php versions on commandline ubuntu 16.04

When installing laravel on Ubuntu 18.04, be default PHP 7.3.0RC3 install selected, but laravel and symfony will not install properly complaining about missin php-xml and php-zip, even though they are installed. You need to switch to php 7.1, using the instructions above or,

 sudo update-alternatives --set php /usr/bin/php7.1

now, running laravel new blog, will proceed correctly