text:
Q: What is required to make Android use a new Audio HAL I am writing a new Android Audio HAL, to let my App to feed audio to other apps, to allow my handheld remote microphone input to reach Google app. Essentially, a Virtual Audio Cable.
Its a work in progress.
I'll probably be overriding AUDIO_DEVICE_IN_BACK_MIC, but this is open for suggestions.
I have doubts on how to make sure Android uses this HAL for input.
Do I need to replace audio.primary.default.so or should I leave it as audio.vcable.default.so?
More specifically: If I am not replacing primary, how will Android know to use my HAL instead  of primary?

Update:
I could really use any help in this work. Any pointers are helpful.
I have written an Audio HAL module. I have added following (bold items) to audio_policy.conf:
global:
global_configuration {
  attached_output_devices AUDIO_DEVICE_OUT_SPEAKER|**AUDIO_DEVICE_OUT_LINE**
  default_output_device AUDIO_DEVICE_OUT_SPEAKER
  attached_input_devices AUDIO_DEVICE_IN_BUILTIN_MIC|AUDIO_DEVICE_IN_BACK_MIC|AUDIO_DEVICE_IN_REMOTE_SUBMIX|**AUDIO_DEVICE_IN_LINE**
}

and under audio_hw_modules
  vloop {
    inputs {
      vloop {
        sampling_rates 16000
        channel_masks AUDIO_CHANNEL_IN_MONO
        formats AUDIO_FORMAT_PCM_16_BIT
        devices AUDIO_DEVICE_IN_LINE
      }
    }
    outputs {
      vloop {
        sampling_rates 16000
        channel_masks AUDIO_CHANNEL_OUT_STEREO
        formats AUDIO_FORMAT_PCM_16_BIT
        devices AUDIO_DEVICE_OUT_LINE
        flags AUDIO_OUTPUT_FLAG_DIRECT
      }
    }
  }

I also added following (bold) to AudioFlinger.cpp
static const char * const audio_interfaces[] = {
    AUDIO_HARDWARE_MODULE_ID_PRIMARY,
    AUDIO_HARDWARE_MODULE_ID_A2DP,
    AUDIO_HARDWARE_MODULE_ID_USB,
    **AUDIO_HARDWARE_MODULE_ID_VLOOP**
};

I can see that during boot, my HAL gets loaded, and I get these logs:
10-06 06:14:40.365 194-194/? I/AudioFlinger: Using default 3000 mSec as standby time.
10-06 06:14:46.664 194-194/? I/AudioPolicyService: AudioPolicyService CSTOR in new mode
10-06 06:14:46.673 194-194/? I/APM::ConfigParsingUtils: loadAudioPolicyConfig() loaded /system/etc/audio_policy.conf
10-06 06:14:46.681 194-194/? D/audio_hw_primary: adev_open: enter
10-06 06:14:46.797 194-194/? I/AudioFlinger: loadHwModule() Loaded primary audio interface from QCOM Audio HAL (audio) handle 1
10-06 06:14:46.797 194-194/? I/AudioFlinger: openOutput(), module 1 Device 2, SamplingRate 48000, Format 0x000001, Channels 3, flags 2
10-06 06:14:46.797 194-194/? I/AudioFlinger: AudioStreamOut::open(), mHalFormatIsLinearPcm = 1
10-06 06:14:46.798 194-194/? I/AudioFlinger: HAL output buffer size 240 frames, normal sink buffer size 960 frames
10-06 06:14:46.813 194-194/? I/AudioFlinger: Using module 1 has the primary audio interface
10-06 06:14:46.816 194-607/? I/AudioFlinger: AudioFlinger's thread 0xb4140000 ready to run
10-06 06:14:46.816 194-607/? D/audio_hw_primary: out_set_parameters: enter: usecase(1: low-latency-playback) kvpairs: routing=2
10-06 06:14:46.818 194-194/? I/AudioFlinger: openOutput(), module 1 Device 2, SamplingRate 48000, Format 0x000001, Channels 3, flags 8
10-06 06:14:46.818 194-194/? I/AudioFlinger: AudioStreamOut::open(), mHalFormatIsLinearPcm = 1
10-06 06:14:46.818 194-194/? I/AudioFlinger: HAL output buffer size 960 frames, normal sink buffer size 960 frames
10-06 06:14:46.818 194-608/? I/AudioFlinger: AudioFlinger's thread 0xb3dc0000 ready to run
10-06 06:14:46.818 194-607/? E/AudioFlinger: no wake lock to update!
10-06 06:14:46.818 194-608/? D/audio_hw_primary: out_set_parameters: enter: usecase(0: deep-buffer-playback) kvpairs: routing=2
10-06 06:14:46.818 194-608/? E/AudioFlinger: no wake lock to update!
10-06 06:14:46.820 194-609/? I/AudioFlinger: AudioFlinger's thread 0xb3c40000 ready to run
10-06 06:14:46.823 194-194/? I/AudioFlinger: loadHwModule() Loaded a2dp audio interface from A2DP Audio HW HAL (audio) handle 7
10-06 06:14:46.828 194-194/? I/AudioFlinger: loadHwModule() Loaded usb audio interface from USB audio HW HAL (audio) handle 8
10-06 06:14:46.832 194-194/? I/r_submix: adev_open(name=audio_hw_if)
10-06 06:14:46.832 194-194/? I/AudioFlinger: loadHwModule() Loaded r_submix audio interface from Wifi Display audio HAL (audio) handle 9
10-06 06:14:46.832 194-194/? D/r_submix: submix_audio_device_create_pipe_l(addr=0, idx=9)
10-06 06:14:46.833 194-610/? I/AudioFlinger: AudioFlinger's thread 0xb3bc0000 ready to run
10-06 06:14:46.833 194-194/? D/r_submix: submix_audio_device_release_pipe_l(idx=9) addr=0
10-06 06:14:46.833 194-194/? D/r_submix: submix_audio_device_destroy_pipe_l(): pipe destroyed
10-06 06:14:46.835 194-194/? D/audio_vloop: adev_open: audio_hw_if
10-06 06:14:46.835 194-194/? D/audio_vloop: adev_open(): 1678
10-06 06:14:46.835 194-194/? D/audio_vloop: adev_open(): 1685
10-06 06:14:46.835 194-194/? D/audio_vloop: adev_open(): 1688
10-06 06:14:46.835 194-194/? D/audio_vloop: adev_open(): 1722
10-06 06:14:46.835 194-194/? D/audio_vloop: adev_init_check(): 1252
10-06 06:14:46.835 194-194/? D/audio_vloop: adev_set_master_volume: 1.000000
10-06 06:14:46.835 194-194/? D/audio_vloop: adev_set_master_mute: 0
10-06 06:14:46.835 194-194/? I/AudioFlinger: loadHwModule() Loaded vloop audio interface from UI_audio_HW_HAL (audio) handle 11
10-06 06:14:46.835 194-194/? D/audio_vloop: adev_open_input_stream(): 1490
10-06 06:14:46.835 194-194/? D/audio_vloop: in_get_sample_rate(): 979
10-06 06:14:46.835 194-194/? D/audio_vloop: in_get_channels(): 1017
10-06 06:14:46.835 194-194/? D/audio_vloop: in_get_channels: 0x00000001
10-06 06:14:46.835 194-194/? D/audio_vloop: in_get_format(): 1029
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_format: 0x00000001
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_format(): 1029
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_format: 0x00000001
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_channels(): 1017
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_channels: 0x00000001
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_buffer_size(): 1005
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_buffer_size: 1600
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_buffer_size(): 1005
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_buffer_size: 1600
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_format(): 1029
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_format: 0x00000001
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_sample_rate(): 979
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_channels(): 1017
10-06 06:14:46.836 194-194/? D/audio_vloop: in_get_channels: 0x00000001
10-06 06:14:46.838 194-613/? I/AudioFlinger: AudioFlinger's thread 0xb3bc0000 ready to run
10-06 06:14:46.838 194-194/? D/audio_vloop: adev_close_input_stream(): 1570
10-06 06:14:46.839 194-194/? W/APM::AudioPolicyManager: Input device 00020000 unreachable
10-06 06:14:46.839 194-611/? D/audio_vloop: looper_thread(): 216: Entered
10-06 06:14:46.839 194-611/? D/audio_vloop: looper_thread(): 366: Exiting
10-06 06:15:07.137 616-616/? I/InputManager: Initializing input manager, mUseDevInputEventForAudioJack=false
10-06 06:15:10.155 616-616/? I/SystemServer: Audio Service
10-06 06:15:10.222 194-607/? E/AudioFlinger: no wake lock to update!
10-06 06:15:10.222 194-608/? E/AudioFlinger: no wake lock to update!
10-06 06:15:10.224 194-614/? D/audio_hw_primary: adev_set_mic_mute: state 0
10-06 06:15:10.224 194-614/? D/audio_vloop: adev_set_mic_mute: 0
10-06 06:15:14.061 194-614/? D/audio_hw_primary: adev_set_parameters: enter: A2dpSuspended=false
10-06 06:15:14.061 194-614/? D/audio_vloop: adev_set_parameters(): [A2dpSuspended=false]
10-06 06:15:14.084 194-194/? I/AudioFlinger: systemReady
10-06 06:15:16.308 194-194/? D/audio_hw_primary: adev_set_mic_mute: state 0
10-06 06:15:16.308 194-194/? D/audio_vloop: adev_set_mic_mute: 0
10-06 06:15:17.072 194-194/? D/audio_hw_primary: adev_set_parameters: enter: A2dpSuspended=false
10-06 06:15:17.072 194-194/? D/audio_vloop: adev_set_parameters(): [A2dpSuspended=false]
10-06 06:15:25.023 733-733/? W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client; transfer 4, track 44100 Hz, output 48000 Hz
10-06 06:15:25.032 194-607/? D/audio_hw_primary: out_set_parameters: enter: usecase(1: low-latency-playback) kvpairs: routing=2
10-06 06:15:25.043 194-607/? D/audio_hw_primary: select_devices: out_snd_device(2: speaker) in_snd_device(0: none)
10-06 06:15:25.043 194-607/? D/audio_hw_primary: enable_snd_device: snd_device(2: speaker)
10-06 06:15:25.050 194-607/? D/audio_hw_primary: enable_audio_route: apply and update mixer path: low-latency-playback
10-06 06:15:26.431 1150-1298/? I/MicrophoneInputStream: mic_starting com.google.android.apps.gsa.speech.audio.ag@c6eb0e1
10-06 06:15:26.443 194-1585/? I/AudioFlinger: AudioFlinger's thread 0xb3bc0000 ready to run
10-06 06:15:26.447 1150-1298/? I/MicrophoneInputStream: mic_started com.google.android.apps.gsa.speech.audio.ag@c6eb0e1
10-06 06:15:26.457 194-1585/? D/audio_hw_primary: select_devices: out_snd_device(0: none) in_snd_device(38: voice-rec-mic)
10-06 06:15:26.457 194-1585/? D/audio_hw_primary: enable_snd_device: snd_device(38: voice-rec-mic)
10-06 06:15:26.460 194-1585/? D/audio_hw_primary: enable_audio_route: apply and update mixer path: audio-record
10-06 06:15:26.942 1150-1271/? I/AudioController: internalShutdown
10-06 06:15:26.943 1150-1271/? I/MicrophoneInputStream: mic_close com.google.android.apps.gsa.speech.audio.ag@c6eb0e1
10-06 06:15:26.943 1150-1298/? E/AudioRecord-JNI: Error -4 during AudioRecord native read
10-06 06:15:26.986 194-1585/? D/audio_hw_primary: disable_audio_route: reset and update mixer path: audio-record
10-06 06:15:26.987 194-1585/? D/audio_hw_primary: disable_snd_device: snd_device(38: voice-rec-mic)
10-06 06:15:27.066 194-607/? D/audio_hw_primary: out_set_parameters: enter: usecase(1: low-latency-playback) kvpairs: routing=2
10-06 06:15:27.100 194-607/? D/AudioFlinger: mixer(0xb4140000) throttle end: throttle time(7)
10-06 06:15:30.257 194-607/? D/audio_hw_primary: disable_audio_route: reset and update mixer path: low-latency-playback
10-06 06:15:30.257 194-607/? D/audio_hw_primary: disable_snd_device: snd_device(2: speaker)
10-06 06:15:30.262 194-607/? D/audio_hw_primary: out_set_parameters: enter: usecase(1: low-latency-playback) kvpairs: routing=2
10-06 06:15:30.272 194-607/? D/audio_hw_primary: select_devices: out_snd_device(2: speaker) in_snd_device(0: none)
10-06 06:15:30.273 194-607/? D/audio_hw_primary: enable_snd_device: snd_device(2: speaker)
10-06 06:15:30.280 194-607/? D/audio_hw_primary: enable_audio_route: apply and update mixer path: low-latency-playback
10-06 06:15:30.347 194-607/? D/AudioFlinger: mixer(0xb4140000) throttle end: throttle time(10)
10-06 06:15:31.517 194-607/? D/audio_hw_primary: out_set_parameters: enter: usecase(1: low-latency-playback) kvpairs: routing=2
10-06 06:15:31.751 1150-1298/? I/MicrophoneInputStream: mic_starting com.google.android.apps.gsa.speech.audio.ag@dd13203
10-06 06:15:31.762 194-1826/? I/AudioFlinger: AudioFlinger's thread 0xb3bc0000 ready to run
10-06 06:15:31.771 1150-1298/? I/MicrophoneInputStream: mic_started com.google.android.apps.gsa.speech.audio.ag@dd13203
10-06 06:15:31.780 194-1826/? D/audio_hw_primary: select_devices: out_snd_device(0: none) in_snd_device(38: voice-rec-mic)
10-06 06:15:31.780 194-1826/? D/audio_hw_primary: enable_snd_device: snd_device(38: voice-rec-mic)
10-06 06:15:31.783 194-1826/? D/audio_hw_primary: enable_audio_route: apply and update mixer path: audio-record
10-06 06:15:34.695 194-607/? D/audio_hw_primary: disable_audio_route: reset and update mixer path: low-latency-playback
10-06 06:15:34.695 194-607/? D/audio_hw_primary: disable_snd_device: snd_device(2: speaker)
10-06 06:15:34.850 1150-1271/? I/AudioController: internalShutdown
10-06 06:15:34.851 1150-1271/? I/MicrophoneInputStream: mic_close com.google.android.apps.gsa.speech.audio.ag@dd13203
10-06 06:15:34.851 1150-1298/? E/AudioRecord-JNI: Error -4 during AudioRecord native read
10-06 06:15:34.885 194-1826/? D/audio_hw_primary: disable_audio_route: reset and update mixer path: audio-record
10-06 06:15:34.885 194-1826/? D/audio_hw_primary: disable_snd_device: snd_device(38: voice-rec-mic)

Mine is audio_vloop. I can see that Android opens my device, then opens input stream, and then closes the input stream. It never attempts to open output stream. audio_vloop implements both input and output streams. After this, nothing in audio_vloop is ever invoked by Android.
I made a small app that plays audio (from a pcm file for now). I want to redirect this output to my HAL. To achieve this, I believe I need to do a AudioTrack.setPreferredDevice() on my audio track. I found that Audio Manager should have a list of all audio devices.
so I call :
AudioDeviceInfo aDevInfo[] = am.getDevices(AudioManager.GET_DEVICES_OUTPUTS);

It  only finds 1 device, more info on this device:
10-06 06:37:01.962 3295-3663/? D/AudioPlayer: Have [1] devices
10-06 06:37:01.964 3295-3663/? D/AudioPlayer: devInfo[0]: [Landroid.media.AudioDeviceInfo;@90bd9da
10-06 06:37:01.965 3295-3663/? D/AudioPlayer: getProductName()AOSP on Flo
10-06 06:37:01.965 3295-3663/? D/AudioPlayer: getType()2
10-06 06:37:01.966 3295-3663/? D/AudioPlayer: isSink()true
10-06 06:37:01.966 3295-3663/? D/AudioPlayer: isSource()false

This seemingly is from audioPort which I have not implemented. So its not from my HAL.
I've obviously missed one or more steps before Android will allow my app to talk to my device.
I need to be able to send audio from my app into my HAL.
Later, I also need to be able to receive audio from my HAL (through AudioRecord etc).
What did I missed in integrating my HAL into Android?
Do I need to implement Audio Ports?
Is something else required?

Update 2
I found there is a typo in AOSP, in AudioPolicyManager.cpp@2922
Instead of Output, it prints Input
I had this log AudioPolicyManager: Input device 00020000 unreachable which I disregarded assuming it is talking about BT/A2DP input device.
I fixed the log for my device, and it turns out to be Line out device which we want to use. I am debugging this direction now.

A: Found answers.
For out stream:

*

*Outputs that don't support AUDIO_CHANNEL_OUT_STEREO are not being opened by Android

*Outputs that mention flag AUDIO_OUTPUT_FLAG_DIRECT are not opened by Android automatically. This is evident in following code in AudioPolicyManager.cpp
    if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
        continue;
    }

from here
There may be a way to open them in programatically, but I have not found answer to that.
These two, once fixed were sufficient for Android to start using my out stream.
For in stream:
In stream was already a part of results of AudioManager.getDevices()
So it was possible to read from vloop in stream after AudioTrack.setPreferredDevice().
To ensure that other apps will read mic input from vloop, I had to declare it to implement AUDIO_DEVICE_IN_BUILTIN_MIC. For this to work, I also removed AUDIO_DEVICE_IN_BUILTIN_MIC from primary HAL in audio_policy.conf.
Additionally, I made in stream stereo only to maintain compatibility with out stream buffer format.
After these changes, I see that there are continuous read and write calls coming to vloop.
UPDATE:
I later found that above mentioned behavior is dependent on Audio Policy Manager implementation. Most of them behave same way, (e.g. most open INBUILT_MIC for VOICE_RECOGNITION input) but some may not (Nexus Player) For these outliers, either implemnent what their APMs open, or modify APMs to open what your HAL implements.


text:
Q: PHP var_dump($_SESSION); I am working on a project and the $_SESSION['username'] was not echoing I used the var_dump and this is what I got back from that result my question is how do I fix it.
    array(4) {
 ["SESS_ID"]=> string(1) "2"
 ["SESS_FIRST_NAME"]=> string(7) "Kevin"
 ["SESS_LAST_NAME"]=> string(6) "Outerbridge"
 ["username"]=> string(0) "" }

I am sort of new to this var_dump so I am not sure if it is in your forum I will relook at all that is posted.

A: PHP var_dump() function will display always null for $_SESSIONS.
You can use :
 Print_r ($_SESSION);

Thought it may help,
Have a nice one

A: "Fix" what?
$_SESSION['username'] has the value "", or the empty string.
If that's not what you wanted, do whatever you need to do to make that not happen.
I'm sorry that this appears like a useless answer, but really it's a useless question.

A:
$_SESSION['username'] was not echoing

It seems like it was potentially echoing an empty value because if you look in your array:
["username"]=> string(0) ""

contains an empty value

A: Your SESSION variable exists, but it is empty. You're filling that variable with an empty string.

A: Do you started the session?
session_start();

A: In case someone needs an answer to this question. In my experience working with $_SESSION global, if you navigate from the original page of a form by opening another instance of the browser, you do not automatically get the same $_SESSION hence the variables are empty. Use the 'action' property of your form to navigate to your processing page so that you have an active session filled with the session variables. Also insure that you have session_start() in some form for each page. This can be easily misunderstood when developing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Syntax error (missing operator) in query expression: System.Data.OleDb.OleDbException I am sending the following SQL query in MS Access 2016 as a string in ASP WebForm:
string showGridViewQuery = "select creditorName, amount, interestRate, interestType, interestCalculationMethod, insertedDate, o.fullName as owner, u.fullName as dataInsertedBy from tbl_savings s left join tbl_users o on ownerID = o.userID left join tbl_users u on dataEnteredByID = u.userID";

When I run, I get the following error:

System.Data.OleDb.OleDbException: Syntax error (missing operator) in query expression 'ownerID = o.userID left join tbl_users u on dataEnteredByID = u.userID'.

when the execution reaches showGridViewCommand.ExecuteNonQuery(); in the following code:
string connectionString = GetConnString();
OleDbConnection con = new OleDbConnection(connectionString);
con.Open();
string showGridViewQuery = "select creditorName, amount, interestRate, interestType, interestCalculationMethod, insertedDate, o.fullName as owner, u.fullName as dataInsertedBy from tbl_savings s left join tbl_users o on ownerID = o.userID left join tbl_users u on dataEnteredByID = u.userID";
OleDbCommand showGridViewCommand = new OleDbCommand(showGridViewQuery, con);
showGridViewCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter olda = new OleDbDataAdapter(showGridViewCommand);
olda.Fill(dt);
GridViewSavingsTracker.DataSource = dt;
GridViewSavingsTracker.DataBind();
con.Close();

What am I missing here?

A: After a lot of trails, I was able to come to the right solution:
string showGridViewQuery = "select savingsID, creditorName, amount, interestRate, interestType, interestCalculationMethod, insertedDate, o.fullName as owner, u.fullName as dataEnteredBy from ((tbl_savings as s) left join tbl_users as o on s.ownerID = o.userID) left join tbl_users as u on s.dataEnteredByID = u.userID";

I knew MS Access was bad. But didn't know it was THIS bad!


text:
Q: How to log HTTP request and response with ApolloClient I'm using both ApolloClient from 'apollo-client' and 'apollo-boost' libraries, like
 const client = new ApolloClient({
  uri: 'https://www.myapp.no/api/',
  request: async (operation) => {

    console.log(operation)

    operation.setContext({
      headers: {
        authorization: tokenHeader,
        'Content-Type': 'application/json'
      }
    })
  },
  onError: (error) => {
    if (error.graphQLErrors) {
      console.log('ApolloClient graphQLErrors')
      console.log(graphQLErrors)
    }
    if (error.networkError) {
      console.log('ApolloClient networkError')
      console.log(graphQLErrors)
    }
  }
})

The operation object only show variables and query information. How to log the actual HTTP requests and response under the hood?
I want to see the outgoing request headers and params, and the responses headers and status code
This seems like a very simple task but I've spent quite some time searching without any mentions about this.

A: You can use this awesome extension: https://github.com/apollographql/apollo-client-devtools


text:
Q: Show independence of terms. Let V be a 2 dimensional vector space. Show that the space of 3-linear symmetric forms on V is 4-dimensional?
I found the basis to be $$ACEw(x,x,x)+(ACF+ADE+BCE)w(x,x,y)+(ADF+BCF+BDE)w(x,y,y)+BDFw(y,y,y)$$ and I need to show that these terms are independent but I am stuck... Thanks. I know the basic ideas of independence but I am having trouble in this situation.


text:
Q: Change Mapped table dynamically in Entity Framework I am using Entity Framework. In my DB, I have a table (DOCMASTER) which is mapped in my model, and on occasion, has a backup from a different date created (e.g. DOCMASTER_10_01_2015). The mappings are identical, with the exception of the keys/constraints. These are not brought over with the backup.
I have an application with a dropdown that is filled with all of the tables in the DB that are of type "DOCMASTER". The user selects which table they would like to query from, and they search for a client in that particular version of the table.
What I would ideally like to do is remap my model to use the selected table instead of the mapped table, however when I do that using DbModelBuilder, it seems to want to remap all of the tables in that model, not just the one table. I receive the error "CodeFirstNamespace.CUSTOM1: : EntityType 'CUSTOM1' has no key defined. Define the key for this EntityType" wherein 'CUSTOM1' is my table name, but I receive this for all of my tables in the model.
I am debating just using a paramaterized query to query the selected table directly. Does anyone have any thoughts on this?


text:
Q: Mesclar dois arrays Tenho os arrays:
$tamanho = ['P', 'M', 'G'];
$quantidade = [1, 3, 5];

O resultado final teria que ficar assim:
$final = [
            ["tamanho" => 'P', "quantidade" => 1],
            ["tamanho" => 'M', "quantidade" => 3],
            ["tamanho" => 'G', "quantidade" => 5]
        ];

Pensei em usar o array_merge, mas ele me retorna isso:
{"P":"1","M":"3","G":5}

E eu preciso dos índices "tamanho" e "quantidade", pois vou usar um foreach para inserir esses dados no banco de dados, então preciso expecificar o tipo de dado.

A: Pode utilizar array_map() para combinar os valores dos arrays $tamanho e $quantidade em um novo com os indices desejados:
$tamanho = ['P', 'M', 'G'];
$quantidade = [1, 3, 5];

$novo = array_map(function($t, $q){return array('quantidade' => $q, 'tamanho' => $t); }, $tamanho, $quantidade);

Saída:
Array
(
    [0] => Array
        (
            [quantidade] => 1
            [tamanho] => P
        )

    [1] => Array
        (
            [quantidade] => 3
            [tamanho] => M
        )

    [2] => Array
        (
            [quantidade] => 5
            [tamanho] => G
        )

)


text:
Q: Как заменить getState и getId(из Thread) при исп. Runnable? Я создавал потоки исп. extends Thread,  решил заменить его на Runnable. Но я использовал методы getState и getId, которых в интерфейсе нет.
Просто не очень понимаю, как внутри JDK устроены потоки, т.е. если я использую Thread thr = new Thread(), а потом thr.getState(), то мне кажется что он покажет мне state не того что мне нужен потока?

A: Обычно по классике делают так.
В классе, который имплементит Runnable, создают переменную private Thread thread;. Далее, в конструкторе этого же класса инициализируют ее вновь созданным потоком, передавая себя как параметр: this.thread = new Thread(this);. Создают getter для этой переменной: public Thread getThread() { return thread; }.
Можно тут же, в конструкторе, и запустить поток (если нужно): thread.start();. Или же потом, с помощью getter-a когда время придет... Так же, при помощи getter-a теперь можно доставать свойства и методы Thread-a.


text:
Q: multiple access to file in r/w I'm planning to write a programm which has to access to a certain file many times in r/w.
So I decided to use fstream, since I can use this class for both reading and writing purpose.
My idea is to open the file at the startup of the application and then close it as the application is closed too.
Since the file can be arbitrarily big, I was planning to use a "paging" structure, in which:
1) preallocate a fixed amount of memory for each page and a fixed number of page
2) load part of the file in to the first free page
3) if there is no free page, I select one non empty with a certain criterion, I commit all edit in it (if there are any)  and then load the part of file in the page.
That's not so hard to code. But I was wondering If I'm going to reinvent the wheel... maybe the fstream itself is written in a smart way so that it also implements a similar paging mechanism. In that case, I would not take care about, just write and read at any time.
Some suggestion?

A: Internal working of the standard C++ library vary by implementation. Hence a test would be needed to get some real data on your preferred platform. Generally memory mapped files are considered to be the fastest way to access data stored in a file (as Uflex has mentioned in his comment, but it has some drawbacks as well (see the linked wiki page). You can either use the standard (POSIX) C functions mmap() and munmap(), or the Boost C++ libraries which also have a portable C++ interface for memory mapped files.

A: Don't do this by yourself. Unless you are using very exotic implementation, the fstream class already implement such a mechanism efficiently.
Checkout http://www.cplusplus.com/doc/tutorial/files/ "Buffers and Synchronization"
There are possible issues if you are seek-ing into file larger than 2GB with a old kernel or implementation of the standard library. Check this
Large file support in C++
or use Boost.Filesystem


text:
Q: How to remove empty tibbles from a list of tibbles returned by get_friends function? I am using the get_friends function of rtweet package to get the list of user_id's of the friends of a set of focal users who are sampled from participants in a Twitter discourse. The function returns a list of tibbles.
Each tibble has two columns - one with the focal user's user_id and the second with user_id's of the focal users friends. Since every user has different number of friends, the number of rows in each tibble is different.
My problem: The accounts of some of the focal users are now non-existent due to reasons unknown. Because of this the list has empty tibbles which look like this:
> userFriends[[88]]
# A tibble: 0 x 0

A non-empty tibble looks like this:
> userFriends[2]
[[1]]
# A tibble: 32 x 2
                 user            user_id
                <chr>              <chr>
 1 777937999917096960           49510236
 2 777937999917096960           60489018
 3 777937999917096960         3190203961
 4 777937999917096960          118756393
 5 777937999917096960         2338104343
 6 777937999917096960          122453931
 7 777937999917096960          452830010
 8 777937999917096960           60937837
 9 777937999917096960 923106269761851392
10 777937999917096960          416882361
# ... with 22 more rows

I want my code to identify these empty tibbles and subset the list without these tibbles.
I used the nrow function on these tibbles to find the number of friends each focal user had.
nFriends <- as.numeric(lapply(userFriends, nrow))

I took the indices where this value is zero as the empty tibbles and removed them using subsetting technique as follows:
nullIndex <- nFriends!=0
userFriendsFinal <- userFriends[nullIndex]

This seems to work as of now. But this way I also removing users with zero friends (although very unlikely) along with users who no longer exist or accessible through the API. I want to make sure that I am removing only those who are not accessible or do not exist.
Please help.

A: Hi you can use the discard function from the purrr package:
Here is small example:
library(purrr)
mylist <- list( a = tibble(n = numeric()),
      b = tibble(n = 1:4))
discard(mylist, function(z) nrow(z) == 0)
$b
# A tibble: 4 x 1
      n
  <int>
1     1
2     2
3     3
4     4

A: We can use Filter with nrow, which will remove all entries with 0 number of rows, i.e.
Filter(nrow, userFriends)


text:
Q: Counting the number of group in a matrix I have found an interesting problem.
A n*m matrix is given, with a such form:
11111111
11111001
11111001
10111111
10111111
11100111
11111111

The goal of the problem is to find the number of '0' blocks. On the previous example, there were 3 '0' blocks.
I don't understand how to solve this problem. I don't ask for any code, I would like to get some hints about how to solve this problem.

A: Given your definition of block:
For every row you check if there are two (or more) contiguous zeros if that is the case you increase the 0's block count by 1 for each one of these occurrences.
You repeat the same  procedure for the columns of the matrix.
I am not sure from your description of the problem how you should count bigger blocks like:
1 1 1 1
1 0 0 1
1 0 0 1
1 1 1 1

Is this a single block?

A: You can use depth-first search to find connected components in a graph where vertices are cells with 0 and an edge between two vertices is present if two cell are adjacent.


text:
Q: Create a Container for WPF Custom Navigation I have an app where there's a small panel that needs to support browser like navigation such has back, forward, and home. Thus it also needs to hold a history of panels the user has gone to. I don't think I can use NavigationWindow because only a small portion of the window will support navigation.
What is the best practice for doing this? I've been looking at NavigationService and the Navigation commands like NavigateBack and etc.. But it's kinda hard to tie this stuff together.
I'm using Prism/MEF as well.

A: You need to use the Journal of the region.  If you get the Region manager and get a reference to the Prism Region instance defined for the panel.  Then you can use the Journal of the Navigation service for the region to go back.  You can also register to the Navigated event of the NavigationService for the region if you need to perform some action when the next view is navigated to.
mainRegion = this.RegionManager.Regions["MainRegionName"];
mainRegion.NavigationService.Navigated += NavigationService_Navigated;
mainRegion.NavigationService.Journal.GoBack();


text:
Q: Can I use REGINI to read and output the current permission set of a registry key? I know I can modify the permissions on a reg key using REGINI, however, from my understanding, it replaces the current values rather than appends them. Can I use the utility to output the current permissions set so that I can modify just the portion I want to change and update it using REGINI? Is my understanding of the utility incorrect? Is there another method that can accomplish the same task that does not require the installation of a 3rd-party tool?

A: You could use REGDMP (from the Windows resource kit) to dump the current state.
Alternatively, you can use the Get-acl and Set-acl PowerShell commands.


text:
Q: On Firefox, my embedded Youtube videos don't display properly I've embedded some YouTube videos in my fansite I'm developing. However, when you scroll through the webpage in Firefox, the divs and headers overlap the videos for some reason. Frankly, it just goes nuts. I opened the Error Console (although I really have no idea what to do with it) and it keeps giving me a JavaScript error. Is this what could cause it? In case someone else wants to see what I mean, view my website in FireFox. The URL is www.theguildwars2hq.com
The first picture is what it's supposed to look like, the second is what happens when you start scrolling.
I can't post images directly, so go here to view the images..
What it looks like normally
What happens when you start scrolling

A: I looked at the site and got this JavaScript error:
Unsafe JavaScript attempt to access frame with URL http://www.theguildwars2hq.com/ from frame with URL http://www.youtube.com/embed/CgYZk8Rkf3g. Domains, protocols and ports must match.

If that doesn't make anything jump out at you it is also possible that it has to do with your OS or browser, have you tried it on different systems or tried similar sites with you system?
Good luck!


text:
Q: Using Rational Team Concert for requirement and test management We are a small team and we need an ALM solution for our ongoing development. We heard that RTC can provide a basic requirement management, test plans and test execution management (besides source control and change management).
Do you think it's really capable of providing them all? In particular, we need the following, as well as be able to link them all:

*

*Requirements

*Test plans

*Features

*Document bugs and test results

Saying again, we're a small team. We do not need rich tools for requirements (such as RRC or DOORS) nor test management tools such as RQM or HP-QC. We'd like to know if RTC itself can provide all these needs for basic usage.
Many thanks

A: You can customize RTC in order to:

*

*define specific work item (that you can call "requirements", or "test", or "feature")

*define one or several timelines, with their own set of iterations (an iteration equals a start date and an end date), for planning purpose

So yes, you can do that as long as:

*

*you don't expect all the features of a dedicated requirement tool (Doors).

*you understand those concepts ("requirements", "tests", ...) aren't there out of the box, and need to be defined.


text:
Q: Is there a way to obfuscate source SSRS code so it cannot be reverse-engineered? I work on a team that creates custom SSRS reports for our end users that are viewed using Report Manager or Sharepoint depending on the end user community. Some end users are technical and know how to use BIDS or Visual Studio. This presents a support problem when the end user makes modifications to our reports. I would like to obfuscate our SSRS custom report source to prevent this. Is there a way to do this?

A: The only solution I see is to build your own report viewer, so the rdls could be stored encrypted and decrypted inside the viewer. But this creates a "propietary" solutions which could not be the suitable one for your customer/project.


text:
Q: I'm having an issue with the calculator that I'm building on Android I currently have all of the buttons needed. However, the Operators button is not using the character. At the time that you click in one of the operators is not returning anything.

package com.example.mycalculator

import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    var lastNumeric : Boolean = false
    var lastDot : Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }

    fun onDigit(view: View){

        tvInput.append((view as Button).text)
        lastNumeric = true
    }

    fun onClear(view: View){

        tvInput.text = ""
        lastNumeric = false
        lastDot = false

    }

    fun onDecimalPoint(view: View){
        if (lastNumeric && !lastDot){
            tvInput.append(".")
            lastNumeric = false
            lastDot = false
        }
    }

    fun onEqual(view: View){
        if(lastNumeric){
            var tvValue = tvInput.text.toString()
             var prefix = "="

            try {
                    if(tvValue.contains("-")){
                        val splitValue = tvValue.split("-")
                        var one = splitValue[0]
                        var two = splitValue[1]

                        if(!prefix.isEmpty()){
                            one = prefix + one
                        }
                    // Check if it is empty or if we have a second minus
                            tvInput.text = (one.toDouble() - two.toDouble()).toString()

                }  else if(tvValue.contains("/")){
                    val splitValue = tvValue.split("/")
                    var one = splitValue[0]
                    var two = splitValue[1]
                    // Check if it is empty or if we have a second minus
                    if(!prefix.isEmpty()){
                        one = prefix + one
                    }

                    tvInput.text = (one.toDouble() / two.toDouble()).toString()

                }else if(tvValue.contains("*")){
                    val splitValue = tvValue.split("*")
                    var one = splitValue[0]
                    var two = splitValue[1]
                    // Check if it is empty or if we have a second minus
                    if(!prefix.isEmpty()){
                        one = prefix + one
                    }
                    tvInput.text = (one.toDouble() * two.toDouble()).toString()

                }else if(tvValue.contains("+")){
                    val splitValue = tvValue.split("+")
                    var one = splitValue[0]
                    var two = splitValue[1]
                    // Check if it is empty or if we have a second minus
                    if(!prefix.isEmpty()){
                        one = prefix + one
                    }

                    tvInput.text = (one.toDouble() + two.toDouble()).toString()
                }
            }catch (e: ArithmeticException){
                e.printStackTrace()
            }
        }
    }

    fun onOperator(view: View){
        if(lastNumeric && !isOperatorAdded(tvInput.toString())){
            tvInput.append((view as Button).text)
            lastNumeric = false
        }
    }

    private fun isOperatorAdded(value: String) : Boolean {
        return if (value.startsWith("-")){
           false
        } else  value.contains("/") || value.contains("*") || value.contains("+") || value.contains("-")
    }
}

Inside of the activity_main, I have that the operator is coming through onClick element call "onOperator."
Example:

<Button
            android:id="@+id/btnAdd"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:width="0dp"
            android:text="+"
            android:onClick="onOperator"
            android:layout_margin="5dp"
            />

Does anyone know what is the best way to solve this issue?

A: what is tvInput? you haven't declared it anywhere, but using in many places... (stripped out code?)
looks like tvInput is a TextView, you are using tvInput.text.toString() in one of your lines
so your if condition in onOperator is wrong
if(lastNumeric && !isOperatorAdded(tvInput.toString())){

you should check text placed in tvInput, not tvInput itself (as View). tvInput.toString() will return some "random" String representing this View, not content of this View. try with this line:
if(lastNumeric && !isOperatorAdded(tvInput.text.toString())){

and get familiar with logging, its crucial... you could put a Log line in onOperator and find out by yourself that these conditions/values are wrong


text:
Q: Windows forms application to access google firestore, through proxy internet. How can i do that? I want my Windows forms application to access google firestore, through proxy internet. How can i do that ??
In my windows forms application, i am able to insert & delete data in google firestore database when i run this code connected to broadband internet.
But in my office internet is available through proxy internet.
How can i make my below mentioned code work through proxy internet.
I am using following APIs
1. Google.Cloud.Storage.V1;
2. Google.Cloud.Firestore;
private async Task InsertData(string project, Dictionary<string, object> user, String empid)
        {
            FirestoreDb db = FirestoreDb.Create(project);
            DocumentReference docRef = db.Collection("employees").Document(empid);
            label1.Text += "Inserting Data to  Google Firestore........ \n";
            WriteResult x = await docRef.SetAsync(user);
            label1.Text += "Data Inserted successfully for EmpNo :- "+empid+ "\n";

        }

I want my application to access google firestore application through proxy internet with minimum changes in my code.


text:
Q: Combobox on userform populating only after cancelling first attempt I have a piece of code in a module:
UserForm1.Show
UserForm1.ComboBox1.clear
UserForm1.ComboBox2.clear
UserForm1.ComboBox1.List = Array("xxxxxxx", "xfdshthr", "tyetrert")

The user runs this code to bring up a userform with 2 comboboxes, the second of which needs to be cleared after the user has entered a new value in the first.
Bizarrely when I run this script, the first combobox doesn't populate so I click the cancel button on the form (unload me) and run the code above again. This time the combobox populates as expected. This happens every time.
Does anyone know what could be causing this?

A: Because you run the wrong procedure:
Populating a combobox/listbox in a userform has to de done when loading the userform. The preferred event for that is Userform_Initialize.
So fill that event in design mode:
Private Sub Userform_Initialize()
  combobox1.list=array("aaa","bbb","ccc")
End Sub

After having done so the command 'Userform1.show' will automatically run the event-code and populate the combobox.


text:
Q: stop vscode suggesting if/else auto-complete I'm typing fast and want to be able to hit enter for a new-line. Instead, vscode pops this up, inserts braces and generally gets the formatting wrong. Honestly, how could it unless it's clang-format aware (and I may be using something else anyway). Better to not try to be too clever and just let me type out what I want.

...

Is there an option to remove this from the suggestions?
Or a way to stop it suggesting stuff unless I ask it to?
Or a way to not overload enter-for-newline with selecting a suggestion?
I found C_Cpp: Autocomplete in settings but disabling it doesn't seem to help.


text:
Q: Running VirtualBox on server I'm trying to setup VirtualBox on a server, and I'm getting this response message when I try to start VBox service:
Mar 24 20:55:49 main vboxdrv.sh[4200]: vboxdrv.sh: Starting VirtualBox services.
Mar 24 20:55:49 main vboxdrv.sh[4242]: Starting VirtualBox services.
Mar 24 20:55:49 main vboxdrv.sh[4200]: vboxdrv.sh: Building VirtualBox kernel modules.
Mar 24 20:55:49 main vboxdrv.sh[4247]: Building VirtualBox kernel modules.
Mar 24 20:55:49 main vboxdrv.sh[4200]: This system is currently not set up to build kernel modules.
Mar 24 20:55:49 main vboxdrv.sh[4200]: Please install the Linux kernel "header" files matching the current kernel
Mar 24 20:55:49 main vboxdrv.sh[4200]: for adding new hardware support to the system.
Mar 24 20:55:49 main systemd[1]: vboxdrv.service: Control process exited, code=exited status=1
Mar 24 20:55:49 main systemd[1]: vboxdrv.service: Failed with result 'exit-code'.
Mar 24 20:55:49 main systemd[1]: Failed to start VirtualBox Linux kernel module.

It asks me to "Please install the Linux kernel "header" files matching the current kernel", but I'm not sure what should I install

A: In Debian you should look for a package named "linux-headers-$(something)", where $(something) is the kernel version and build. In other distro like Ubuntu, this may be different (I think it's called "linux-generic").

A: I got it fixed by following Scaleway's guide on GitHub.
https://github.com/scaleway/kernel-tools


text:
Q: How to set the HTTP body for a request using AFNetworking? In the early versions of AFNetworking if I had to make my own custom client then I would simply inherit from AFHTTPClient and create my methods. In AFNetworking 2.0 I believe I need to inherit from AFHTTPSessionManager.
@interface MyCustomClient : AFHTTPSessionManager
    {

    }

In my situation I need to send in request as soap. This means that HTTP Body will be soap and HTTP HEADERS will be text/xml.
Let's say I have a variable which contains the entire soap body I need to send to the server.
NSString *soapBody = @"Soap body";

Using my custom class defined above which inherits from AFHTTPSessionManager how will I set the soap body to the Request HTTPBody.
If there is anyway to access NSURLRequest from inside the AFHTTPSessionManager then I can simply do setHTTPBody but it seems there is not?
I hope I am making sense now!

A: You should create a subclass of AFHTTPRequestSerializer, then implement the protocol AFURLRequestSerialization, this class is going to care about adding the body and headers to the request
 - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
                                withParameters:(id)parameters
                                         error:(NSError * __autoreleasing *)error
{
     NSParameterAssert(request);

     if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
         return [super requestBySerializingRequest:request withParameters:parameters error:error];
     }

     NSMutableURLRequest *mutableRequest = [request mutableCopy];

     [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
         if (![request valueForHTTPHeaderField:field]) {
             [mutableRequest setValue:value forHTTPHeaderField:field];
         }
     }];

     [mutableRequest setValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
     [mutableRequest setHTTPBody:@"This is the soap Body!!"];

     return mutableRequest;
}

You can read the implementation or other AFHTTPRequestSerializer subclasses https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFURLRequestSerialization.m#L1094

A: Init a NSMutableURLRequest *request; and  set httpBody to request by:
[request setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
You can try this code.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestURL]];
    request.HTTPMethod = @"POST";
    [request setValue:@"application/soap+xml;charset = utf-8" forHTTPHeaderField:@"Content-Type"];
    request.HTTPBody = [soapMessage dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
              if (!error) {
                  // parse response here
              } else {
                  // error
              }
          }];
    [sessionTask resume];

hope it help You.


text:
Q: How would Anglophones judge the rhetoric that was typical of 1600-1900? My question is related to the Irish orator, politician, lawyer and judge, John Philpot Curran (24 July 1750 – 14 October 1817)
Source: p 54-55, The Art of the Advocate (1993) by Richard Du Cann QC (called to the Bar of England and Wales).

Here he [Curran] attacks the English idea of freedom
  which gives liberty to its colonial subjects immediately they land
  on English soil but keeps them in their own subjugated territory
  in a state akin to slavery:
CURRAN: No matter in what language his doom may have been pronounced; no matter what complexion incompatible with English freedom an African or Indian sun may have burnt upon him; no matter in what disastrous battle his liberty may have been cloven down; no matter with what solemnities he may have been devoted upon the
  altar of slavery, the first moment he touches the soil of Britain, the
  altar and the God sink together in the dust; his soul walks abroad
  in his own majesty; his body swells beyond the measure of the chains
  that burst from round him, and he stands redeemed, regenerated, and
  disenthralled by the irresistible genius of universal emancipation.
This is eloquence of a very high order and of another age. [1.] There is not an advocate in practice at the Bar today who could
  formulate and then deliver a sentence of this kind.
[End of 1.]  John Buchan
  recognized that eloquence is rarely found in those who practise law.

*In [1.] the modal auxiliary verb 'could' appears ambiguous. Does the author intend that advocates lack the intellectual linguistic capacity to produce eloquent speech, or they are restrained somehow (e.g. Judges in the 21st century disfavour long speeches, or lay juries nowadays cannot follow)?

*What rhetorical devices did Curran use in his speech?

*How would Anglophones in 2016 rate or view the rhetoric I cited above? Writing in 1993, the author judges it favourably because he describes this as of a very high order and of another age.

A: Regarding which  rhetorical devices the author used,

No matter in what language his doom may have been pronounced; no matter what complexion incompatible with English freedom an African or Indian sun may have burnt upon him; no matter in what disastrous battle his liberty may have been cloven down; no matter with what solemnities he may have been devoted upon the altar of slavery

is an example of anaphora, defined as:

Rhetoric. repetition of a word or words at the beginning of two or more successive verses, clauses, or sentences.

Next, the larger sentence in which this anaphora is present:

No matter in what language his doom may have been pronounced; no matter what complexion incompatible with English freedom an African or Indian sun may have burnt upon him; no matter in what disastrous battle his liberty may have been cloven down; no matter with what solemnities he may have been devoted upon the altar of slavery, the first moment he touches the soil of Britain, the altar and the God sink together in the dust

is an example of a periodic sentence, defined as:

a stylistic device employed at the sentence level, described as one that is not complete grammatically or semantically before the final clause or phrase.
The periodic sentence emphasizes its main idea by placing it at the end, following all the subordinate clauses and other modifiers that support the principal idea. The sentence unfolds gradually, so that the thought contained in the subject/verb group only emerges at the sentence's conclusion. Obviously artificial, it is used mostly in what in oratory is called the grand style....
According to William Harmon, the periodic sentence is used "to arouse interest and curiosity, to hold an idea in suspense before its final revelation." In the words of William Minto, "the effect...is to keep the mind in a state of uniform or increasing tension until the dénouement."
(my emphasis)

The main idea of the first sentence is what I have emboldened above. But this idea is only revealed after the tension-building anaphora. As such, it is an example of a periodic sentence.

Next,

he stands redeemed, regenerated, and disenthralled

is an example of rule of three and/or a tricolon.
Rule of three

is a writing principle that suggests that things that come in threes are funnier, more satisfying, or more effective than other numbers of things.

A tricolon is

a rhetorical term for a series of three parallel words, phrases, or clauses.

The words "redeemed", "regenerated", and "disenthralled" are parallel in that each is composed of a prefix and a root.

Lastly, the construction

his soul walks abroad...; his body swells beyond

is a loose example of a clausal bicolon (defined similarly to tricolon above).

Regarding how an English speaker of 2016 would view this passage, I can speak from my own experience as well as from that of a hypothetical everyman.
From my own experience as someone who is interested in rhetoric, I can appreciate the passage as one in which time-tested rhetorical devices are used. But I don't think they're used particularly effectively. For example, the anaphora of "no matter" is used four times, when a golden three would have been sufficient and the resultant sentence easier to parse.
From the point of view of an everyman, the passage is needlessly prolix. The syntax certainly seems "of another age". The diction, however, is colorful yet grounded enough to be easily understood.

A: (2) My first thought was that "could" means "having the capacity" not "is permitted", and I think that's confirmed by the next sentence saying "is rarely found in" rather than "is rarely expressed by".
(4) I personally (being a technical writer) prefer simpler language that's easier to parse. IMO it's emotive language, and I try to understand the meaning (what it says) rather than experiencing whatever emotion the speech is intended to make me feel. It's also clearly a prepared speech. I've never studied rhetoric but it's using some obviously rhetorical techniques (starting with the repetition of "No matter"). It's uncommon but not exclusively pre-20th century, it's not unlike Churchill's speeches for example.

I don't think it's especially good rhetoric by the way.
It's one sentence, far too long. I had to reread it to understand it, therefore I think it's a failure as a speech (admittedly it would have been easier to understand in real life, where I'd probably already know in advance what kind of thing he was trying to say). Compare Churchill's speech which includes, "we shall never surrender." Having heard Churchill's sentence you know, there's no doubt, what he's saying (it's like "Thou shalt not kill", i.e., it leaves no real room for confusion). The second clause of Curran's speech (i.e. "no matter what complexion incompatible...") is especially weak because it's too long (I find myself wondering if it might be any clearer in Latin or German which have a different sentence structure e.g. with the verb at the end). Anyway the sentence structure seems to me to be practiced, artificial, automated, not person-to-person.
Apart from the structure I also didn't find the content evocative, it doesn't make me imagine something concrete. Consider "conceived in liberty, and dedicated to the proposition", that really makes me imagine the Founding Fathers having a get-together. Contrast that with "the first moment he touches the soil of Britain, the altar and the God sink together in the dust". The first thing I think when I read that are if the altar and the God sink together at the first moment then why are you talking about them and when will you get to the present point? The next thing, since when have people landed on soil and/or dust? Maybe William the conqueror landed on "soil" (he stumbled and seized the earth in his hands), but I don't imagine soil (I imagine a wooden jetty or paved quay) if someone arrives from overseas in the 18th century and lands in London or Portsmouth or Bristol etc. "Sink together in the dust" is just a set phrase, a poetic fragment, and it's chosen because it's a set phrase, a stock phrase, and not because it's especially on-message. It's not even especially good poetry.
"His body swells beyond the measure" puts me in mind of a bloating corpse (though if I were being polite and not a literary critic, I would overlook that and not say so).
But OK, maybe I get Du Cann's point: it's at least clearly meant to be eloquent rather than prosaic.


text:
Q: Android back button from WebViewClient doesn't return to current Activity I want to have a button press display a web page, I use the standard approach with a WebViewClient and WebChromClient like so:
final Button revsButton = (Button) this.findViewById(R.id.buttonReviews);
revsButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        wb.setWebViewClient(new ShareWebViewClient());
        wb.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                activity.setTitle("Loading Reviews...");
                activity.setProgress(progress * 100);
                if(progress == 100)
                    activity.setTitle(R.string.app_name);
            }
        });
        wb.getSettings().setJavaScriptEnabled(true);
        wb.loadUrl(revString );
        setContentView(wb);
    }
});

private class ShareWebViewClient extends WebViewClient {
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
          Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
      }
}

This is all working great, the thing is when I press the Back button it exits my Activity entirely and returns to the previous page.  What I really want the back button to do is to close the WebViewClient and return to the dispaly with the button on it.  This is what I tried to do so far which half worked -- it didn't leave the activity, but the activity page was just a blank screen instead of showing the controls that should be on there.
@Override
public void onBackPressed() {
    if (wb.getVisibility() == View.VISIBLE) {
        wb.setVisibility(View.INVISIBLE);
    } else {
        finish();
    }
}

A: I suppose this happens because you're using WebViewClient rather than launching browser using standard:
Uri uri=Uri.parse(urlString);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
activity.startActivity(intent);

In this case BACK button would close browser activity and you'll get back your primary activity.
In your case I would propose in onBackPressed() - restore your original content selecting
setContentView(my_original_layout);


text:
Q: GeoJSON layer shows/enables only one row in attribute table in QGIS I have a GeoJSON polygon layer which I converted from a shapefile layer. The layer opens up in geojson.io, for example, with no problem, displays the table correctly, etc:

However, in QGIS the Attribute Table only shows one polygon, with "Features Total:146, Filtered:1, Selected:0", see the image below

I've tried to remove this "filter", using SQL to select all the polygons or just a couple of the polygons, then export selected, and still, I only get this one unit, 146.
How can I get QGIS to display the whole attribute table in GeoJSON and other formats?
One caveat: the original shapefile had a "lock" file on it. I don't have this problem when I export to .shp, though if I try to select polygons and export a subset of the original shapefile in any format, I run into the same problem.

A: I went back to the original shapefile and removed the .lock file, this solved the problem. I guess it corrupted the data when I converted it to geojson.


text:
Q: How to handle checkbox using json object in angularjs 4 I had displayed below data in checkbox,
roomLists = {'4': {'name': 'Standard Room', 'typeID': '4', 'price': 100}, '5': {'name': 'Delux Room', 'typeID': '5', 'price': 100}}

this json object is retrieve using http. For testing purpose i have store it in roomlist.
Using pipe, data are getting display properly inside modal
 <app-modal #modal1>
   <div class="app-modal-body">
    <div *ngFor="let room of roomLists | jsonPipe">
     <label>
      <input type="checkbox"/>{{room.name}}
     </label>
   </div>
 </div>

but when I try to click on check box its not getting click. Is something i m missing in code.

A: Guess you are pairing checkbox with its own label, you can try give checkbox an id and and give label a for property which bind to the id of checkbox.
<div *ngFor="let room of roomLists | jsonPipe; let i = index;">
  <label for="{{'checkbox' + i}}">
    <input id="{{'checkbox' + i}}" type="checkbox"/>{{room.name}}
  </label>
</div>


text:
Q: Switching positive and negative voltage I struggle to understand how can you switch positive or negative supply from a battery.
Firstly, what is a positive voltage and negative voltage?
I read many posts stating it all depends on your point of reference. To my understanding, current flows from negative to positive. Positive and negative current is just a difference in current flow.
The reason I am asking is I am in a process of studying Inverter Field control for Hybrid vehicles.
The booklet states:

By switching the positive or negative post of the battery to the three MG (Motor Generator) connections a current starts flowing through the MG's coils. The current through the MG coils creates a revolving or still magnetic field, making the rotor magnets in the MG's follow this field.

Please notice the current flow highlighted orange. I don't understand how can you switch positive or negative voltage and how does that affect anything. I also don't understand how can you have a positive voltage flowing in and the other end has negative voltage flowing out.
Moreover, how can 'give' or rectify negative voltage to the negative terminal a positive voltage to the positive terminal depicted below. What does that even mean?

I would appreciate an answer from an engineer explained in non-engineer terms. I know there are a lot of smart folks out there, but please keep it simple.
Thanks.

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. A single-coil motor in a 'H-bridge' configuration.
Really easy:

*

*In Figure 1 left current flows through SW1, the motor and SW4. The left motor terminal is positive and the right is negative.

*If we switch the switches carfully to avoid 'shoot-through' (e.g., if SW1 and 2 were on simultaneously enough current might flow to destroy the circuit) we can reverse the current flow through the motor. In Figure 1 right current flows through SW7, the motor and SW6. Note that the motor polarity has been reversed.

The result is that either motor terminal can be connected to battery positive or negative. For a simple DC motor this allows reversal of rotation.
The three-phase situation is more complex but still understandable:

*

*If one winding is connected to positive then at least one of the other two has to provide the return path to the supply negative.

*To approximate the sinusoidal waveform pulse-width modulation (PWM) is used with progressively wider pulses averaging to the rising voltage on the sine.


text:
Q: Tomcat starting failure due to timeout in Spring source The issue is : i'm getting timeout errors when starting tomcat inside eclipse and it doesn't start at all in debug  mode.
debug mode error :
FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)
ERROR: transport error 202: connect failed: Connection refused
ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510)
JDWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [../../../src/share/back/debugInit.c:741]

normal mode error : Server Tomcat v7.0 at localhost was unable to start within 45 seconds. If the server requires more time...
Please not that i'm starting tomcat without any application deployed.
I've checked ports and they are not used for sure.
Any idea please?

A: It seems your JDWP is not loading. Here in this article you can get an idea to resolve your problem. Check the answer from Jaikiran Pai in the post. He says that you must use the command line options to load your JDWP.
-agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=n

Hope this can helps you.

A: Try with this options:-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

A: The solution is to add memory to tomcat launching (Xms and Xmx VM parameters) script and increase timeout time. This way, the process will never fire a timeout.


text:
Q: Ajax POST sends null Value in the template of my website I try to do an Ajax POST request to send the cordinates of the user to the server, which then should output the corresponding nearest city. However currently the only thing Ajax does is outputing a null value.
The whole project uses the django framework. To make sure that the crsf is not the reason I disabled crsf protection for the whole site. I also tried instead of passing json, strings integers etc, all returned null. Additionally my success function is fireing, so the ajax function is clearly working.
<script>
var loc = [] ;

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    loc.push( "Geolocation is not supported by this browser.");
  }
}

function showPosition(position) {
  loc.push(position.coords.latitude) ;
  loc.push(position.coords.longitude) ;
}

</script>
<script >
window.onload = function(){
  getLocation();
};

$.ajax({

  url: '{% url "locnews" %}',
  type : "post",
  data:  {
    "location": loc
  },
  datatype : "json",
  success : console.log("succ"),

})

</script>

A: in the line:
navigator.geolocation.getCurrentPosition(showPosition)
aren't you calling showPosition without passing "position" parameter?

A: So I figured the problem out myself. Apparently AJAX was fireing before getLocation() was finished. The issue got resolved once I added the Ajax call into the getLocation() function.


text:
Q: How to prove that $\log_2(n!) = \Theta(n\log_2[n])$? My first thought was to use $$\lim_{n\rightarrow\infty}\frac{n!}{n^n} = 0$$so I thought it should be $$\log_2n!=O(n\log_2n=\log_2n^n)$$ but I was told that $$\log_2n!=\Omega(n\log_2n)$$ is also true. So per definition I have to find $\alpha>0$ s.t. $$\exists n_0\in\Bbb N : \forall n\geq n_0 (n \in \Bbb N) \\\log_2n!\geq \alpha\cdot\log_2n^n$$ What is the idea to deal with this? Thanks in advance!
Cheers

A: The inequalities
$$
(n/2)^{(n/2)} \le n! \le n^n
$$
are easy.  Take logs.

A: $\log n!=\sum_{k=1}^n\log k$, which lies between $\int_0^n\log x\,\mathrm dx$ and $\int_1^{n+1}\log x\,\mathrm dx$ because $\log$ is monotonic.
(P.S. This is part of the idea behind Stirling's approximation.)

A: By considering only the largest $n/2$ terms of $n!$, we have $n! \geq \left(\dfrac{n}{2}\right)^{n/2}$, so
$$\log_2 n! \geq \log_2 \left(\left(\frac{n}{2}\right)^{n/2}\right) = \frac{1}{2} \left(n \log_2 n\right) - \frac{1}{2} (n \log_2 2) = \frac{1}{2} \left(n \log_2 n\right) - \frac{1}{2} n.$$
For large $n$, the term $n$ is negligible compared to the term $n \log_2 n$. So taking $\alpha$ slightly less than $1/2$ and $n_0$ sufficiently large should work.

A: Try using that
$$\lim_n \frac{\sqrt[n]{n!}}{n} =\frac{1}{e}$$
Then
$$\sqrt[n]{n!}\geq (\frac{1}{e}-\epsilon)n \,.$$
or
$$\log_2(n!) \geq n \log_2 (\frac{1}{e}-\epsilon)+\log_2(n^n) \,.$$
Now, all you have to do is find some $\beta<1$ so that
$$  \log_2 (\frac{1}{e}-\epsilon) \geq \beta \log_2(\frac{1}{n})$$
PS For the first limit, if you didn't see it before, just take the $\ln$ and apply Stolz-Cezaro.

A: I came across the same limit some months ago, my idea was this:
$$\lim _{n\rightarrow+\infty } \dfrac{\ln(n!)}{\ln(n^n)}=\lim _{n\rightarrow +\infty} \dfrac {n\ln (n)+\sum _{k=1}^{n}\ln (1-\frac {k}{n}) }{n\ln(n)}=1+\ell $$
assuming the last part converges. Then (multiplying by $\frac{n}{n}$):
$$\ell =\lim _{n\rightarrow+\infty }\dfrac{\sum _{k=1}^{n}\ln (1-\frac{k}{n})^{n}}{n^2\ln n}$$
Here comes the part that I don't know how to formalize better and it would be great if someone is able to fix this:
$$\ell=\lim _{n\rightarrow+\infty}\dfrac{\sum_{k=1}^{n}\ln (1-\frac{k}{n})^n}{n^2\ln n}\sim \dfrac {\sum_{k=1}^{\infty}k}{\lim_nn^2\ln n}\sim \lim _{n\rightarrow+\infty }\dfrac{O(n^2)}{n^2\ln n}=0$$


text:
Q: Find specific parent of element in AngularJS directive I have a list setup like so

            2015

July

June

May

                ...

I have a function that gets called when page scrolling should change the navigation in this list.  This works but what I want to do is also add a class to the parent on scrolling.
I.e. if June is highlighted (using current class) then I also want 2015 to be highlighted.
Currently my code to add the class looks like so:
elem.addClass("current");

In straight up jQuery, the selector I'd like to us is the following:
elem.closest("ul").closest("li").find("a").first().addClass("current")


text:
Q: How to make twitter bootstrap compatible with IE8? I included below tags in my example, Still it's not working. col-md-* is taking full with of the div. col-md-* width is not showing at all in developer tool.
<meta content="text/html; charset=windows-1252" http-equiv="Content-Type" />
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="html5shiv.min.js"></script>
          <script src="respond.min.js"></script>
           <link href="//netdna.bootstrapcdn.com/respond-proxy.html" id="respond-proxy" rel="respond-proxy">
        <![endif]-->

A: For supporting @media queries in IE 8 and below, check out
https://code.google.com/p/css3-mediaqueries-js/
css3-mediaqueries.js by Wouter van der Graaf is a JavaScript library to make IE 5+, Firefox 1+ and Safari 2 transparently parse, test and apply CSS3 Media Queries. Firefox 3.5+, Opera 7+, Safari 3+ and Chrome already offer native support.
Reference:  Twitter Bootstrap Responsive layout does not work in IE8 or lower
Also See : http://getbootstrap.com/getting-started/#support-ie8-ie9
Update: There are plenty of questions/answers. You Just need to google it.

A: Have you look the size of your CSS, For IE up to IE9 the css file size is max 288kb. Maybe thats is a problem


text:
Q: How To Justify this Step - Calculus Convergence Problem I was fiddling with a question that has already been answered on MSE. I (ostensibly) came up with a different solution that was not listed for my own recreational fun. I am having trouble rigorously justifying (to myself) that one step in my solution is valid.
Original question [also provided in the linked question]: Consider a circle of radius one centered at (0,0) and a circle of radius 1/2 centered at (3/2,0). There are three lines that lay tangent to both circles, one is trivial and the other two are reflections of each other. Find the equation of one of the non-trivial lines.
My solution: I seek the equation of the line with a negative slope (laying atop the two circles).
part 1: When I look at a graph of the two circles and the tangent line, I am curious what is this lines $x-$ intercept? I imagine; what if there were more shrinking circles instead of just the first two - another with radius 1/8, 1/16, 1/32... each touching the one before it in a single point. This would look like this (though with the circles continuing indefinitely):

Each of these circles should also lay tangent to the solution line, and the total sum of the length of the circles in the positive $x$ direction should be converging to the intercept.
This length is easily found to be $$1+2 \cdot \sum_{k = 1}^{\infty} \left(\frac{1}{2}\right)^k = 3. $$
part 2: An equation for a line that lies tangent to the first circle at an arbitrary point in the first quadrant can easily be found to be
$$f_a(x) = \frac{1-ax}{\sqrt{1-a^2}}.$$
Using the intercept from part 1 we can solve to yield $a = 1/3$ which allows us to determine the equation of the line.

How can I rigorously justify that the sum of the length of the circles
will converge to the intercept of the line?


text:
Q: Puppet-Like Configuration Tool? In the business environment I work in, we tried to use Puppet to manage both our Linux and Windows machines. This includes tasks like installation of programs that are needed for our department and also managing what programs are easily accessible to all employees. We decided not to use Puppet due to the many dependencies it has and other complications, however we still want to employ the same idea of managing both Linux and Windows. Is there another program or way to do this?

A: Cfengine might be an alternative. You could also check this list of alternatives to puppet.

A: Salt is a remote execution and configuration management tool.  Salt also has support for Windows.  Salt is created using Python. However, Python knowledge is not required to perform most of the tasks.  The configuration files are normally written using YAML and Jina2.

A: Puppet is much easier and better for handling linux configurations..However it can be used for windows machines also. The main advantage of using puppet is that you can define customized facts for your machine, and manage configuration for that fact.
the below links might provide some info..
http://slashroot.in/puppet-tutorial-how-does-puppet-work
http://slashroot.in/puppet-tutorial-installing-puppet-master-and-puppet-agent

A: I think you'd have to be more explicit about the problems you had with puppet.  Generally, puppet is a good way to go.  An alternative that's been around for a long time is cfengine. It will come with it's own challenges.  Chef is also popular (and newer), though I haven't used it myself.
Also see Why is there only one configuration management tool in the main repository? .

A: Puppet integration with Windows is still young. Maybe some scripts in Perl are enough for what you need? The learning curve is however a bit steep.


text:
Q: How to extract and transform XML into a Perl data structure I have xml files in a folder, I need to extract some information from xml files and store in a hash.My xml files look like this
<?xml version="1.0" encoding="UTF-8"?>
<Servicemodule xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<Service Id="478" Name="Pump Motor">
<Description>It delivers actual pump speed</Description>
<ServiceCustomers>
   <SW Service="SKRM" Path="/work/hr_service.xml"/>
</ServiceCustomers>
<ServiceSuppliers>
   <HW Type="s" Nr="12" Service="1" Path="/work/hardware.xml"/>
   <HW Type="v" Nr="2" Service="1" Path="/work/hardware.xml"/>
   <HW Type="mt" Nr="1" Service="1" Path="/work/hardware.xml"/>
 </ServiceSuppliers>
 </Service>
 </Servicemodule>

I want to save this information in a hash like Service Id as the key and reaming information as the array of hash values of that key. SW and HW attributes in both service  customers and suppliers elements are the array of values for the hash key(service Id). Its easy task for experts but I am new learner so this problem suffers me.
I tried like this
use strict;
use warnings;
use feature ':5.10';
use XML::Twig;
use File::Find;

my $num=0;
my %combeh;
my $dir="V:/Main/work";
find(\&wanted, $dir);
 sub wanted() {
    if ( -f and /(_service\.xml)$/) {# find all the files with a suffix of .xml
 my $tweak_server =sub{
                my @bhi;
    my ($twig, $root) =@_;
    my $code=$root->first_child_text('Service Id');
    my $ser=$root->first_child('ServiceCustomers');
    my $ser_cnt=$root->first_child_text('SW');
     my $ser1=$root->first_child('ServiceSuppliers');
    my $ser1_cnt=$root->first_child_text('HW');
    if ($ser){
    push (@bhi, $ser->toString,$File::Find::name);
       $combeh{$code}=[@bhi];
         }
       if ($ser1){
    push (@bhi, $ser1->toString,$File::Find::name);
       $combeh{$code}=[@bhi];
            };
        my $roots = { Service => 1 };
  my $handlers = { 'Servicemodule/Service' => $tweak_server,
                       };
       my $twig = new XML::Twig(TwigRoots => $roots,
                             TwigHandlers => $handlers,
                               pretty_print  => 'indented'
                               );
               $twig->parsefile($_);
                             }
                       }
               return (%combeh) ;
                }

I am not able to create hash with as I want using above script. please help me with script how to get attribute values and store in a hash like this
out put need like this
 '478'=>[
          {
          Description='It delivers actual pump speed'
          }
         {
           Service='SKRM',
           Path='/work/hr_service.xml'
          }
          {
             Type='s'.
             Nr='12',
             Service='s',
             path='/work/hardware.xml'
           }

          {
             Type='v'.
             Nr='2',
             Service='s',
             path='/work/hardware.xml'
           }
          {
             Type='mt'.
             Nr='1',
             Service='1',
             path='/work/hardware.xml'
           }
         ...
          ...
          ....

Please help me with this problem.
Thanks in advance.
I tried like this After your suggestion
#!/usr/bin/perl
 use warnings;
 use strict;
 use XML::Simple;
 use Carp;
 use File::Find;
 use File::Spec::Functions qw( canonpath );
 use Data::Dumper;

 my @ARGV ="C:/Main/work";die "Need directories\n" unless @ARGV;
 find(
  sub {
     return unless ( /(_service\.xml)$/ and -f );
     extract_information();
    return;
  },
 @ARGV
  );

sub extract_information {
         my $path= $_;

my $xml=XMLin($path);
   my $xml_services = $xml->{Service};
   my %services;
   for my $xml_service (@$xml_services) {

    my %service = (
        description     => $xml_service->{Description},
        name            => $xml_service->{Name},
        id              => $xml_service->{Id},
    );

     $service{sw} = _maybe_list( $xml_service->{ServiceCustomers}{SW} );
    $service{hw} = _maybe_list( $xml_service->{ServiceSuppliers}{HW} );
    $service{sw} = _maybe_list( $xml_service->{ServiceSuppliers}{SW} );
     $services{ $service{id} } = \%service;
 }

 print Dumper \%services;

  }
 sub _maybe_list {
 my $maybe = shift;
 return ref $maybe eq 'ARRAY' ? $maybe : [$maybe];
 }

Thanks for your reply,I am new to XML::Simple and I studied that module and I understand your script. But when I run your code I am getting error like "Not an array Reference" at for loop line.I tried in different ways to overcome this but still same error. And some times I have SW and HW attribute in ServiceSuppliers. So I added one more line same as your format. I have one question You said "If there's a single element in the XML it won't be wrapped in" but some times In ServiceCustomers I have only one element with some attributes like as I shown in my xml file.Is it OK ? or what should I do? Can you help me with these problems.
please any one help me with this error.

A: If the XML file isn't too big, you can transform it much easier with XML::Simple.
The advantage to XML::Simple is it is far more convenient to manipulate Perl data structures than XML.
The downsides are that it will consume more memory, since it must load the whole XML file into memory.  It is also sensitive to the casing in the XML.
use strict;
use warnings;

use XML::Simple;
use Data::Dumper;

process_service_xml(shift);

sub process_service_xml {
    my $xml = XMLin(shift);

    # Illustrating what you've got after XML::Simple processes it.
    print "******* XML::Simple input ********\n";
    print Dumper $xml;
    print "**********************************\n";

    # Pull out the Services
    my $xml_services = $xml->{Service};

    # Iterate through each Service to transform them
    my %services;
    for my $xml_service (@$xml_services) {
        # Pull out the basic information
        my %service = (
            description     => $xml_service->{Description},
            name            => $xml_service->{Name},

            # Redundant with the key, but useful to keep all the data about the
            # service in one place.
            id              => $xml_service->{Id},
        );

        # Get SW and HW as their own attributes.
        # If there's a single element in the XML it won't be wrapped in
        # an array, so make sure each are a list.
        $service{sw} = _maybe_list( $xml_service->{ServiceCustomers}{SW} );
        $service{hw} = _maybe_list( $xml_service->{ServiceSuppliers}{HW} );

        # Store the service in the larger hash, keyed by the ID.
        $services{ $service{id} } = \%service;
    }

    # And here's what the information has been transformed into.
    print "******* Services ********\n";
    print Dumper \%services;
    print "*************************\n";
}

sub _maybe_list {
    my $maybe = shift;
    return ref $maybe eq 'ARRAY' ? $maybe : [$maybe];
}


text:
Q: Parse html files in the directory and remove specific tags with BeautifulSoup I have multiple html files within directory and subfolders. I want to parse all html files (recursively), and remove from code specific divs (with all content), plus all scripts and css. I want to clean out divs with id="wrapper", "header", "columnLeft", "adbox", "footer", plus all stylesheets and scripts. The cleaned html files should be saved, preserving original names, in a new directory. I tried regex, but this is not suitable for such tasks.
I installed BS4 for Python 2.x, Debian.
What commands could be used for this?
HTML element example:

Book Search

                    <form action="http://www.dspguide.com/search.php" method="post">
                        <input type="text" name="searchfor" class="txtField" />
                        <input type="image" src="new/images/btn-go.png" name="Submit" value="Submit" class="button" />

                    </form>

Download this chapter in PDF format

                Chapter15.pdf

Table of contents

1: The Breadth and Depth of DSP

The Roots of DSP

Telecommunications

Audio Processing

Echo Location

Image Processing

2: Statistics, Probability and Noise

Signal and Graph Terminology

Mean and Standard Deviation

Signal vs. Underlying Process

The Histogram, Pmf and Pdf

The Normal Distribution

Digital Noise Generation

Precision and Accuracy

3: ADC and DAC

Quantization

The Sampling Theorem

Digital-to-Analog Conversion

Analog Filters for Data Conversion

Selecting The Antialias Filter

Multirate Data Conversion

Single Bit Data Conversion

4: DSP Software

Computer Numbers

Fixed Point (Integers)

Floating Point (Real Numbers)

Number Precision

Execution Speed: Program Language

Execution Speed: Hardware

Execution Speed: Programming Tips

5: Linear Systems

Signals and Systems

Requirements for Linearity

Static Linearity and Sinusoidal Fidelity

Examples of Linear and Nonlinear Systems

Special Properties of Linearity

Superposition: the Foundation of DSP

Common Decompositions

Alternatives to Linearity

6: Convolution

The Delta Function and Impulse Response

Convolution

The Input Side Algorithm

The Output Side Algorithm

The Sum of Weighted Inputs

7: Properties of Convolution

Common Impulse Responses

Mathematical Properties

Correlation

Speed

8: The Discrete Fourier Transform

The Family of Fourier Transform

Notation and Format of the Real DFT

The Frequency Domain's Independent Variable

DFT Basis Functions

Synthesis, Calculating the Inverse DFT

Analysis, Calculating the DFT

Duality

Polar Notation

Polar Nuisances

9: Applications of the DFT

Spectral Analysis of Signals

Frequency Response of Systems

Convolution via the Frequency Domain

10: Fourier Transform Properties

Linearity of the Fourier Transform

Characteristics of the Phase

Periodic Nature of the DFT

Compression and Expansion, Multirate methods

Multiplying Signals (Amplitude Modulation)

The Discrete Time Fourier Transform

Parseval's Relation

11: Fourier Transform Pairs

Delta Function Pairs

The Sinc Function

Other Transform Pairs

Gibbs Effect

Harmonics

Chirp Signals

12: The Fast Fourier Transform

Real DFT Using the Complex DFT

How the FFT works

FFT Programs

Speed and Precision Comparisons

Further Speed Increases

13: Continuous Signal Processing

The Delta Function

Convolution

The Fourier Transform

The Fourier Series

14: Introduction to Digital Filters

Filter Basics

How Information is Represented in Signals

Time Domain Parameters

Frequency Domain Parameters

High-Pass, Band-Pass and Band-Reject Filters

Filter Classification

15: Moving Average Filters

Implementation by Convolution

Noise Reduction vs. Step Response

Frequency Response

Relatives of the Moving Average Filter

Recursive Implementation

16: Windowed-Sinc Filters

Strategy of the Windowed-Sinc

Designing the Filter

Examples of Windowed-Sinc Filters

Pushing it to the Limit

17: Custom Filters

Arbitrary Frequency Response

Deconvolution

Optimal Filters

18: FFT Convolution

The Overlap-Add Method

FFT Convolution

Speed Improvements

19: Recursive Filters

The Recursive Method

Single Pole Recursive Filters

Narrow-band Filters

Phase Response

Using Integers

20: Chebyshev Filters

The Chebyshev and Butterworth Responses

Designing the Filter

Step Response Overshoot

Stability

21: Filter Comparison

Match #1: Analog vs. Digital Filters

Match #2: Windowed-Sinc vs. Chebyshev

Match #3: Moving Average vs. Single Pole

22: Audio Processing

Human Hearing

Timbre

Sound Quality vs. Data Rate

High Fidelity Audio

Companding

Speech Synthesis and Recognition

Nonlinear Audio Processing

23: Image Formation & Display

Digital Image Structure

Cameras and Eyes

Television Video Signals

Other Image Acquisition and Display

Brightness and Contrast Adjustments

Grayscale Transforms

Warping

24: Linear Image Processing

Convolution

3x3 Edge Modification

Convolution by Separability

Example of a Large PSF: Illumination Flattening

Fourier Image Analysis

FFT Convolution

A Closer Look at Image Convolution

25: Special Imaging Techniques

Spatial Resolution

Sample Spacing and Sampling Aperture

Signal-to-Noise Ratio

Morphological Image Processing

Computed Tomography

26: Neural Networks (and more!)

Target Detection

Neural Network Architecture

Why Does it Work?

Training the Neural Network

Evaluating the Results

Recursive Filter Design

27: Data Compression

Data Compression Strategies

Run-Length Encoding

Huffman Encoding

Delta Encoding

LZW Compression

JPEG (Transform Compression)

MPEG

28: Digital Signal Processors

How DSPs are Different from Other Microprocessors

Circular Buffering

Architecture of the Digital Signal Processor

Fixed versus Floating Point

C versus Assembly

How Fast are DSPs?

The Digital Signal Processor Market

29: Getting Started with DSPs

The ADSP-2106x family

The SHARC EZ-KIT Lite

Design Example: An FIR Audio Filter

Analog Measurements on a DSP System

Another Look at Fixed versus Floating Point

Advanced Software Tools

30: Complex Numbers

The Complex Number System

Polar Notation

Using Complex Numbers by Substitution

Complex Representation of Sinusoids

Complex Representation of Systems

Electrical Circuit Analysis

31: The Complex Fourier Transform

The Real DFT

Mathematical Equivalence

The Complex DFT

The Family of Fourier Transforms

Why the Complex Fourier Transform is Used

32: The Laplace Transform

The Nature of the s-Domain

Strategy of the Laplace Transform

Analysis of Electric Circuits

The Importance of Poles and Zeros

Filter Design in the s-Domain

33: The z-Transform

The Nature of the z-Domain

Analysis of Recursive Systems

Cascade and Parallel Stages

Spectral Inversion

Gain Changes

Chebyshev-Butterworth Filter Design

The Best and Worst of DSP

34: Explaining Benford's Law

Frank Benford's Discovery

Homomorphic Processing

The Ones Scaling Test

Writing Benford's Law as a Convolution

Solving in the Frequency Domain

Solving Mystery #1

Solving Mystery #2

More on Following Benford's law

Analysis of the Log-Normal Distribution

The Power of Signal Processing

How to order your own hardcover copy

                Wouldn't you rather have a bound book instead of 640 loose pages?

                Your laser printer will thank you!

                Order from Amazon.com.

Chapter 15: Moving Average Filters

The moving average is the most common filter in DSP, mainly because it is the easiest digital
filter to understand and use.  In spite of its simplicity, the moving average filter is optimal for
a common task: reducing random noise while retaining a sharp step response.  This makes it the
premier filter for time domain encoded signals.  However, the moving average is the worst filter
for frequency domain encoded signals, with little ability to separate one band of frequencies
from another.  Relatives of the moving average filter include the Gaussian, Blackman, and
multiple-pass moving average.  These have slightly better performance in the frequency domain,
at the expense of increased computation time.

Implementation by Convolution

Noise Reduction vs. Step Response

Frequency Response

Relatives of the Moving Average Filter

Recursive Implementation

So far I have some incomplete draft:
from bs4 import BeautifulSoup
import re
import os, os.path
import sys

directory = '~/Downloads/abc/def'
for root, dirnames, filenames in os.walk(directory):
    for filename in filenames:
        if filename.endswith('.html'):
soup.find('div', id="columnLeft").decompose()
pretty = (text.prettify())

A: You can use htql, for example:
html = """
<title>Moving Average Filters</title>
<link href="new/css/default.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" href="new/css/droppy.css" type="text/css" />

    Home | The Book by Chapters | About the Book | Steven W. Smith | Blog | Contact

    Copyright 1997-2011 by California Technical Publishing

"""

import htql
x=htql.query(html, "


text:
Q: Is there any free or low cost tool for drawing sequence diagrams? I have been using Visual Studio ultimate to draw sequence diagrams. Visual Studio sequence diagrams are quite easy to work with and I am much more productive compare to drawing them in Visio.
However, Visual Studio Ultimate is quite expensive. Is there any free or low budget tool for drawing sequence diagrams?
Thank you,

A: Hi you could use Argo UML its good tool and free http://argouml.tigris.org/

A: Yes Allan , IBM provides its Rational Software for all types of diagrams including sequence diagram. They provide free trial of that. Even for most of the university students, they provide it free for academic sessions.
Check this link
You can also prefer previous answers of stackoverflow
Free Sequence Diagram Tool


text:
Q: Strange effect of CSS overflow hidden vs. visible on position of parent element I've never read anything to suggest that the overflow property of an element would have the strange effect on element positioning that I'm seeing here:
https://codepen.io/kshetline/pen/ZEzLVxN
Toggle the toggle button in the example, and watch how somehow the background of a
 mysteriously slides upward, covering previous content, while its contents stays in the same screen-relative place (meaning the content is moving lower relative to its parent's background).
The example is a very simplified version of something I'm trying to do with an Angular component that's meant to scale its <ng-content> — but the example is only CSS and HTML with a tiny touch of JavaScript, no Angular, since I'm trying to isolate the relevant variables.
The content of an HTML element can be scaled down using transform: scale( less-than-1 scaling factor ), but even though the content of the element is rendered smaller, by default the element's pixel dimensions remain the same, with the content (unless otherwise specified) shrinking toward the center of the element, and blank space left around that content that leaves the element at its original unscaled dimensions..
You need to compute negative margins that match the degree of scaling in order for the element itself to be considered smaller. I've done that, but I've found that unless the container for the scaled element has CSS overflow set to hidden, some weird positioning can occur, as if the extra blank space required that's supposed to be removed by the negative margins is still having some partial, hard-to-explain effect on the overall layout of other elements.
I'm seeing this behavior in Chrome, Firefox, Safari and Edge -- so I'm guessing it's "proper" CSS behavior, but it makes no sense to me, and I'm hoping someone can explain what's going on. I'd like to be able to keep overflow set to visible so that scaled content can still do things like show floating dropdown menus that don't get clipped at the boundaries of the element.

let hidden = true;
const inner = document.getElementById('inner')

function toggleOverflow() {
  hidden = !hidden;
  inner.style.overflow = hidden ? 'hidden' :
  'visible'
}
html, body {
  height: calc(100vh - 10em);
}

.page {
  font: 32px Arial, Helvetica, sans-serif;
  height: calc(100% - 1em);
}

.container {
  background-color: #ACF;
  height: 100%;
}

.outer-wrapper {
  background-color: rgba(187, 255, 204, 0.5);
  font-size: 2em;
  margin: 0 1em;
  position: relative;
}

.inner-wrapper {
  overflow: hidden;
  position: relative;
  width: fit-content;
}

.ng-content {
  margin: -18.75px 0;
  transform: scale(0.5);
}

.container-text {
  display: inline-block;
  position: absolute;
  bottom: 1em;
}

  <button onclick="toggleOverflow()">Toggle Overflow</button>

  Content outside of the

  panel being scaled and its

  containing <div>, 32pt font

          50% scaled content goes here, 64pt font

    This is an absolutely positioned <span> in the same <div>

A: From CSS 2.2 spec

Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.

So adding overflow:hidden is stopping the margins from collapsing.

A: You have set a negative margin in your .ng-content. If overflow is set to hidden, it will hide the negative margin. Set the margin to a positive number and it will fix this jumping issue.
.ng-content { margin: 18.75px 0; }
If you are trying to change the height of the element up and down, try using max-height with overflow: hidden. When max height is set to 0, it will be hidden. When set to something like 500px, your content will show!

A: Follow-up...
I created a variant on my first code pen here:
https://codepen.io/kshetline/pen/WNeRmOo
In this case, I'm using transform-origin: top center when I scale, and putting all of the needed negative margin on at the bottom of the scaled element, rather than splitting it evenly between top and bottom. That eliminates the weird vertical position shifting.
overflow: hidden is still needed to hide the excess of background color from "leaking out" of its container, but in the (common) case where the background of the scaled element is transparent, there would be no visible effect from using overflow: visible instead, and no worries about clipped dropdown menus originating inside the scaled element.
Follow-up #2...
Here's the best solution, using padding: 0.05px to deal with the real issue that @Alochi helped me understand — stopping border collapse:
https://codepen.io/kshetline/pen/zYONgzV


text:
Q: Python and Photoshop I have used python to write script for Photoshop using versions from CS6 to CC 2014 and my scripts have worked flawlessly. Last week I updated my Photoshop to CC 2015 and my scripts stopped working. I got error messages about missing attributes. I thought this was due to CC 2015 having changed something about the COM interface. When I checked the available attributes, I noticed that only a small subset of all the attributes was avilabe.
I then reinstalled the CC 2014 but the problem did not disappear, I still see just a small subset of the attributes, all the rest gave the same error message. I noticed the splash screen had changed from my previous version of CC 2014 which may mean that some changes has been made in my newer CC 2014 as well.
I can still run the script on my old machine with CS6.
I have of course run makepy prior to using the new Ps version.
I have tried two approaches: win32com and comtypes. Neither works. I get different sets of exported methods for the win32com and comtypes approaches which is surprising.
I am very dependent on my scripts and would like to find a solution.
If you are using Photoshop CC 2014 with python, I recommend you don't upgrade until this problem is solved.

A: It seems this is due to a change in the Photoshop API.
You may want to report it to them and get the right feedback.
Since most of the stackflow user might be more "code-oriented", it is likely that you won't get effective answer.


text:
Q: При тестировании AJAX запросов JQuery загружается после старта тестов на Jasmine У меня есть функция которая отправляет AJAX запрос на сервер
JS
function loadImage(e){

    var id = $('#idDomain').val();
    var nameHolder = $('#nameImgHolder').val();
    var data = new FormData();

    data.append('file', e.files[0]);
    data.append('id', id);
    data.append('nameHolder', nameHolder);

    $.ajax({
        method: "POST",
        url: "/mr_generator/loadImageAjax/",
        processData: false,
        contentType: false,
        dataType: "JSON",
        data: data
        })
    .success(function (data) {
       addHistory(nameHolder, data["fileName"]);
       replaceSrc(data, nameHolder);
    });
}

И есть тест который должен проверить корреткность URL куда будет отправлен запрос
JS
it("should make an Ajax request to the correct URL", function () {
     spyOn($, "ajax");
     var file = {
        files: ['file.jpg']
     };
     loadImage(file);
     expect($.ajax.calls.mostRecent().args[0]["url"]).toBe('/mr_generator/clearLastHistoryAjax/');
});

Но при запуске теста выдает следующую ошибку
TypeError: $.ajax(...) is undefined in ....

Я так понял, что у меня тесты запускаются раньше загрузки JQuery? Как это исправить?

A: Спасибо @Vitaliy Shevchenko за совет, но я сделал немного по-другому, я в функцию beforEach вынес вызов функции, в которой вызывается AJAX запрос (loadImage()), и обернул вызов в setInterval(), получился следующий тест
JS
describe('Clear history Ajax', function () {

    var configuration = {
        url: "/mr_generator/clearLastHistoryAjax/",
        remainingCallTime: 30000
    };
    var file = {
        files: ['file.jpg']
    };

    beforeEach(function (done) {
        var ajaxInterval = setInterval(function () {
            loadImage(file);
            done();
        }, 400);
    });

    //checking url of request
    it("should make an Ajax request to the correct URL", function () {
        spyOn($, "ajax");
        expect($.ajax.calls.mostRecent().args[0]["url"]).toBe('/mr_generator/clearLastHistoryAjax/');
    });
 });