text:
Q: Animating (moving) ImageView works one way but not the other I creating a "Add" button by using sdk, so i wan it to move it to left when i press that "Add" button, and come back to original place when i press again. The problem i have is the button only can go to the left when press, and cannot come back to the original place after i trying to press it again. Does it i having some problem on the if...else function there? any help would appreciate.
public class TestImage2 extends Activity {
/** Called when the activity is first created. */

ImageView image_plus;
ImageView image_subtract;
ImageView image_multiply;
ImageView image_div;

String op;

boolean pergi = false;
final  Animation animation = new TranslateAnimation(0,100,0,0);
final  Animation animation2 = new TranslateAnimation(100,0,0,0);

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    image_plus     = (ImageView)findViewById(R.id.test_image);
    image_subtract = (ImageView)findViewById(R.id.test_image2);
    image_multiply = (ImageView)findViewById(R.id.test_image3);
    image_div      = (ImageView)findViewById(R.id.test_image4);

    image_plus.setOnClickListener(new OnClickListener(){

        public void onClick(View view) {

                if(pergi == false)
                {

                        animation.setDuration(1000);
                        image_plus.startAnimation(animation);
                        pergi= true;

                        animation.setFillAfter(true);
                }
                else
                {

                        animation2.setDuration(1000);
                        image_plus.startAnimation(animation2);
                        pergi = false;
                        animation2.setFillAfter(true);
                }
                }});

A: i think that there is something wrong in
final  Animation animation2 = new TranslateAnimation(100,0,0,0);

it should be
final  Animation animation2 = new TranslateAnimation(0,-100,0,0);

:)


text:
Q: Extracting specific HTML elements using the xml package in R I'm using R with the xml package to parse data stored in html files. Using the advice from another question (https://stackoverflow.com/a/1849388/1409652), I am cooking with gas on this using the readHTMLTable function.
I have one problem which is that there are two headers for the html table of interest. One of which isn't being picked up by readHTMLTable and gives some identifying information of the units the data relates to (which vary across all the different html files so I need to read them rather than just putting a default in).
I figure that I need to point a function in the xml package at the html file and target the specific row I want. Unfortunately I don't know which function and my knowledge of the terminology around this isn't great. I've put a sample of the HTML code below but haven't included values as they're sensitive, I can swap in some dummy data and post it if it's helpful. So the header that contains "Period", "Volume", "Tariff" is coming through fine, as is all the data in the table body. The header containing "Unit1", "Unit2 etc. is not coming through.

	Unit1	Unit2	Unit3	Others

Period	Volume	%	Tariff	%	Volume	%	Tariff	%	Volume	%	Tariff	%	Volume	%	Tariff	%

…all the data…

So in summary, does anyone have any pointers on how to extract the Unit information in the above html using the xml package in R (though happy to use other packages if that's the best way)?

A: All I needed was some subject knowledge ;-)
using xpath syntax I managed to get a list of the unit names using the following:
xpathSApply(doc, "//th[@class='center']/text()")

Believe I can make this more efficient by addressing those //'s too.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "every" vs "each"? Consider:

The ten lucky winners will ................. receive $1,000.

A) every
B) each
The answer in the book is each. As far as I know, every and each are used before singular nouns. I cannot understand the grammatical structure of the sentence. The only thing that I can guess is that each, as oppose to every, is also pronoun but, I don't know how this would help!

Note 1: The book preview option is not available although the book can be found on the google books!
Note 2: I know each has different connotation from every; the former has one-by-one connotation, the latter has a collective connotation; the problem is about the grammar.

A: The syntactic difference (between the possible usage of each and every) is probably best demonstrated by examples.

CORRECT: There were five men. Each had a sword and a bow.
  CORRECT: There were five men. Each man had a sword and a bow.
  CORRECT: There were five men. Each of them had a sword and a bow.
  INCORRECT: There were five men. Every had a sword and a bow.
  FIXED: There were five men. Every man had a sword and a bow.
  INCORRECT: There were five men. Every of them had a sword and a bow.
  FIXED: There were five men. Every one of them had a sword and a bow.
CORRECT: They each had a sword and a bow.
  CORRECT: Each of them had a sword and a bow.
  INCORRECT: They every had a sword and a bow.
  FIXED: Every one of them had a sword and a bow.
CORRECT: They could each choose to use a sword or a bow.
  CORRECT: Each of them could choose to use a sword or a bow.
  INCORRECT: They could every choose to use a sword or a bow.
  FIXED: Every one of them could choose to use a sword or a bow.

A: The ten lucky winners will......receive $1,000.
Each and every are often similar in meaning.  The only difference is between their usage as follows:
First, you use each when there are two or more things in a group, whereas you use every when there are three or more things in a group.
Second, the usage of each gives stress to individual things in the group, whereas  every refers to  things in the group as a whole. For example, every student passed the test = All the students passed the test.
Third, each is used as a determinor, pronoun, or adverb, but every is only used as a determiner.
Each and every are only interchangeable to convey the same meaning when there are three or more things in a group, and we use them as a determiner, without considering the stress they indicate.
Look at the following sentences to find how every is used as a determiner, and each is used as a determiner, pronoun, and adverb:
Every lucky winner will receive $1,000. (determiner)
Every one of the ten lucky winners will receive $1,000.(determiner)
Each lucky winner will receive $1,000. (determiner)
Each of the ten lucky winners will receive $1000.(pronoun)
The ten lucky winners will each receive $1,000. (pronoun)
The ten lucky winners will receive $1,000 each. (adverb).
As 'each' as a pronoun fits in the blank space of the sentence presented by the OP, you cannot use the determiner every here.

A: The difference is well explained in Solutions 2nd edition Intermediate Student's book.

Determiners
Each and Every are followed by a singular countable noun.
Each is used when all the people or things it refers to are seen individually. Every is used to refer to all the people or things.
   Each egg is painted in different colours.
     Every egg can be purchased for ten euros.

A: 'Each' and 'every' are two similar words with almost identical meanings and very similar uses.  This makes the difference in meanings of these words unclear and stumps a lot of English native speakers when they try to explain the differences.
This is because 'each' and 'every' appear to be the same when we first look at them.  Both words are used to talk about individuals in a group; which makes understanding when to use 'each' and when to use 'every' challenging.
We can usually change one for the other without changing the meaning of the sentence, but there are times when we must use one or the other.
Below is an example of when using 'each' or 'every' doesn't affect the meaning of the sentences:
"Each boy grows up to be a man" and "Every boy grows up to be a man".
These sentences have the same meaning, but 'each' focuses on the individual boys while 'every' focuses on the group of individual boys as a whole.  The sentences have a different connotation or feeling, about them, but they have the same meaning.
https://www.krisamerikos.com/blog/each-vs-every

A: "Each" is used when addressing individual members of a group

The ten lucky winners will each receive $1,000.
Each of the ten lucky winners will receive $1,000.

"Every" is used to describe members of a group (singular - winner)

Every lucky winner will receive $1,000.

They can also be combined

Every lucky winner will each receive $1,000.


text:
Q: Android MVVM and Shared Element Transitions with RecycleView I'm trying to wrap my head around implementation of shared view transitions between fragments
The challenge is coming from the MVVP restricitons:

*

*Adapter of RecycleView has knowledge of selected element and view attached via callback from View

*Adapter is passing information about click to ViewModel stripping out all information about view, as it can't hold it. That's because of rule - no android imports in ViewModel except of *arch

*ViewModel sends event to Fragment to open another Fragment

*At this point Fragment doesn't know what view to use to start transition in .addSharedElement(..)
How to address this issue?
I was thinking about saving reference to clicked View inside Fragment instance but it looks like a cheating
Any ideas and suggestions are very welcome


text:
Q: Unknown datatypes IRQn_Type, When trying to build my project, I get errors like:
Drivers/CMSIS/Include/core_cm4.h:1816:41: error: unknown type name 'IRQn_Type'; did you mean 'ITM_Type'?
 1816 | __STATIC_INLINE void __NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
      |                                         ^~~~~~~~~

or
Drivers/CMSIS/Include/core_cm4.h: In function 'NVIC_EncodePriority':
Drivers/CMSIS/Include/core_cm4.h:1869:64: error: '__NVIC_PRIO_BITS' undeclared (first use in this function)
 1869 |   PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp);

So it seems that IRQn_Type and __NVIC_PRIO_BITS are not defined.
As far as I understand, the datatypes are defined in the stm32f407xx.h file and I am telling make already where to find it:
-IDrivers/CMSIS/Device/ST/STM32F4xx/Include

Edit
I just saw the first errors are these:
In file included from Drivers/CMSIS/DSP/Include/arm_math.h:322,
                 from Src/dsp/dsp.c:1:
Drivers/CMSIS/Include/core_cm4.h:105:8: error: #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
  105 |       #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
      |        ^~~~~

In file included from Src/dsp/dsp.c:3:
Drivers/CMSIS/Include/core_cm4.h:1688:39: error: unknown type name 'IRQn_Type'; did you mean 'ITM_Type'?
 1688 | __STATIC_INLINE void __NVIC_EnableIRQ(IRQn_Type IRQn)
      |                                       ^~~~~~~~~
      |                                       ITM_Type

My template makefile was generated by CubeMX, but I made some changes (changed the structure of my folders, added defines and include directories).
# C defines
C_DEFS =  \
-DUSE_HAL_DRIVER \
-DSTM32F407xx \
-DARM_MATH_CM4

# C includes
C_INCLUDES =  \
-IConfigs \
-ISrc \
-IDrivers/STM32F4xx_HAL_Driver/Inc \
-IDrivers/STM32F4xx_HAL_Driver/Inc/Legacy \
-IDrivers/CMSIS/Device/ST/STM32F4xx/Include \
-IDrivers/CMSIS/Include \
-IDrivers/CMSIS/DSP/Include

I get just this error:
In file included from Drivers/CMSIS/DSP/Include/arm_math.h:322,
                 from Src/dsp/filter.h:9,
                 from Src/dsp/filter.c:1:
Drivers/CMSIS/Include/core_cm4.h:105:8: error: #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
  105 |       #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
      |        ^~~~~
make: *** [Makefile:228: build/filter.o] Error 1

if I put this lines above my #include <arm_math.h>.
#define STM32F407xx
#include "stm32f4xx.h"

After adding also -D__FPU_PRESENT to the defines, I still get the error:
In file included from Src/dsp/dsp.c:4:
Drivers/CMSIS/Include/core_cm4.h:1688:39: error: unknown type name 'IRQn_Type'; did you mean 'ITM_Type'?
 1688 | __STATIC_INLINE void __NVIC_EnableIRQ(IRQn_Type IRQn)

A: To ensure that the header file for your particular microcontroller is included, you need to define the relevant macro. In your case, you need to ensure that -DSTM32F407xx is passed to your compiler. How exactly you do this will depend on your build environment.
Once you have done so, the relevant header file will be automatically included via stm32f4xx.h.
In case you're wondering how to ensure that stm32f4xx.h, in turn, is included - and if it needs to be included explicitly in your own source files ...
Typically, you won't need to explicitly include stm32f4xx.h. As long as you include the header file for one of the standard peripherals - such as the RCC or GPIO - it will be automatically included.
So the include chain might look something like follows:

*

*stm32f4xx_rcc.h <- include in your source files

*

*stm32f4xx.h

*

*stm32f407xx.h
The latter two are automatic - as long as -DSTM32F407xx is passed in your pre-processor flags.

A: core_cm4.h is not supposed to be included directly.
Instead, you #define the MCU line, and #include the header for the MCU series.
#define STM32F407xx
#include "stm32f4xx.h"

That would include stm32f407xx.h which in turn includes core_cm4.h.
Including stm32f407xx.h directly, without the #define might work too.

A: IRQn_Type is basically a enumeration that holds the value of all types of interrupts the controller have. For example
enum    IRQn_Type {
  NonMaskableInt_IRQn = -14,
  HardFault_IRQn = -13,
  MemoryManagement_IRQn = -12,
  BusFault_IRQn = -11,
  UsageFault_IRQn = -10,
  SecureFault_IRQn = -9,
  SVCall_IRQn = -5,
  DebugMonitor_IRQn = -4,
  PendSV_IRQn = -2,
  SysTick_IRQn = -1,
  WWDG_STM_IRQn = 0,
  PVD_STM_IRQn = 1
}

If it is not present your header file that means file is corrupted or someone had made changes is that file. Replace your file with new one might solve your problem.


text:
Q: GROUP_CONCAT: search for subset and retrieve all values I have this two tables:
posts
+--------------------------------------------------------------------+
|id          ¦status¦type ¦url                                       |
+------------+------+-----+------------------------------------------+
|25949664    ¦80    ¦link ¦http://example.com/25949664               |
|25777570    ¦80    ¦photo¦http://example.com/25777570               |
+--------------------------------------------------------------------+

attributes
╔════════════╦════════════╦══════════════════════════════════════════╗
║id          ║attr        ║value                                     ║
╠════════════╬════════════╬══════════════════════════════════════════╣
║25949664    ║timestamp   ║1430836105                                ║
║25949664    ║tag         ║red                                       ║
║25949664    ║tag         ║yellow                                    ║
║25949664    ║tag         ║brown                                     ║
║25949664    ║source      ║http://example.com/wallin/                ║
║25949664    ║source_title║wallin                                    ║
║25949664    ║state       ║published                                 ║
║25949664    ║format      ║html                                      ║
║25777570    ║timestamp   ║1430836105                                ║
║25777570    ║tag         ║red                                       ║
║25777570    ║tag         ║yellow                                    ║
║25777570    ║tag         ║brown                                     ║
║25777570    ║tag         ║black                                     ║
║25777570    ║tag         ║orange                                    ║
╚════════════╩════════════╩══════════════════════════════════════════╝

Performing this query:
  SELECT posts.id, GROUP_CONCAT(attributes.value) as tags
    FROM posts
    JOIN attributes ON attributes.id = posts.id
   WHERE ( attributes.attr = 'tag' )
     AND ( attributes.value IN ('red','brown') )
GROUP BY posts.id
  HAVING COUNT(DISTINCT attributes.value) = 2

I have this result:
╔════════════╦════════════╗
║id          ║tags        ║
╠════════════╬════════════╣
║25949664    ║red,brown   ║
║25777570    ║red,brown   ║
╚════════════╩════════════╝

I would rather have this:
╔════════════╦════════════════════════════════╗
║id          ║tags                            ║
╠════════════╬════════════════════════════════╣
║25949664    ║red,yellow,brown                ║
║25777570    ║red,yellow,brown,black,orange   ║
╚════════════╩════════════════════════════════╝

Practically, having n tags, I would retrieve all post's tags performing only one query.
Anyone have a suggestion, or this is totally impossible?

A:   SELECT posts.id, GROUP_CONCAT(attributes.value) as tags
    FROM posts
    JOIN attributes ON attributes.id = posts.id
   WHERE ( attributes.attr = 'tag' )
     AND ( attributes.value IN ('red','brown') )
GROUP BY posts.id

With the and condition, you only get the attributes red and brown. So you need to remove this and condition and rewrite that condition.
I think that this can help you:
 SELECT posts.id, GROUP_CONCAT(attributes.value) as tags
    FROM posts
    JOIN attributes ON attributes.id = posts.id
   WHERE ( attributes.attr = 'tag' )
GROUP BY posts.id
  HAVING Find_In_Set('red',tags)>0 AND Find_In_Set('brown',tags)>0

Online Demo


text:
Q: Cambie UIWebView a WkWebView Estoy realizando una app IOS soy nuevo en swift en la aplicación contenía un componente UIWebView y el html que es el contenido se veía bien el tamaño al correr la aplicación y asi se veía pero tuve que cambiarlo a WKWebView y sale bien pequeño todo el Html
Este es con UIWebView

Este es con WKWebView

Que puedo hacer ahi y porque es más pequeño el texto en WKWebView y en UIWebView el texto es normal?
El twiiter me sale bien pequeño en WkWebView.
Realice otro ejemplo con el WKWebView y UIWebView y necesito que este el WKWebView como el UIWebView con el tamaño del twitter por favor


text:
Q: How to compare two LiveData whether they are equal in Android Studio? I have two LiveData, aMVoice1, and aMVoice2.
I hope to check if they are equal.
I know I need to use observe to get the value of a LiveData.
so I think  isEqual = (mDetailViewModel.aMVoice1.value==mDetailViewMode2.aMVoice1.value ) is wrong.
But I think there are some problems with  fun observeVoice(), how can I fix it?
class FragmentDetail : Fragment() {

    private lateinit var binding: LayoutDetailBinding

    private val mDetailViewModel by lazy {
       ...
    }

    var isEqual=false

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        ...
        binding.lifecycleOwner = this.viewLifecycleOwner
        binding.aDetailViewModel=mDetailViewModel

        isEqual = (mDetailViewModel.aMVoice1.value==mDetailViewMode2.aMVoice1.value ) // I don't think it's correct.

        observeVoice()
        return binding.root
    }

    fun observeVoice() {
        mDetailViewModel.aMVoice1.observe(viewLifecycleOwner){value1->
           isEqual = (value1==mDetailViewModel.aMVoice2.value)  // mDetailViewModel.aMVoice2.value maybe null
        }
    }

}

class DetailViewModel(private val mDBVoiceRepository: DBVoiceRepository, private val voiceId1:Int,private val voiceId2:Int) : ViewModel() {
   val aMVoice1=mDBVoiceRepository.getVoiceById(voiceId1)
   val aMVoice2=mDBVoiceRepository.getVoiceById(voiceId2)
}

class DBVoiceRepository private constructor(private val mDBVoiceDao: DBVoiceDao){
    fun getVoiceById(id:Int)=mDBVoiceDao.getVoiceById(id)
}

@Dao
interface DBVoiceDao{
   @Query("SELECT * FROM voice_table where id=:id")
   fun getVoiceById(id:Int):LiveData<MVoice>
}

data class MVoice(
    @PrimaryKey (autoGenerate = true) @ColumnInfo(name = "id") var id: Int = 0,
    var name:          String = "",
    var path:          String = ""
)

Added Content
Is it Ok for the following code?
fun observeVoice() {
    mDetailViewModel.aMVoice1.observe(viewLifecycleOwner){value1->
       mDetailViewModel.aMVoice2.observe(viewLifecycleOwner){value2->
             isEqual = (value1==value2)
       }
    }
 }

A: According to the official documents, the best way to achieve a solution for such cases is to use MediatorLiveData as a LiveData merger. Using it, you can check the equality of values when a new value is posted on either of LiveDatas:
class DetailViewModel(...) : ViewModel() {

    val areMVoicesEqual = MediatorLiveData<Boolean>().apply {
        addSource(aMVoice1) { postValue(it == aMVoice2.value) }
        addSource(aMVoice2) { postValue(it == aMVoice1.value) }
    }
}

Then:
fun observeVoice() {
    mDetailViewModel.areMVoicesEqual.observe(viewLifecycleOwner){ equality ->
       // do whatever you want with `equality`
    }
 }

Note that Added Content snippet you mentioned is not correct. In fact, in this case, every time a value is being observed on aMVoice1, a new Observer starts to observe on aMVoice2 which is not right.


text:
Q: Read a value from DataStore once to update options menu checkbox state in a fragment I save the state of an options menu checkbox item (checked/unchecked) in Jetpack DataStore:
override fun onOptionsItemSelected(item: MenuItem) =
    when (item.itemId) {
        R.id.action_hide_completed_tasks -> {
            item.isChecked = !item.isChecked
            viewModel.hideCompleted(item.isChecked)
            true
        }
        else -> super.onOptionsItemSelected(item)
    }

which calls through to this method:
suspend fun updateHideCompleted(hideCompleted: Boolean) {
    dataStore.edit { preferences ->
        preferences[PreferencesKeys.HIDE_COMPLETED] = hideCompleted
    }
}

Now I want to restore this checkbox state when my fragment comes onto the screen. But since Jetpack DataStore provides the user preferences in form of a Flow, this feels a bit hacky. I collect from this Flow in onPrepareOptionsMenu and use the take(1) operator to only do it once, because after that I don't need to update the checkbox from the preferences anymore, the state automatically changes when I click the options menu item:
override fun onPrepareOptionsMenu(menu: Menu) {
    lifecycleScope.launch {
        viewModel.preferencesFlow
            .take(1) // I want this to update only when the fragment comes onto the screen, afterward it's unnecessary
            .collect {
                menu.findItem(R.id.action_hide_completed_tasks).isChecked = it.hideCompleted
            }
    }
}

Is this the correct approach? It feels a bit hacky. Will the asynchronicity cause problems in certain cases?

A: I believe the proper way to do it is using the Flow<T>.first() operator.
override fun onPrepareOptionsMenu(menu: Menu) {
    lifecycleScope.launch {
        val value = viewModel.preferencesFlow.first()
        menu.findItem(R.id.action_hide_completed_tasks).isChecked = value.hideCompleted
    }
}


text:
Q: System format exception on outfrom from database? I have the following bit of code:
    string updatestr= "UPDATE t1 SET  c3= @v3,c4=@v4,c5=@v5,c6=@v6 WHERE c2 = 'test' SELECT SCOPE_IDENTITY()";

    SqlCommand updatecmd= new SqlCommand(updatestr, conn);
    updatecmd.Parameters.AddWithValue("@v3",value3)
    updatecmd.Parameters.AddWithValue("@v4",value3)
    updatecmd.Parameters.AddWithValue("@v5",value3)
    updatecmd.Parameters.AddWithValue("@v6",value3)
    object ind = updatecmd.ExecuteScalar();
    int distindex = int.Parse(ind.ToString());

Now I would expect the output of the scope identity to be an int (namely 29) however I get a format exception. at int.Parse(ind.ToString());. I printed the value of ind.tostring and for some reason it's test. Note that the first colum and the primairy key of the database (called id) is an autoincrementing int and I was hoping to select that. What am I doing wrong?
Oh and here is a better formated version of the query:
UPDATE t1
 SET  c3= @v3,c4=@v4,c5=@v5,c6=@v6
WHERE c2 = "test"
SELECT SCOPE_IDENTITY()

A: SELECT SCOPE_IDENTITY()

Is for getting the auto-generated Id when a new row is INSERTED, in your case its an update so its probably returning null, you should use
select CAST(@@rowcount as int)

instead

A: As I have said in comment:

You are updating based on non primary key so there can be more that
  1 updated row. Which one do you want in result? You are looking for
  OUTPUT clause I think.

So the solution is to use OUTPUT clause with Inserted or Deleted virtual tables in case of update statement:
string updatestr= "UPDATE t1 SET c3= @v3,c4=@v4,c5=@v5,c6=@v6
                   OUTPUT Inserted.id
                   WHERE c2 = 'test'";

A: try this:
int distindex = 0;
object ind = updatecmd.ExecuteScalar();
if(ind != null)
 int.TryParse(ind.ToString(), out distindex);


text:
Q: Submitting nested class within a model to a controller I am trying to submit a form with a model that has a nested class within it.  However when I get the data to the controller, the nested class has null fields.
Model:
 public class Person
 {
    public string Name { get; set; }

    public ExtraStuff Stuff { get; set; } = new ExtraStuff();
 }

   public class ExtraStuff
   {
    public string Field1 { get; set; }

    public string Field2 { get; set; }

  }

View:
@model ProjectName.Models.Person

@Html.TextBoxFor(model => model.Name)
@Html.TextBoxFor(model => model.Stuff.Field1)
@Html.TextBoxFor(model => model.Stuff.Field2)

Controller:
   public ActionResult ActionName (Person data)
    {
      data.Name       //this is fine
      data.Stuff.Field1 //comes in empty
      data.Stuff.Field2 //comes in empty
    }

A: I'm wondering if you're doing some custom form submission, because there doesn't seem to be anything wrong with the code provided. If you make a form like the following it should work:
@using (Html.BeginForm("ActionName", "MyController"))
{
    @Html.TextBoxFor(model => model.TopValue)
    @Html.TextBoxFor(model => model.Nested.SomeValue)

    <input type="submit" value="Submit"/>
}

Take a look at this fiddle for example.


text:
Q: how can i access logcat file on device How can I access and read the logcat file (at "/system/bin/logcat") from the device, using my application. My phone is not rooted.
Do I need a super user permission?

A: you can read through this code from your application
ArrayList<String> commandLine = new ArrayList<String>();
commandLine.add("logcat"); //$NON-NLS-1$
commandLine.add("-d"); //$NON-NLS-1$
ArrayList<String> arguments =
    ((params != null) && (params.length > 0)) ? params[0] : null;
if (null != arguments) {
    commandLine.addAll(arguments);
}

Process process = Runtime.getRuntime().exec(commandLine.toArray(new String[0]));
BufferedReader bufferedReader = new BufferedReader(
    new InputStreamReader(process.getInputStream()), 1024);

bufferedReader.readLine()

Store this bufferedReader in an string or string builder to check your logs
yes you need permission in your manifest file:
<uses-permission android:name="android.permission.READ_LOGS"/>


text:
Q: What do Trainer Levelups Do? In Penny Arcade's On the Rainslick Precipice of Darkness 4, both trainers and monsters levelup.  I understand that monster's gain attributes on levelup and that both monsters and trainers gain abilities on certain levels but what about the levels where the trainers don't gain an ability?  What effect do those levelups have?

A: No effect, really.  Trainer levelups only grant new abilities, much like the class pins in Penny Arcade 3.


text:
Q: Sort file 'per paragraph' in Vim Given a file that looks like:
Crab
  some text that doesn't need sorting.
  more textual descriptination
Albatross
  some text or other
  perhaps a list that needs no sorting:
    1. a
    2. bee
Dolphin
Pterodactyl
  long story about this particular animal.

How would I tell Vim (version 7) to sort this file alphabetically by animal name? Impossible? How else would one sort this file?

A: Yeah, you can do it in vim:
:%s/$/$/
:g/^\w/s/^/\r/
:1del t | $put t
:g/^\w/,/^$/-1join!
:sort
:%s/\$/\r/g
:g/^$/d

output
Albatross
  some text or other
  perhaps a list that needs no sorting:
    1. a
    2. bee
Crab
  some text that doesn't need sorting.
  more textual descriptination
Dolphin
Pterodactyl
  long story about this particular animal.

You should use a special char to indicate EOL(other than $)!

A:
How else would one sort this file?

$perl sortparagraphs animals.txt

Albatross
  some text or other
  perhaps a list that needs no sorting:
    1. a
    2. bee
Crab
  some text that doesn't need sorting.
  more textual descriptination
Dolphin
Pterodactyl
  long story about this particular animal.

Where sortparagraphs is
#!/usr/local/bin/perl
use strict;
use warnings;

my ($paragraph, @list);
while(<>) {
  if (/^\S/) {
    push @list, $paragraph if $paragraph;
    $paragraph = '';
  }
  $paragraph .= $_;
}
push @list, $paragraph if $paragraph;
print sort @list;

There is probably a better Perl solution but the above is a quick answer.
If the file is larger than memory, it might be sensible to transform the file into a line per animal, sort and finally transform back.


text:
Q: How to listen to future path in firebase How can we listen in advanced to a non existed path on firebase which going to be created in the future outside the app(via the server side) ?

A: You don't have to do anything special to listen to a location in the database that doesn't exist yet.  It works just like any other listener, and your code will get invoked as soon as data is written to that location.


text:
Q: How to write select query in django in chain of one-to-many relationship? How to write select query in django? I have 2 one-to-may relationship
At the beginning, i am not very good at english. i am so sorry :). I have 3 tables. Driver, Car and Ride. The relationship between Driver and Car is (one-to-many: a Driver can have multiple Car. The relationship between Car and Ride is (one-to-many: a Car can have multiple Ride. I want list of drivers who have x times of rides.
My Models:
class Driver(models.Model):
    account = GenericRelation(Account, related_query_name='drivers')

class Car(models.Model):
    owner = models.ForeignKey(Driver, on_delete=None)

class Ride(models.Model):
    car = models.ForeignKey(Car, on_delete=models.CASCADE)
    request = models.OneToOneField(RideRequest, on_delete=models.CASCADE, null=False)

I expect something like this: <QuerySet [<Driver: 1>, <Driver: 2>]>which is Drivers with greater than or equal x Rides

A: You can count the number of Rides per Driver, and then filter on that number, like:
from django.db.models import Count

Driver.objects.annotate(
    nride=Count('car__ride')
).filter(nride__gte=x)
We thus first annotate each Driver object with the Count(..) [Django-doc] of related Rides, next we filter that queryset by specifying that the nrides field annotation should be greater than or equal to x, by using the __gte lookup [Django-doc]. Here x is of course the number of required rides you need to fill in (for example 5).


text:
Q: RAII-style C++ class for linked list Nodes I'm playing with linked lists as an exercise at the moment.
The examples I'm looking at in the Cracking The Coding Interview book have no LinkedList (manager) class, just Nodes, and you hang on to the head Node in your main function.
I looked up C++ implementations, but most seem to be more C-style than C++, i.e. not object-oriented. They use structs, no classes, and have a static method for deleting the list, which you need to explicitly remember to call. I wanted to write a sensible RAII (Resource Acquisition Is Initialization) style C++ class with sensible destructors to handle memory deallocation, and I wanted to use only a Node class (no LinkedList class).
The only way I saw to have this work was to have Node's destructor delete the next Node if there was one, but I've read that this kind of recursive delete is a bad idea, because you end up creating a callstack the same length as the linked list.
So to summarize my question:

*

*If writing an object-oriented class to handle linked lists in C++, do you have to have a LinkedList (manager) class which handles the deletion of the list nodes in its destructor?

*If not, how would you deal with destruction of Nodes?

Thanks!

A:
If writing an object-oriented class to handle linked lists in C++, do you have to have a LinkedList (manager) class which handles the deletion of the list nodes in its destructor?

No, the structure is defined by the links between nodes, so there's no need for a separate manager object. It can sometimes be more convenient to have one, especially if you're designing a library like the STL and want all the containers to have a similar interface, but you can certainly implement a linked list with just a node type.

If not, how would you deal with destruction of Nodes?

One way to avoid recursion is to remove each node from the list before deleting it, something like:
~node() {
    while (node * victim = next) {
        next = victim->next;
        victim->next = nullptr;
        delete victim;
    }
}


text:
Q: Как получить IP-адрес в андроид приложении? Есть сервер с ip-адресом и непосредственно андроид приложение. Если придется менять сервер, то пользователи останутся без данных, так как в приложении ip не поменяется, поэтому надо сделать получение ip-адрес независимо от самого сервера.
Как это лучше сделать?

A: Самое лучшее - это DNS запись. Вы можете менять сколько угодно IP-адресов, но имя всегда можно перенести на новый адрес. В течении максимум 4 часов (по стандарту), хотя обычно в течение нескольких минут ваши пользователи снова смогут подключиться.


text:
Q: Skewed order of magnitude when copying text from tab-separated text to Excel I have the following data points formatted as follows in a tab-separated text file:
7.23e-10    0.125   9.0375e-11
4.946739999999999e-07   0.16666666666666666 8.244566666666665e-08

When I manually copy these data to Excel however, it seems like the order of magnitude is skewed in some, but not all of the cases, namely:
7.23E-10    0.125   9.04E-07
4.95E+08    0.166666667 8.24E+07

I tried looking for a reason and solution e.g. here, but didn't manage to find anything.
Any help is greatly appreciated, thanks!

A: The issue was with the settings regarding the separators for decimal and thousands.
I changed these in Excel in options>advanced to . and empty, respectively (e.g. 1.000,01 would be represented as 1000.01).
However, Excel does not allow an empty separator for thousands, so silently added back in . for the thousand separator.
As a result, both the decimal and thousands separator were now . (periods).
This caused the unexpected behavior as described in the question.
The remedy is to change these separators in the regional settings of your Windows machine and have Excel use the system settings, instead of changing these separators directly in the Excel settings.


text:
Q: Backbone.js - What is the best approach for global/shared/related models? I'm currently building an application using Backbone.js with a number of different models that all relate to each other in various ways. I'm currently experimenting with various architectural approaches.
In a nutshell the model relationships looks something like this:
Workspace > Projects > Tasks

There are a few other models, such as lists and categories, that are attached to a project.
On a page with a task list, I'm dumping the JSON of the tasks onto the page and filling up the collection. This works ok, but at the moment all tasks are pulling in their own project data.
task.project.id
task.project.name

The projects are also being pulled in various other locations on the page for various lists. Tasks can also be part of a List which is assigned to a Project. This means I'm also making requests to pull in the lists for a project in various places as well.
The main problem with this is that when updating a model in place I need to find some way to 'sync' them. Which is crazy. They should all be using the same model instance so that each view is using the same model and is updated accordingly without having to do anything.
I've been researching various Backbone.js architectural designs to try and find the answer. Chaplin (https://github.com/moviepilot/chaplin), for example, uses a mediator object to pass data between views. Using this approach, I could have a Projects collection on the mediator and pass this around to the various views via the mediator object.
Each project would include all of it's lists, categories, assigned users etc. Then I could request for a project model like so:
App.Projects.get(12)

Then the task would just need the project ID and a getter and setter method. Views could get access to available projects, project lists, project users easily as well without relying on digging into the model or making further AJAX calls. Additionally, the task models wouldn't require any of the project data on them.
However, dumping all this data in a global object seems bad.
I would possibly end up with something like this:
App.Workspaces
App.Workspaces.get(1)
App.Projects
App.Projects.get(12).get('lists')[0]
App.Projects.get(12).get('users')

To use like this:
var projectId = model.get('project')
var project = App.Projects.get(projectId)

Or with a getter method:
var project = model.getProject()

And add the mediator as a dependency at the model level instead.
Adding a large global object like this adds a fairly large dependency that could make testing difficult. It also seems wrong to assume that the mediator will even have the project available. Maybe it could make the model, fetch it and return it if it doesn't exist.
Any help here would be great! I'd love to know how other people have solved this problem.

A: I recommend to have a common Collection for all your Task Models. Kind of cache.
Something like: App.Store.Tasks.
Any time you need to feed the Poject.Tasks look first in the App.Store.Tasks and then:
A. If you found the Task there then take it and add it to your Project.Tasks.
B. If not found there then create, fetch and add it to both: App.Store.Tasks and your Project.Tasks.
This way other Project that tries to fetch a Task that already exits will do the same and they both will share the same Model.
Any time you modify one of your Task models in a Project you'll be modifying this Task in every other Project.


text:
Q: Mac OS X: Print directly from file/URL? I want to code a litte utility that can print a page from a an URL, the URL would deliver a standard file (like a pdf or a jpg picture) and I just want to print this from within my cocoa app without showing any dialog, is that possible? I can't find anything about this in the docs except for a thing telling me to build a view with the file and then print this view but is this really necessary?
Any help appreciated.
Thanks,
Philip

A: You don't need to show the NSView in order to print.
Just create the NSView programmatically and pass it to the NSPrintOperation.
Example code:
// Get Print Info
NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];

// Printing Text
NSRect textRect = NSMakeRect(0,0,100,50);
NSTextView *theTextView = [[NSTextView alloc] initWithFrame:textRect];
[theTextView setString: @"Hello World"];
NSPrintOperation *textPrint = [NSPrintOperation printOperationWithView:theTextView printInfo:printInfo];
[textPrint setCanSpawnSeparateThread:YES];
[textPrint runOperation];

// Printing Picture
NSImage *pic =  [[NSImage alloc] initWithContentsOfFile: @"/Users/Anne/Desktop/Sample.png"];
NSRect picRect = NSRectFromCGRect(CGRectMake(0, 0, pic.size.width, pic.size.height));
NSImageView *imageView = [[NSImageView alloc] initWithFrame:picRect];
[imageView setImage:pic];
NSPrintOperation * picPrint = [NSPrintOperation printOperationWithView:imageView printInfo:printInfo];
[picPrint setCanSpawnSeparateThread:YES];
[picPrint runOperation];

For PDF documents use PDFView (add the Quartz framework).
You might also consider using WebView (add the WebKit framework).
WebView supports many formats and makes formatting a breeze (HTML).


text:
Q: Passing a struct Type in Golang? Please forgive my question, I'm new to Golang and possibly have the wrong approach.
I'm currently implementing a Terraform provider for an internal service.
As probably expected, that requires unmarshalling JSON data in to pre-defined Struct Types, e.g:
type SomeTypeIveDefined struct {
    ID   string `json:"id"`
    Name String `json:"name"`
}

I've got myself in to a situation where I have a lot of duplicate code that looks like this
    res := r.(*http.Response)
    var tempThing SomeTypeIveDefined
    dec := json.NewDecoder(res.Body)
    err := dec.Decode(&tempThing)

In an effort to reduce duplication, I decided what I wanted to do was create a function which does the JSON unmarshalling, but takes in the Struct Type as a parameter.
I've trawled through several StackOverflow articles and Google Groups trying to make sense of some of the answers around using the reflect package, but I've not had much success in using it.
My latest attempt was using reflect.StructOf and passing in a set of StructFields, but that still seems to require using myReflectedStruct.Field(0) rather than myReflectedStruct.ID.
I suspect there may be no way until something like Generics are widely available in Golang.
I considered perhaps an interface for the structs which requires implementing an unmarshal method, then I could pass the interface to the function and call the unmarshal method. But then I'm still implementing unmarshal on all the structs anyway.
I'm just wondering what suggestions there may be for achieving what I'm after, please?

A: Create a helper function with the repeated code.  Pass the destination value as a pointer.
func decode(r *http.Repsonse, v interface{}) error {
     return json.NewDecoder(res.Body).Decode(v)
}

Call the helper function with a pointer to your thing:
var tempThing SomeTypeIveDefined
err := deocde(r, &tempThing)

A: You can do this with interfaces:
func decodeResponse(r *http.Response, dest interface{}) error {
    dec := json.NewDecoder(r.Body)
    return dec.Decode(dest)
}

func handler(...) {
    res := r.(*http.Response)
    var tempThing SomeTypeIveDefined
    if err:=decodeResponse(res,&tempThing); err!=nil {
      // handle err
    }
   ...
}

You don't need to implement an unmarshal for the structs, because the stdlib decoder will use reflection to set the struct fields.


text:
Q: Sign off of Windows with out of box LDAP provider on 2013 causes encodedValue error I've hit upon yet another encodedValue error scenario:
Exception of type 'System.ArgumentException' was thrown.  Parameter name: encodedValue   at
Microsoft.SharePoint.Administration.Claims.SPClaimEncodingManager.DecodeClaimFromFormsSuffix(String encodedValue)     at
Microsoft.SharePoint.Administration.Claims.SPClaimProviderManager.GetProviderUserKey(IClaimsIdentity claimsIdentity, String encodedIdentityClaimSuffix)     at
Microsoft.SharePoint.Administration.Claims.SPClaimProviderManager.GetProviderUserKey(String encodedIdentityClaimSuffix)     at
Microsoft.SharePoint.Utilities.SPUtility.GetFullUserKeyFromLoginName(String loginName)     at
Microsoft.SharePoint.ApplicationRuntime.SPHeaderManager.AddIsapiHeaders(HttpContext context, String encodedUrl, NameValueCollection headers)     at
Microsoft.SharePoint... bca6039c-35a7-5087-0000-057fa64c1d5b

The reproduction seems to be the following:

*

*Have a working site with Windows Authentication.

*Add Forms-Based

*Authentication with any working provider, properly configured.

*Test FBA. Everything works.

*Sign out. Everything works.

*When prompted after sign out, choose Windows Authentication.

*Everything works.

*Sign out.

At that point you are signed out, but you get an error. If you refresh the error page, it will work eventually (the number of refreshes needed seemed to be steady at two, but that proved false).
The FBA sign in before Windows is not necessary, it is just here to allow demonstrating that the FBA provider is working and not causing the issue (seemingly).
Ideas?

A: I called Microsoft on this (case 113030110256288) and it's a product bug in 2013 - apparently a regression from 2010. Another customer had reported the same issue. It's an acknowledged bug with no KB yet. They hope to pick it up in an upcoming cumulative update but it wasn't know when to expect it yet.


text:
Q: tapkey Tapkey is an open platform for mobile access control—with an open API, Mobile and Lock SDK to integrate smartphone-based access into existing apps and locks.
Use this tag for questions about interacting with the Tapkey Smart Lock API or SDK.


text:
Q: Check if table tr td is not empty I want to check if the table tr td still gots the dummy text.
If thats true then a message should appear that they have to enter some text there ( by drag and dropping )
Drag and drop is working thats not the problem i just need to check if the td still got the dummy tekst
else the cannot proceed to the next step
here is my html table layout :

                       s

s

                                Menu

Drop  content

                             Menu

Drop  content

                             Main Content

Drop  content

the p tag is removed if people drop content there
if they didn't a message should appear there
I tried this :
function checkTemplate(){
            $jQ('.Required > tbody > tr > td').each(function(index){
            if($jQ(this).children().hasClass('dummyText'));
            console.log('Empty');
             });
           }

A: As I commented:

dummyTekst != dummyText

You're checking for a class dummyText where you provide dummyTekst as actual classname.
Besides that. You don't have to each all the TD's and loop the children. Just check if the class is present. See fiddle: http://jsfiddle.net/z5oyL9cw/
$(document).ready(function(){
    if ($(".dummyTekst").length > 0) {
        alert('We still have dropzones');
    }
});

A: I would have written it something like this:
function checkTemplate(){
    $jQ('table > tbody > tr > td').each(function(index){
        if($jQ(this).children('p.dummyTekst').length == 0){
            console.log('Empty');
        }
    });
}

A: Take a look into jQuery's .each(): http://api.jquery.com/each/
It iterates over every instance of... whatever you want to target.  So, yours might be:
$( "td" ).each(function() {

From there, I'd have to look at your javascript to know the best way to check to see if the user changed anything.  One option is using jQuery's .has to see if the p exists. http://api.jquery.com/has/  Or you can simply check the child element itself.  Once you post your JS, I can say with more certainty.

A: Why don't you just add a CSS class to your cells (i.e. has-dummy-text) and use it as a flag?
In your example, say for instance:

     Menu

Drop  content

That way you can manage cell's state by adding or removing the class via jQuery's .addClass() or .removeClass() methods, and then check if cell still has your initial dummy-text state by checking with  .hasClass() method. (See jQuery class manipulation methods for more info).

A: If you want to make sure that your child 'p.dummyTekst' is there and also not empty, you should use the .is() from jquery UI. Just to be sure and avoid flying eggs and stuff :P. Also, to place text in the P, use .append.
$jQ('.required > tbody > tr > td').each(function(index){
    if( $jQ(this).children('p.dummyTekst').is(":empty") ) {
        $jQ(this).children('p.dummyTekst').append("Your text here");
    }
});

Please note that browsers can mess around with this, if you have problems using the .is(":empty") try to use $.trim() from jQuery. If he can't trim ( $.trim() ), the element should be empty.
$jQ('.required > tbody > tr > td').each(function(index){
    if ( !$jQ(this).children('p.dummyTekst').trim() ) {
        $jQ(this).children('p.dummyTekst').append("Your text here");
    }
});

A: I'd try something on the line of this (I don't know JQuery very well, but I do know some JavaScript, and maybe you can convert it; sorry if it isn't helpful.
function checkTemplate()  {
  var dummy = document.getElementByClassName(dummyTekst);
  if(dummy.innerHTML == "s")  {
  [Your Continue Function]
  }
  else  {
    alert(You must have the dummy text!)
  }
  }


text:
Q: How to preserve < and > in element value with SimpleXML? I have this XML file I want to parse with simple XML in PHP :
<?xml version="1.0" encoding="UTF-8"?>
<data>
    <title>Lorem ipsum</title>
    <content>Whoa, <ducks>!</content>
</data>

I want to preserve the  in the content element, so I tried to HTML encode it :
<?xml version="1.0" encoding="UTF-8"?>
<data>
    <title>Lorem ipsum</title>
    <content>Whoa, <ducks>!</content>
</data>

But then SimpleXML give me this error :
Warning: simplexml_load_string(): Entity: line 3: parser error : Premature end of data in tag content

Then I tried URLencode :
<?xml version="1.0" encoding="UTF-8"?>
<data>
    <title>Lorem ipsum</title>
    <content>Whoa%2C%20%3Cducks%3E!</content>
</data>

And it give me this instead :
Warning: simplexml_load_string(): Entity: line 3: parser error : Opening and ending tag mismatch: ducks

Here's my current PHP code, pretty simple, right?
$request = simplexml_load_string($_POST["data"]);

So, what's the correct way to parse that XML file while still keeping the special characters?

A: Wrap your values in CDATA
<title><![CDATA[Lorem ipsum]]></title>


text:
Q: How do you get/set non root CSS variables from JavaScript Lots of answers on how to get/set "root" CSS variables but none that I've found on how to get/set NON root CSS variables.
NOTE: This is NOT answer: https://stackoverflow.com/a/36088890/104380  That answer only handles root variables and or variables on elements, not on classes
Also: These are not answers (from: https://www.google.com/search?q=get%2Fset+css+variables). Checked the first page of links. All of them only handle root variables. I'm trying to deal with non-root variables.

.foo {
  --fg-color: red;
}
.bar {
  --fg-color: blue;
}
div {
 color: var(--fg-color);
}

foo

foo

How do you get someFunctionToGetCSSVariable('.foo', '--fg-color') (yes, I made that up). The point is I want to get/set the --fg-color variable on the .foo CSS rule. Whatever the solution is, getting the value it should return 'red' or '#FF0000') and how do you set it to something else?

A: I think what OP tries to do is not to change the all elements of that certain class, but to change the class itself, there is a difference. What you need (if I understood well) is actually cssRules change on the certain class. I've created a quick (and dirty) snippet of how to search the cssRules and change the CSS properties in it (including custom one):

lorem ipsum

A: You could make use of the fact that we have cascading style sheets.
It depends on exactly what your structure is of course, (e.g. are there style elements buried in body?).
For the simple case you could add another stylesheet onto the bottom of the head element.
<!doctype html>

foo

foo

<button>Click me</button>

Of course, it could get messy if this happens more than once. You'd want to remember that you'd added a style sheet and get rid of it before adding another one, or alter it in situ, depending on exactly what the situation is. And if there is styling scattered in the body you'll have to add the stylesheet to the bottom of that.

A: Looks like I have to iterate through all the stylesheets and find the rule. Here's one try.

function getCSSRuleBySelector(selector) {
  for (let s = 0; s < document.styleSheets.length; ++s) {
    const rules = document.styleSheets[s].cssRules;
    for (let i = 0; i < rules.length; ++i) {
      const r = rules[i];
      if (r.selectorText === selector) {
        return r;
      }
    }
  }
}

function setCSSVariableBySelector(selector, varName, value) {
  const rule = getCSSRuleBySelector(selector);
  rule.style.setProperty(varName, value);
}

function getCSSVariableBySelector(selector, varName) {
  const rule = getCSSRuleBySelector(selector);
  return rule.style.getPropertyValue(varName);
}

console.log('was:', getCSSVariableBySelector('.foo', '--fg-color'));
setCSSVariableBySelector('.foo', '--fg-color', 'green');
.foo {
  --fg-color: red;
}
.bar {
  --fg-color: blue;
}
div {
  color: var(--fg-color);
}

foo

foo

foo

bar

bar

A: You can use document's styleSheets property to access the CSS rules of the linked .css file, and perform some operations on it to get the value of the custom css variable.
To set a value of custom CSS variable (of the class itself), you can create a new style element, and add a rule for it.

function getStyle(selector, prop) {
  let rules = getRule(selector).cssText;
  return rules.split(prop + ":")[1].replace(";", "").replace("}", "").trim();
}

function setStyle(selector, prop, val) {
  let style = document.querySelector("style.customStyle");
  if(style === null){
    style = document.createElement("style");
    style.className = "customStyle";
    style.innerHTML = `${selector}{${prop}:${val}}`;
    document.head.appendChild(style);
  } else{
    style.innerHTML += `${selector}{${prop}:${val}}`;
  }
}

function getRule(selector) {
  let rulesObj = document.styleSheets[0];
  let classes =  rulesObj.rules || rulesObj.cssRules;
  classes = Object.values(classes)
  let rules = classes.filter(c => c.selectorText === selector)[0];
  return rules;
}

console.log(getStyle(".foo", "--fg-color"));
console.log(getStyle(".bar", "--fg-color"));

document.querySelector("button").onclick = ()=>{
  setStyle(".bar", "--fg-color", "green");
}
.foo {
  --fg-color: red;
}

.bar {
  --fg-color: blue;
}

div {
  color: var(--fg-color);
}

foo

foo

<button>Click</button>

A: Get
Iterate all styles
Styles can be injected via external CSS file, a `)

And when you want to update it, just overwrite the #whatever


text:
Q: Trying to optimize CPU usage, 'pgrep -x spotify' running despite never installing spotify I recently installed Arch Linux on a very old laptop. As such, I am trying to optimize it as much as possible and cut down on CPU/RAM usage. Attached is a screenshot I took of htop on the laptop without much running other than a terminal:

There are several things about this that confuse me.

*

*The first is that the total CPU usage seems much larger than the sum of the individual CPU usages from all the processes (there are a few more if you scroll down, but all show 0.0% CPU usage). Why is this? There have been times where both cores have been at around 80% capacity, with the CPU audibly being put under a fair amount of strain, and htop still shows a similar output.

*I was unable to get a screenshot of this because they only show up for a short time, but occasionally the commands pgrep -x cmus and pgrep -x spotify will briefly show up on htop, while using somewhere around 10% of the CPU. I have very few programs installed on this laptop and have never installed Spotify or (I believe) anything Spotify-related. What's the cause of these commands showing up?

A: Regarding the pgrep portion of the question, from the pgrep man page:
pgrep  looks  through  the  currently running processes and lists the process IDs
       which match the selection criteria to stdout.  All the criteria  have  to  match.

and the -x option:
-x, --exact
              Only match processes whose names (or command line if -f is specified)  ex‐
              actly match the pattern.

So, those pgrep lines indicate that something on your system is searching to see if cmus and/or spotify are running on your system (and presumably not finding them, if they are not installed).
About the mismatch with CPU utilization: I am not sure. However, I think one possibility is that htop is only showing userspace processes. Presumably, the kernel itself is also using some of the CPU, but I would not expect htop to include a line for the kernel space. However, I don't know if 25%+ CPU usage by the kernel on average would make sense. You say your system is 'very old' but don't go into specifics. Perhaps it is so old that the kernel itself is requiring a significant proportion of the CPU? Maybe some kernel module is 'misbehaving' or not working well with that hardware and thrashing the CPU?


text:
Q: Make list of ones and zeroes in R with probability New to R, looking for some help with a problem.
I'm looking to make a numeric vector in R of length N where the elements are either a 1 or a 0. I'd like roughly 30% of the elements to be ones. The code I have thus far
probs=rep(0.3,N)
x<-sample(0:1,N,replace=TRUE,prob=probs)

But this returns the following error:
Error in sample.int(length(x), size, replace, prob) :
 incorrect number of probabilities

I'm sure I'm making a very simple mistake here. Could anyone point me in the right direction?

A: How about this:
N <- 100
set.seed(123)
x <- sample(c(0,1),size=N,replace=TRUE,prob=c(.7,.3))
##
> table(x)
x
 0  1
71 29

Equivalently, you can represent this with a Binomial distribution:
set.seed(123)
y <- rbinom(N,1,.3)
> table(y)
y
 0  1
71 29

A: For extremely simple cases like yours,  it's just as easy to do
foo<-c(rep(1,3),rep(0,7))
sample(foo,100,replace=TRUE)

For more complicated or varying sets of weights, do what the other answers and comments suggest.


text:
Q: Using conditions in custom react hook which uses useQuery I have a custom react hook which is used to get a user's data by sending a POST request. I would like my custom react hook to check if the argument passed into the hook meets certain conditions, however I'm aware that I cant use conditions with hooks. Does any one have any idea how to improve my code so that I can check if an argument is valid?
...
import { useQuery } from "@tanstack/react-query";

export const useLiquidityPositions = (userAddress: string): GraphQLResponse<LiquidityPositions> => {
    const {
        status: status,
        isLoading: loading,
        error: error,
        data: response,
    } = useQuery({
        queryKey: ["USER_POSITIONS", userAddress],
        queryFn: async () => {
            if (!isAddress(userAddress)) {
                return undefined
            }
            const res = await getLiquidityPositionsData(userAddress);
            return res;
    }});
    const payload = response?.data;

    return { status, loading, error, response, payload }
}

A: You can enable or disable useQuery by your condition
like this :
export const useLiquidityPositions = (
  userAddress: string,
  enabled: boolean
): GraphQLResponse<LiquidityPositions> => {
  const {
    status: status,
    isLoading: loading,
    error: error,
    data: response,
  } = useQuery({
    queryKey: ['USER_POSITIONS', userAddress],
    queryFn: async () => {
      if (!isAddress(userAddress)) {
        return undefined;
      }
      const res = await getLiquidityPositionsData(userAddress);
      return res;
    },
    enabled,
  });
  const payload = response?.data;

  return { status, loading, error, response, payload };
};

and in usage:
const result = useLiquidityPositions('...',true //your condition )

A: Two ways to validate query using react-query.
1. only validate a single request. https://react-query-v3.tanstack.com/guides/dependent-queries
import { useQuery } from "@tanstack/react-query";

export const useLiquidityPositions = (userAddress: string): GraphQLResponse<LiquidityPositions> => {
    const {
        status: status,
        isLoading: loading,
        error: error,
        data: response,
    } = useQuery({
        queryKey: ["USER_POSITIONS", userAddress],
        queryFn: ()=>getLiquidityPositionsData(userAddress),
          // The query will not execute until isAddress(userAddress) is true.
        enabled: isAddress(userAddress)
        });
    const payload = response?.data;

    return { status, loading, error, response, payload }
}

2. validate all request.
https://react-query-v3.tanstack.com/guides/query-invalidation
Add validate functions to queryClient

const queryClient = new QueryClient()
queryClient.invalidateQueries({
  predicate: query =>
    query.queryKey[0] === 'USER_POSITIONS' && isAddress(query.queryKey[1]) ,
})

<QueryClientProvider client={queryClient}>
</QueryClientProvider>


text:
Q: Javascript in application.js for a field in the _form partial fails to work for the edit action I have some javascript to control how some fields in the _form partial work based on the radio buttons clicked. Everything works well when I am entering a new record (new) action, but during editing, where the same _form partial is rendered, the javascript does not seem to have any effect.
Why the strange behaviour?
Here is the code sample:
$(document).ready(function(){
    $('input[name="staff[optquestion]"]').on('change', function() {
        $('select[name="staff[Redesignation]"]').attr('disabled', this.value
!= "true")
    });
});

$(document).ready(function(){
    $('input[name="staff[staffpresent]"]').on('change', function() {
        $('select[name="staff[absent_reason]"]').attr('disabled', this.value
!= "false")
    });
});

I have also noted that the javascript does not seem to work when I load the same page on my phone.

A: If you have turbolinks installed then it must not work, see the turbolinks documentation, write code like this
$(document).on('turbolinks:load', function(){
    $('input[name="staff[optquestion]"]').on('change', function() {
        $('select[name="staff[Redesignation]"]').attr('disabled', this.value
!= "true")
    });
});

added turbolinks:load


text: Q: From Kernel Density to a polygon that covers 80 % of points I have a set of occurrences as points in a district. I used Kernel Density tool, to show the areas of various densities. I also want to create one polygon that covers X % of points. I've tried the Locate Region tool but dont feel like this is quite the right method, as its not clear to me how it works and seems to be more for finding locations at set distances to other 'suitable' locations. I'm working in ArcGIS 10.1.5.


text:
Q: PreparedStatement , CallableStatement and Performance Considerations I have a oracle stored proc that needs to be called from my Java program. I had used CallableStatement to pass parameters to the stored proc. I am using oracle thin driver (configured in web logic server against the relevant jndi entry).This stored proc does not have any OUT values. This stored proc accepts a numeric value and does a lot of updates in the db based on the value received.
I get a connection object and then call this stored proc in loop (20 times for passing 20 numbers). When I directly call this stored proc from an oracle client , the execution gets completed in 2-3 seconds. However the behaviour is not predictable from my java code. Some of the calls take even 30-40 seconds to get completed.
I tried to use PreparedStatement instead of CallableStatement and could see marginal performance improvement (though the behaviour is still inconsistent).

*

*Is it OK in my case to use PreparedStatement instead of CallableStatement given that the storedproc does not have any OUT parameters?

*Is there any reason why PreparedStatement has some performance gain over CallableStatement or is it something that I might have observed incorrectly?

*Is there a better approach for solving this performance issue?

A: From your comment, you have prepareCall inside your loop. An advantage of prepared statements (and callable statements) is that you can prepare it once, and then swap out the values passed in the parameters; there is overhead each time the call is prepared, so if you could bring that outside of your loop, you may find that run time decreases. You may find that turning off AutoCommit also helps, as there is overhead with each commit.
conn.setAutoCommit(false);
CallableStatement stmt = conn.prepareCall(sql);
while(true) {
    stmt.setInt(1, value);
    stmt.execute();
}
conn.commit();
conn.setAutoCommit(true);

(conn.setAutoCommit(true) does commit, but I find it clearer to be explicit).

A: Shouldn't you consider using batch?
conn.setAutoCommit(false);
CallableStatement stmt = conn.prepareCall(sql);
while(true) {
    stmt.setInt(1, value);
    stmt.addBatch();
}
stmt.executeBatch()
conn.commit();


text:
Q: Q. If you compile and execute an application with the following code in its main() method: Why " s" is created two objects If you compile and execute an application with the following code in its main() method:
In this program why the " s" create the two objects.
   String s = new String( "Computer" );

   if( s == "Computer" )
   System.out.println( "Equal A" );
   if( s.equals( "Computer" ) )
   System.out.println( "Equal B" );

A: The first s == "Computer" test will fail, since s and the literal string "Computer" are sitting at different addresses.
The second s.equals("Computer") will succeed. The two strings have equal contents.
Any good tutorial book on Java would explain that better than we have time to.

A: To compare String objects you should do:
if( s.equals("Computer" ))

instead of == operator.


text:
Q: How can I extract a string prefix that comes before a given character? Is there a way of extracting a prefix defined by a character without using split? For instance, given "some-text|more-text" how can I extract "some-text" which is the string that comes before "|"?

A: If your issue with split is that it may also split rest of the string, then consider str.splitn(2, '|') which splits into maximum two parts, so you get the string up to the first | and then the rest of the string even if it contains other | characters.

A: Split may be the best way. But, if for whatever reason you want to do it without .split(), here's a couple alternatives.
You can use the .chars() iterator, chained with .take_while(), then produce a String with .collect().
// pfx will be "foo".
let pfx = "foo|bar".chars()
                   .take_while(|&ch| ch != '|')
                   .collect::<String>();

Another way, which is pretty efficient, but fallable, is to create a slice of the original str:
let s   = "foo|bar";
let pfx = &s[..s.find('|').unwrap()];

// or - if used in a function/closure that returns an `Option`.
let pfx = &s[..s.find('|')?];

A: as @Kornel point out, you can use the Split function:
let raw_text = "some-text|more-text";
let extracted_text = raw_text.split("|").next().unwrap();

<iframe src="https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&code=fn%20main()%20%7B%0A%20%20%20%20let%20raw_text%20%3D%20%22some-text%7Cmore-text%22%3B%0A%20%20%20%20let%20extracted_text%20%3D%20raw_text.split(%22%7C%22).next().unwrap()%3B%0A%20%20%20%20println!(%22%7B%7D%22%2Cextracted_text)%3B%0A%7D" style="width:100%; height:400px;"></iframe>


text:
Q: C++ recursive pointer function calls I currently have a base class Expr and some derivatives like AddExpr, MultExpr and NumExpr. I am trying to overload a general print() function that recursively calls the print() function of its members which are pointers to other Expr objects.
//Addition Expression
AddExpr::AddExpr( Expr* l, Expr* r ) {
    left = l;
    right = r;
}
string AddExpr::print() {
    string s;
    stringstream out;
    out << "(+" << left->print() << right->print() << ")";
    s = out.str();
}

NumExpr::NumExpr( string n ) {
    number = atoi( n.c_str() );
}
string NumExpr::print() {
    string s;
    stringstream out;
    out << number;
    s = out.str();
    return s;
}

So ultimately I want the add expression to print out a ( number + number ) if the left and right pointers are numbers, ( expression + number ), ( expression + expression ), etc. by recursively calling the print() function.
However I don't think I'm approaching this correctly as I am getting jumbled output :(
I am not too familiar with pass by pointer and pass by reference, however every post that I have gone through with similar question are not quite relevant to my situation.
Here's a debug sample for calling the functions:
NumExpr* left = new NumExpr("1");
cout << left->print() << endl;
NumExpr* right = new NumExpr("2");
cout << right->print() << endl;
AddExpr* temp = new AddExpr( left, right );
cout << temp->print() << endl;
Expr* temp2 = temp;
cout << temp2->print() << endl;

This will print out 1 and 2 but has the problem on the AddExpr.
Any help is appreciated!
EDIT:
the header for my expression classes:
class Expr {
    public:
        virtual string name();
        virtual string print();
};

class AddExpr : public Expr {
    public:
        AddExpr(Expr* l, Expr* r);
        string print();
    private:
        Expr* left;
        Expr* right;
};

class NumExpr : public Expr {
    public:
        NumExpr( string v );
        string print();
    private:
        int number;
};

A: AddExpr::print() does not return any value.

A: I see two problems with your AddExpr::print() method:

*

*It doesn't actually return anything.  You should have at least gotten a compiler warning, if not an error, for this.

*It doesn't put any space between left and right.
Try this:
string AddExpr::print() {
    string s;
    stringstream out;
    out << "(+" << left->print() << " " << right->print() << ")";
    s = out.str();
    return s;
}

Though actually, it would be better to do the following -- no need to create an explicit string variable:
string AddExpr::print() {
    stringstream out;
    out << "(+" << left->print() << " " << right->print() << ")";
    return out.str();
}


text:
Q: Does Java 9 contain built-in JSON? I was wondering if Java 9 has built-in support for JSON. If so how can I import it? I'm writing a socket program so I'm not talking about Java EE and my target to import to is a simple Java SE class.

A: There is JSON-P which has a JSR.

JSON Processing (JSON-P) is a Java API to process (for e.g. parse, generate, transform and query) JSON messages. It produces and consumes JSON text in a streaming fashion (similar to StAX API for XML) and allows to build a Java object model for JSON text using API classes (similar to DOM API for XML).

That's as close as you can get to official JSON support in Java.

A: There was a proposal to drop the feature by Mark Reinhold, Oracle's Head of the Java:

We may reconsider this [JSON API] JEP for JDK 10 or a later release, especially if new language features such as value types and generics over primitive types (JEP 218) enable a more compact and expressive API.

And it doesn't appear in the finalized features. So it appears Java 9 doesn't have a native JSON API.


text:
Q: 'currentApple' is already defined showing in jslint I have have some js code;
in that I ran the js lint.
I have this error:

'currentApple' is already defined

Do I need to remove var currentApple from else to make it work?
I'm providing my code below:
if(appleTab == Lifeline){
    var currentApple = appleWorklist.getcurrentAppleTime("currentAppointmentcurrentAppleTime");
    fo.allApples = currentApple;
}
else
{
    var currentApple = appleWorklist.getcurrentAppleTime("CalendarcurrentAppointmentcurrentAppleTime");
    fo.allApples = currentApple;
}

A: var currentApple;
if (appleTab == Lifeline) {
    currentApple = /* etc. */

A: there is no blockscope in javascript, so currentApple in your code snippet is basically the same thingy.
from Douglas Crockford's  bible, paragraph Variables:

JavaScript does not have block scope, so defining variables in blocks
  can confuse programmers who are experienced with other C family
  languages. Define all variables at the top of the function.

Just declare every used variable once with a var statement at the start of your function.


text:
Q: Click function and hover function When user hovers on a circle, that particular circle along with the circles to its left should get filled with yellow and when user clicks on a circle, that particular circle along with the circles to its left should get filled with green.
When user hovers again, last active circles should rollback to hover effect function and get filled with yellow, and if the user doesn't like to click again, the previously filled circle with green must be retained.
I've given !important for the rating-hover class to give it a priority when user hovers again, now the problem is when user rates 4 for the first time and again thinks to rate 2 after that and hovers on second circle the previously filled 4 stars are still seen, I don't want to see that, the user must feel like rating newly when he hover again, if left unclicked the previously clicked stars must be retained. And please I don't like to use !important; any other solutions are welcome!

$(function() {
  $('.rating-circle').hover(function() {
      $(this).prevAll().addBack().addClass('rating-hover');
    },
    function() {
      $(this).prevAll().addBack().removeClass('rating-hover');
    });
});

$(function() {
  $('.rating-circle').click(function() {
    $('.rating-circle').removeClass('rating-chosen');
    $(this).prevAll().addBack().addClass('rating-chosen');
  });
});
.rating-circle {
  height: 2em;
  width: 2em;
  border: .1em solid black;
  border-radius: 1.1em;
  display: inline-block;
  margin: 0;
  padding: .1em;
}
.rating-hover {
  background-color: yellow !important;
}
.rating-chosen {
  background-color: green;
}

A: To achieve the effect you require you just need to set the .rating-hover class to be more specific that .rating-chosen so that it overrides. To do this I prefixed it with an element selector, specifically div. You then need to also remove the .rating-hover class when the click event fires.
Finally, note that you can also put all the code in a single document.ready handler. Try this:

$(function() {
  $('.rating-circle').hover(function() {
    $(this).prevAll().addBack().addClass('rating-hover');
  }, function() {
    $(this).prevAll().addBack().removeClass('rating-hover');
  });

  $('.rating-circle').click(function() {
    $('.rating-circle').removeClass('rating-chosen rating-hover');
    $(this).prevAll().addBack().addClass('rating-chosen');
  });
});
.rating-circle {
  height: 2em;
  width: 2em;
  border: .1em solid black;
  border-radius: 1.1em;
  display: inline-block;
  margin: 0;
  padding: .1em;
}
div.rating-hover {
  background-color: yellow;
}
.rating-chosen {
  background-color: green;
}

A: Try adding !important to the rating-hover class. The hover is working correctly but because of the rating-chosen last in your style, you will need the !important there.

$(function() {
  $('.rating-circle').hover(function() {
      $(this).prevAll().addBack().addClass('rating-hover');
    },
    function() {
      $(this).prevAll().addBack().removeClass('rating-hover');
    });
});

$(function() {
  $('.rating-circle').click(function() {
    $('.rating-circle').removeClass('rating-chosen');
    $(this).prevAll().addBack().addClass('rating-chosen');
  });
});
.rating-circle {
  height: 2em;
  width: 2em;
  border: .1em solid black;
  border-radius: 1.1em;
  display: inline-block;
  margin: 0;
  padding: .1em;
}
.rating-hover {
  background-color: yellow !important;
}
.rating-chosen {
  background-color: green;
}


text:
Q: Why did I need to use this statement twice - Matrix Multiplication I was developing a program to find matrix multiplication.
#include <iostream>

using namespace std;

int main()
{
    int a=0,b=0,c=0,d=0,e=0;
    cout<<"Enter the order of the first matrix  A  \n\nNumber of Rows : ";
    cin>>a;
    cout<<"\nNumber of Columns : ";
    cin>>b;
    cout<<endl;
    int matrixA[a][b];
    cout<<"Enter the matrix Elements "<<endl;
    for(int m=0; m<a; m++)
    {

        for(int n=0; n<b; n++)
        {
            cout<<"A ("<< m+1 <<" , "<<n+1<<" ) =";
            cin>>matrixA[m][n];
            //cout<<",";
        }
        cout<<endl;
    }

//////////////////////////  Startup

    cout<<"Enter the order of the Second matrix  A  \n\nNumber of Rows : "<<b;
    c=b;
    cout<<"\nNumber of Columns : ";
    cin>>d;
    cout<<endl;
    int matrixB[c][d];
    cout<<"Enter the matrix Elements "<<endl;
    for(int p=0; p<c; p++)
    {
        for(int q=0; q<d; q++)
        {
            cout<<"B ("<< p+1 <<" , "<<q+1<<" ) =";
            cin>>matrixB[p][q];
            //cout<<",";
        }
        cout<<endl;
    }

    ///////////// initialisting matrixAns
    int matrixAns[a][d];

    for(int p=0; p<a; p++)
    {
        for(int q=0; q<d; q++)
        {
            matrixAns[p][q]=0;
        }
    }

////////////////////  finding ans
    for(int r=0; r<a; r++)
    {
        for(int s=0; s<d; s++)
        {
            for(int t=0; t<b; t++)
            {
                e = matrixA[r][t]*matrixB[t][s];
            }
            matrixAns[r][s] = e+matrixAns[r][s];
            matrixAns[r][s] = e+matrixAns[r][s];   //dont know why i have to add this same code again
    }
    }

////////////////////// Ans Printing
    cout<<"\nMatrix Multiplication Answer  \n"<<endl;
    for(int h=0; h<a; h++)
    {
        for(int i=0; i<d; i++)
        {
            cout<<" "<<matrixAns[h][i]<<" ";
        }
        cout<<endl;
    }
}

And one important thing: this is not my homework or assignment!
The method that I have used  works perfectly but it does not give me the right answer until I use this statement twice. (I got  this by a trial and error method).
matrixAns[r][s] = e+matrixAns[r][s];

I have also initailised the matrixAns by using a loop (and had set it to 0).
I am new to C++ and want to know what was the error that I got and how the use of the two statements gives me correct answer.
Is there any way to get rid of one of the statements without destroying the app?

A: You're not doing the dot products correctly when calculating your answer. You need to multiply individual cells between the two matrices, then sum all those products for an individual cell in your answer.
Your code is only taking the product, in e, of the last multiplication - matrix[r][b - 1] * matrixB[b - 1][s] -  and discarding the first N-1 products. Adding e - this last multiplication - once, or twice or 3 times are all incorrect, though it may appear to work with certain inputs.
Your answer loop, with comments:
for(int r=0; r<a; r++)
{
    for(int s=0; s<d; s++)
    {
        for(int t=0; t<b; t++)
        {
            e = matrixA[r][t]*matrixB[t][s];
        }

        // now e only has the value from that final multiplication, of
        //    matrix[r][b - 1] * matrixB[b - 1][s]. All of the other
        //    products were lost.

        // so now it doesn't matter how many times you add e, you'll
        //    get the wrong product:
        matrixAns[r][s] = e+matrixAns[r][s];
        matrixAns[r][s] = e+matrixAns[r][s];
    }
}

Change your answer loop to:
for(int r=0; r<a; r++)
{
    for(int s=0; s<d; s++)
    {
        for(int t=0; t<b; t++)
        {
            e = matrixA[r][t]*matrixB[t][s];

            // accumulation of the products should be INSIDE the loop:
            matrixAns[r][s] = matrixAns[r][s] + e;
        }
    }
}

A: Have you printed matrixAns[r][s] to make sure it holds something?
It sounds like matrixAns[r][s] is empty; this is what I think is happening:
matrixAns[r][s] = e+matrixAns[r][s]; //stores e in matrixAns[r][s]
matrixAns[r][s] = e+matrixAns[r][s]; //adds e to e (whats in matrixAns[r][s])


text:
Q: SSRS 2017 machineKey deleted on restart I've implemented the solution from here (with the 2017 equivalents from comments) but i've hit a roadblock and i'm not able to find a solution. The '<'machineKey'>' tag from web.config and from rsportal.exe.config are deleted after restart .
Because of that (i think) after i log in i get a 500 Internal server error. I've searched the logs and found this error :

Throwing
  Microsoft.ReportingServices.Diagnostics.Utilities.UnhandledHttpApplicationException:
  ,
  Microsoft.ReportingServices.Diagnostics.Utilities.UnhandledHttpApplicationException:
  The report server encountered an unhandled exception in
  HttpApplication.
  ---> System.Web.HttpException: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that
  machineKey configuration specifies the same validationKey and
  validation algorithm.  AutoGenerate cannot be used in a cluster.

I've set the machineKey tag in RSPortal.exe.config , web.config and in rsreportserver.config .I've tried deleting the encryption key's and restarting it and it did not help.   Any ideea how to fix this or what is causing it ?

A: it happened to me as well and was resolved by adding the machine key to rsreportserver.config inside Configuration section right after Dsn element
in the following case:
MachineKey

A: I had the same issue, it is related to the format. Please use the below format
<MachineKey
ValidationKey="BE4663BB11C14E8C7C1DB0A48022D517CB668C65A46174B0C4CFF4D9B7CE2498EA998C4E5A8C15EE5262D5C297479349B2A9783700AB3C1C891B914D12691A0D"
DecryptionKey="7121FD4D52F0035DBBB113B9E449ED4467CA01DDD26684FF"
Validation="SHA1"
Decryption="AES"/>


text:
Q: Expectation of dice
What is the expectation of $\frac{1}{N}$ where $N$ is the number of times you roll a fair dice in order to get the number $1$?

I know the expectation of $N$ is $6$, so surely the expectation of $\frac{1}{N}$ is $\frac16$?
Please could someone confirm if this is correct.

A: You go with the definition of an expectational value:
\begin{align*}
\mathbb{E}[1/N] = \sum _{n=1}^\infty \frac{1}{n}\mathbb{P}[N = n]
\end{align*}
As you will know
\begin{align*}
\mathbb{P}[N = n] = \frac{1}{6}\left(\frac{5}{6}\right)^{n-1}
\end{align*}
Plug that in and you get
\begin{align*}
\mathbb{E}[1/N] = \frac{1}{6}\sum _{n=1}^\infty \frac{1}{n}\left(\frac{5}{6}\right)^{n-1} = \frac{\log(6)}{5}
\end{align*}
according to WolframAlpha.


text:
Q: Third Cassandra node has different load We had a cassandra cluster with 2 nodes in the same datacenter with a keyspace replication factor of 2 for keyspace "newts". If i ran nodetool status i could see that the load was somewhat the same between the two nodes and each node sharing 100%.
I went ahead and added a third node and i can see all three nodes in the nodetool status output. I increased the replication factor to three since i now have three nodes and ran "nodetool repair" on the third node. However when i now run nodetool status i can see that the load between the three nodes differ but each node owns 100%. How can this be and is there something im missing here?
nodetool -u cassandra -pw cassandra status
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address       Load       Tokens       Owns (effective)  Host ID                               Rack
UN  84.19.159.94  38.6 GiB   256          100.0%            2d597a3e-0120-410a-a7b8-16ccf9498c55  rack1
UN  84.19.159.93  42.51 GiB  256          100.0%            f746d694-c5c2-4f51-aa7f-0b788676e677  rack1
UN  84.19.159.92  5.84 GiB   256          100.0%            8f034b7f-fc2d-4210-927f-991815387078  rack1

nodetool status newts output:
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address       Load       Tokens       Owns (effective)  Host ID                               Rack
UN  84.19.159.94  38.85 GiB  256          100.0%            2d597a3e-0120-410a-a7b8-16ccf9498c55  rack1
UN  84.19.159.93  42.75 GiB  256          100.0%            f746d694-c5c2-4f51-aa7f-0b788676e677  rack1
UN  84.19.159.92  6.17 GiB   256          100.0%            8f034b7f-fc2d-4210-927f-991815387078  rack1

A: As you added a node and there are now three nodes and increased your replication factor to three - each node will have a copy of your data and so own 100% of your data.
The different volume for "Load" can result from not running nodetool cleanup after adding your third node on the two old nodes - old data in your sstables won't be removed when adding the node (but later after a cleanup and/or compaction):

Load - updates every 90 seconds The amount of file system data under
  the cassandra data directory after excluding all content in the
  snapshots subdirectories. Because all SSTable data files are included,
  any data that is not cleaned up, such as TTL-expired cell or
  tombstoned data) is counted.

(from https://docs.datastax.com/en/cassandra/3.0/cassandra/tools/toolsStatus.html)

A: You just run nodetool repair on all 3 nodes and run nodetool cleanup one by one on existing nodes then restart the node one after another seems it works.


text:
Q: Read txt file real time with Javascript I would like to know if there is some way to read a .txt file from Javascript in real-time?
I have a log file that updates every few seconds. I want to parse some data from that log file as it updates and display it in a html.
Can I do this live?
Thanks a lot guys!

A: Assuming the file is somewhere publicly accessible, you can have a javascript function which makes an AJAX request every few seconds to read the file. Something like the following:
function getLog() {
    $.ajax({
        url: 'logfile.txt',
        dataType: 'text',
        success: function(text) {
            $("#containerDiv").text(text);
            setTimeout(getLog, 30000); // refresh every 30 seconds
        }
    })
}

getLog();

A: No, you can't read/write a file with Javascript, cause it would be a terrible security issue.
But, in your case, you can use some Ajax calls to a server-side script.


text:
Q: 3rd party css not compiled in production on Heroku (Rails 6 - Webpack ) My app is working fine in my dev & qa environment which both have all environment variables set to "DEV". However, in my production environment on Heroku, CSS related to 3rd larty JS libraries doesn't seem to get compiled. The specific libraries are:
- FullCalendar: https://fullcalendar.io/docs#toc
- DateTimePicker: https://xdsoft.net/jqplugins/datetimepicker/
My stack is:
- Rails 6 (using webpacker)
- jQuery
- Bootstrap
The main bootstrap css is fine in PRD and so is all of the javascript. Just the CSS that belongs to calendar and datepicker isn't there.
This is my application.js file
require("bootstrap")
require("@fortawesome/fontawesome-free/js/all")
require('summernote')
require("summernote/dist/summernote.css")
require('jquery-ui/ui/widgets/sortable')
require('jquery-ui/ui/effects/effect-blind')
require('jquery-ui/ui/effects/effect-highlight')
require('jquery-datetimepicker')
require('jquery-datetimepicker/jquery.datetimepicker.css')

// custom scripts
require("application/calendar")
require("application/datepicker")
require("application/custom")

within the calendar file, I require and initiate FullCalendar as follows:
import { Calendar } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
//import listPlugin from '@fullcalendar/list';
import '@fullcalendar/core/main.css';
import '@fullcalendar/daygrid/main.css';
import '@fullcalendar/timegrid/main.css';
//import '@fullcalendar/list/main.css';
import bootstrapPlugin from '@fullcalendar/bootstrap';

in my layouts, I use the following markup:
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <!--   -->
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload'  %> <!-- -->

All of this is fine in development.
The result in PRD looks like this:

should look like this:

Similar effect with the datepicker. The calendar seems to have the bootstrap css which is part of the application but the specific css is missing.
I already tried a lot of different things.
- assets are not precompiled but compiled during deployment to production
- I tried a css-pack_tag instead of a css_include_tag but that just throws an error. Doesn;t see to be related from what I can tell since the css is imported within the .js files.
Not sure where to go from here.
update:
I also noticed that the styles for datepicker and calendar are not present in the stylesheet in production. all calendar styles start with 'fc-', all datepicker styles start with 'xdsoft_'. None of these keys are in  the loaded stylesheets.

A: Temporary solution:
I switched the webpacker configuration in PRD to:
  extract_css: false

This will cause JS related css to be included inline in the JS file.
However, my question now would be: is that best practice? What are the pros and cons of this approach?

A: I am not sure if this will be your case, but I had a very similar issue and I fixed it by including a stylesheet_pack_tag (not link_tag) in my application layout. In my case the third party CSS styles were imported in an application.scss file inside app/javascript/stylesheets, so I had to add this in my layout:
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>

A: You must to add a stylesheet_pack_tag in your layout.
<%= stylesheet_pack_tag 'application', 'data-turbolinks-track': 'reload'  %>

this happen because extract_css: is true for production environment in webpack.yml.


text:
Q: Firebase + SugarORM - App Crash I have a class Session that is a model which gets created using Firebase using onDataChange.
When I extend this model from SugarRecord, the app crashes with the following stacktrace:
FATAL EXCEPTION: main
com.firebase.client.FirebaseException: Failed to bounce to type
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:185)
at xyz.eventapp.apiclient.APIClient$1.onDataChange(APIClient.java:14)
at com.firebase.client.core.ValueEventRegistration.
fireEvent(ValueEventRegistration.java:56)
at
com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not
access private java.lang.reflect.Field() (from class
java.lang.reflect.Field; failed to set access: Can't make field
constructor accessible

This is not only the case with SugarRecord but with any ORM like DBFlow.
So does it mean that I cannot extend any class from a model that is being created using the onDataChange contract?


text:
Q: Targeting html elements with css not working I have an html string which I am setting inside Angular here
<div
  [innerHtml]="privacyPolicyHtml"
    class="privacy-policy">
</div>

and attempting to target. elements within that string like this
.privacy-policy {
  width: toRem(715px);
  color: #363636;
  margin: toRem(40px) auto;
  font-size: toRem(14px);

  ul {
    list-style: none;
    padding-left: 0;
  }
}

However, the changes are not being applied even when not using SASS and just
.privacy-policy ul {}


text:
Q: pasting images from an array to a bigger image This is my program, I'm trying for a 1x2 array of two cv2 images to past it to a bigger one. the idea is to do that for a bigger array of images and see them as a mosaic.
Problem is that this seems a mixture of cv2 and PIL and couldn't manage it to work.
Here my little code:
from PIL import Image
from matplotlib import cm

#example of one of the two images added
new_array = cv2.resize(x_test[0], (IMG_SIZE, IMG_SIZE))
trp.append(new_array2)

im_pil=[]
#I create the big image
new_im = Image.new('RGB', (IMG_SIZE,IMG_SIZE * 2))

k=0
#here i want to place my image in the mosaic
for i in range(0,IMG_SIZE,IMG_SIZE):
    for j in range(0,IMG_SIZE *2,IMG_SIZE):
        #paste the image at location i,j:

        im_pil.append(Image.fromarray(trp[k])
        new_im.paste(im_pil[k], (i,j))
        k+=1

new_im

that's all the code( a little summarized) and I don't really know where the problem is. I get different kinds of errors in each modification, from invalid syntax to not defined or some crazy ones i dont understand.
although that
plt.imshow(trp[1])
plt.show()

works and shows one image
I'm sorry if the answer is obvious buy I'm trying my best to figure it out and I can't manage it.
Thanks in advance

A: I don't know why you use cv2 because you can do all in PIL. You can even display it without matplot
from PIL import Image

IMG_SIZE = 128

filenames = ['image1.png', 'image2.png']
images = []

for name in filenames:

    img = Image.open(name)
    img = img.resize((IMG_SIZE, IMG_SIZE))

    images.append(img)

new_im = Image.new('RGB', (IMG_SIZE, IMG_SIZE*2))

k = 0
for i in range(0, IMG_SIZE, IMG_SIZE):
    for j in range(0, IMG_SIZE *2, IMG_SIZE):
        new_im.paste(images[k], (i,j))
        k += 1

new_im.save('output.png')
new_im.show()

For images from cv2 you have to

*

*convert colors from BGR to RGB

*convert array to Image

*do what you want

*convert back Image to array

*if you want to use again with cv2 then convert colors from RGB to BGR
Code:
from PIL import Image
import cv2
import numpy as np
import matplotlib.pyplot as plt

IMG_SIZE = 128

filenames = ['image1.png', 'image2.png']

images = []

for name in filenames:

    im = cv2.imread(name)
    im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
    im = cv2.resize(im, (IMG_SIZE, IMG_SIZE))

    img = Image.fromarray(im)
    images.append(img)

new_im = Image.new('RGB', (IMG_SIZE, IMG_SIZE*2))

k = 0
for i in range(0, IMG_SIZE, IMG_SIZE):
    for j in range(0, IMG_SIZE *2, IMG_SIZE):
        new_im.paste(images[k], (i,j))
        k += 1

im = np.array(new_im)

plt.imshow(im)
plt.show()

#cv2.imshow('window', cv2.cvtColor(np.array(new_im), cv2.COLOR_RGB2BGR))
#cv2.waitKey(0)