text:
Q: How to disable temporally the Firefox cache? I have a router that whenever it lost the connection it uses Permanently Moved (301) HTTP responses and literally I'm unable to access that link in Firefox. In Chrome/ium I can type the url then press Ctrl + Enter or opening the Developers Tool and disable the cache there in the options. Sadly, I haven't found a way which Firefox can imitate such behavior.
For now I'm appending ?a=1 at the end of the url to circumvent this problem, but is not desirable since if I click the url coming from another page I'll be in the same situation again.
EDIT: Private Browsing do some of this magic, but is actually Overkill for my proposes, since it kills the cookies.
What is Permanetly Moved (301) in the HTTP protocol?
For the answers/comments I'm getting seems that there is a misunderstanding of what is happening so I'm going to dwell more specifically in the topic.
Whenever I type http://superuser.com Firefox uses the cache (I can't press F5/Ctrl + F5 since I'm not in any page now) and see that the URL was Permanently Moved hence, it never goes to http://superuser.com but to http://deviceip/DeviceStatus_Warning.htm without delay nor stop. This question requires the understanding of both, the HTTP protocol and Firefox.

The HTTP response status code 301 Moved Permanently is used for permanent redirection, meaning current links or records using the URL that the 301 Moved Permanently response is received for should be updated to the new URL provided in the Location field of the response.

I doubt the "feature" can be disabled since it's a ISP modified firmware, but here it goes:
Maker: Huawei
Model: HG530
Software release: V100R001B025 Codetel
Firmware Release: 3.12.8.20

I have Telnet, HTTP and FTP access to the router, but I haven't seen anything similar:
TELNET commands available:
HG530> help
Valid commands are:
sys             exit            diag            ether
wan             etherdbg        tcephydbg       ip
bridge          dot1q           pktqos          show
set             lan

A: You can use the Developer tools to temporally disable the cache, with a caveat.

*

*Open the Developer tools (F12 or Ctrl-Shift-K)

*Search for toolbox options

*In the "Advanced settings" section, look for "Disable HTTP Cache (when toolbox is open)"

As you have noticed, this temporally disable the cache while you have the toolbox open, for the tab where the toolbox is open. It more or less covers your use case.
There's a bug/feature request asking for a more discoverable way.

A: Go into private browsing mode.
Use this shortcut: command + shift + P.


text:
Q: Is there a way to update the graphics in opengl when a window is being moved?
I am working on an application in java and I would like to know if it is possible to keep updating the graphics in LWJGL3 even when the window is being moved or resized?

A: I think that this source may help. Link
I believe that your problem is that GLFW methods like glfwWindowShouldClose() block while the window is being changed. Therefore, if you use that code to split the rendering into it's own thread, you should be able to render even while the window is resizing.
Note: I have not tested that code myself, but based on who wrote it I am confident that it works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can't back ticks be used in JavaScript objects Why are back ticks for object properties invalid syntax? For example, this is valid:
const test = {
  "test1": "test2"
}

So why can't it have back ticks instead?
const test = {
  `test1`: "test2"
}
//throws unexpected token error

It would be really helpful if back ticks could be used like this, but we can't. Is there a simple alternative, or maybe this works in some browsers?

A: You need to put it into brackets like this because it's evaluated at runtime.
const test = {
  [`test1`]: "test2"
}

As @Amadan pointed out in the comment, you can use any expression as a property key by putting it into brackets.

A: You can write like this:
const key = `test1`
const test = { [key]: 'test2' }


text:
Q: How to create table with links to another table? I'm trying to create table of text elements with links to another table. It means if you press one element, another table appears near, if you press another element second table changes to another. How to do it in shortest way?

A: jquery - links are requesting to the another table's id so it triggers the whatever you have scripted i.e. changes a table from display: none to display: block


text:
Q: Firebase Value Event listener being skipped When debugging, the program doesn't get into user ref value event listener why would this happen?
I get rid = null but the firebase instantiation is correct from what I can tell.
[text so stack overflow lets me post since there's too much code and no further explanation for the issue]
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.send_message_chat);
    getSupportActionBar().hide();

    String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();

    useref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot snap : snapshot.getChildren()) {
                rid = snap.child("receiverid").getValue(String.class);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
 throw error.toException();
        }
    });

    rv = findViewById(R.id.rvcahtitems);
    b = findViewById(R.id.chatsendb);
    field = findViewById(R.id.chatfield);
    user = FirebaseAuth.getInstance().getCurrentUser();
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String msg = field.getText().toString();
            if ((!msg.equals("")))
            {
                SendM(user.getUid(), rid, msg);
            }
            else
            {
                Toast.makeText(ChatScreen.this, "Can't send an empty message", Toast.LENGTH_SHORT);
            }
            field.setText("");

        }
    });
    rv.setLayoutManager(new LinearLayoutManager(this));
    readmsgs(userID, rid);
}


text:
Q: How do I make a website automatically display files from a file structure? I'm currently creating a website as part of a high school internship for a professor as a university.
Since he is constantly uploading new assignments, I am wondering if there is a way that I can php or JavaScript to automatically add files inside the webpage.
To go into description of my concept, there is a set file structure for the professor's website. The website correlates with that file structure but every time he adds a file he has to go into the code and link it.
I know this would be easy with Dreamweaver, but I want to make the process speedy for him. I want to have it so that he adds a file to the structure and the website automatically adds the name of the file within the webpage and makes a link to download it. I know nothing about PHP but I am familiar with JavaScript, just not with integrating it into HTML.

A: Check the readdir function for php.
//Example #2 List all entries in the current directory and strip out . and ..
<?php
if ($handle = opendir('.')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "$entry\n";
        }
    }
    closedir($handle);
}
?>

Now you could change the opendir('.') part to match any directory available to the webserver. And instead of just echo you can output htmlcode that links to the file.


text:
Q: How do you run rdoc on single files without overwriting all other files? I am working on a very large rails project and I want to standardize the usage of rdoc in the codebase. I figured I could run it once over the whole project (to at least generate docs for the classes and methods themselves) and then devs can add single files as they add documentation.
The problem is that if I run rdoc /path/to/some_file.rb, it then removes all other files from the generated index.html, and only includes the one. Running rdoc on the whole project takes 3-4 minutes and it shouldn't be necessary to parse the entire project every time new comments are added. The output of rdoc --help provides no solutions.
Is there a way to configure rdoc such that it will always persist docs until I specifically run rdoc over those files again?
Thanks for any insight!

A: I don't think rdoc removes anything from index.html, just overwrites it and isn't actually capable of modifying it. Regarding performance, I'm not 100% sure but most likely rdoc doesn't cache the parse results. Yard does, with -c, --use-cache option, and it speeds up things significantly.


text:
Q: Pattern with three stripes I'm new to svg (and design in general) and looking for a way to fill a svg shape/path with three equally-sized diagonal stripes in different colors. For two stripes, I already found a solution on Stack Overflow (Simple fill pattern in svg : diagonal hatching):
<svg width="300" height="30" viewBox="0 0 200 10">
    <pattern id="diagonalHatch" width="15" height="10"
     patternTransform="rotate(135 0 0)" patternUnits="userSpaceOnUse">
         <rect x="0" y="0" width="100%" height="100%" fill="orange"></rect>
         <line x1="0" y1="0" x2="0" y2="10" style="stroke:blue; stroke-
          width:15" />
    </pattern>

    <rect x="0" y="0" width="100%" height="100%" fill="url(#diagonalHatch)"/>
</svg>

I modified the solution somewhat, including a rectangle for background color (is there a better way to do this?). But I just can't figure out how to do it for three stripes. Another thing I also wondered is whether there is a way to pass the colors as some kind of parameters to the pattern, so that there is no need to declare multiple patterns just for color switching?

A: I've added a second line to your pattern. Also I've removed the attributes with a value == 0. If your stroke-width is 10 (for example) you will need to begin your line at 5 since a line is drawn 5 units to one side and 5 to the other side. I hope it helps.

<svg width="300" height="300" viewBox="0 0 200 200">
    <pattern id="diagonalHatch" width="30" height="10"
     patternTransform="rotate(130)" patternUnits="userSpaceOnUse">
         <rect width="100%" height="100%" fill="orange"></rect>
         <line x1="5" x2="5" y2="10" style="stroke:blue; stroke-width:10" />
         <line x1="15" x2="15" y2="10" style="stroke:red; stroke-width:10" />
    </pattern>
    <rect x="0" y="0" width="100%" height="100%" fill="url(#diagonalHatch)"/>
</svg>

A: Another approach is to create your stripes using a repeating linear gradient.

<svg width="300" height="300" viewBox="0 0 200 200">
  <defs>
    <linearGradient id="diagonalHatch" gradientUnits="userSpaceOnUse"
                    x2="30" spreadMethod="repeat" gradientTransform="rotate(-45)">
      <stop offset="0" stop-color="orange"/>
      <stop offset="0.33" stop-color="orange"/>
      <stop offset="0.33" stop-color="blue"/>
      <stop offset="0.67" stop-color="blue"/>
      <stop offset="0.67" stop-color="red"/>
      <stop offset="1.0" stop-color="red"/>
    </linearGradient>
  </defs>
  <rect x="0" y="0" width="100%" height="100%" fill="url(#diagonalHatch)"/>
</svg>


text:
Q: geofence android not work with me I'm working now with coding project that requires me to use GEOFENCE feature that provided by google map on android, which is in general, give you a notification when you become inside the specific region and this is done by tracking your movement with google map.
Generally, to make this code work you need to identify locations(latitude, longitude)and radious(region).
I tried to implement this code by following one of the resources available on the internet that guide me on how to do it by using Google API.And after I finish writing the code no errors appears but, no notification I receive!
I don't now what's the problem ! is itin the code, with the setting of the phone, or the way that I test the code is not correct.!!!!!!
The link that I took code from is:https://classroom.udacity.com/courses/ud876-1/lessons/3976758718/concepts/43294700190923
The code is:
mainactivity.java:
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;

import java.util.ArrayList;
import java.util.Map;

public class MainActivity extends ActionBarActivity implements
    GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, ResultCallback<Status> {

//array list of gepfence location
protected ArrayList<Geofence> mGeofenceList;

protected GoogleApiClient mGoogleApiClient;
private Button mAddGeofencesButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mAddGeofencesButton = (Button) findViewById(R.id.add_geofences_button);
    // Empty list for storing geofences.
    mGeofenceList = new ArrayList<Geofence>();

    // Get the geofences used. Geofence data is hard coded in this sample.
    populateGeofenceList();

    // Kick off the request to build GoogleApiClient.
    buildGoogleApiClient();
}

public void onResult(Status status) {
    if (status.isSuccess()) {
        Toast.makeText(
                this,
                "Geofences Added",
                Toast.LENGTH_SHORT
        ).show();
    } else {
        // Get the status code for the error and log it using a user-friendly message.
        String errorMessage = GeofenceErrorMessages.getErrorString(this,
                status.getStatusCode());
    }
}

private PendingIntent getGeofencePendingIntent() {
    Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling addgeoFences()
    return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

//هذي البتوون اللي راح تكون في الانترفيس وراح تشغل شغلنا كله اللي سويناه فا لوتلاحظبن فيها استدعائات للفنكشن المهمه والرئيسيه
public void addGeofencesButtonHandler(View view) {
    if (!mGoogleApiClient.isConnected()) {
        Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
        return;
    }

    try {
        LocationServices.GeofencingApi.addGeofences(
                mGoogleApiClient,
                // The GeofenceRequest object.
                getGeofencingRequest(),
                // A pending intent that that is reused when calling removeGeofences(). This
                // pending intent is used to generate an intent when a matched geofence
                // transition is observed.
                getGeofencePendingIntent()
        ).setResultCallback(this); // Result processed in onResult().
    } catch (SecurityException securityException) {
        // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
    }
}

public void populateGeofenceList() {
    //this fun do:1-read hashmap from constant class
    // 2-create geofence obj and add them to array list
    for (Map.Entry<String, LatLng> entry : Constants.BAY_AREA_LANDMARKS.entrySet()) {
        //for each entry on hashmap I will abstrct it as "Entry:var and the code will deal with it
        //Entery used to bring lat and long

        mGeofenceList.add(new Geofence.Builder()//انشانا اوبجيكت من الجيوفينس بيلدر واسندناه لل لليست
                // Set the request ID of the geofence. This is a string to identify this
                // geofence.
                .setRequestId(entry.getKey())

                // Set the circular region of this geofence.
                .setCircularRegion(
                        entry.getValue().latitude,
                        entry.getValue().longitude,
                        Constants.GEOFENCE_RADIUS_IN_METERS
                )

                // Set the expiration duration of the geofence. This geofence gets automatically
                // removed after this period of time.
                .setExpirationDuration(Geofence.NEVER_EXPIRE)

                // Set the transition types of interest. Alerts are only generated for these
                // transition. We track entry and exit transitions in this sample.
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
                        Geofence.GEOFENCE_TRANSITION_EXIT)

                // Create the geofence.
                .build());//بعد ما انشاءت اوبجيكت من الجيوفينس بيلدر واسندت له كل القيم اللي حتاجها لوت لونج راديوس والاكبايريشن راح اسوي لها بيلد يعني راج انشاءها وبعدين راح تتخزن في ام جيوفينس ليست
        //mGeofenceList الحين تحمل كل الاماكن اللي ابي يكون عليها جيوفينس

    }
}

/**
 * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the LocationServices API.
 */
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
///////////////////////////menu////////////////

@Override
protected void onStart() {
    super.onStart();
    if (!mGoogleApiClient.isConnecting() || !mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }
}

@Override
protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnecting() || mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

/**
 * Runs when a GoogleApiClient object successfully connects.
 */
@Override
public void onConnected(Bundle connectionHint) {

}

@Override
public void onConnectionFailed(ConnectionResult result) {
    // Do something with result.getErrorCode());
}

@Override
public void onConnectionSuspended(int cause) {
    mGoogleApiClient.connect();
}

private GeofencingRequest getGeofencingRequest() {
    //انشاءت اوبجيكت من نوع جيوفينس ريكويست
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    //راح اخزن بالاولجيكت  وش التريقر اللي يخلي الجيو فينس او النتوفيكيشن يشتغل :انا حطيته انه لما يدخل منطه الجغرافيه الجيوفينس
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
    //خرنت في الاوبجيكت ايش اللوكيشن اللي يسوي عليها مونتير في حال لو دخل الجيوفينس حقها
    builder.addGeofences(mGeofenceList);
    //جسويت بيلد لل اوبجيكت واسندرت في قيمه اللي فوقه ومررتها للجيوفينس ريقويست
    return builder.build();
}

private void test_sendNotification(String notificationDetails) {
    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    // Construct a task stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Add the main Activity to the task stack as the parent.
    stackBuilder.addParentStack(MainActivity.class);

    // Push the content Intent onto the stack.
    stackBuilder.addNextIntent(notificationIntent);

    // Get a PendingIntent containing the entire back stack.
    PendingIntent notificationPendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    // Define the notification settings.
   // builder.setSmallIcon(R.drawable.ic_launcher)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
           // .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                   // R.drawable.ic_launcher))
    builder.setColor(Color.RED)
            .setContentTitle(notificationDetails)
            .setContentText(getString(R.string.geofence_transition_notification_text))
            .setContentIntent(notificationPendingIntent);

    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Issue the notification
    mNotificationManager.notify(0, builder.build());
}
}

2.GeofenceTransitionsIntentService.java
package com.example.ranaali.geofence3;

import android.annotation.SuppressLint;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.text.TextUtils;
import android.util.Log;

import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;

import java.util.ArrayList;
import java.util.List;

public class GeofenceTransitionsIntentService extends IntentService {

    protected static final String TAG = "geofence-transitions-service";
//كونستركتور
    public GeofenceTransitionsIntentService() {
        // Use the TAG to name the worker thread.
        super(TAG);
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
    }
////هذي عباره عن تهيئه الاايفينت ومعناها الحالات اللي ممكن استقبلها مع الجيوفنس.يعني الحين انا سويت هيكله الايفنت وبعدين راح احدد نوع الايفنت
//اللي راح يتعامل معها الكود... واحنا راح نتعامل مع تو ايفينت لما يدخل الجيو فينس ولما يطلع منه
 //راح اخذ الجيوفينس داتا من الانتيت intentاللي تم تمريرها على السيرفس
    @SuppressLint("LongLogTag")
    @Override
    protected void onHandleIntent(Intent intent) {
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        //لو حدث مشكله لجلب الجيوفينس ايفنت الكود اللي تحت راح يشتغل عشان يطلع له ايررور مسج
        if (geofencingEvent.hasError()) {
            String errorMessage = GeofenceErrorMessages.getErrorString(this,
                    geofencingEvent.getErrorCode());
            Log.e(TAG, errorMessage);

            return;
        }

        // Get the transition type.راح نتعامل مع تو ترانزيشن اكزت و انتر لما يدخل الجيو فينس راح يكون له بلوك اوف كود ولما يطلع منه الجيو فينس راح يكون فيه بلوك اوف كود يتعامل معه ايضا
        int geofenceTransition = geofencingEvent.getGeofenceTransition();

        // Test that the reported transition was of interest.

        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
                geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

            // Get the geofences that were triggered. A single event can trigger multiple geofences.
            //عباره عن ليست راح تحمل اي مكان راح يكون عنده تريقر يعني مثلا لو انا بالسياره وفيه مكانين دخلت الجيوفينس حقهم راح تتخزن بارري..
            // استخدمت الارري عشان لو صار في تريقر على اكثر من مكان لان احنا راح نتعامل مع اكثر من مكان
            List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

            // Get the transition details as a String.
            //
            // ئبعدين راح اخذ ليسته وامررها على الفنكشن اللي تحتي على طول+راح امرر التريقرس وهي اللي راح تكون يا دخول او خروج من الجيوفينس
            //وبعدين النتواتج النهائيه من هالفنكشن راح تخزن في فار من نوع سترينج اسمه geofenceTransitionDetails
            String geofenceTransitionDetails = getGeofenceTransitionDetails(
                    this,
                    geofenceTransition,
                    triggeringGeofences
            );

            // Send notification and log the transition details.هنا الفنكشن المتعلقه بالنتوفكيشن اللي يطلع لليوزر لما يدخل او يطلع
            sendNotification(geofenceTransitionDetails);
            Log.i(TAG, geofenceTransitionDetails);
        } else {
            // Log the error.
            Log.e(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition));
        }
    }

    private String getGeofenceTransitionDetails(
            Context context,
            int geofenceTransition,
            List<Geofence> triggeringGeofences) {
        //مررت نوع الترنزيشن لهذا الفاريبل
        String geofenceTransitionString = getTransitionString(geofenceTransition);
         //غرضي من هذي الفنكشن انه اجمع كل الاماكن الي ابي يصير لها جيوفرينس واقوله في حال جاء مثلا مكانين مع بعض في نفس النطاق اجمعهم كلهم لي في ون نوتفيكيشن بدال ماكل واحد له رساله
        //وهذا تم تنفيذه عن طريق اني جمعت كل الليست بصيفه سترنينج
        // Get the Ids of each geofence that was triggered.
        ArrayList triggeringGeofencesIdsList = new ArrayList();
        for (Geofence geofence : triggeringGeofences) {
            triggeringGeofencesIdsList.add(geofence.getRequestId());
        }
        String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);
        //فا راح ارجمع نوع الترانزيشن هل هي اكزت او انترنس ومجموعه الاماكن اللي طلع منها او دخل عليها كصيغه اي دي وهو راح يكون اسم المكان
        return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
    }

    private String getTransitionString(int transitionType) {
        switch (transitionType) {
            case Geofence.GEOFENCE_TRANSITION_ENTER:
                return getString(R.string.geofence_transition_entered);
            case Geofence.GEOFENCE_TRANSITION_EXIT:
                return getString(R.string.geofence_transition_exited);
            default:
                return getString(R.string.unknown_geofence_transition);
        }
    }

    private void sendNotification(String notificationDetails) {
        // Create an explicit content Intent that starts the main Activity.
        Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

        // Construct a task stack.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

        // Add the main Activity to the task stack as the parent.
        stackBuilder.addParentStack(MainActivity.class);

        // Push the content Intent onto the stack.
        stackBuilder.addNextIntent(notificationIntent);

        // Get a PendingIntent containing the entire back stack.
        PendingIntent notificationPendingIntent =
                stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        // Get a notification builder that's compatible with platform versions >= 4
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

        // Define the notification settings.
       // builder.setSmallIcon(R.drawable.ic_launcher)
                // In a real app, you may want to use a library like Volley
                // to decode the Bitmap.
                //.setLargeIcon(BitmapFactory.decodeResource(getResources(),
                       // R.drawable.ic_launcher))
        builder.setColor(Color.RED)
                /////////////////////////////////////////////////////////////////////هنا فقط اللي يهمني لو تلاحظين اخذت الفاريبل نوتيفيكشن ديتيلس وخليتها التايتل اللي يطلع للشخص لما تنعرض له التنوفيكيشن مسج//////////////////////
                .setContentTitle(notificationDetails)
                .setContentText(getString(R.string.geofence_transition_notification_text))
                .setContentIntent(notificationPendingIntent);
        /////////////////////////////////////////////////////////////////////هنا فقط اللي يهمني//////////////////////

        // Dismiss notification once the user touches it.
        builder.setAutoCancel(true);

        // Get an instance of the Notification manager
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Issue the notification
        mNotificationManager.notify(0, builder.build());
    }

}

3.GeofenceErrorMessages.java
package com.example.ranaali.geofence3;

import android.content.Context;
import android.content.res.Resources;
import com.google.android.gms.location.GeofenceStatusCodes;

public class GeofenceErrorMessages {

private GeofenceErrorMessages() {}

/**
 * Returns the error string for a geofencing error code.
 */
public static String getErrorString(Context context, int errorCode) {
    Resources mResources = context.getResources();
    switch (errorCode) {
        case GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE:
            return "geofence servisce not avilable";
        case GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES:
            return "your app has registerd too many geofencses";
        case GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS:
            return "geofence too many pending intents";
        default:
            return "unknown error:the geofence service is not avilable now";
    }
}
 }

4.Constants.java
package com.example.ranaali.geofence3;

import com.google.android.gms.maps.model.LatLng;

import java.util.HashMap;

public final class Constants {

private Constants() {
}

public static final String PACKAGE_NAME = "com.google.android.gms.location.Geofence";

public static final String SHARED_PREFERENCES_NAME = PACKAGE_NAME + ".SHARED_PREFERENCES_NAME";

public static final String GEOFENCES_ADDED_KEY = PACKAGE_NAME + ".GEOFENCES_ADDED_KEY";

/**
 * Used to set an expiration time for a geofence. After this amount of time Location Services
 * stops tracking the geofence.
 */
public static final long GEOFENCE_EXPIRATION_IN_HOURS = 24;

/**
 * For this sample, geofences expire after twelve hours.
 */
public static final long GEOFENCE_EXPIRATION_IN_MILLISECONDS =
        GEOFENCE_EXPIRATION_IN_HOURS * 60 * 60 * 1000;
//public static final float GEOFENCE_RADIUS_IN_METERS = 1609; // 1 mile, 1.6 km
public static final float GEOFENCE_RADIUS_IN_METERS = 1609; // 1 mile, 1.6 km

/**
 * Map for storing information about airports in the San Francisco bay area.
 */
public static final HashMap<String, LatLng> BAY_AREA_LANDMARKS = new HashMap<String, LatLng>();
static {
    // San Francisco International Airport.
    BAY_AREA_LANDMARKS.put("My home", new LatLng(  24.764171, 46.722942));

    // Googleplex.
    BAY_AREA_LANDMARKS.put("aljwadah school", new LatLng( 24.7657308,46.7242295));

}

}

5.build.gradle
apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "com.example.ranaali.geofence3"
    minSdkVersion 17
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}

}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.0'
testCompile 'junit:junit:4.12'

compile 'com.google.android.gms:play-services:10.2.0'
compile 'com.google.android.gms:play-services-location:7.8.0'
compile 'com.google.android.gms:play-services-location:10.2.0'
}

6.AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>

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

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

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>
</application>

A: There are 2 things that need to be fixed:

*

*In your Manifest, you must declare your Service (GeofenceTransitionsIntentService). This is why your geofences are not working.

*In your build.gradle file, of these three dependencies, you only need one.
com.google.android.gms:play-services:10.2.0
com.google.android.gms:play-services-location:7.8.0
com.google.android.gms:play-services-location:10.2.0 <-- Keep this one


text:
Q: Unchecked Overriding when defining a base mapper for mybatis? I'm trying to define a base mapper interface for MyBatis. I've tried this:
public interface IMapper<T> {
    <T> T select(int id);
}

public interface FooMapper extends IMapper<Foo>{
    @Override
    @Select("SELECT * FROM foos WHERE id = {#id}")
    Foo select(int id);
}

But I'm getting Unchecked Overriding warnings from IntelliJ. Should I disable them, or am I really doing something wrong?

A: Remove the extra <T> on the select method so it is:
interface IMapper<T> {
    T select(int id);
}


text:
Q: Wordpress website with membership subscription, multi vendor product selling and Show content only subscriber users i m new to wordpress. i need to create wordpress website with following functionlity.

*

*Membership subscription with role and payment (one time/ recurring).

*Three type of role (Admin,Provider,Enduser)

Functionality:
 1. Both provider and enduser need to register with payment. After registration admin should approve the registration then only they can able to login.
 2. Provider can able to submit their content, video. (Subscribed enduser only able to see this)
 3. Provider can submit their product to the website with payment. Admin should approve the product then only it should be listed in the shop page.
 4. Enduser wants to buy any product they can choose and checkout with online payment.
 5. Providers able to view their product sales details in their dashboard.
 6. Providers are able to put their live webinars in the website and track audiance count
Above are the major functionalities. Now my problem is what are all the plugins i needs to use for this functionalities. Because Most of the membership plugins not supporting the multi-vendor product selling. If its support multi-vendor then its not support upload content, video and content protection.
Please any one guide me to choose a plugins for this requirement.
Thanks in advance
Obuliraj Chandran


text:
Q: How to add HTTP proxy to JAX-WS? I have a WSDL file which I've turned into Java code by using WSDL2Java inside SoapUI, it works fine, but now I need to add my company's proxy to it, so every SOAP http request would go through it (but not other http requests).
I've looked through multiple threads concerning the same issue and found these options:

*

*system wide proxy by adding
System.getProperties().put("proxySet", "true");
System.getProperties().put("https.proxyHost", "10.10.10.10");
System.getProperties().put("https.proxyPort", "8080");

which doesn't work for me, since it affect the whole jvm.

*adding the following code
HelloService hello = new HelloService();
HelloPortType helloPort = cliente.getHelloPort();
org.apache.cxf.endpoint.Client client = ClientProxy.getClient(helloPort);
HTTPConduit http = (HTTPConduit) client.getConduit();
http.getClient().setProxyServer("proxy");
http.getClient().setProxyServerPort(8080);
http.getProxyAuthorization().setUserName("user proxy");
http.getProxyAuthorization().setPassword("password proxy");

which I don't get how to use. My generated code doesn't have any traces of org.apache.cxf, only javax.xml.ws.

*Adding this to my port configuration:
((BindingProvider) port).getRequestContext().put("http.proxyHost", "proxy@example.com");
((BindingProvider) port).getRequestContext().put("http.proxyPort", "80");

Here I use a random non-existing proxy and expect to get an error of any sort(timeout, invalid proxy, etc.), but instead it goes through without any errors.

A: Here is an example without using 3rd party libraries.

https://github.com/schuch/jaxws-proxy-example/blob/master/jaxws-client-with-proxy/src/main/java/ch/schu/example/helloworld/Client.java

package ch.schu.example.helloworld;

import java.net.ProxySelector;

import ch.schu.example.hello.HelloImpl;
import ch.schu.example.hello.HelloImplService;

public class Client {

    public static void main(String[] args) {

        ProxySelector.setDefault(new MyProxySelector());

        HelloImplService service = new HelloImplService();
        HelloImpl hello = service.getHelloImplPort();
        System.out.println(hello.sayHello("Howard Wollowitz"));
    }

}

https://github.com/schuch/jaxws-proxy-example/blob/master/jaxws-client-with-proxy/src/main/java/ch/schu/example/helloworld/MyProxySelector.java

package ch.schu.example.helloworld;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.*;
import java.util.*;

public class MyProxySelector extends ProxySelector {

    @Override
    public List<Proxy> select(URI uri)
    {
        System.out.println("select for " + uri.toString());
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 9999));
        ArrayList<Proxy> list = new ArrayList<Proxy>();
        list.add(proxy);
        return list;
    }

    @Override
    public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        System.err.println("Connection to " + uri + " failed.");
    }
}


text:
Q: Creating an rpm package that untars a file I would like to create a rpm package that does the following:
When setup:

*

*copies a script across into the rpm

*untars a file into the rpm
When run:

*

*runs script.sh

*runs install file that is extracted into the rpm
When the user runs the rpm it should execute 2 and 3 because the files already exist in the rpm.
I know how to do the setup stuff, the *.spec file is:
%description
# lets skip this for now

%prep
# lets skip this for now

%build
# lets skip this for now

%install
cd ${RPM_BUILD_ROOT}
cp -v /home/methuselah/script.sh ${RPM_BUILD_ROOT}
tar xvpf /home/methuselah/bin.tar
chmod 775 -R ${RPM_BUILD_ROOT}/*

%files
/*

%changelog
* Tue Jan 28 2014 Pavel Šimerda  - 3.0.9-14
- Resolves: #1052814 - rsync command is terminated with SIGSEGV
- Resolves: #1052814 - add missing patch file

I'm not sure where to put the actual installation steps that run when the rpm is executed.

A: the %install section is there to install the files during the rpm build process in the rpm build root. This part is not run during installation on the target machine. That is the confusing part of spec files.
During the building of the rpm (in this order):

*

*%prep

*%build

*%install

*%check

during the installation of the rpm (in this order):

*

*%pre

*(real installation: files from %files section are installed)

*%post

NOTE: this page on the full rpm scripts order
some more remarks:

*

*two rpms cannot own the same file/folder, so make sure you don't package /home, /usr or something like that (when specifying /* under %files you are packaging the whole tree)

*don't package files in the /home directory of a user. Packages are installed system-wide, so package only files in generic directories like /etc , /usr, ...

A: Maybe you want to put your files (script.sh and bin.tar) under the "%files" section and leave all installation with %install.
Take a look here and maybe here for more information.

I'm not sure where to put the actual installation steps that run when the rpm is executed.

I think this link can help you.


text:
Q: Контент вылезает за пределы резинового div Есть 4 резиновых div. Расположены они по такой схеме:
┌────┬────┬────┐
│ w1 │ w2 │ w3 │
├────┴────┴────┤
│      w4      │
└──────────────┘

Вот код:

div {
  height: 50%;
  width: 33.3%;
}

div div {
  overflow-y: visible;
  max-height: 100%;
}

#w1 {
  position: absolute;
  top: 0;
  left: 0;
}

#w2 {
  position: absolute;
  top: 0;
  left: 33.3%;
}

#w3 {
  position: absolute;
  top: 0;
  left: 66.5%;
}

#w4 {
  position: absolute;
  top: 50%;
  left: 0;
  width: 100% !important;
}

sometext<input type="text">

sometext<input type="text">

sometext<input type="text">

Javascript периодически получает данные с сервера с помощью AJAX и добавляет их в #content1, #content2 и #content3.
Проблема в том, что в #w1 #w2 #w3 не должно быть скроллбаров, так как они уже есть в их content, но content расширяются и вытесняют sometext за пределы div. Поставить max-height: 80% нельзя, так как content при расширении должен прислонить sometext к границе и активировать скроллбар. В моём варианте расширение останавливается когда content достигает границы сам.

A: Вопроса нету. Что сделать нужно ?
Если Вы хотите прижать блок с инпутом вниз, Вам нужно сделать padding-bottom: 50px у #w1, #w2, #w3, и потом на input[type="text"] сделать position: absolute; bottom: 0px; Тогда Вы его поместите в заранее зарезервированное место и он будет там. Это если говорить о текущей структуре которую я вижу.
Но скорее всего, я не правильно понимаю Ваш вопрос. Покажите на картинке.


text:
Q: using secret strings inside pwsh command I'm trying to run some commands using pwsh command as below:
$securePassword = "sdfd-334-sdfd-23fd" | ConvertTo-SecureString -AsPlainText -Force;
$ApplicationId ="sdfd-wef-dfdf-23dsd";
$Tenant = "sdfjkd-dfdsf-32r3-dfd";

pwsh -c Connect-DataGatewayServiceAccount -ApplicationId $ApplicationId -ClientSecret $securePassword -Tenant $Tenant

However, I get this error when I run the above script in powershell
PS C:\Windows\System32> powershell .\datagw.ps1
Connecting to DataGateway
Connect-DataGatewayServiceAccount: Cannot bind parameter 'ClientSecret'.
Cannot convert the "System.Security.SecureString" value of type "System.String" to type "System.Security.SecureString".

For some reason the params passed to -c option are treated as System.String instead of System.Security.SecureString.
How can I pass securePassword as value of type System.Security.SecureString?


text:
Q: What are the options for storing hierarchical data in a relational database? Good Overviews
Generally speaking, you're making a decision between fast read times (for example, nested set) or fast write times (adjacency list). Usually, you end up with a combination of the options below that best fit your needs. The following provides some in-depth reading:

*

*One more Nested Intervals vs. Adjacency List comparison: the best comparison of Adjacency List, Materialized Path, Nested Set, and Nested Interval I've found.

*Models for hierarchical data: slides with good explanations of tradeoffs and example usage

*Representing hierarchies in MySQL: very good overview of Nested Set in particular

*Hierarchical data in RDBMSs: a most comprehensive and well-organized set of links I've seen, but not much in the way of explanation

Options
Ones I am aware of and general features:

*

*Adjacency List:

*

*Columns: ID, ParentID

*Easy to implement.

*Cheap node moves, inserts, and deletes.

*Expensive to find the level, ancestry & descendants, path

*Avoid N+1 via Common Table Expressions in databases that support them

*Nested Set (a.k.a Modified Preorder Tree Traversal)

*

*Columns: Left, Right

*Cheap ancestry, descendants

*Very expensive O(n/2) moves, inserts, deletes due to volatile encoding

*Bridge Table (a.k.a. Closure Table /w triggers)

*

*Uses separate join table with ancestor, descendant, depth (optional)

*Cheap ancestry and descendants

*Writes costs O(log n) (size of the subtree) for insert, updates, deletes

*Normalized encoding: good for RDBMS statistics & query planner in joins

*Requires multiple rows per node

*Lineage Column (a.k.a. Materialized Path, Path Enumeration)

*

*Column: lineage (e.g. /parent/child/grandchild/etc...)

*Cheap descendants via prefix query (e.g. LEFT(lineage, #) = '/enumerated/path')

*Writes costs O(log n) (size of the subtree) for insert, updates, deletes

*Non-relational: relies on Array datatype or serialized string format

*Nested Intervals

*

*Like nested set, but with real/float/decimal so that the encoding isn't volatile (inexpensive move/insert/delete)

*Has real/float/decimal representation/precision issues

*Matrix encoding variant adds ancestor encoding (materialized path) for "free", but with the added trickiness of linear algebra.

*Flat Table

*

*A modified Adjacency List that adds a Level and Rank (e.g. ordering) column to each record.

*Cheap to iterate/paginate over

*Expensive move and delete

*Good Use: threaded discussion - forums / blog comments

*Multiple lineage columns

*

*Columns: one for each lineage level, refers to all the parents up to the root, levels down from the item's level are set to NULL

*Cheap ancestors, descendants, level

*Cheap insert, delete, move of the leaves

*Expensive insert, delete, move of the internal nodes

*Hard limit to how deep the hierarchy can be

Database Specific Notes
MySQL

*

*Use session variables for Adjacency List
Oracle

*

*Use CONNECT BY to traverse Adjacency Lists

PostgreSQL

*

*ltree datatype for Materialized Path

SQL Server

*

*General summary

*2008 offers HierarchyId data type that appears to help with the Lineage Column approach and expand the depth that can be represented.

A: My favorite answer is as what the first sentence in this thread suggested.  Use an Adjacency List to maintain the hierarchy and use Nested Sets to query the hierarchy.
The problem up until now has been that the coversion method from an Adjacecy List to Nested Sets has been frightfully slow because most people use the extreme RBAR method known as a "Push Stack" to do the conversion and has been considered to be way to expensive to reach the Nirvana of the simplicity of maintenance by the Adjacency List and the awesome performance of Nested Sets.  As a result, most people end up having to settle for one or the other especially if there are more than, say, a lousy 100,000 nodes or so.  Using the push stack method can take a whole day to do the conversion on what MLM'ers would consider to be a small million node hierarchy.
I thought I'd give Celko a bit of competition by coming up with a method to convert an Adjacency List to Nested sets at speeds that just seem impossible. Here's the performance of the push stack method on my i5 laptop.
Duration for     1,000 Nodes = 00:00:00:870
Duration for    10,000 Nodes = 00:01:01:783 (70 times slower instead of just 10)
Duration for   100,000 Nodes = 00:49:59:730 (3,446 times slower instead of just 100)
Duration for 1,000,000 Nodes = 'Didn't even try this'

And here's the duration for the new method (with the push stack method in parenthesis).
Duration for     1,000 Nodes = 00:00:00:053 (compared to 00:00:00:870)
Duration for    10,000 Nodes = 00:00:00:323 (compared to 00:01:01:783)
Duration for   100,000 Nodes = 00:00:03:867 (compared to 00:49:59:730)
Duration for 1,000,000 Nodes = 00:00:54:283 (compared to something like 2 days!!!)

Yes, that's correct.  1 million nodes converted in less than a minute and 100,000 nodes in under 4 seconds.
You can read about the new method and get a copy of the code at the following URL.
http://www.sqlservercentral.com/articles/Hierarchy/94040/
I also developed a "pre-aggregated" hierarchy using similar methods.  MLM'ers and people making bills of materials will be particularly interested in this article.
http://www.sqlservercentral.com/articles/T-SQL/94570/
If you do stop by to take a look at either article, jump into the "Join the discussion" link and let me know what you think.

A: I am using PostgreSQL with closure tables for my hierarchies.
I have one universal stored procedure for the whole database:
CREATE FUNCTION nomen_tree() RETURNS trigger
    LANGUAGE plpgsql
    AS $_$
DECLARE
  old_parent INTEGER;
  new_parent INTEGER;
  id_nom INTEGER;
  txt_name TEXT;
BEGIN
-- TG_ARGV[0] = name of table with entities with PARENT-CHILD relationships (TBL_ORIG)
-- TG_ARGV[1] = name of helper table with ANCESTOR, CHILD, DEPTH information (TBL_TREE)
-- TG_ARGV[2] = name of the field in TBL_ORIG which is used for the PARENT-CHILD relationship (FLD_PARENT)
    IF TG_OP = 'INSERT' THEN
    EXECUTE 'INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth)
        SELECT $1.id,$1.id,0 UNION ALL
      SELECT $1.id,ancestor_id,depth+1 FROM ' || TG_ARGV[1] || ' WHERE child_id=$1.' || TG_ARGV[2] USING NEW;
    ELSE
    -- EXECUTE does not support conditional statements inside
    EXECUTE 'SELECT $1.' || TG_ARGV[2] || ',$2.' || TG_ARGV[2] INTO old_parent,new_parent USING OLD,NEW;
    IF COALESCE(old_parent,0) <> COALESCE(new_parent,0) THEN
      EXECUTE '
      -- prevent cycles in the tree
      UPDATE ' || TG_ARGV[0] || ' SET ' || TG_ARGV[2] || ' = $1.' || TG_ARGV[2]
        || ' WHERE id=$2.' || TG_ARGV[2] || ' AND EXISTS(SELECT 1 FROM '
        || TG_ARGV[1] || ' WHERE child_id=$2.' || TG_ARGV[2] || ' AND ancestor_id=$2.id);
      -- first remove edges between all old parents of node and its descendants
      DELETE FROM ' || TG_ARGV[1] || ' WHERE child_id IN
        (SELECT child_id FROM ' || TG_ARGV[1] || ' WHERE ancestor_id = $1.id)
        AND ancestor_id IN
        (SELECT ancestor_id FROM ' || TG_ARGV[1] || ' WHERE child_id = $1.id AND ancestor_id <> $1.id);
      -- then add edges for all new parents ...
      INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth)
        SELECT child_id,ancestor_id,d_c+d_a FROM
        (SELECT child_id,depth AS d_c FROM ' || TG_ARGV[1] || ' WHERE ancestor_id=$2.id) AS child
        CROSS JOIN
        (SELECT ancestor_id,depth+1 AS d_a FROM ' || TG_ARGV[1] || ' WHERE child_id=$2.'
        || TG_ARGV[2] || ') AS parent;' USING OLD, NEW;
    END IF;
  END IF;
  RETURN NULL;
END;
$_$;

Then for each table where I have a hierarchy, I create a trigger
CREATE TRIGGER nomenclature_tree_tr AFTER INSERT OR UPDATE ON nomenclature FOR EACH ROW EXECUTE PROCEDURE nomen_tree('my_db.nomenclature', 'my_db.nom_helper', 'parent_id');

For populating a closure table from existing hierarchy I use this stored procedure:
CREATE FUNCTION rebuild_tree(tbl_base text, tbl_closure text, fld_parent text) RETURNS void
    LANGUAGE plpgsql
    AS $$
BEGIN
    EXECUTE 'TRUNCATE ' || tbl_closure || ';
    INSERT INTO ' || tbl_closure || ' (child_id,ancestor_id,depth)
        WITH RECURSIVE tree AS
      (
        SELECT id AS child_id,id AS ancestor_id,0 AS depth FROM ' || tbl_base || '
        UNION ALL
        SELECT t.id,ancestor_id,depth+1 FROM ' || tbl_base || ' AS t
        JOIN tree ON child_id = ' || fld_parent || '
      )
      SELECT * FROM tree;';
END;
$$;

Closure tables are defined with 3 columns - ANCESTOR_ID, DESCENDANT_ID, DEPTH. It is possible (and I even advice) to store records with same value for ANCESTOR and DESCENDANT, and a value of zero for DEPTH. This will simplify the queries for retrieval of the hierarchy. And they are very simple indeed:
-- get all descendants
SELECT tbl_orig.*,depth FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth <> 0;
-- get only direct descendants
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth = 1;
-- get all ancestors
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON ancestor_id = tbl_orig.id WHERE descendant_id = XXX AND depth <> 0;
-- find the deepest level of children
SELECT MAX(depth) FROM tbl_closure WHERE ancestor_id = XXX;

A: Adjacency Model + Nested Sets Model
I went for it because I could insert new items to the tree easily (you just need a branch's id to insert a new item to it) and also query it quite fast.
+-------------+----------------------+--------+-----+-----+
| category_id | name                 | parent | lft | rgt |
+-------------+----------------------+--------+-----+-----+
|           1 | ELECTRONICS          |   NULL |   1 |  20 |
|           2 | TELEVISIONS          |      1 |   2 |   9 |
|           3 | TUBE                 |      2 |   3 |   4 |
|           4 | LCD                  |      2 |   5 |   6 |
|           5 | PLASMA               |      2 |   7 |   8 |
|           6 | PORTABLE ELECTRONICS |      1 |  10 |  19 |
|           7 | MP3 PLAYERS          |      6 |  11 |  14 |
|           8 | FLASH                |      7 |  12 |  13 |
|           9 | CD PLAYERS           |      6 |  15 |  16 |
|          10 | 2 WAY RADIOS         |      6 |  17 |  18 |
+-------------+----------------------+--------+-----+-----+

*

*Every time you need all children of any parent you just query the parent column.

*If you needed all descendants of any parent you query for items which have their lft between lft and rgt of parent.

*If you needed all parents of any node up to the root of the tree, you query for items having lft lower than the node's lft and rgt bigger than the node's rgt and sort the by parent.

I needed to make accessing and querying the tree faster than inserts, that's why I chose this
The only problem is to fix the left and right columns when inserting new items. well I created a stored procedure for it and called it every time I inserted a new item which was rare in my case but it is really fast.
I got the idea from the Joe Celko's book, and the stored procedure and how I came up with it is explained here in DBA SE
https://dba.stackexchange.com/q/89051/41481

A: This design was not mentioned yet:
Multiple lineage columns
Though it has limitations, if you can bear them, it's very simple and very efficient. Features:

*

*Columns: one for each lineage level, refers to all the parents up to the root, levels below the current items' level are set to 0 (or NULL)

*There is a fixed limit to how deep the hierarchy can be

*Cheap ancestors, descendants, level

*Cheap insert, delete, move of the leaves

*Expensive insert, delete, move of the internal nodes

Here follows an example - taxonomic tree of birds so the hierarchy is Class/Order/Family/Genus/Species - species is the lowest level, 1 row = 1 taxon (which corresponds to species in the case of the leaf nodes):
CREATE TABLE `taxons` (
  `TaxonId` smallint(6) NOT NULL default '0',
  `ClassId` smallint(6) default NULL,
  `OrderId` smallint(6) default NULL,
  `FamilyId` smallint(6) default NULL,
  `GenusId` smallint(6) default NULL,
  `Name` varchar(150) NOT NULL default ''
);

and the example of the data:
+---------+---------+---------+----------+---------+-------------------------------+
| TaxonId | ClassId | OrderId | FamilyId | GenusId | Name                          |
+---------+---------+---------+----------+---------+-------------------------------+
|     254 |       0 |       0 |        0 |       0 | Aves                          |
|     255 |     254 |       0 |        0 |       0 | Gaviiformes                   |
|     256 |     254 |     255 |        0 |       0 | Gaviidae                      |
|     257 |     254 |     255 |      256 |       0 | Gavia                         |
|     258 |     254 |     255 |      256 |     257 | Gavia stellata                |
|     259 |     254 |     255 |      256 |     257 | Gavia arctica                 |
|     260 |     254 |     255 |      256 |     257 | Gavia immer                   |
|     261 |     254 |     255 |      256 |     257 | Gavia adamsii                 |
|     262 |     254 |       0 |        0 |       0 | Podicipediformes              |
|     263 |     254 |     262 |        0 |       0 | Podicipedidae                 |
|     264 |     254 |     262 |      263 |       0 | Tachybaptus                   |

This is great because this way you accomplish all the needed operations in a very easy way, as long as the internal categories don't change their level in the tree.

A: This is a very partial answer to your question, but I hope still useful.
Microsoft SQL Server 2008 implements two features that are extremely useful for managing hierarchical data:

*

*the HierarchyId data type.

*common table expressions, using the with keyword.

Have a look at "Model Your Data Hierarchies With SQL Server 2008" by Kent Tegels on MSDN for starts. See also my own question: Recursive same-table query in SQL Server 2008

A: If your database supports arrays, you can also implement a lineage column or materialized path as an array of parent ids.
Specifically with Postgres you can then use the set operators to query the hierarchy, and get excellent performance with GIN indices.  This makes finding parents, children, and depth pretty trivial in a single query.  Updates are pretty manageable as well.
I have a full write up of using arrays for materialized paths if you're curious.

A: This is really a square peg, round hole question.
If relational databases and SQL are the only hammer you have or are willing to use, then the answers that have been posted thus far are adequate. However, why not use a tool designed to handle hierarchical data? Graph database are ideal for complex hierarchical data.
The inefficiencies of the relational model along with the complexities of any code/query solution to map a graph/hierarchical model onto a relational model is just not worth the effort when compared to the ease with which a graph database solution can solve the same problem.
Consider a Bill of Materials as a common hierarchical data structure.
class Component extends Vertex {
    long assetId;
    long partNumber;
    long material;
    long amount;
};

class PartOf extends Edge {
};

class AdjacentTo extends Edge {
};

Shortest path between two sub-assemblies: Simple graph traversal algorithm. Acceptable paths can be qualified based on criteria.
Similarity: What is the degree of similarity between two assemblies? Perform a traversal on both sub-trees computing the intersection and union of the two sub-trees. The percent similar is the intersection divided by the union.
Transitive Closure: Walk the sub-tree and sum up the field(s) of interest, e.g. "How much aluminum is in a sub-assembly?"
Yes, you can solve the problem with SQL and a relational database. However, there are much better approaches if you are willing to use the right tool for the job.


text:
Q: get query string into js/jquery i hae a link like ( domain.com/jsapi?key=123456 )
hov can i get this "key" into my JS code? i use jQuery and i don't know about its are easy way to get this "key" into JS variable.
tanks for all.

A: This plugin might helps: jquery url parser
key = $.url.setUrl($(yourlink).attr('href')).param('key');
(not tested)

A: It's not jquery. It's pure javascript. You can use regexp.
str = "domain.com/jsapi?key=123456" # Take it from wherever you want
splitted = str.split(/\?key=([0-9]+)/)

Then you'll have an array in the "splitted" variable, it's second element (at the id 1) containing the value.

A: jQuery not needed. The query string is available from the DOM:
window.location.search.match(/key=([^&]*)/);

Which gives you an array that has your value in it.

A: You can use the URL constructor as follows:
let url = new URL('https://example.com/jsapi?key=123456');
console.log(url.searchParams.get('key')); // Outputs 123456

Using this method you can parse and get any part of a URL.
Important:

*

*Note that I've added the protocol (https://) to the sample URL so I make sure it is a valid URL and it can be parsed.

*Take into account the browser compatibility. You can check it here
For more details you can also the the specification.


text:
Q: How to integrate the following expression in multivariable calculus? Let we have a manifold $S$ of dimension $n$.and also let that $\xi^i$ and $\rho^s$ be two coordinate system for $S$ and suppose that $\frac{\partial^2\xi^k}{\partial\rho^r\partial\rho^s}=0$
My question is if I integrate this twice what do we get, Actually I am finding it difficult to do in $n$ dimension space.for example if we have a function $y=f(x)$ of $\mathbb{R}$ and suppose $\frac{dy}{dx}=0$ so if I integrate it then we will get $y=c(constant).$


text:
Q: AVAssetWriter fails when Application enters Background during Rendering In my app I am rendering a Video generated from images I retrieve from the users photos. I have set up an AVAssetwriter with a AVAssetwriterInput has an AVAssetWriterInputPixelBufferAdaptor. I'm able to transform the ALAsset objects I retrieve from the users library to CVPixelBuffers and add them to the Video, which then is saved as an mp4. Adding all the images to the video is done on a background thread which sends a Notification to the main thread every frame, so the interface can be updated. All this works well, and I get a usable Movie file out of the app.
My problem now is, that when the user enters another application, after becoming active again the status of the ALAssetWriter changes to "failed", an I am not able to add any more images to the movie file. First I thought I might have to end the current Session on the writer and reopen a new one, once the app has become active again, but that doesn't seem to help.
I was just wondering how the general approach would be when I'd like the user to enter other applications. The best solution would be, if the rendering could continue in the background. I suppose I'd need a background thread from the UIApplication. But for now I'd be happy, if rendering could just continue after resuming my app.
I won't post any code for now, because it's really a lot, and my question possibly is conceptual. If you need to see code, I'll post it.
Edit 1:
Tested on iOS 4.3 and iOS 5. I've seen background rendering on other apps such as iTimelapse, but I'm not sure which frameworks they use.
Edit2:
I now have the information of an apple devforum member, that AVAssetWriter does not work in the background. So is there any other framework out there capable of rendering quicktime videos?

A: Turns out that AVAssetWriter just won't survive the app being suspended. You can add an extra 10 Minutes of rendertime by requesting background time, but after that the AssetWriter fails. Same happens if you use certain services on the phone. For example making or answering a call will make the AVAssetWriter fail as well.

A: If there are any OpenGL calls made when your app is in the background then that would explain this behaviour, looks fairly likely. From the OpenGL ES Pragramming Guide

Background Applications May Not Execute Commands on the Graphics Hardware
An OpenGL ES application is terminated if it attempts to execute
  OpenGL ES commands on the graphics hardware. This not only refers to
  calls made to OpenGL ES while your application is in the background,
  but also refers to previously submitted commands that have not yet
  completed. The main reason for preventing background applications from
  processing OpenGL ES commands is to make the graphics processor
  completely available to the frontmost application. The frontmost
  application should always present a great experience to the user.
  Allowing background applications to hog the graphics processor might
  prevent that. Your application must ensure that all previously
  submitted commands have been finished prior to moving into the
  background.

The docs go on to enumerate a set of guidelines for the enter background/foreground app delegate callbacks. I think finding a way to do the rendering without the graphics hardware would be tricky, also the frameworks that allow mp4 encoding (like ffMpeg) are mainly GPL/LGPL, so you need to be careful if dealing with a commercial product (LGPL means you can link to the library dynamically, not statically, which is useless on iOS), as the license would propagate to your code.


text:
Q: How does a large number of various "installed apps" affect your PC and overall PC performance? I have recently gotten an "Adobe Creative Cloud" account. I am wanting to experiment with some of the apps, so I was thinking of downloading the entire set of apps for Creative Cloud and just start learning some, see what might, and might not benefit me as an IT guy.
I have a Windows 7 - 64 bit - Alienware MX17 that is about 2-3 years old. No issues with it ever, besides two times overheating/shutting down, where I had to send it to someone and have it cleaned, and thermal paste applied (twice in it's lifetime). Overall I get great performance, and no drag. I work and game on it "a lot".  I have 176 free out of 500, but a good bit of that are Comics.
Anyway, I installed Dreamweaver, Photoshop and a few others with no difference on performance. If I just go through and download them all, will it affect my overall performance when gaming or anything else, or does it not matter how much you have installed on it..as long as it's limited on what is running at a given time?  Thanks!

A: @Ramhound's comment really says it all.
Many large Windows applications (and some small ones) will install

*

*services

*scheduled tasks

*and things to run on system startup or login.

A common reason for these services is to allow the application to update itself, keep a system tray icon up, or even report on your usage of the application.  Having too many of these running can affect system performance.
CCleaner has a friendly interface to look at and disable programs that run on startup.
You can also check running services in Start Menu -> Control Panel -> Administrative Tools -> Services.
Sysinternals' Autoruns is more complex to use (and you must exercise caution because you can take out critical Windows components if you are not careful), but lets you look at everything that runs when your computer starts up - including services.
Be careful if you look at this - some run-on-startup programs and many services are needed for proper operation of your system so make sure you investigate things before disabling.
Some applications may install drivers or other software that hooks into various operating system functions or COM components.  Antivirus or firewall software is a prime example of this - if you have real-time scanning enabled, a component of your antivirus software is running every time a file operation is performed.  This obviously affects performance.


text:
Q: Two-dimensional generic array initialization I tried creating a two-dimensional generic array in java. I get no compile errors, but I get an exception when running the code:
Exception in thread "main" java.lang.ClassCastException: Cannot cast [[[Ljava.lang.String; to [[Ljava.lang.String;
at java.lang.Class.cast(Unknown Source)
at Tabela.<init>(Tabela.java:8)
at TabelaTest.main(TabelaTest.java:4)

Here is the code:
import java.lang.reflect.Array;

public class Tabela<T> {

    private T[][] data;

    public Tabela(Class<T[][]> c,int sizeX, int sizeY) {
        this.data = c.cast(Array.newInstance(c.getComponentType(), sizeX, sizeY));
    }

    public void setInfoAt(T info, int x, int y) {
        this.data[x][y] = info;
    }
    public T getObjectAt(int x, int y) {
        return this.data[x][y];
    }
}

public class TabelaTest {

    public static void main(String args[]) {
        Tabela<String> tabela = new Tabela<String>(String[][].class, 2, 2);

        tabela.setInfoAt("a", 0, 0);
        tabela.setInfoAt("b", 0, 1);
        tabela.setInfoAt("c", 1, 0);
        tabela.setInfoAt("d", 1, 1);

        System.out.println(tabela.getObjectAt(1, 0));
    }
}

It looks like I can't use this method for two dimensional arrays.
EDIT:
Using the method from unholysampler it works now.
The constructor was changed to:
public Tabela(Class<T> c,int sizeX, int sizeY) {
    this.data = (T[][])Array.newInstance(c, sizeX, sizeY);
}

The thing is that eclipse keeps warning me about this cast (T[][]). I can supress it, but is it ok to ignore?

A: If you look at the error message, you will see that the number of square brackets differ.
Cannot cast [[[Ljava.lang.String; to [[Ljava.lang.String;
            ---                      --

You are ending up with the extra array level because of how you are calling Array.newInstance(). If you wanted to just create a String array, you would use:
String[] arr = (String[])Array.newInstance(String.class, 5);

Notice that you pass in the base class type and the method "adds" a layer of brackets. Your call is saying that you want an array that contains instances of 2D arrays of String. Instead, you want to just pass in the base class normally, then specify the dimensions.
Array.newInstance(String.class, sizeX, sizeY);

A: This error is in your constructor:
public Tabela(Class<T[][]> c,int sizeX, int sizeY) {
        this.data = c.cast(Array.newInstance(c.getComponentType(), sizeX, sizeY));
}

*

*c.getComponentType() is actually a T[].

*Array.newInstance(Class, int...) return an array of as much dimension as they are in a the array. You pass two values, the array is a two dimensional one.
Array.newInstance(
  c.getComponentType(), // returns T[]
  sizeX, sizeY
) // returns T[][][]

Which would be a runtime equivalent to new T[sizeX][sizeY][] if it were possible (type erasure).
I would do that:
public Tabela(Class<T> c,int sizeX, int sizeY) {
        this.data = Array.newInstance(c, sizeX, sizeY);
}

A: The javadoc of Array#newInstance(..) states

If componentType represents an array class, the number of dimensions
  of the new array is equal to the sum of dimensions.length and the
  number of dimensions of componentType. In this case, the component
  type of the new array is the component type of componentType.

Since componentType is String[], an array class, the number of dimensions becomes the sum of dimensions.length, 2, and the number of dimensions of componentType, 1, for a total of 3.
Your call
Array.newInstance(c.getComponentType(), sizeX, sizeY)

becomes equivalent to
new String[2][2][]

You can, instead, invoke the newInstance(Class, int) method as
Array.newInstance(c.getComponentType(), sizeX)

to create a
new String[2][]

but you'll have to instantiate the nested arrays manually.
Or refactor your constructor parameters to implement unholysampler's solution.


text:
Q: populate spinner with sqlite data Hi I have created following code to populate spinner with list of data in column 1 of table stored in SQLite database. When I ran the program nothing appears on the spinner. I have pasted the code below. If someone could help me with the issue that would be highly appreciated.
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemSelectedListener {
    DatabaseHelper myDb;
    Spinner group;
    Spinner volt1;
    Spinner sf;
    Spinner energy;
    String group_text;
    String sf_text;
    String energy_text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myDb = new DatabaseHelper(this);

        volt1 = (Spinner) findViewById(R.id.spinner_voltage);

        List<String>names = myDb.getAllNames();
        ArrayAdapter<String> adaptervolt = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, names);
        adaptervolt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        volt1.setAdapter(adaptervolt);
    }

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String TABLE_NAME2 = "Spark Energy Table";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public List<String> getAllNames() {
        List<String> names = new ArrayList<String>();
        SQLiteDatabase db = this.getReadableDatabase();
        String selectQuery = "SELECT * FROM"+ TABLE_NAME2;

        db.beginTransaction();
        try {
            Cursor cursor_volt = db.rawQuery(selectQuery, null);
            if (cursor_volt.moveToFirst()) {
                do {
                    names.add(cursor_volt.getString(0));
                } while (cursor_volt.moveToNext());
                cursor_volt.close();
            }

            db.setTransactionSuccessful();
        } catch (SQLiteException e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
            db.close();
        }
        return names;
    }
}

Xml file 1:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1">

    <TextView
        android:id="@+id/txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

Xml file 2:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:id="@+id/id1">

    <Spinner
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:id="@+id/spinner_voltage"
        android:layout_alignTop="@+id/textView2"
        android:layout_toRightOf="@+id/textView2"
        android:layout_toEndOf="@+id/textView2" />
</RelativeLayout>

A: you have not created your database in your helper class.
first create your database inside your oncreate method of you're helper class.
you need to execute your create statement to create table and columns.
try this tutorial for help
sqlite tutorial


text:
Q: Hibernate could not load requested class with composite id I used Hibernate Code Generation tool in eclipse plugins to generate pojo classes, hbm files and DAO classes for the world database. This generated City.java, Country.java, Countrylanguage.java and CountrylanguageId.java, but only three hbm files City.hbm.xml Country.hbm.xml and Countrylanguage.hbm.xml.
I have added the java class files in the configuration through addClass
    protected SessionFactory getSessionFactory() {
    Configuration config = new Configuration()
            .configure("hibernate.cfg.xml")
            .addClass(Country.class)
            .addClass(City.class)
            .addClass(Countrylanguage.class);

But on attempting to create the service registry using
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();

It throws the following error -
Exception in thread "main" org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.component.PojoComponentTuplizer]
at org.hibernate.tuple.component.ComponentTuplizerFactory.constructTuplizer(ComponentTuplizerFactory.java:107)
at org.hibernate.tuple.component.ComponentTuplizerFactory.constructDefaultTuplizer(ComponentTuplizerFactory.java:128)
at org.hibernate.tuple.component.ComponentMetamodel.<init>(ComponentMetamodel.java:77)
at org.hibernate.tuple.component.ComponentMetamodel.<init>(ComponentMetamodel.java:52)
at org.hibernate.mapping.Component.getType(Component.java:227)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:455)
at org.hibernate.mapping.RootClass.validate(RootClass.java:268)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:343)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:461)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at dao.DefaultService.getSessionFactory(DefaultService.java:24)
at dao.DefaultService.<init>(DefaultService.java:14)
at dao.CityService.<init>(CityService.java:21)
at App.main(App.java:6)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.hibernate.tuple.component.ComponentTuplizerFactory.constructTuplizer(ComponentTuplizerFactory.java:104)
... 13 more
Caused by: org.hibernate.MappingException: component class not found: CountrylanguageId
at org.hibernate.mapping.Component.getComponentClass(Component.java:177)
at org.hibernate.tuple.component.PojoComponentTuplizer.setComponentClass(PojoComponentTuplizer.java:147)
at org.hibernate.tuple.component.AbstractComponentTuplizer.<init>(AbstractComponentTuplizer.java:37)
at org.hibernate.tuple.component.PojoComponentTuplizer.<init>(PojoComponentTuplizer.java:41)
... 18 more
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [CountrylanguageId]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:133)
at org.hibernate.mapping.Component.getComponentClass(Component.java:174)
... 21 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : CountrylanguageId
at org.hibernate.boot.registry.classloading.internal.AggregatedClassLoader.findClass(AggregatedClassLoader.java:210)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:130)
... 22 more

I tried adding

.addClass(CountrylanguageId.class)

but this throws up another error that the corresponding hbm file Countrylanguage.hbm.xml is missing.
Are hbm files needed for Classes which are generated based on composite-id relations ? Why does this error surface even though the class has been specified in the hibernate configuration instance ?

A: Figured out the issue.
Using the hibernate tool when I generated the pojo classes, I specified it to be default package, but generated them under a sub-folder src/main/java/entity.
The hbm files have been updated to have the class="..." references and name="..." references to be entity.Countrylanguage, after which it is working fine.
Also verified that using hibernate generation tool configured with package as entity, and folder as default src/main/java outputs the hbm files correctly as expected.
Will mark this question as answered and close it.


text:
Q: Catch Specific MySQL-Error (C#) Is there way to catch a specific MySQL Error or more than one specific MySQL-Error?
I want to call a method if the error is "no selected database".
I am working with the MySQL-Connector / Net.

A: In your catch clause of your exception, you should be able to examine the Number property of the exception to determine which MySql exception was thrown. For example:
try
{
    //Blah
}
catch (MySqlException ex)
{
    if (ex.Number == 1046)
    {
        //Handle
    }
    throw;
}
catch (OtherExceptionType oet)
{
    //Handle
}

If you are using C# 6.0, you can use exception filters.
try
{
    //Blah
}
catch (MySqlException ex) when (ex.Number == 1046)
{
    // Handle
}
catch (OtherExceptionType oet)
{
    //Handle
}

The error number for "no database selected" is 1046 according to the documentation. Other error numbers are listed there as well.


text:
Q: Rails IPv6 server I'm using a development server which I currently only have IPv6 connectivity to, and I'm working on a rails application.
I tried to use bundle exec rails s -e development -p 3003 -d to start a server, but it seems it only binds to IPv4:
tcp        0      0 0.0.0.0:3003                0.0.0.0:*                   LISTEN      27165/ruby

thus I can't connect to it. What's my best option to proceed? I'm not really very familiar with rails just trying to fix a few issues on an existing application.
version info:
:; ruby --version
ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-linux]
:; rails --version
Rails 3.2.8

A: On puma you should do:
rails s -b [::]

as per RFC2732, literal IPv6 addresses should be put inside squares. If not, you will receive a parsing error.

A: Figured it out myself, -b :: will make it listen on both IPv6 and IPv4 (depending on sysctl net.ipv6.bindv6only probably).


text:
Q: cordapp-template-java "Cannot resolve symbol 'docs'" I have been working my way through the Hello, World! Tutorial from V2.0 and cannot import the following variable.
import static net.corda.docs.java.tutorial.helloworld.TemplateContract.TEMPLATE_CONTRACT_ID;

Intellij informs me that it "Cannot resolve symbol 'docs'".
Is this a known issue or have I incorrectly setup the cordapp-template-java project?

A: Resolved this issue by using:
import static com.template.TemplateContract.TEMPLATE_CONTRACT_ID;

The definition for this variable can be found here.


text:
Q: Simple Neural Network using only one class I have implemented a simple neural network in Java that is supposed to solve the XOR problem (http://www.mind.ilstu.edu/curriculum/artificial_neural_net/xor_problem_and_solution.php).
I was wondering what you need Neuron and a NeuronLayer etc. classes for, so I decided to try to make it work using only one class.
Unfortunately, after some epochs, it reaches a state where the error is one of two values: 0.5 or -0.5.
I have tried limiting the range that the starting weights are chosen from but that didn't change anything.
Maybe, some of you can help me spot a mistake or improve the network.
Thanks in advance!
Here is my code:
int inCount = 2;
int hidCount = 3;
int outCount = 1;

float learningRate = 0.01;

float[] inputs = new float[inCount];
float[] hidden = new float[hidCount];
float[] outputs = new float[outCount];

float[][] IHweights = new float[inCount][hidCount];
float[][] HOweights = new float[hidCount][outCount];

void setup ()
{
  for (int i = 0; i < IHweights.length; i++)
  {
    for (int e = 0; e < IHweights[i].length; e++)
    {
      float newWeight = random(-1,1);
      while(newWeight > -0.5 && newWeight < 0.5)
      {
        newWeight = random(-1,1);
      }
      IHweights[i][e] = newWeight;
      println(IHweights[i][e]+"\n");
    }
  }

  for (int i = 0; i < HOweights.length; i++)
  {
    for (int e = 0; e < HOweights[i].length; e++)
    {
      float newWeight = random(-1,1);
      while(newWeight > -0.5 && newWeight < 0.5)
      {
        newWeight = random(-1,1);
      }
      HOweights[i][e] = newWeight;
    }
  }
}

void draw ()
{
  float[] inData = {round(random(1)),round(random(1))};
  println(inData[0]+"   "+inData[1]);
  float[] expResult = {(int) inData[0]^(int) inData[1]};
  println("  ->  "+expResult[0]);
  feedForward(inData,expResult);
}

public float sigmoid (float x)
{
  if (x>10)
  {
    return 1;
  }
  if (x<-10)
  {
    return 0;
  }
  return 1/(1+exp(-x));
}

public void feedForward (float[] input, float[] expOut)
{
  inputs = input;

  for (int i = 0; i < hidCount; i++)
  {
    float var = 0;
    for (int e = 0; e < inCount; e++)
    {
      var += inputs[e] * IHweights[e][i];
    }
    hidden[i] = sigmoid(var);
  }

  for (int i = 0; i < outCount; i++)
  {
    float var = 0;
    for (int e = 0; e < hidCount; e++)
    {
      var += hidden[e] * HOweights[e][i];
    }
    outputs[i] = sigmoid(var);
  }

  float[] error = new float[outCount];
  float[] deltaOut = new float[outCount];

  for (int i = 0; i < outCount; i++)
  {
    error[i] = expOut[i] - outputs[i];
    deltaOut[i] = outputs[i] * (1-outputs[i]) * error[i];
  }

  float[] deltaHid = new float[hidCount];

  for (int i = 0; i < hidCount; i++)
  {
    deltaHid[i] = hidden[i] * (1-hidden[i]);
    for (int e = 0; e < outCount; e++)
    {
      deltaHid[i] += HOweights[i][e] * outputs[e];
    }
  }

  for (int i = 0; i < inCount; i++)
  {
    for (int e = 0; e < hidCount; e++)
    {
      IHweights[i][e] += inputs[i] * deltaHid[e] * learningRate;
    }
  }

  for (int i = 0; i < hidCount; i++)
  {
    for (int e = 0; e < outCount; e++)
    {
      HOweights[i][e] += hidden[i] * deltaOut[e] * learningRate;
    }
  }

  println(error[0]);
}


text:
Q: Prevent dropdown from closing if click is happening inside the dropdown menu I am using bootstrap with angular and using the dropdown module of bootstrap. I am trying to keep the dropdown menu open if click happens on the inside.
I was able to achieve this using event.stopPropagation(). However, if I have 2 dropdowns and I do the following, this doesn't work:
Scenario1: (Correct Behavior)
1) Open Dropdown 1
2) Click anywhere inside the dropdown menu, it works perfectly and the menu does not close.
3) Click outside. Menu Closes. Correct behavior.

Scenario1: (Unexpected Behavior)
1) Open Dropdown1
2) Open Dropdown2

In this scenario, dropdown1 menu should have closed the moment I clicked on dropdown2. But this is not happening.
Here is my code:

Action

Another action

Action

Another action

Here is my openDropdown method:
  openDropdown(e){
    e.stopPropagation();
  }

Here is the Stackblitz link:  Stackblitz
My question is how can I keep the dropdown menu open if click is happening inside of an opened dropdown but close it if click happens anywhere outside. In my case, if outside click happens to be another dropdown, the earlier opened dropdown menu does not close.

A: I updated your HTML file (see below) so that the event.stopPropagation() method is called directly once the user clicks on the dropdown. Seems to be working, I found the answer here: How to prevent an angular-bootstrap dropdown from closing (Unbind Event which was bound by a directive)
The openDropdown() method can be removed from the ts file. Hope this helps!

Action

Another action

Action

Another action


text:
Q: Declaring Maps with typescript private itemsMap: Map<Array<string>,string> = new Map([
    [['shp'], 'Shapefile'],
    [['doc', 'docx'], 'Microsoft Word']
]);

Typescript doesn't like this, it gives me: "Argument of type '(string | string[])[][]' is not assignable to parameter of type 'Iterable<[{},{}]>"
This is a valid way to declare a "Map literal" though.  Is there a way to do this that isn't going to cause an issue?

A: What TypeScript version are using?  This appears to work correctly with the current TypeScript version (currently 2.2.x).
See this playground


text:
Q: Is it always a good idea to divide large classes into smaller ones? I've heard time and time again that in object-oriented programming, you should try to split objects that 'do too much' into multiple classes, to avoid the "God Object" problem.
This seems like fine advice for a project that has plenty of room to expand, but in our project, our packages are already loaded down with too many objects - some that are very bare-bones - while we also have the problem of very large objects that do too much.
Is it a better idea, for code sanitation, to split our larger objects that do too much work into smaller objects?  Or is there a limit to the amount of good it can do?

A: I assume you're on a legacy project where you weren't the one who developed the code. I am in a similar situation.
In my opinion, don't touch the code unless:

*

*You have been tasked with the refactor by a superior.

*You are in fact a senior guy who knows the code inside and out.
Otherwise I would have to say I would apply the "if it isn't broke, don't fix it" law. While it is quite possible that you may achieve better modulation and encapsulation by breaking up huge classes, it could also introduce tons of problems that are not there currently.

A: It seems to me that the fundamental principle to apply here would be the Single Responsibility Principle.  Does each class have a single, clearly articulated, well-bounded responsibility?
Note that I don't mean "does each class do one thing."  For example, a repository "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects."  But it still might have several methods that accomplish parts of this overall responsibility.
If you find that a clearly-articulated, well-bounded responsibility that should be contained in a single class with multiple methods is instead being split over many smaller classes, then your classes are getting too small.

A:
Is it a better idea, for code sanitation, to split our larger objects that do too much work into smaller objects?

It is not about the length of the class but about the responsibility.
You could potentially have a class that is a bit too long but is taking care of only one responsibility. So, definitely don't go by length.
Instead, try to understand the problem it is trying to solve.
If it is solving a single problem then it is following the single responsibility principle and you could either leave it the way it is or DI some of its private methods as helpers classes.
If you notice that it is taking care of more than one responsibility then no matter how long the class I would suggest to break it down into two or however many responsibilities it takes to have them all take care of singular concerns.

A: There are a couple of principles that apply here

*

*SOLID design principles for OO
The main one that applies to your description is the single responsibility principle.
Although the Interface segregation principle by its nature tends to keep class sizes reasonable.

*Refactoring Question
So whilst it is better to keep classes smaller, the decision to refactor is a more cokplex one.
Do you have good Test cases.
With good test cases you can be more adventurous with refactoring . But as usual if the original developers were getting OO build done with a good set of test classes, then they would have already refactored.
Did the large class need to be changed?
If you have to change of fix something, that is often a point were a refactor can be worth the investment.
Refactoring to make it more elegant
As much as it is nice to have clean and more easily maintained code, without sufficient maintainability issues it is most likely hard to justify refactoring for elegance.
When to refactor Blog, worth a look
if you happen to have a pluralsight subscription, there is an excellent course on this  topic refactoring on plural - subscription fee applies


text:
Q: Cannot perform estimation via MHRM algorithm in mirt package I am trying to estimate a mmultilevel multidimensional item response theory (MMIRT) model in R by using mirt package (Chalmers, R. Philip. "mirt: A multidimensional item response theory package for the R environment." Journal of statistical Software 48 (2012): 1-29.). The function mixedmirt() is supposed to do this via the Metropolis-Hastings Robbins-Monro (MHRM) algorithm but, for some reason, I get the following message.
> library(mirt)

> 2l.model <- mixedmirt(data = my.data, model = EUR, itemtype = "graded", survey.weights = my.weights, fixed =~ 0, random =~ 1 | my.groups)
Error in ESTIMATION(data = data, model = model, group = rep("all", nrow(data)),  :
  opts$method %in% c("EM", "QMCEM", "MCEM") non è TRUE

So, I tried to change the method as suggested by the error line. However, as clearly explained in the documentation of the function, this is not allowed (https://www.rdocumentation.org/packages/mirt/versions/1.37.1/topics/mixedmirt).
> 2l.model <- mixedmirt(data = my.data, model = my.model, itemtype = "graded", method = "QMCEM", survey.weights = my.weights, fixed =~ 0, random =~ 1 | my.groups)
Error: method cannot be changed in mixedmirt() function

Furthermore, I checked if the MHRM method worked for unilevel mirt models by using the function mirt(), which should be allowed according to the documentation (https://www.rdocumentation.org/packages/mirt/versions/1.37.1/topics/mirt). However, once again, I get the following message.
> mirt.model <- mirt(data = my.data, model = my.model, method = "MHRM", survey.weights = my.weights)
Error in ESTIMATION(data = data, model = model, group = rep("all", nrow(data)),  :
  opts$method %in% c("EM", "QMCEM", "MCEM") non è TRUE

All this evidence led me to the conclusion that there is something wrong which prevent me to use the MHRM algorithm in my code or perhaps in my laptop. If so, is there a way to fix the problem and perform a estimation via the MHRM algorithm?
All the code was run in R 4.2.2 version.


text:
Q: unable to compile libraries in Ubuntu22.04 - issue with c compiler I was trying to compile some libraries such as hdf5, netcdf and mpich, but was getting error saying "C compiler cannot create executables".
configure: netCDF 4.7.1
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking target system type... x86_64-pc-linux-gnu
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /usr/bin/mkdir -p
checking for gawk... no
checking for mawk... mawk
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking whether to enable maintainer-specific portions of Makefiles... no
configure: checking user options
checking whether a NCIO_MINBLOCKSIZE was specified... 256
checking for valgrind... no
checking if fsync support is enabled... no
checking if jna bug workaround is enabled... no
checking whether we should build netCDF-4... yes
checking whether we should build with HDF5... yes
checking do we require hdf5 dynamic-loading support... yes
checking whether reading of HDF4 SD files is to be enabled... no
checking whether to fetch some sample HDF4 files from Unidata ftp site to test HDF4 reading (requires wget)... no
checking whether we should attempt to install netcdf-fortran (EXPERIMENTAL)... no
checking whether parallel IO tests should be run... no
checking whether a user specified program to run mpi programs... mpiexec
checking whether a default chunk size in bytes was specified... 4194304
checking whether a maximum per-variable cache size for HDF5 was specified... 67108864
checking whether a number of chunks for the default per-variable cache was specified... 10
checking whether a default file cache size for HDF5 was specified... 4194304
checking whether a default file cache maximum number of elements for HDF5 was specified... 1009
checking whether a default cache preemption for HDF5 was specified... 0.75
checking whether netCDF-4 logging is enabled... no
checking whether nc_set_log_level() function is included (will do nothing unless enable-logging is also used)... yes
checking whether DAP client(s) are to be built... no
checking whether make supports the include directive... yes (GNU style)
checking for gcc... gcc
checking whether the C compiler works... no

please find the config.log file from the link.
I tried to install hdf5 first, but was getting same error. Then I hv installed hdf5 using   sudo apt-get install libhdf5-serial-dev
bashrc has the following lines:
export DIR=$HOME/Libraries
export CC=gcc
export CXX=g++
export FCFLAGS=-m64
export F77=gfortran
export FFLAGS=-m64

export HDF5=/usr/lib/x86_64-linux-gnu/
export LD_LIBRARY_PATH=/usr/lib
export CPPFLAGS="-I/usr/lib/x86_64-linux-gnu/ -I/usr/include"
export LDFLAGS="-L/usr/lib/x86_64-linux-gnu/ -L/usr/lib"

config.log: https://drive.google.com/file/d/1X2b2-TeT91fOD2LZISFp2CPvyyKITYzW/view?usp=sharing