text:
Q: Can we use fork/join and executor service at the same time in Java? In essence, I am coding an algorithm that involves summing all numbers in a big array, each of which takes a parameter. And I have a bunch of parameters to run. To me, the summing of all numbers can be a good candidate of leveraging fork/join in Java, and running the algorithm with different parameter can be effectively done with fixed pool of executor service.
However, anyone knows how to combine those two? Or is it possible to combine them, considering that they are both thread pools and we should not have two pools at the same time?
Any suggestions would be very much appreciated.

A: You can have one pool, and submit all tasks to this pool.
The main question is how many threads the pool should have (the parallelism). You can start with the default (N=number of processors) and test throughputs with different parallelism. My guess is the peak throughput is at somewhere between N and 2N.
In Java 8, there is even a common pool :

A static commonPool() is available and appropriate for most applications.

The nice thing about FJP is that the performance is near optimal and not sensitive to tuning (as long as config is within reasonable range, say, not 10*N threads)

A: As zhong.j.yu said, the number ot pools is not as important as the number of simultaneously active threads in those pools combined.
A ForkJoinPool is most appropriate for tasks the lend themselves to subdivision/combination schemes, as hinted by the name RecursiveTask. They may not be the best choice for summing up array values, which sounds like a cache/memory-limited kind of task.
You should do some profiling or at least experimenting with the number of threads, as cache thrashing will limit performance at some point.
ForkJoinPool is highly optimized (check the class comments), much more so than ThreadPoolExecutor, but for memory-limited jobs, you will not notice the difference.
In my experience, each task submitted to either pool should take at least 100µs for optimum balance. Many small jobs may provide best thread utilization, but there is a cost in overhead for handling all the Runnables in the job queue.


text:
Q: Android MediaCodec dequeueOutputBuffer returns illegal buffer index I compiled https://github.com/dpolishuk/simple-mediaplayer-android as is.
Presumably this worked somewhere but on my Nexus 7 (version 1) with Kitkat, the outIndex returned is 5 while videoOutputBuffers is only 5 long, leading to an IndexOutOfBoundsException?
The main relevant loop is:
int outIndex = videoDecoder.dequeueOutputBuffer(info, 10000);
    switch (outIndex) {
      case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED:
        Log.d(Const.TAG, "INFO_OUTPUT_BUFFERS_CHANGED");
        videoOutputBuffers = videoDecoder.getOutputBuffers();
        break;
      case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED:
        Log.d(Const.TAG, "New format " + videoDecoder.getOutputFormat());
        break;
      case MediaCodec.INFO_TRY_AGAIN_LATER:
        Log.d(Const.TAG, "dequeueOutputBuffer timed out!");
        break;
      default:
        ByteBuffer buffer = videoOutputBuffers[outIndex];

        while (audioPtsUs > 0 && (info.presentationTimeUs / 1000.0 - getAudioPtsMs()) > 40.0) {
          try {
            Log.d(Const.TAG, "Wait video " + info.presentationTimeUs / 1000.0 + " audio " + audioPtsUs / 1000.0);
            Thread.sleep(10);
          } catch (InterruptedException e) {
            e.printStackTrace();
            break;
          }
        }

        if ((info.presentationTimeUs / 1000.0 - getAudioPtsMs()) < -40.0) {
          Log.d(Const.TAG, "Need to SKIP Video frame video " + info.presentationTimeUs / 1000.0 + " audio " + getAudioPtsMs());
        }

        videoDecoder.releaseOutputBuffer(outIndex, true);
        break;
    }

With output:
06-03 00:53:11.965: D/OpenGLRenderer(32252): Enabling debug mode 0
06-03 00:53:13.495: I/OMXClient(32252): Using client-side OMX mux.
06-03 00:53:13.495: D/NvOsDebugPrintf(126): NvxLiteH264DecoderInit : Opening TVMR H264 block
06-03 00:53:13.505: E/OMXNodeInstance(126): OMX_SetParameter() failed for StoreMetaDataInBuffers: 0x80001006
06-03 00:53:13.505: E/ACodec(32252): [OMX.Nvidia.h264.decode] storeMetaDataInBuffers failed w/ err -2147483648
06-03 00:53:13.515: I/OMXClient(32252): Using client-side OMX mux.
06-03 00:53:13.605: D/NvOsDebugPrintf(126): NvMMLiteOpen : Block : BlockType = 261
06-03 00:53:13.605: D/NvOsDebugPrintf(126): ++++++ NvAvpOpen +++++++
06-03 00:53:13.605: I/Choreographer(32252): Skipped 105 frames!  The application may be doing too much work on its main thread.
06-03 00:53:13.625: D/NvOsDebugPrintf(126): NvMMLiteBlockCreate : Block : BlockType = 261
06-03 00:53:13.625: D/NvOsDebugPrintf(126): ++++++++++++ TVMRFrameDelivery +++++++++++++++
06-03 00:53:13.635: D/MyMediaPlayer(32252): dequeueOutputBuffer timed out!
06-03 00:53:13.635: I/SoftAAC2(32252): Reconfiguring decoder: 0->44100 Hz, 0->2 channels
06-03 00:53:13.635: D/NvOsDebugPrintf(126): BeginSequence 1280x720
06-03 00:53:13.635: D/NvOsDebugPrintf(126): pnvsi->nDecodeBuffers = 2
06-03 00:53:13.645: D/MyMediaPlayer(32252): dequeueOutputBuffer timed out!
06-03 00:53:13.645: D/MyMediaPlayer(32252): dequeueOutputBuffer timed out!
06-03 00:53:13.655: D/MyMediaPlayer(32252): INFO_OUTPUT_BUFFERS_CHANGED
06-03 00:53:13.655: D/NvOsDebugPrintf(126): Display Resolution : (1280x720)
06-03 00:53:13.655: D/NvOsDebugPrintf(126): Display Aspect Ratio : (1280x720)
06-03 00:53:13.655: D/NvOsDebugPrintf(126): cbBeginSequence@448: SurfaceLayout = 2
06-03 00:53:13.655: D/NvOsDebugPrintf(126): pStreamInfo->NumOfSurfaces = 6, MaxDPB = 24, InteraceStream = 0, InterlaceEnabled = 0
06-03 00:53:13.655: D/NvOsDebugPrintf(126): Allocating new output: 1280x720 (x 8)
06-03 00:53:13.665: D/MyMediaPlayer(32252): New format {sample-rate=44100, channel-count=2, what=1869968451, mime=audio/raw}
06-03 00:53:13.665: D/MyMediaPlayer(32252): dequeueOutputBuffer timed out!
06-03 00:53:13.675: D/MyMediaPlayer(32252): dequeueOutputBuffer timed out!
06-03 00:53:13.705: I/ActivityManager(505): Displayed io.dp.media.player/.MainActivity: +2s169ms
06-03 00:53:13.725: D/MyMediaPlayer(32252): INFO_OUTPUT_BUFFERS_CHANGED
06-03 00:53:13.735: D/MyMediaPlayer(32252): New format {height=720, what=1869968451, color-format=256, slice-height=0, crop-left=0, width=1280, crop-bottom=719, crop-top=0, mime=video/raw, stride=1280, crop-right=1279}
06-03 00:53:13.775: D/MyMediaPlayer(32252): Need to SKIP Video frame video 0.0 audio 46.439909297052154
06-03 00:53:13.835: I/hwcomposer(123): Setting interactive mode: Off
06-03 00:53:13.865: W/dalvikvm(32252): threadid=12: thread exiting with uncaught exception (group=0x419b6ba8)
06-03 00:53:13.875: E/AndroidRuntime(32252): FATAL EXCEPTION: Thread-1887
06-03 00:53:13.875: E/AndroidRuntime(32252): Process: io.dp.media.player, PID: 32252
06-03 00:53:13.875: E/AndroidRuntime(32252): java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
06-03 00:53:13.875: E/AndroidRuntime(32252):    at io.dp.media.player.Player.processVideo(Player.java:154)
06-03 00:53:13.875: E/AndroidRuntime(32252):    at io.dp.media.player.Player.access$500(Player.java:34)
06-03 00:53:13.875: E/AndroidRuntime(32252):    at io.dp.media.player.Player$VideoThread.run(Player.java:276)
06-03 00:53:13.885: W/ActivityManager(505):   Force finishing activity io.dp.media.player/.MainActivity

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use SQLJ with Eclipse? There is not a plugin for SQLJ. So which files i have to import to project? How can i make the compiler understand SQLJ commands?
I am currently using JDBC.

A: The new application development environment for DB2 called IBM Optim Data Studio permits to edit from Eclipse SQLJ files.
http://www-01.ibm.com/software/data/optim/data-studio/
This application is not open source, but it is free to use.
You can also use several products from IBM Rational that includes this feature.


text:
Q: Mapping A Field To A Custom Query in OpenJPA I have a class, Location. Location contains a List of coordinates that define its border.
@Entity
@Table(name="LOCATION")
public class Location implements Serializable {

   private int id;
   private List<Coordinates> coordinateList;

   // setters and getters w/ mapping annotations

}

The coordinateList is mapped @OneToMany with the table that holds the coordinates.
What I would like to do is add four fields (or a Map) to the Location class:

*

*maxLat (maximum Latitude)

*minLat (minimum Latitude)

*maxLng (etc)

*minLng

Is it possible to annotate this fields with a custom query to populate them? i.e.
@CustomQueryOrSomething("select max(lat) from Coordinates C where C.location.id = " this.id)
public getMaxLat() {}

Jason

A: To answer your question, no I don't think there is a way to populate an Entity single field with a specific query. You could use a select to create a special Range class/Entity/Embeddable for a given location.
SELECT NEW com.bla.Range(max(lat), min(lat), max(long), min(long)) Coordinates C where C.location.id = :loc_id


text:
Q: I have a list of keys which I need to search in a directory and then print the keys which are not found I am new to bash scripting. Need help.
I have a text file with 700 keys which I need to search in a folder and then return the keys which did not match

A: Try this:
file='translationDownloaded.txt'
while read line; do
    grep -sqr "$line" /Users/id856795/myproximus-rn/src || echo $line
done < $file

-s suppresses error messages and -q suppresses normal output, so grep itself won't print anything on the screen.


text:
Q: Why is my unit test failing via Hudson/Phing, but succeeding via Phing on the command line? General Info:
PHP 5.3.3
PHPUnit 3.4
Zend Framework 1.10.8
Phing build target
 <target name="test">
  <echo msg="PHPUnit..." />
  <phpunit codecoverage="false" haltonfailure="true" haltonerror="true" printsummary="true" bootstrap="${testdir}/application/bootstrap.php">
   <batchtest>
    <fileset dir="${testdir}">
     <include name="**/*Test.php" />
     <exclude name="./application/ControllerTestCase.php" />
     <exclude name="./application/bootstrap.php" />
    </fileset>
   </batchtest>
   <formatter type="xml" todir="${builddir}" outfile="phpunit-results.xml" />
  </phpunit>
  <phpunitreport infile="${builddir}/phpunit-results.xml"
     styledir="${phpunit.styles.dir}"
     format="frames"
     todir="${builddir}" />
 </target>

This works...
phing -f build.xml test

Hudson/Phing
My Phing target listed in Hudson, which uses the same build.xml file, does not work.  I get the same type of error (strpos(): Empty delimiter) for every unit test, which occurs whenever $this->dispatch(..url..) is executed.
Occurs within the console output upon execution of the unit test target in Hudson
'strpos(): Empty delimiter' in /opt/phing/classes/phing/tasks/ext/phpunit/PHPUnitTask.php:279

Within the PHPUnit results XML file
strpos(): Empty delimiter

/opt/zend/library/Zend/Controller/Request/Http.php:504
/opt/zend/library/Zend/Controller/Request/Http.php:551
/opt/zend/library/Zend/Controller/Request/Http.php:615
/opt/zend/library/Zend/Test/PHPUnit/ControllerTestCase.php:187
/var/lib/hudson/.hudson/jobs/IPS/workspace/trunk/tests/application/IndexControllerTest.php:6
/opt/phing/bin/phing.php:37

Can anyone shed some light on this?

A: Technically speaking, I solved this problem, but by deciding not to run PHPUnit via a Hudson Phing target.  Instead, I decided to run a shell command in Hudson, which at the moment works fine for our needs.  If anyone has any other ideas, I'm all ears.  Thanks!


text:
Q: Ergodicity of the Drude model The Drude model of electric conduction in solids deals with independent free electrons subject to random collisions with the crystal lattice (the direction where the electrons are scattered after a collision is random).
A simplified model is the Lorentz gas, where the collision are deterministic. If I understand correctly, it was shown by Sinai that this model is ergodic.
What about the original Drude model: is it ergodic? (Are there references on that?) A side question is whether this would have a physical significance?

A: As far as I know, Gallavotti proved the ergodicity of the Lorentz gas, while Sinai proved that of a system of $N \leq 5$ rigid spheres. Anyway, this is a minor detail. For certain aspects, a more suitable model for the Drude model is the Boltzmann gas. Lanford has shown (in 1970s, I think) that the entropy for this model is always increasing, but anyone has proved that Boltzmann gas is ergodic. So the answer to your question is: if, at our level of accuracy, Lorentz gas was an appropriate mathematical scheme for the Drude model, than it would be ergodic. Else we can't conclude, since Sinai's result is very important but too limited. (at the present day.)
However, it is an interesting question from a mathematical point of view (for me, for example, it really is), but for a physicist it is not very important, since Drude model does not provide an appropriate level of precision for most of calculations carried out nowadays in solid state physics (at least, concerning what I have seen in my course of condensed matter, I'm not a specialist in solid state physics). Moreover, any of that models takes in account coulombian interactions between charged particles. (this remark restricts - in principle - a lot the domain of applicability of such schematizations.)
I think you could find very interesting the treatments of this subject (ergodic theory) by Halmos and Arnold in their classical monographs.
References.
P. R. Halmos, Lectures on ergodic theory
V.I. Arnold, Ergodic problems of classical mechanics and Mathematical methods of classical mechanics
G. Gallavotti, Statistical mechanics and The elements of mechanics


text:
Q: How to get cordova android push notifications, when the app is in idle state or is in background? How can we get GCM push notifications in a phonegap android application even when the app goes idle or is in background.
"katzer/cordova-plugin-background-mode" doesn't seems to work...
"I'am getting the push notifications successfully when the app runs foreground"
cordova version:4.3.0
android 4.4
phonegap 4.2.0
I'll copy my notification functions below...
on deviceready
function onDeviceReady() {
        try
            {
                      pushNotification = window.plugins.pushNotification;
              jQuery("#app-status-ul").append('
registering ' + device.platform + '
');
                      if (device.platform == 'android' || device.platform == 'Android' ||
                                device.platform == 'amazon-fireos' ) {
            pushNotification.register(successHandler, errorHandler, {"senderID":"my-project-id","ecb":"onNotification"});
              } else {
                          pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"});  // required!
                      }
            }
        catch(err)
            {
              txt="There was an error on this page.\n\n";
              txt+="Error description: " + err.message + "\n\n";
              alert(txt);
            }
        }

and
function onNotification(e) {
            switch( e.event )
            {
                case 'registered':

      if ( e.regid!='' )
      {

           android_reg_id =  e.regid;

          jQuery.ajax({
            type:"POST",
            url:SITEURL+"index.php?r=Manageuser/App_Reg_Android",
            data:{regid: android_reg_id,employeeno:employeeno}
        }).done(function(msg) {

        });

      }
                break;
                case 'message':
                  // if this flag is set, this notification happened while we were in the foreground.
                  // you might want to play a sound to get the user's attention, throw up a dialog, etc.
                  if (e.foreground)
                  {
               //jQuery("#app-status-ul").html('
MESSAGE -> MSG: ' + e.payload.message + '
');
                // on Android soundname is outside the payload.
                      // On Amazon FireOS all custom attributes are contained within payload
                      var soundfile = e.soundname || e.payload.sound;
                      // if the notification contains a soundname, play it.
                      // playing a sound also requires the org.apache.cordova.media plugin
                      var my_media = new Media("/www/"+ soundfile);

                      my_media.play();
                   }
        else
        {

               if (e.coldstart)
                    $("#app-status-ul").append('
--COLDSTART NOTIFICATION--' + '
');
               else
                    $("#app-status-ul").append('
--BACKGROUND NOTIFICATION--' + '
');
                    //location.href = e.payload.redid;
        // otherwise we were launched because the user touched a notification in the notification tray.

        }

          jQuery("#app-status-ul").html('
MESSAGE -> MSG: ' + e.payload.message + '
');
        //window.localStorage.setItem("push_que", e.payload.redid);
        //location.href = e.payload.redid;

        break;

                case 'error':
        jQuery("#app-status-ul").append('
ERROR -> MSG:' + e.msg + '
');
                break;

                default:
        jQuery("#app-status-ul").append('
EVENT -> Unknown, an event was received and we do not know what it is
');
                break;
            }
        }

Plugin that is used is com.phonegap.plugins.PushPlugin 2.4.0 "PushPlugin"

A: I'm not sure which plugin you are using to catch the Push Notification but I would recommend you use the phonegap-build/PushPlugin. It has a handler which catches the Notifications when the app is opened, in the background or closed. If you press on the Notification it will open your app.
To use the plugin just put this in your code:
var pushNotification;

document.addEventListener("deviceready", function(){
    pushNotification = window.plugins.pushNotification;
    if ( device.platform == 'android' || device.platform == 'Android' ){
        pushNotification.register(
        successHandler,
        errorHandler,
        {
            "senderID":"replace_with_sender_id",
            "ecb":"onNotification"
        });
    }
    //the rest of your deviceReady function
});

// result contains any message sent from the plugin call
function successHandler (result) {
    alert('result = ' + result);
}

// result contains any error description text returned from the plugin call
function errorHandler (error) {
    alert('error = ' + error);
}

Now we have set an instance of the plugin to the global variable pushNotification and an if-statement that registers your android device with the GCM service but you need to place the senderID of your Google API Project here: "senderID":"replace_with_sender_id".
If the device was successfully registered it will call the function onNotification.
That function should do something like this:
function onNotification(e) {
    console.log('event received: '+e.event);

    switch( e.event )
    {
    case 'registered':
        if ( e.regid.length > 0 )
        {
            //Here you should call a function that sends the registration-ID
            //to your server so you can save it and send push notifications to your device
            console.log("regID = " + e.regid);
        }
    break;

    case 'message':
        if ( e.foreground )
        {
            //App was open when the notification was received
            console.log('foreground');
            // on Android soundname is outside the payload.
            var soundfile = e.soundname || e.payload.sound;
            // if the notification contains a soundname, play it.
            var my_media = new Media("/android_asset/www/"+ soundfile);
            my_media.play();
        }
        else
        {
            if ( e.coldstart )
            {
                //App was closed
                console.log('coldstart');
            }
            else
            {
                //App was open in the background
                console.log('background');
            }
        }
       alert('message: '+e.payload.message);
    break;

    case 'error':
        alert('GCM error: '+e.msg);
    break;

    default:
        alert('An unknown event has occurred');
    break;
  }
}

This function receives an event from the GCM service which tells it what to do. If the device was registered it logs the device registration-ID in the console and if a message was received it checks if the app is open, closed or open in the background and it will alert the message alert('message: '+e.payload.message);.
Since you are using Android I have just included the code for Android.
I hope this is what you were looking for.

A: Receiving push notifications does not require the app to be running in the background.
The Cordova Push Plugin
I recommend this plugin: https://github.com/phonegap-build/PushPlugin for receiving push notifications (when the app is not running).
The documentation on that page is pretty good.
The plugin supports iOS, Android, and other platforms.
Server-side options
I don't know what you are running on the server, and it doesn't actually sound like you necessarily have any problems on the server end, but in the interests of providing a more complete (and more general) cordova push solution answer, I want to mention this:
For Android GCM push messaging check out https://www.npmjs.com/package/node-gcm
And for iOS APN push messaging there is https://github.com/argon/node-apn
I've included these links because, even if you are not running node on the server, the documentation on these pages is a great starting point and they both have links out to more really useful info.
----- Update 4/12/2015 -----
The plugin recommended above has been deprecated, the replacement plugin, https://github.com/phonegap/phonegap-plugin-push, has a much simpler interface.
This simple example of the client-side code has everything you need for most use cases : https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/EXAMPLES.md


text:
Q: Database disappears in emulator MainActivity Code
package kz.talipovsn.database;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private final int LARGE_FONT = 16; // Размер шрифта для режима крупного шрифта
    private final int SMALL_FONT = 12; // Размер шрифта для режима обычного шрифта
    private int fontSize = SMALL_FONT; // Выбранный размер шрифта

    MySQLite db = new MySQLite(this); // Класс работы с нашей базой данных

    EditText editText; // Компонент для задания строки поиска
    TextView textView; // Компонент для вывода ответа
    CheckBox checkBox1;
    CheckBox checkBox2;
    CheckBox checkBox3;
    CheckBox checkBox4;
    CheckBox checkBox5;
    CheckBox checkBox6;

    static final String FILTER = "FILTER"; // Имя параметра для сохранения при переворачивании экрана
    String filter = ""; // Фильтр поиска

    SharedPreferences sPref; // Класс для работы с настройками программы
    static final String CONFIG_FILE_NAME = "Config"; // Имя файла настроек приложения
    static final String FONT_SIZE = "FontSize"; // Имя параметра для сохранения размера шрифта в настройках приложения

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Сохранение данных при перевороте экрана
        savedInstanceState.putString(FILTER, filter);
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // Активация меню
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Доступ к компонентам
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        checkBox1 = findViewById(R.id.checkBox1);
        checkBox2 = findViewById(R.id.checkBox2);
        checkBox3 = findViewById(R.id.checkBox3);
        checkBox4 = findViewById(R.id.checkBox4);
        checkBox5 = findViewById(R.id.checkBox5);
        checkBox6 = findViewById(R.id.checkBox6);

        textView.setKeyListener(null); // Запрет на изменение данных с клавиатуры

        // Чтение сохраненной настройки размера шрифта из параметров приложения
        sPref = getSharedPreferences(CONFIG_FILE_NAME, MODE_PRIVATE);
        fontSize = sPref.getInt(FONT_SIZE, SMALL_FONT);

        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize); // Установка начально размера шрифта
        textView.requestFocus(); // Передача фокуса на комонент чтобы закрылось окно ввода у "editText"

        // Восстановление фильтра после переворота экрана
        if (savedInstanceState != null) {
            editText.setText(savedInstanceState.getString(FILTER));
        }

        textView.setText(R.string.Загрузка_данных);

        // Обработчик изменения текста в компоненте "editText"
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {

                // Сделаем поиск данных в другом потоке
                new Thread(new Runnable() {
                    public void run() {
                        filter = editText.getText().toString().trim();
                        final String data = db.getData(filter, checkBox1.isChecked(), checkBox2.isChecked(), checkBox3.isChecked(), checkBox4.isChecked(), checkBox5.isChecked(), checkBox6.isChecked());
                        // Сделаем вывод результата синхронно с основным потоком
                        textView.post(new Runnable() {
                            public void run() {
                                textView.setText(data);
                            }
                        });
                    }
                }).start();

            }

        });

        // Инициализация начального поиска (показать все записи)
        editText.post(new Runnable() {
            public void run() {
                editText.setText(filter);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        // Установка правильного отображения пункта выбора крупного шрифта
        menu.findItem(R.id.large_font).setChecked(fontSize == LARGE_FONT);
        return true;
    }

    // Обработчик выбора пунктов меню
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        // Написать автору
        if (id == R.id.email) {
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("message/rfc822");
            i.putExtra(Intent.EXTRA_EMAIL, new String[]{getString(R.string.myemail)});
            i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.Добавьте_еще_номер));
            i.putExtra(Intent.EXTRA_TEXT, getString(R.string.Предлагаю_такой_номер));
            try {
                startActivity(Intent.createChooser(i, getString(R.string.Посылка_письма)));
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(MainActivity.this, R.string.Нет_установленного_почтового_клиента, Toast.LENGTH_SHORT).show();
            }
            return true;
        }
        // Установка/снятие крупного шрифта
        if (id == R.id.large_font) {
            item.setChecked(!item.isChecked());
            int size = item.isChecked() ? LARGE_FONT : SMALL_FONT;
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
            fontSize = size;
            return true;
        }
        // Выход
        if (id == R.id.exit) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // Метод при закрытии окна
    @Override
    protected void onStop() {
        super.onStop();
        // Сохранение размера шрифта в настройках программы
        SharedPreferences.Editor ed = sPref.edit();
        ed.putInt(FONT_SIZE, fontSize);
        ed.apply();
    }
}

..................................................
Here is the MySQLite code, for working with the database, it does not show errors in the code. Possible errors with the emulator version. With one filter PRICE worked...................................
MySQLite Code
    package kz.talipovsn.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class MySQLite extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 3; // НОМЕР ВЕРСИИ БАЗЫ ДАННЫХ И ТАБЛИЦ !

    static final String DATABASE_NAME = "phones"; // Имя базы данных

    static final String TABLE_NAME = "emergency_service";
    static final String ID = "id";
    static final String NAME = "name";
    static final String PRICE = "price";
    static final String TYPE = "type";
    static final String POWER = "power";
    static final String WEIGHT = "weight";
    static final String COUNTRY = "country";

    static final String ASSETS_FILE_NAME = "telephone.txt"; // Имя файла из ресурсов с данными для БД
    static final String DATA_SEPARATOR = "|"; // Разделитель данных в файле ресурсов с телефонами

    private Context context; // Контекст приложения

    public MySQLite(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    // Метод создания базы данных и таблиц в ней
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
                + ID + " INTEGER PRIMARY KEY,"
                + NAME + " TEXT,"
                + PRICE + " INTEGER,"
                + TYPE + " TEXT,"
                + POWER + " INTEGER,"
                + WEIGHT + " INTEGER,"
                + COUNTRY + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
        System.out.println(CREATE_CONTACTS_TABLE);
        loadDataFromAsset(context, ASSETS_FILE_NAME,  db);
    }

    // Метод при обновлении структуры базы данных и/или таблиц в ней
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        System.out.println("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    // Добавление нового контакта в БД
    public void addData(SQLiteDatabase db, String name, int price, String type, int power, int weight, String country) {
        ContentValues values = new ContentValues();
        values.put(NAME, name);
        values.put(PRICE, price);
        values.put(TYPE, type);
        values.put(POWER, power);
        values.put(WEIGHT, weight);
        values.put(COUNTRY, country);
        db.insert(TABLE_NAME, null, values);
    }

    // Добавление записей в базу данных из файла ресурсов
    public void loadDataFromAsset(Context context, String fileName, SQLiteDatabase db) {
        BufferedReader in = null;

        try {
            // Открываем поток для работы с файлом с исходными данными
            InputStream is = context.getAssets().open(fileName);
            // Открываем буфер обмена для потока работы с файлом с исходными данными
            in = new BufferedReader(new InputStreamReader(is));

            String str;
            while ((str = in.readLine()) != null) { // Читаем строку из файла
                String strTrim = str.trim(); // Убираем у строки пробелы с концов
                if (!strTrim.equals("")) { // Если строка не пустая, то
                    StringTokenizer st = new StringTokenizer(strTrim, DATA_SEPARATOR); // Нарезаем ее на части
                    String name = st.nextToken().trim(); // Извлекаем из строки название организации без пробелов на концах
                    int price = Integer.parseInt(st.nextToken().trim());
                    String type = st.nextToken().trim();
                    int power = Integer.parseInt(st.nextToken().trim());
                    int weight = Integer.parseInt(st.nextToken().trim());
                    String country = st.nextToken().trim();
                    addData(db, name, price, type, power, weight, country);
                }
            }

        // Обработчики ошибок
        } catch (IOException ignored) {
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignored) {
                }
            }
        }

    }

    public String getData(String filter, boolean isName, boolean isCountry, boolean isPrice, boolean isWeight, boolean isPower, boolean isType) {

        String selectQuery; // Переменная для SQL-запроса

        if (filter.equals("")) {
            selectQuery = "SELECT  * FROM " + TABLE_NAME + " ORDER BY " + NAME;
        } else {
            if (isName) {
                selectQuery = "SELECT  * FROM " + TABLE_NAME + " WHERE (" + NAME + filter + ") ORDER BY " + NAME;
            } else if (isCountry) {
                selectQuery = "SELECT  * FROM " + TABLE_NAME + " WHERE (" + COUNTRY + filter + ") ORDER BY " + COUNTRY;
            } else if (isPrice) {
                selectQuery = "SELECT  * FROM " + TABLE_NAME + " WHERE (" + PRICE + " >= " + filter + ") ORDER BY " + PRICE;
            } else if (isWeight) {
                selectQuery = "SELECT  * FROM " + TABLE_NAME + " WHERE (" + WEIGHT + filter + ") ORDER BY " + WEIGHT;
            } else if (isPower) {
                selectQuery = "SELECT  * FROM " + TABLE_NAME + " WHERE (" + POWER + filter + ") ORDER BY " + POWER;
            } else if (isType) {
                selectQuery = "SELECT  * FROM " + TABLE_NAME + " WHERE (" + TYPE + filter + ") ORDER BY " + TYPE;
            } else {
                selectQuery = "SELECT  * FROM " + TABLE_NAME + " WHERE (" + TYPE + " LIKE '%" + filter + "%'" + " OR " + POWER + " LIKE '%" + filter + "%'"
                        + " OR " + WEIGHT + " LIKE '%" + filter + "%'" + " OR " + COUNTRY +
                        " LIKE '%" + filter + "%'" + " OR " + NAME + " LIKE '%" + filter + "%'" + ") ORDER BY " + NAME;
            }
        }

        SQLiteDatabase db = this.getReadableDatabase(); // Доступ к БД
        try {
        Cursor cursor = db.rawQuery(selectQuery, null); // Выполнение SQL-запроса

        StringBuilder data = new StringBuilder(); // Переменная для формирования данных из запроса

        int num = 0;
        if (cursor.moveToFirst()) { // Если есть хоть одна запись, то
            do { // Цикл по всем записям результата запроса
                int n = cursor.getColumnIndex(NAME);
                int t = cursor.getColumnIndex(PRICE);
                int k = cursor.getColumnIndex(TYPE);
                int s = cursor.getColumnIndex(POWER);
                int a = cursor.getColumnIndex(WEIGHT);
                int d = cursor.getColumnIndex(COUNTRY);
                String name = cursor.getString(n); // Чтение названия организации
                int price = cursor.getInt(t); // Чтение телефонного номера
                String type = cursor.getString(k);
                String power = cursor.getString(s);
                String weight = cursor.getString(a);
                String country = cursor.getString(d);
                data.append(String.valueOf(++num) + ") " + name + ": " + price + ": " + type + ": " + power + ": " + weight + ": " + country + ": " + "\n");
            } while (cursor.moveToNext()); // Цикл пока есть следующая запись
        }

        return data.toString(); // Возвращение результата
    }
    catch (Exception e)
    {
        return "";
    }
}

}

    The errors themselves
12/08 20:52:48: Launching 'TSN_DEMO_06_Database' on Pixel 2 API 22.
Install successfully finished in 7 s 497 ms.
$ adb shell am start -n "kz.talipovsn.database/kz.talipovsn.database.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 3903 on device 'Pixel_2_API_22 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/art: Late-enabling -Xcheck:jni
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
W/art: Suspending all threads took: 5.066ms
I/art: Background sticky concurrent mark sweep GC freed 1193(84KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 3MB/3MB, paused 5.853ms total 64.414ms
I/WebViewFactory: Loading com.android.webview version 39 (6695563-x86_64) (code 300008)
I/LibraryLoader: Time to load native libraries: 0 ms (timestamps 7557-7557)
I/LibraryLoader: Expected native library version number "",actual native library version number ""
V/WebViewChromiumFactoryProvider: Binding Chromium to main looper Looper (main, tid 1) {15b25306}
I/LibraryLoader: Expected native library version number "",actual native library version number ""
I/chromium: [INFO:library_loader_hooks.cc(104)] Chromium logging enabled: level = 0, default verbosity = 0
I/BrowserStartupController: Initializing chromium process, singleProcess=true
W/art: Attempt to remove local handle scope entry from IRT, ignoring
W/chromium: [WARNING:resource_bundle.cc(304)] locale_file_path.empty()
I/chromium: [INFO:aw_browser_main_parts.cc(65)] Load from apk succesful, fd=31 off=46184 len=3037
I/chromium: [INFO:aw_browser_main_parts.cc(78)] Loading webviewchromium.pak from, fd:32 off:229484 len:1089587
W/AudioManagerAndroid: Requires BLUETOOTH permission
D/: HostConnection::get() New Host Connection established 0x7fb17cd03c50, tid 3903
D/EGL_emulation: eglCreateContext: 0x7fb17ccf88e0: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0x7fb17ccf88e0: ver 2 0 (tinfo 0x7fb17cd07e80)
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
D/Atlas: Validating map...
I/OpenGLRenderer: Initialized EGL, version 1.4
D/: HostConnection::get() New Host Connection established 0x7fb1863fb550, tid 3946
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0x7fb17cd4cca0: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0x7fb17cd4cca0: ver 2 0 (tinfo 0x7fb17cdd5600)
D/OpenGLRenderer: Enabling debug mode 0
D/EGL_emulation: eglMakeCurrent: 0x7fb17cd4cca0: ver 2 0 (tinfo 0x7fb17cdd5600)
I/System.out: DROP TABLE IF EXISTS emergency_service
I/System.out: CREATE TABLE emergency_service(id INTEGER PRIMARY KEY,name TEXT,price INTEGER,type TEXT,power INTEGER,weight INTEGER,country TEXT)

Tried to completely reinstall the database


text:
Q: Nested JSON and AngularJS confusion Basically I have a PHP quasi-API that results in this JSON:
{"0":{"id":"325","course":"{\"0\":{\"id\":\"31\",\"title\":\"Ticket Seller     II\",\"code\":\"STN\"},\"nm\":1}","batch":"29","start_date":"2016-04-20 08:30:00","end_date":"2016-05-17 17:00:00"}}

But while I retrieved the first JSON array by the JS script:
var prog=[];
var res=response.data;

for(var i=0; i<=res['nm'];i++){

     prog.push(res[i]);

}

vm.events = prog;

I have no idea how to retrieve the nested JSON, "course".   I have this Angular script:
ng-repeat="event in table1.events"

But something like event.course[0].title gives out an error.   Nesting a repeat like

Still doesn't work.  How do I retrieve it?
I've tried the following:

    {{ event.course }}
{{ value.title }} 5664

And it doesn't work.  the 5664 doesn't appear, but the event.course shows the JSON snippet.  It's as if the snippet is not being read as JSON.
UPDATE: Sorry, it works now.  I didn't see the solution work because the first few rows really had empty content, but it works now.

A: You JSONis missing a } at the end
{
   "0":{
      "id":"325",
      "course":"{\"0\":{\"id\":\"31\",\"title\":\"Ticket Seller     II\",\"code\":\"STN\"},\"nm\":1}",
      "batch":"29",
      "start_date":"2016-04-20 08:30:00",
      "end_date":"2016-05-17 17:00:00"
   }
}

Use a validator to check validity of your JSON. https://jsonformatter.curiousconcept.com/

A: you can use ng-repeat nested,Please see the code below.it may help you to figure it out.

<!DOCTYPE html>

{{value.title}}

see code is working for span also.

<!DOCTYPE html>

      {{value.title}}


text:
Q: Using Spring to configure SOAP handlers I have a custom SOAP handler that I am using for schema validation of the SOAP messages. It works for on web service, I'd like to be able to use it for others. The code that does the validation itself is quite generic - the only real input to it is the name of the schema to use for validation. I'm mentally stuck on how/if I can use Spring to configure different instances of the SOAP handler for different services.
The web service is declared as:
@WebService(name = "MyService", ...)
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@HandlerChain(file="handler-chain.xml")
public interface MyService
{
   ....
}

The handler-chain.xml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
  <handler-chain>
    <handler>
      <handler-name>com.ws.MyCustomSoapHandler</handler-name>
      <handler-class>com.ws.MyCustomSoapHandler</handler-class>
    </handler>
  </handler-chain>
</handler-chains>

Inside the custom SOAP handler, I have this:
public class MyCustomSoapHandler implements SOAPHandler<SOAPMessageContext>
{
    //assume getter/setter for this.
    private String schemaLocation = "schema/validation/service1.xsd";
    @Override
    public boolean handleMessage(SOAPMessageContext context)
    {
        ...
        //This is the only place where the schema needs to vary
        schema = schemaFactory.newSchema(this.getClass().getClassLoader().getResource(schemaLocation));

I know I could use Spring to create multiple beans based on MyCustomSoapHandler and give them different values for schemaLocation, but how do I connect those beans to the correct web services in my application? Would it be through handler-chain.xml? Or would I have to do it programmatically?

A: It doesn't look like this is possible (or if it is, I can't seem to get it working) because the SOAP handlers are created by the WebSphere container, and they are not managed by Spring. So I just created an abstract handler with most of the logic and used a .properties file to configure the details that were more specific to different handlers.


text:
Q: What's the relationship between hadoop's TFile and HFile? It seems hadoop support both TFile and HFile. I'd like to know the difference between then and how they appeared (e.g. was HFile derived from TFile?).

A: It seems that http://hbase.apache.org/book.html#_hfile_format_2 has most of answers.
HFile is derived from TFile. It was designed to improve HBase performance over MapFile format. Sounds like tweaks were made and TFile could not be used as is, so HFile appeared.


text:
Q: 'An attempt has been made to start' in lr_find with fast.ai I am running this small piece of code to identify learning rate:
import cv2
from fastai.vision import *
from fastai.callbacks.hooks import *
path = untar_data(URLs.CAMVID)
path_lbl = path/'labels'
path_img = path/'images'
fnames = get_image_files(path_img)
lbl_names = get_image_files(path_lbl)
img_f = fnames[0]
img = open_image(img_f)
get_y_fn = lambda x: path_lbl/f'{x.stem}_P{x.suffix}'
mask = open_mask(get_y_fn(img_f))
src_size = np.array(mask.shape[1:])
src_size,mask.data
codes = np.loadtxt(path/'codes.txt', dtype=str); codes
size = src_size//2
bs=4
src = (SegmentationItemList.from_folder(path_img)
       .split_by_fname_file('../valid.txt')
       .label_from_func(get_y_fn, classes=codes))
data = (src.transform(get_transforms(), size=size, tfm_y=True)
        .databunch(bs=bs)
        .normalize(imagenet_stats))
name2id = {v:k for k,v in enumerate(codes)}
void_code = name2id['Void']
def acc_camvid(input, target):
    target = target.squeeze(1)
    mask = target != void_code
    return (input.argmax(dim=1)[mask]==target[mask]).float().mean()
wd=1e-2
learn = unet_learner(data, models.resnet34, metrics=acc_camvid, wd=wd)
lr_find(learn)
print("end")

And I get this error:
RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

and also this one:
Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.4\helpers\pydev\pydevd.py", line 1664, in <module>
    main()
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.4\helpers\pydev\pydevd.py", line 1658, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.4\helpers\pydev\pydevd.py", line 1068, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/steve/Project/fastai_unet/main.py", line 32, in <module>
    lr_find(learn)
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastai\train.py", line 32, in lr_find
    learn.fit(epochs, start_lr, callbacks=[cb], wd=wd)
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastai\basic_train.py", line 199, in fit
    fit(epochs, self, metrics=self.metrics, callbacks=self.callbacks+callbacks)
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastai\basic_train.py", line 99, in fit
    for xb,yb in progress_bar(learn.data.train_dl, parent=pbar):
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastprogress\fastprogress.py", line 72, in __iter__
    for i,o in enumerate(self._gen):
  File "C:\Users\steve\Miniconda3\lib\site-packages\fastai\basic_data.py", line 75, in __iter__
    for b in self.dl: yield self.proc_batch(b)
  File "C:\Users\steve\Miniconda3\lib\site-packages\torch\utils\data\dataloader.py", line 193, in __iter__
    return _DataLoaderIter(self)
  File "C:\Users\steve\Miniconda3\lib\site-packages\torch\utils\data\dataloader.py", line 469, in __init__
    w.start()
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Users\steve\Miniconda3\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
BrokenPipeError: [Errno 32] Broken pipe

how can I fix this?

A: Oh, the solution is to wrap code in a method and invoke it:
import cv2
from fastai.vision import *
from fastai.callbacks.hooks import *

def main():
    path = untar_data(URLs.CAMVID)
    path_lbl = path/'labels'
    path_img = path/'images'
    fnames = get_image_files(path_img)
    lbl_names = get_image_files(path_lbl)
    get_y_fn = lambda x: path_lbl/f'{x.stem}_P{x.suffix}'
    mask = open_mask(get_y_fn(img_f))
    src_size = np.array(mask.shape[1:])
    src_size,mask.data
    codes = np.loadtxt(path/'codes.txt', dtype=str); codes
    size = src_size//2
    bs=4
    src = (SegmentationItemList.from_folder(path_img)
           .split_by_fname_file('../valid.txt')
           .label_from_func(get_y_fn, classes=codes))
    data = (src.transform(get_transforms(), size=size, tfm_y=True)
            .databunch(bs=bs)
            .normalize(imagenet_stats))
    name2id = {v:k for k,v in enumerate(codes)}
    void_code = name2id['Void']
    def acc_camvid(input, target):
        target = target.squeeze(1)
        mask = target != void_code
        return (input.argmax(dim=1)[mask]==target[mask]).float().mean()
    wd=1e-2
    learn = unet_learner(data, models.resnet34, metrics=acc_camvid, wd=wd)
    lr_find(learn)
    print("end")
if __name__ == '__main__':
    main()

A: In my case, running under Windows, I had to set the number of num_workers to 0 in the dataloaders. Here, I presume this could be set within databunch(bs=bs).


text:
Q: How do I make a transparent WPF window stay on top of all other windows, but have no affect on user input? I am trying to develop a Windows application that allows people to "draw on their screen."
I'm developing with:
.NET 3.5
C#/WPF
I have a WPF Window that hosts an InkCanvas, both having transparent backgrounds.
Window XAML properties:
ShowInTaskbar="True" ResizeMode="NoResize" Background="Transparent"
WindowStyle="None" AllowsTransparency="True" Topmost="True"

InkCanvas properties:
Background="#11FFFFFF"

I need an event handler for the following:
- right click anywhere in window
- press escape
desired result:
- WPF window remains on top of all other windows, but is no longer active and no longer accepts input
- WPF window can longer be focused on. All input from the users should go to their current focused window and ignore the wpf window with the inkcanvas that is on top of everything
Basic usage example:
A user of the app is playing a game. They stop and draw some arrows in the wpf window / inkcanvas. They finish by pressing escape. The wpf window remains on top, with the shapes the user drew open, and the user's input returns to whatever window they have open/focused.
So far, I've tried this:
MouseRightButtonUp ::

mywindow.isenabled = false

and I've tried:
mywindow.IsInputMethodEnabled = false

Not working so far, the wpf window still starts grabbing user input. I somehow need to make this window as showing but without it being activated .. even after it has been "used" for some period of time.
Thank you in advance for any advice!

A: You can intercept the WndProc (using the AddHook of the HwndSource as shown here) and intercept the WM_NCHITTEST and return HTTRANSPARENT. That will only let it pass to other windows in that thread though. Another option might be to set the WS_EX_TRANSPARENT extended style bit. See this question's answer for an example.


text:
Q: prevent multiple http request send by using fetch I'm creating a chrome extension, in which I take input from using prompt and send it to the server using an HTTP request. By doing this I'm facing duplication of data, which means the extension is sending multiple requests to the server, which I want to prevent. (Note: by taking data from prompt only once it is sending multiple requests of same data)
Example code:
Front-End:
var data = prompt("Enter your data here");
if (data !== null || data !== ''){
fetch('http://localhost:3000/post', {
  method: 'POST',
  body: JSON.stringify({
    data: data
  }),
  headers: {
    'Content-Type': 'application/json',
  }
}).then((res) => {
  console.log("wait for whole req");
  return res.json();
}).then((resData) => {
  console.log(resData);
  console.log("req send successfully");
  // note = null;
}).catch((error) => {
  // note = null;
  console.log(error.message);
  // alert(error.message);
});

Back-End:
app.post("/post", function(req, res) {
    const data = req.body.data;
    dataList.push(data);
    res.status(200).json({
       status: "uploaded"
    });
});

Here, data is one array that stores data taken from the user.

A: You can limit concurrent requests by a flag
var data = null,
isLoading = false, // perhaps you need to make this persistent depending on your overall architecture
if (!isLoading)
{
   data = prompt("Enter your data here");
}
if (data !== null || data !== ''){
isLoading = true;
fetch('http://localhost:3000/post', {
  method: 'POST',
  body: JSON.stringify({
    data: data
  }),
  headers: {
    'Content-Type': 'application/json',
  }
}).then((res) => {
  console.log("wait for whole req");

  return res.json();
}).then((resData) => {
  console.log(resData);
  console.log("req send successfully");
  isLoading = false
  // note = null;
}).catch((error) => {
  // note = null;
  console.log(error.message);
  isLoading = false
  // alert(error.message);
});


text:
Q: FileSavePicker and deprecated ApplicationViewState In the documentation for the FileSavePicker, it states:

Warning  If you try to show the file picker while your app is snapped the file picker will not be shown and an exception will be thrown. You can avoid this by making sure your app is not snapped or by unsnapping it before you call the file picker.

I'm currently checking to see if the app is snapped or not, and my app responds differently in each case. My default behavior isn't showing the FileSavePicker, either, so I can't just try and then fall back to something else. Nor do I want to force the app to unsnap.
However, ApplicationViewState is deprecated post-8.1. In that documentation and related searching, developers are advised to access the window size directly in order to determine proper behavior. However, if the view state is no longer available, how do I know if the file picker will throw an exception or not? At what size is the app considered 'snapped'?
Also, I'm using C++, so an answer compatible with C++ would be splendid. I wouldn't mind seeing the C# solution, too.

A: In regards to the FileSavePicker documentation - I believe that it is just an oversight. The text you quote was from the Windows 8 version, and to me it looks like it didn't get updated for Windows 8.1.
If you look at the FileOpenPicker documentation, you see that it was updated:

Important  In Windows 8 if you attempt to display the file picker while your app is snapped, the file picker will not be shown and an exception will be thrown. You can avoid this by making sure your app is not snapped, or by unsnapping it before you call the file picker. ...Note that Windows 8.1 does not define a specific snapped window size. Instead, users can resize apps to any width, down to the minimum. Therefore, if your app will deploy only on Windows 8.1, you can ignore the EnsureUnsnapped function and calls to it in this topic's example code.

The last sentence (in bold) above essentially says that you can ignore state and safely open the file dialogs if you are running under Windows 8.1.

To test the above, I used VS 2012 to create a Windows 8 application with a file save picker (in C#). I believe the outcome will be the same with C++, but I am not 100% certain.
I should note that my test application does not check for view state and always tries to open a file dialog.
When the application is run under Windows 8 in the snapped state, the application causes an error. That same application (same binary) when run under Windows 8.1 allows the file save dialog to open without issue. As mentioned previously there is no snapped state in Windows 8.1, so the way I tested the application was to open the application to the minimum width (320 pixels).

To summarize:

*

*If you are targeting Windows 8.0, you will have to make sure the application is unsnapped prior to opening the file picker dialogs.

*If you are targeting Windows 8.1, you do not have to worry about state, as the file picker dialogs no longer throw any exceptions.


text:
Q: PHP - How to catch a 'Trying to get property of non-object' error I am trying to catch 'Trying to get property of non-object' error with a try/catch statement but it is failing, I still get a PHP error. I am using as:
try{
  $id = Model()->find('id=1')->id;
}catch(Exception $e){
  echo 'failed';
}

My find function returns an object (Active Record) and I can access the id column as shown via object prop.
However, it will be null object if AR is not found. I thought the try statement would catch this. A work around for myself would be to use an isset(). But I am confused as to why the try statement does not accept and catch this error.

A: The model needs to be able to throw an exception.
Here's what your model might look like:
class Model{

   public function find($id){
      $result = //do stuff to find by id

      if (!isset($result)){
          throw new Exception("No result was found for id:$id");
      }
      return $result

   }
}

Then you would use your try/catch block:
try{

    $id = Model()->find('id=1')->id;

}catch(Exception $e){
    echo 'failed';
}

However, exceptions should only be thrown under "exceptional" circumstances. I don't think using exceptions to direct program flow is the right way to go about it.
Having said that, if returning a NULL when you attempt to retrieve the ID property is an exceptional situation, then exceptions are certainly suitable.

A: try..catch works on thrown exceptions. Errors are not exceptions. You can silence errors, but please don't do that. Instead, properly check what you're getting:
$result = Model()->find('id=1');
if ($result) {
    $id = $result->id;
} else {
    // handle this situation
}


text:
Q: How to compare PDF using nightwatch.js I would like to compare two PDF during an automated test. One will be generate on a website, and the other one will be stored on my computer.
As I am a beginner in automation I would like to know if I can use Nightwatch during an existing test case to compare PDF during a new step.


text:
Q: Match first word then remove it from string with PHP If I have a string like this:
$subject = "This is just a test";

I want to find the first word then remove it from $subject in PHP. I use preg_match to get the first word but can I use a single operation to also remove it?
preg_match('/^(\w+)/', trim($subject), $matches);

After matching my first word the string should be
$subject = "is just a test";

and $matches should contain the first word

A: Preg_match can capture, preg_replace can replace. I'd use the preg_replace_callback, http://php.net/manual/en/function.preg-replace-callback.php, to store your value and replace the original. I also modified your regex a bit you can swap it back to the \w if you find that is better. That will allow the line to start with - and 0-9 as well though so no necessarily a word.
<?php
$subject = "This is just a test";
preg_replace_callback('~^([A-Z]+)\s(.*)~i', function($found) {
        global $subject, $matches;
        $matches = $found[1];
        $subject = $found[2];
    }, $subject);
echo $subject . "\n";
echo $matches;

Output:

is just a test
  This

A: Like chris' answer, my method relies on the fact that there will be at least 2 words in the substring separated by a single space.
Code: (Demo)
$subject = "This is just a test";
$halves=explode(' ',$subject,2);  // create a two-element(maximum) array
$first=array_splice($halves,0,1)[0];  // assign first element to $first, now $halves is a single, reindexed element
$subject=$halves[0];
echo "First=$first and Subject=$subject";
// output: First=This and Subject=is just a test

Or you could more simply use this one-liner:
list($first,$subject)=explode(' ',$subject,2);  // limit the number of matches to 2

Or
echo "First=",strstr($subject,' ',true)," and Subject=",ltrim(strstr($subject,' '));

Or
echo "First=",substr($subject,0,strpos($subject,' '))," and Subject=",substr($subject,strpos($subject,' ')+1);

If you particularly want a regex solution for some crazy reason, preg_split() works just like explode():
Code: (Demo)
$subject = "This is just a test";
list($first,$subject)=preg_split('/ /',$subject,2);  // limit the number of matches to 2
echo "First=$first and Subject=$subject";
// output: First=This and Subject=is just a test


text:
Q: ABAC in microservices I am applying the ABAC methodology for access to protected resources.
My question is what is the best way to apply limits to certain fields that returns the api according to the user who is invoking it.
For example:
I want to allow access to /get-data to authenticated users, /get-data returns:
Date
Names
Address
Balance
I want to show the "balance" field only to users who are allowed access to view amounts, such as a counter.
Can I take balance as an attribute of the resource /get-data?


text:
Q: What is the point of defining new class as a struct in Python C API The docs for Python C API describes the pattern of defining a new type:
typedef struct {
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
} Noddy;
...

Then methods such as init could be added.
My question is - what is the point to define custom fields in a struct, why not define them in init, just like in Python, using PyObject_SetAttr function calls on self?

A: *

*Struct member access is far more efficient than dict lookups.

*Struct member access is far more convenient to do in C. It's much easier to do thing->foo than PyObject_GetAttrString(thing, "foo").

*Using struct members allows you to store data that isn't of a Python type. This allows you to do things that can't be implemented in terms of Python types, or that would be much less efficient in terms of Python types.

*Using struct members prevents every object from needing its own dict. The most important result of this is that a dict doesn't have to have an infinite descending chain of dicts, but it also improves space efficiency.

*This API existed before Python-level class statements and the way those statements do things.


text:
Q: Need help making PDO prepared statements more secure I'm building a custom CMS in PHP, and I had the idea to generate MySQL from an array. I'm guessing that's not the safest thing to do, as I'll be putting variables directly into prepared statements. I'm hoping someone more experienced could look at what I've done so far and give me some insight into how I can make this safer.
Here's the class that I store all my data manipulation methods in
abstract class MySQLData extends MySQLDataHelper {

    // connection to database
    abstract public function getConn();
    // table name from concrete class
    abstract public function getTable();

    public function insert( $args ) {
        try {
            $stmt = $this->getConn()->prepare( $this->generateInsertSQL( $args ) );

            foreach ($args as $arg => &$value) {
                $stmt->bindParam(":{$arg}", $value);
            }

            $stmt->execute();
        } catch (PDOException $e) {
            echo "Insert error: " . $e->getMessage();
        }
    }
//............................................
// More methods below, including delete, select and update, but lets focus on 'insert' only to keep things simple.
}

Helper method class, including insert SQL generator
abstract class MySQLDataHelper {

    public function generateInsertSQL( $args ) {
        $columns = array_keys( $args );

        $placeholders = implode(', :', $columns);
        $columns = implode(', ', $columns);

        return "INSERT INTO `{$this->getTable()}` ({$columns}) VALUES (:{$placeholders})";
    }
}

Example use case
require_once 'core/Pages.php';
$pages = new Pages( $db->conn() );  // Pages extends MySQLData

$args = array(
    'name'      => 'New page',
    'content'   => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quisquam, laboriosam!',
    'enabled'   => true);

$pages->insert( $args );

Note that the output from generateInsertSQL in this case would be:
INSERT INTO `pages` (name, content, enabled) VALUES (:name, :content, :enabled)

Reminder, this code works perfectly fine, I'd just like to know if it could be made safer.
Thank you. I'm new to SO so sorry if this is a bad question or in the wrong place.

A: This is a community wiki answer. Anybody can edit it to chime in.
The problem solved by bind variables is this: SQL is a language, and when you assemble statements in the language by interpolating data as if it were text, you're providing a way for untrusted people to augment your SQL programs.
So, you have to diligently sanitize everything. For example, if you're doing this kind of thing:
 id IN (4 5,6,7)

it's not too hard to make sure all the numbers are actually numbers. But you have to do it, every time, without fail, or be pwned. On the other hand, if you're doing
name IN ('cyanographics', 'Rocket Hazmat', 'Fred -ii-1')

and somebody feeds you a malicious username -- think
    cyano'); DELETE FROM TABLE USER CASCADE CONSTRAINTS; //

You end up asking your SQL language interpreter to run this.
name IN ('cyano'); DELETE FROM TABLE users CASCADE CONSTRAINTS; //', 'Rocket Hazmat', 'Fred -ii-1')

This kind of thing can potentially make a big mess of your application.
So, you need to think carefully about how to sanitize text input. You can consider cleaning your text strings with something like PDO::quote(). It puts escape sequences around dangerous characters (like ') in the strings.
But look, you're better off using the built-in bind variable support in PDO, even if it gets harder to handle the lists you want to process.
Read this:  What are the best PHP input sanitizing functions?
Also, don't forget to think about browser script injection.  What if you're handed the name
 <script>alert('You are pwned, sucka!');</script>

or something worse? You need to clean that stuff out of your input too.


text:
Q: Maze solving algorithm gets stuck between two places I'm trying to make a program (in Java) that solves a maze as part of a school project.  I'm almost done, but my algorithm seems to have a problem.  I'm using the right hand rule, but because of the way my maze is made, there isn't always a wall (see picture here? --not exactly mine, but very similar http://upload.wikimedia.org/wikipedia/commons/2/28/Prim_Maze.svg).  Consequently, The algorithm just bounces back and forth between the same two places.  Any tips/hints/help on how to avoid this problem would be greatly appreciated!  Thank you in advance!  Here's the code I'm working with right now:
public void solve(){
    /*if you can go right go right
    else if you can go forward go forward
    else if you can go left go left
    else if you can go back go back */

    int direction = 0; //0=down, 1=right, 2=up, 3=left

    int lastXSquare = 0;
    int lastYSquare = 0;

    for (int i = 0; i < 100; i++) {

        tryDirection(direction);
        hasMoved = false;
        direction = 0;
        if(lastXSquare == xSquareLocation && lastYSquare == ySquareLocation){
            tryDirection(++direction);
            hasMoved = false;
            direction = 0;
        }

    }
    if(solution[xSquareLocation][ySquareLocation]){
        lastXSquare = xSquareLocation;
        lastYSquare = ySquareLocation;
        direction++;
    }
    //if we get stuck between two, change the starting direction to try and break out of the loop
    // *****NOT WORKIKNG***
    for (int i = 0; i < 100; i++) {

        tryDirection(direction);
        hasMoved = false;
        direction = 0;
        if(lastXSquare == xSquareLocation && lastYSquare == ySquareLocation){
            tryDirection(++direction);
            hasMoved = false;
            direction = 0;
        }

    }

}

private void tryDirection(int direction){

    if(direction == 0){
        moveVertically(1);
        if(hasMoved){
            if(solution[xSquareLocation][ySquareLocation]){
                moveVertically(-1);
                direction++;
            }
            else
                solution[xSquareLocation][ySquareLocation] = true;
        }
        else{
            direction++;
        }
    }
    if(direction == 1){
        moveHorizontally(1);
        if(hasMoved){
            if(isSolved()){   return;   }
            if(solution[xSquareLocation][ySquareLocation]){
                moveHorizontally(-1);
                direction++;
            }
            else
                solution[xSquareLocation][ySquareLocation] = true;
        }
        else{
            direction++;
        }
    }
    if(direction == 2){
        moveVertically(-1);
        if(hasMoved){
            if(solution[xSquareLocation][ySquareLocation]){
                moveVertically(1);
                direction++;
            }
            else
                solution[xSquareLocation][ySquareLocation] = true;
        }
        else{
            direction++;
        }
    }
    if(direction == 3){
        moveHorizontally(-1);
        if(hasMoved){
            if(solution[xSquareLocation][ySquareLocation]){
                moveHorizontally(1);
                direction++;
            }
            else
                solution[xSquareLocation][ySquareLocation] = true;
        }
        else{
            direction = 0;
        }
    }

}

A: It seems like you are doing some variation of DFS - you are exploring a 'branch' (a single path) on the maze, and hope to find a solution.
However, DFS is not complete. It does not guarantee to find a path if one exists, and might get stuck in infinite loops. This is exacrtly the behavior you are observing.
In addition - it is not optimal - even the path it found, is not guaranteed to be the best (shortest) one.
An optimal and complete algorithm that solves this problem is BFS.
In BFS you explore all possible moves up to depth 1. Then up to depth 2, and so on and so on.
There are more advanced algorithms such as A* search algorithm (possibly with the manhattan distance heuristic), and bi-directional search, but you should stick to the simpler BFS for the time being.

A: I think your problem is that you are not really following the right-hand rule. The rule should be interpreted local to your orientation, whereas you seem to be interpreting it relative to a global orientation.
What you should be doing is:
If I can move left - turn left and step forwards
else If I can move forwards - step forwards
else If I can move right - turn right and step forwards
else turn right

where left, forwards, and right are relative to your current orientation.
The algorithm can be simplified to:
repeat
  If I could move left then
    turn left
  else
    if I can move forwards then
      move forwards
    else
      turn right
until exit reached

This should find the exit of any 2D maze where the entrance and exit are both on the external walls.


text: Q: Giving Ubuntu the same ID as Windows I alternate between Windows and Ubuntu, depending on what program I am using. However, there are some pieces of software that I only have one license to (mostly Windows software that I can run on Ubuntu with Wine). For some reason, the software registers that my Ubuntu OS is on a different device than my Windows OS. How do I make my Ubuntu OS identify as the same device that my Windows OS identifies itself as?


text:
Q: dropdown checkbox list html I have a requirement where in i wish to display a dropdown box when i click in a textbox.... Scenario is.... When i click in the textbox, there should be a list of checkboxes corresponidng to some values.... Whichever checkbox i click on, the correspoding value should get appeneded in the textbox... I tried to google this... But unable to find any solution...

A: Got the answer.... there is jquery plugin called dropdownchecklist.... It performs the function as desired...


text:
Q: Accessing Firebase data in a node with JS So I have an object being returned from Firebase that looks like this:
{key: {name: "test", email: "test", id: "test"}}
How can I get the id out of this object?
If I do returnItem I get that object, so I tried to do returnItem[0] but it's not an array, and I've tried (Object.keys(tempSnap) but that just gives me the key not the object inside it.
This is my current code:
export function sendInvitation(email) {
    firebaseRef.database().ref().child('users').orderByChild('email').equalTo(email).on("value", function(snapshot) {
        let tempSnap = snapshot.val();
        if(tempSnap != null) {
            console.log(tempSnap);
        }
    });
    return dispatch => firebaseRef.database().ref(`${userID}/invites`).push("This is a test Message!");
}

This is what it outputs:

Help would be awesome :D

A: If you already know id and it's a literal, then it's a matter of returnItem.id.
If you already know id and it's a variable, then it's returnItem[id].
If you don't know the keys and want to print all keys and their values, it's:
Object.keys(returnItem).forEach(function(key) {
  console.log(key, returnItem[key]);
});

Update
Your new code shows the problem. When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result. Your callback needs to handle the fact that it gets a list by looping over the results with snapshot.forEach():
firebaseRef.database().ref().child('users').orderByChild('email').equalTo(email).on("value", function(snapshot) {
  snapshot.forEach(function(child) {
    let tempSnap = child.val();
    console.log(tempSnap);
  });
});

A: Try this:
firebaseRef.database().ref().child('users').orderByChild('email').equalTo(email).on("value", function(snapshot) {
snapshot.forEach(function(child) {
    let keys=child.key;
    let ids=child.val().id;
      )};
   )};

you have:
 users
  keyid
   email:email
   name:yourname
   id: test


text:
Q: How do you use flexbox on an mp4 file to adjust size relative so that it scales with other items within one container? I am trying to have a video next to a paragraph of text side by side so that they both grow and shrink with the browser window size. However, when you decrease the width of the browser window the video retains the same size and squishes all the text down. I am trying to use flex box and setting both children to flex:1 but it won't scale properly.
I am including the HTML code for the section here:

                    Come Home to Simple Rick's

                    Capturing the sweetest moments into our every wafer. Simple Rick's has become the top selling experience snack in the whole Citadel. Come home to the warm feeling of happiness loved by Ricks and Mortys alike, come home to Simple Rick's.

                <button class="button">Order Now</button>

            <video class="video" controls>
                <source src="./media/Simple-Rick's-Ad.mp4" type="video/mp4">
                Your browser does not support the video tag.
            </video>

and the CSS code:
.content1 {
    padding: 60px 120px 100px 120px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.content1 .left {
    max-width: 500px;
    flex: 1;
}

.content1 .button {
    margin-top: 12px;
}

.video {
    max-width: 500px;
    margin: 0 50px;
    vertical-align: center;
    flex: 1;
}

Ideally both the video and the items within the  container can scale in the same proportions.

A: The reason why this happens is because the max-width property on the .video class keeps the video the same size regardless of the window size, so the text gets squished.
You can do the following:
.video {
    max-width: 40%;
    margin: 0 50px;
    vertical-align: center;
    flex: 1;
}

You can change the percentage value for max-width so it's to your liking. This makes the video size scale based on the size of its parent container, which will prevent it from taking up too much space within the parent and squishing the text.

A: You could also use float instead

.content1 {
  padding: 60px 120px 100px 120px;
  height: 100%;
  min-height: 100%;
  position: relative;
}

.content1 .left {
  float: left;
  width: 50%;
  max-width: 500px
}

.content1 .right {
  float: right;
  width: 40%;
}

.content1 .button {
  margin-top: 12px;
}

.videoWrapper {
  position: relative;
  padding-bottom: 56.25%;
  padding-top: 25px;
  height: 0;
}

.videoWrapper .video {
  position: absolute;
  top: 0;
  left: 0;
  width: 90%;
  height: auto;
}

      Come Home to Simple Rick's

      Capturing the sweetest moments into our every wafer. Simple Rick's has become the top selling experience snack in the whole Citadel. Come home to the warm feeling of happiness loved by Ricks and Mortys alike, come home to Simple Rick's.

    <button class="button">Order Now</button>

      <video class="video" controls>
            <source src="./media/Simple-Rick's-Ad.mp4" type="video/mp4">
            Your browser does not support the video tag.
        </video>


text:
Q: meaning of: Eating me up inside Example from Ex Machina movie:
In fact, I wanna share it with you so much, it's eating me up inside

A: Figuratively, it can mean a couple of things, depending on the context (which is clear in your example).
It can mean that you are holding something in (for example, keeping something secret) and that you are keen to let it out (tell somebody). This is the context of your example.
It can also have a more negative connotation, that something is troubling you, and that you are hurting 'inside', even though you might seem ok externally.


text:
Q: Why doesn "clpasswd" knows the "-R"? There is a symbolic link:
2:root@SERVER:/root # ls -la /usr/bin/passwd
lrwxrwxrwx    1 root     system           39 Feb  3 2014  /usr/bin/passwd -> /usr/es/sbin/cluster/utilities/clpasswd
2:root@SERVER:/root #

And there is the original binary:
2:root@SERVER:/root # ls -la /usr/es/sbin/cluster/utilities/clpasswd
-rwsr-xr-x    1 root     system       413726 Aug 29 2013  /usr/es/sbin/cluster/utilities/clpasswd
2:root@SERVER:/root #

The symbolic link knows the "-R":
2:root@SERVER:/root # /usr/bin/passwd -R files root
Changing password for "root"
root's New password:
Terminating from signal
2:root@SERVER:/root #

The clpasswd, original binary doesn't knows the "-R"
2:root@SERVER:/root # /usr/es/sbin/cluster/utilities/clpasswd -R files root
/usr/es/sbin/cluster/utilities/clpasswd: illegal option -- R

Usage: clpasswd cluster_user [ -g ResourceGroup ]
Where:
    -g ResourceGroup - Update on participating nodes only
                       Otherwise all cluster nodes receive update

2:root@SERVER:/root #

Why doesn't the original binary knows the "-R" option, when the symbolic link knows it?
We tried with hard link too, didn't worked.

A: The binary checks its filename.
0:root@SERVER:/root # ln -s /usr/es/sbin/cluster/utilities/clpasswd /tmp/passwd
0:root@SERVER:/root # /tmp/passwd -R files root
Changing password for "root"
root's New password:
Terminating from signal
0:root@SERVER:/root # mv /tmp/passwd /tmp/clpasswd
0:root@SERVER:/root # /tmp/clpasswd -R files root
/tmp/clpasswd: illegal option -- R

Usage: clpasswd cluster_user [ -g ResourceGroup ]
Where:
    -g ResourceGroup - Update on participating nodes only
                       Otherwise all cluster nodes receive update

0:root@SERVER:/root #


text:
Q: How to set the width of playground liveview? As shown in below, I just code to see a square ImageView, in LiveView, it will only show partially. I cannot scroll the view left or right, but can only need to drag the view left (and shrink my coding editor view) in order to see the full cyan color ImageView.

My question is

*

*How to get the liveview shown by default aligned left (e.g. showing the entire left part of the view OR

*Is there a way to define the width of the liveview, so that I can make is smaller and fitting to my screen (so I don't need to drag to see the left edge)?

Note: I'm using Xcode 12.1
UPDATE
Using Xcode 11.7, it looks better with the same code. Is this Xcode 12 issue?

A: I worked around it using
    override func viewDidLoad() {
        imageView.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
        imageView.backgroundColor = .cyan
        view.addSubview(imageView)

        imageView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
            imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        ])
    }


text:
Q: python crash course 19-1 Blog editing posts not working I'm working on the project Blog, the new_post works but I can't get edit_post to work. In posts.html, if I keep the post.id on the link 'edit post' when I run localhost:8000, it shows NoReverseMatch; if I delete the post.id, I'm able to get the edit post tag on the homepage but when clicking on it, it shows:

TypeError at /edit_post/

What did I do wrong? I've been going through this problem a couple days, yet can't find the solution, please help!
models.py
from django.db import models

class BlogPost(models.Model):
    '''A blog'''
    title = models.CharField(max_length=200)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        '''Return a string representation of the model.'''
        return self.title

    def __str__(self):
        '''Return a string representation of the model.'''
        if len(self.text) > 50:
            return self.text[:50] + '...'
        else:
            return self.text

forms.py
from django import forms
from .models import BlogPost

class PostForm(forms.ModelForm):
    class Meta:
        model = BlogPost
        fields = ['text']
        labels = {'text': ''}

urls.py
'''Defines URL patterns for blogs.'''

from django.urls import path
from . import views

app_name = 'blogs'
urlpatterns = [
    # Home page
    path('', views.posts, name='posts'),

    # Page for adding a new post
    path('new_post/', views.new_post, name='new_post'),

    # Page for editing a post
    path('edit_post/', views.edit_post, name='edit_post'),
]

views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse

from .models import BlogPost
from .forms import PostForm

def posts(request):
    '''The home page for blog and shows all posts'''
    posts = BlogPost.objects.order_by('date_added')
    context = {'posts': posts}
    return render(request, 'blogs/posts.html', context)

def new_post(request):
    '''Add a new post.'''
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = PostForm()
    else:
        # POST data submitted; process data.
        form = PostForm(data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('blogs:posts'))

    context = {'form': form}
    return render(request, 'blogs/new_post.html', context)

def edit_post(request, post_id):
    '''Edit an existing post.'''

    post = BlogPost.objects.get(id=post_id)

    if request.method != 'POST':
        # Initial request; pre-fill form with the current post.
        form = PostForm(instance=post)
    else:
        # POST data submitted; process data.
        form = PostForm(instance=post, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('blogs:posts', args=[post.id]))

    context = {'post': post, 'posts': posts, 'form': form}
    return render(request, 'blogs/edit_post.html', context)

posts.html

Blog Posts

  {% for post in posts %}

{{ post }}

  {% empty %}

No posts have been added yet.

  {% endfor %}

  Add a new post:

  edit post

{% block content %}{% endblock content %}

new_post.html
{% extends "blogs/posts.html" %}

{% block content %}

Add a new post:

  <form action="{% url 'blogs:new_post' %}" method='post'>
    {% csrf_token %}
    {{ form.as_p }}
    <button name="submit">add post</button>
  </form>

{% endblock content %}

edit_post.html
{% extends "blogs/posts.html" %}

{% block content %}

Edit post:

  <form action="{% url 'blogs:edit_post' post.id %}" method='post'>
    {% csrf_token %}
    {{ form.as_p }}
    <button name="submit">save changes</button>
  </form>

{% endblock content %}

A: In your urls.py, you need to add a URL pattern. Read more here.
'''Defines URL patterns for blogs.'''

from django.urls import path
from . import views

app_name = 'blogs'
urlpatterns = [
    # Home page
    path('', views.posts, name='posts'),

    # Page for adding a new post
    path('new_post/', views.new_post, name='new_post'),

    # Page for editing a post
    path('edit_post/<int:id>/', views.edit_post, name='edit_post'),
    # Assuming 'id' is an integer, add it as a URL pattern
]

A: You are closing forloop before the edit_post url so you need to change here:
{% for post in posts %}

{{ post }}

  {% empty %}

No posts have been added yet.

  Add a new post:

  edit post

  {% endfor %}

And also pass the post_id in your url
path('edit_post/<int:post_id>/', views.edit_post, name='edit_post'),


text:
Q: C++ constructor prototype parameter For example, there is a class foo :
class foo {
public:
      foo (int = 10);
.....
}

The prototype of the constructor  has "int = 10" inside. So, what does it mean? Int is just an integer type, isn't? So, isn't  that illegal to assign a value to it?  I was trying to find such an example in Prata's book, and everywhere else, but I didn't  find the explanation.

A: You can omit the name of parameter in function declaration (in definition too), but still you are able to specify default value of that parameter.
Consider:
void f(int x = 10) {
    printf("%d\n", x);
}

void g(int = 10);

void g(int x) {
    printf("%d\n", x);
}

int main() {
    f();
    g();
    return 0;
}

Result:
10
10

The same situation is in the constructor case.

A:
So, isn't that illegal to assign a value to it?

There is absolutely no assignment involved here. The = character can have quite different meanings in C++:

*

*Assignment: i = 0;

*Initialisation: int i = 0;

*Making a member function pure virtual: virtual void f() = 0;

*Specifiying default arguments: void f(int i = 0);
The latter is what you have encountered. A constructor can have default arguments like any other normal function.


text:
Q: Customize Issue Tracker list form with powerapps I have an issue tracker list in SharePoint 2013 environment. In the course of migration to SharePoint online, we are successfully able to migrate Issue Tracker list. Now the goal is to customize the list form using powerapps. In list setting -> form settings, the option to customize the form is not available. If we plan to create an independent powerapps form this list as a data source, the issue tracker list doesn't appear to be available there. Is it possible to customize an issue tracker list's form using powerapps or creating a powerapps form on the top of legacy issue tracker list in SharePoint online? or are there any other work arounds?
your suggestions are welcomed.
Thanks.

A: Power Apps customized forms are only supported in modern experience currently.
You cannot customize the list forms for classic experience list forms.
References:

*

*SharePoint Classic experience list forms Power Apps not working

*Customize a Microsoft Lists or SharePoint form by using Power Apps


text:
Q: Re-adding removed elements in d3.js
Note that there is not currently a dedicated API to add removed elements back to the document; however, you can pass a function to selection.append or selection.insert to re-add elements.

https://github.com/mbostock/d3/wiki/Selections
What is meant by passing a function? I am not sure how to go about implement this. I tried passing an function that appends the removed div back to the parent, but didnot work. Any ideas?
This is a relatively new feature in d3.

A: a function that returns the DOM element to append
So you could simply do something like:
d3.select("body").append(function() {
    return document.createElement("div");
});

Instead of simply using the string name
d3.select("body").append("div");

When you are using d3 selectors, keep in mind they are not single elements. They are an array of groups. Thus, if you said:
var divs = d3.select("div").remove(); // actually a multidimensional array
var firstElement = divs[0][0]; // this can be appended by returning it

The relevant text from Mike is: One nuance is that selections are grouped: rather than a one-dimensional array, each selection is an array of arrays of elements
Here is a simple working fiddle to show a very basic example.


text:
Q: What happens if I concurrently access a single go map? I know that go maps are not safe for concurrent access, but what happens if I do access them concurrently? Are they safe for concurrent read-access? Could I break it to a point where it loses all or some of its data? Is there a point where the whole program could crash if I modify it and read it at the same time? Do I need to have two different processes modifying it concurrently to mess things up?
I'm interested in both the standard go compiler, and gccgo.
What can happen if I concurrently access/modify a go map?


text:
Q: Embed current View Controller in Tab Bar Controller I currently have a single view application which I need to convert to a tab bar application. I'm new to iOS and not quite sure how to embed the current view controller into the controller for the tab bar. Can anyone help with this?

A: You can select your view controller and then from Edit, select Embed In and then Tab Bar Controller

For more info, you can check this in-detail tutorial: http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1


text:
Q: Lectura de archivos en c #include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct pila{
   int clave;
   char nombre[50];
   float salario;
   struct pila *psig;
}pila;

pila *pmaestro;
pila *NuevoElem();
void push(int clave,char nombre[],float salario);
void imprimir(pila *);

int main()
{
    char nmbre[50];
    int clve;
    float slrio;
    FILE *f1;
    f1=fopen("listas.txt","r");
    if(f1!=NULL){
            // ********
            while(!feof(f1)){
                fscanf(f1,"%d,%s,%f",&clve,nmbre,&slrio);
                push(clve,nmbre,slrio);
            }
            // ********
    }else{
        printf("Error de apertura");
    }
    imprimir(pmaestro);
    fclose(f1);
 return 0;
}

void push(int clave,char nombre[],float salario)
{ pila *q = NuevoElem();
   q->psig = pmaestro;
   q->clave = clave;
   strcpy(q->nombre,nombre);
   q->salario = salario;
   pmaestro = q;
}

pila *NuevoElem()
{ pila *q = (pila *)malloc(sizeof(pila));
  if (q==NULL) { printf("Falta memoria"); exit(0);}
  return q;
}

void imprimir(pila *pmaestro)
{
   while(pmaestro!=NULL)
   {
      printf("%d\t%s\t%f", pmaestro->clave,pmaestro->nombre,pmaestro->salario);
      pmaestro = pmaestro->psig;
   }
   printf("\n");
}

Este código debe de leer un archivo que contiene una serie de claves, nombres y salarios. Al momento de querer leer el archivo, por algún motivo se cicla el while y no avanza de ahí. ¿Por qué se cicla?

A: Por lo que vi tenes 2 problemas en tu codigo. El primero es en el fscanf() en la cadena de formato. Vos indicaste "%d,%s,%f", podría deducir que tu archivo lista.txttiene formato del tipo <Clave>,<Nombre>,<Salario>, en caso de equivocarme, por favor indícame como es el formato correcto. El error aca esta que cuando lea el formato %sva a leer nombre y salario junto. Ya que la lectura se realiza hasta encontrar un espacio o un '\n'.
Si podes modificar el archivo de texto, simplemente agrégale, en vez de una coma, un espacio entre el campo de nombre y salario. Caso contrario te recomiendo cambiar de estrategia de lectura.
Algunas ideas que se me ocurren es usar fgets para obtener toda la linea del archivo (recorda que esta funcion captura el '\n' asi que tendras que removerlo de alguna manera e ir separando los campos.
Como segundo error esta en este fragmento de codigo
 while(!feof(f1)){
    fscanf(f1,"%d,%s %f",&clve,nmbre,&slrio);
    push(clve,nmbre,slrio);
 }

Si ubicas de esta forma el fscanf o cualquier metodo para leer el contenido del archivo vas a entrar 1 vez mas al while de lo debido. Te hago un ejemplo con los siguientes datos:
 1,Juan 107.50
 2,Ana 109.25

PD: en este caso asumí que se podía hacer la modificación explicada mas arriba de cambiar la , por un espacio.
En la primera etapa del bucle, tu indicador de registro activo apunta al registro de Juan, lees el contenido y lo almacenas en la pila. Como no es el fin del archivo, sigo entrando en el while (el indicador de registro sigue apuntado a Juan)
En la segunda etapa se lee el registro de Ana (el ultimo registro del archivo) y se inserta. Vuelve a evaluar la condición del while, devuelve trueya que el apuntador esta en el registro de Ana pero esto ya es un error ya que no hay mas registros para leer u almacenar y lo que estarás insertando en la pila es basura.
Esto lo solucionaria de la siguiente manera:
fscanf(f1, "%d,%s %f", &clve, nmbre, &slrio);
        while (!feof(f1)) {
            push(clve, nmbre, slrio);
            fscanf(f1, "%d,%s %f", &clve, nmbre, &slrio);
        }

Cosa de ya leer el primer registro y almacenarlo en la lista (siempre y cuando haya mas de 1 registro). Y de esta manera evitas leer basura. O sino podrias agregar un if preguntando si es el fin del archivo y salir del bucle o como mas te guste.
Tambien encontre en la funcion mostrar, que no es un error, que te olvidaste el \n luego de mostrar el contenido de la pila. Para visualizar cada registro uno abajo del otro y no todo seguido.
Espero que te haya ayudado y si algo no se entendió o me falto explicar, házmelo saber.
Saludos


text:
Q: Get class input with closest I want to get class .mGMZs in input name=age with .closest, I try it in following demo but i doesn't work as expected, how can I fix it?

        <input name="age[0][]" class="mGMZs" placeholder="Age(Geting class this)">

    <button>Click Me</button>

$('button').live('click', function () {
    var class_age = '.' + $(this).closest('div.age').find('input[name="age"]').prop('name');
    alert(class_age);
})

A: Replace:
.find('input[name="age"]')

With:
.find('input.mGMZs')

So you can find based on input's class:
$('button').live('click', function () {
    var class_age = '.' + $(this).closest('div.age').find('input.mGMZs').prop('name');
    alert(class_age);
});

A: You can do this with a little change:
.find('input[name*="age"]')

http://jsfiddle.net/g8wjC/11/


text:
Q: jQuery: fade in 1 element on hover while fading out many others in a smooth fashion In my page I have severals divs. When the user hovers over 1 div I want to fade out all other elements except the one the user is hovering over.
This works with the code below, however:
When the user moves fast with his mouse over all items, it appears as if the fading proces for each item is queued and even though the user is no longer moving his mouse, the fading out continues until the queue is empty.
To test, check my code below and move your mouse for example from the left to the right and notice the effect.
What I want to achieve is that the current item on which the user hovers has opacity of 1 while the others are then given 0.7.
How can I do this?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Item

Item

Item

Item

Item

Item

A: You can add .stop() prevent the queue from building:
curelement.stop().fadeTo(500, 1.0);

$('.element').not('.elementhovered').stop()fadeTo(500, 0.7);


text:
Q: How to display grid lines in a flex 4 list? I am newbie with Flex 4 (and Flex/AS in general).
I am using a spark list control to display certain items with my custom Item Renderer.
I am trying to achieve the following:
(1) show a separating line between rows in my list control
(2) even when not a single row has been added, I want a horizontal grid lines to be displayed in the background
I am not sure whether (1) and (2) can be achieved in one go.
I can solve (1) by modifying my item renderer to have a border, I guess. But I want to know whether there is a better or more conventional way.
I am not sure how to address (2).
Thanks!

A: I would do it like you said , drawing a line at the bottom of the item renderer.
As for (2), you could add a line directly on a custom list skin and remove it when the dataprovider is set


text:
Q: How VM Name is resolved over the LAN Network? I have hosted a VM (Red Hat Linux) named test-vm on my Desktop machine (Windows) with a static IP address but I don't have any DNS entry for this static IP address.
Without having an entry in the client's host file, to my wonder the ping test-vm responds. How is this possible? How test-vm is resolved at other machines on our LAN Network without having a DNS entry for test-vm?
Regards,
Adil Khalil

A: I guess you are using vmware client in your windows desktop. In this case, the hostname is associated to your vmware virtual DNS. With a ping of broadcast in your network, your vmware virtual DNS is forwarding the ping to your VM Client.


text:
Q: Passing form variables offsite to an iframe I have Site A, which has a form on it.  That passes the form info via GET to another website, Site B.  This works perfectly fine.
NOW, I want to send the form to an IFRAME located on Site B instead.  So on Site A, I have the code:
<form method="get" action="http://<page with iframe on site B>" target="iframeName">

On the PAGE itself on Site B, I have THIS code:
   <iframe id="iframeName" src="<page that uses the passed variables>" name="iframeName" frameborder="0" noresize="noresize">
   </iframe>

The PROBLEM is, the passed variables don't seem to get getting to the iframe.  They appear in the URL of the PARENT of the iframe, but don't seem to get to the iframe itself.
I can NOT modify the site that loads in the iframe.
Why am I doing this?  Just like on codecanyon when you view something, it has the bar at the top for the original page navigation.

A: Try to send the parameter on the Src, when you initiliaze the iframe ;)
   <iframe id="iframeName" src="<page that uses the passed variables>?PARAMETER=XXX" name="iframeName" frameborder="0" noresize="noresize">
   </iframe>

So basically, retrieve the parameter from the site A by using a GET, and the initialize your iframe by passing these paramete.