text:
Q: Convert std::string to ci_string I used this approach to create a case-insensitive typedef for string. Now, I'm trying to convert a std::string to ci_string. All of the following throw compiler errors:
std::string s {"a"};
ci_string cis {s};
ci_string cis (s);
ci_string cis {(ci_string)s};
ci_string cis ((ci_string)s);
ci_string cis = s;

I spent some time trying to figure out how to overload the = operator, and I attempted to use static_cast and dynamic_cast without success. How can I do this?

A: Your two types are different, so you cannot use the constructor with a regular std::string. But your string is still able to copy a C string, so this should work:
std::string s{"a"};
ci_string cis{ s.data() }; // or s.c_str(), they are the same

A: std::string and ci_string are unrelated types. Why would static_cast or dynamic_cast be able to convert them? Remember: Two different instantiations of the same template are unrelated types and are potentially completely incompatible.
Give up on the idea of overloading operator= or on some magic that performs the conversion automatically. You have two unrelated types. But they both offer member functions that can you can successfully use to copy the char elements from one to the other.
Just write a simple conversion function that takes advantage of the fact that both std::string and ci_string have their value_type defined as char, and appropriately use one of std::basic_string's constructors, either one which takes a pointer to raw data or one which takes two iterators which form a range.
Here is a complete example:
#include <string>
#include <iostream>

struct ci_char_traits : public std::char_traits<char> {
    static bool eq(char c1, char c2) { return toupper(c1) == toupper(c2); }
    static bool ne(char c1, char c2) { return toupper(c1) != toupper(c2); }
    static bool lt(char c1, char c2) { return toupper(c1) <  toupper(c2); }
    static int compare(const char* s1, const char* s2, size_t n) {
        while( n-- != 0 ) {
            if( toupper(*s1) < toupper(*s2) ) return -1;
            if( toupper(*s1) > toupper(*s2) ) return 1;
            ++s1; ++s2;
        }
        return 0;
    }
    static const char* find(const char* s, int n, char a) {
        while( n-- > 0 && toupper(*s) != toupper(a) ) {
            ++s;
        }
        return s;
    }
};

typedef std::basic_string<char, ci_char_traits> ci_string;

ci_string to_ci_string(std::string const& src)
{
    return ci_string(src.begin(), src.end());
    // or:
    // return ci_string(src.c_str());
}

int main()
{
    std::string s {"a"};
    auto cis = to_ci_string(s);

    std::cout << cis.c_str() << "\n";
}


text:
Q: Is it possible to use Espresso's IdlingResource to wait until a certain view appears? In my test I have a stage where after pressing a button application does a lot of asynchronous calculations and requests to the cloud service, after which it displays a certain view.
Is it possible to use Espresso's IdlingResource implementation to wait until a certain view appears?
I've read an answers here and comments seems to suggest that you can use IdlingResource instead, but I don't understand how. Espresso does not seem to have any built-in way to handle long operations, but having to write your own waiting loops feels like a hack.
Any way to solve this or should I just do as the answer in the linked thread suggests?

A: I took inspiration from Anatolii, but instead of using methods from the View.class I still only use ViewMatchers.
/**
 * {@link IdlingResource} that idles until a {@link View} condition is fulfilled.
 */
public class ViewIdlingResource implements IdlingResource {

    private final Matcher<View>    viewMatcher;
    private final Matcher<View>    idleMatcher;
    private       ResourceCallback resourceCallback;

    /**
     * Constructor.
     *
     * @param viewMatcher The matcher to find the view.
     * @param idlerMatcher The matcher condition to be fulfilled to be considered idle.
     */
    public ViewIdlingResource(final Matcher<View> viewMatcher, Matcher<View> idlerMatcher) {
        this.viewMatcher = viewMatcher;
        this.idleMatcher = idlerMatcher;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isIdleNow() {
        View view = getView(viewMatcher);
        boolean isIdle = idleMatcher.matches(view);

        if (isIdle && resourceCallback != null) {
            resourceCallback.onTransitionToIdle();
        }

        return isIdle;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
        this.resourceCallback = resourceCallback;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getName() {
        return this + viewMatcher.toString();
    }

    /**
     * Tries to find the view associated with the given {@link Matcher<View>}.
     */
    private static View getView(Matcher<View> viewMatcher) {
        try {
            ViewInteraction viewInteraction = onView(viewMatcher);
            Field finderField = viewInteraction.getClass().getDeclaredField("viewFinder");
            finderField.setAccessible(true);
            ViewFinder finder = (ViewFinder) finderField.get(viewInteraction);
            return finder.getView();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

And how to use the idler in your test case, I pass the ViewMatchers.isDisplayed() to be my expected condition in the idler.
private void waitUntilViewIsDisplayed(Matcher<View> matcher) {
        IdlingResource idlingResource = new ViewIdlingResource(matcher, isDisplayed());
        try {
            IdlingRegistry.getInstance().register(idlingResource);
            // First call to onView is to trigger the idler.
            onView(withId(0)).check(doesNotExist());
        } finally {
            IdlingRegistry.getInstance().unregister(idlingResource);
        }
    }

With this you can pass any Matcher.class to the ViewIdlingResource constructor to be the required condition for the view found by the viewMatcher parameter.

A: Atte Backenhof's solution has a small bug (or maybe I don't fully understand the logic).
getView should return a null instead of throwing an exception to make IdlingResources work.
Here's a Kotlin solution with the fix:
/**
 * @param viewMatcher The matcher to find the view.
 * @param idleMatcher The matcher condition to be fulfilled to be considered idle.
 */
class ViewIdlingResource(
    private val viewMatcher: Matcher<View?>?,
    private val idleMatcher: Matcher<View?>?
) : IdlingResource {

    private var resourceCallback: IdlingResource.ResourceCallback? = null

    /**
     * {@inheritDoc}
     */
    override fun isIdleNow(): Boolean {
        val view: View? = getView(viewMatcher)
        val isIdle: Boolean = idleMatcher?.matches(view) ?: false
        if (isIdle) {
            resourceCallback?.onTransitionToIdle()
        }
        return isIdle
    }

    /**
     * {@inheritDoc}
     */
    override fun registerIdleTransitionCallback(resourceCallback: IdlingResource.ResourceCallback?) {
        this.resourceCallback = resourceCallback
    }

    /**
     * {@inheritDoc}
     */
    override fun getName(): String? {
        return "$this ${viewMatcher.toString()}"
    }

    /**
     * Tries to find the view associated with the given [<].
     */
    private fun getView(viewMatcher: Matcher<View?>?): View? {
        return try {
            val viewInteraction = onView(viewMatcher)
            val finderField: Field? = viewInteraction.javaClass.getDeclaredField("viewFinder")
            finderField?.isAccessible = true
            val finder = finderField?.get(viewInteraction) as ViewFinder
            finder.view
        } catch (e: Exception) {
            null
        }
    }

}

/**
 * Waits for a matching View or throws an error if it's taking too long.
 */
fun waitUntilViewIsDisplayed(matcher: Matcher<View?>) {
    val idlingResource: IdlingResource = ViewIdlingResource(matcher, isDisplayed())
    try {
        IdlingRegistry.getInstance().register(idlingResource)
        // First call to onView is to trigger the idler.
        onView(withId(0)).check(doesNotExist())
    } finally {
        IdlingRegistry.getInstance().unregister(idlingResource)
    }
}

Usage in your UI tests:
    @Test
    fun testUiNavigation() {
        ...
        some initial logic, navigates to a new view
        ...
        waitUntilViewIsDisplayed(withId(R.id.view_to_wait_for))
        ...
        logic on the view that we waited for
        ...
    }

Important update: default timeout for the IdlingResources is 30 seconds, they don't wait forever. To increase a timeout you need to call it in @Before method for example:
IdlingPolicies.setIdlingResourceTimeout(3, TimeUnit.MINUTES)

A: Your IdlingResource could look like this:
import android.support.test.espresso.IdlingResource;
import android.support.test.espresso.ViewFinder;
import android.support.test.espresso.ViewInteraction;
import android.view.View;

import org.hamcrest.Matcher;

import java.lang.reflect.Field;

import static android.support.test.espresso.Espresso.onView;

public class ViewShownIdlingResource implements IdlingResource {

    private static final String TAG = ViewShownIdlingResource.class.getSimpleName();

    private final Matcher<View> viewMatcher;
    private ResourceCallback resourceCallback;

    public ViewShownIdlingResource(final Matcher<View> viewMatcher) {
        this.viewMatcher = viewMatcher;
    }

    @Override
    public boolean isIdleNow() {
        View view = getView(viewMatcher);
        boolean idle = view == null || view.isShown();

        if (idle && resourceCallback != null) {
            resourceCallback.onTransitionToIdle();
        }

        return idle;
    }

    @Override
    public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
        this.resourceCallback = resourceCallback;
    }

    @Override
    public String getName() {
        return this + viewMatcher.toString();
    }

    private static View getView(Matcher<View> viewMatcher) {
        try {
            ViewInteraction viewInteraction = onView(viewMatcher);
            Field finderField = viewInteraction.getClass().getDeclaredField("viewFinder");
            finderField.setAccessible(true);
            ViewFinder finder = (ViewFinder) finderField.get(viewInteraction);
            return finder.getView();
        } catch (Exception e) {
            return null;
        }
    }
}

Then, you could create a helper method waiting for your view:
public void waitViewShown(Matcher<View> matcher) {
    IdlingResource idlingResource = new ViewShownIdlingResource(matcher);///
    try {
        IdlingRegistry.getInstance().register(idlingResource);
        onView(matcher).check(matches(isDisplayed()));
    } finally {
        IdlingRegistry.getInstance().unregister(idlingResource);
    }
}

Finally, in your test:
@Test
public void someTest() {
    waitViewShown(withId(R.id.<some>));

    //do whatever verification needed afterwards
}

You could improve this example by making IdlingResource wait for any condition, not just for the visibility one.

A: To wait for a view display and can do action on it. You can use this method:
    private const val sleepTime = 1000L
    private const val maximumWaitedTime = 10000L // maximum waited time in milliseconds to wait a view visible

    fun waitViewVisible(viewInteraction: ViewInteraction?, block: (() -> Unit)? = null) {
        waitAssertView(viewInteraction, ViewAssertions.matches(isDisplayed()), block)
    }

    fun waitViewGone(viewInteraction: ViewInteraction?, block: (() -> Unit)? = null) {
        waitAssertView(viewInteraction, ViewAssertions.matches(not(isDisplayed())), block)
    }

    fun waitAssertView(viewInteraction: ViewInteraction?, assertion: ViewAssertion?, block: (() -> Unit)? = null) {
            if (viewInteraction == null || assertion == null) throw NullPointerException()
            val startedTime: Long = System.currentTimeMillis()
            var elapsedTime: Long = 0
            var isVisible = false
            do {
                isVisible = runCatching {
                    viewInteraction.check(assertion)
                }.isSuccess
                if (isVisible) break
                Thread.sleep(sleepTime)
                elapsedTime = System.currentTimeMillis() - startedTime
            } while (elapsedTime <= maximumWaitedTime)
            if (!isVisible) throw TimeoutException("Waited time exceed the maximum waited time")

            block?.invoke()
        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set EditText above listview with swiperefreshlayout I'm trying to put EditText above listview but I don't understand why listiview is overlapping over edit text. Here is the layout source:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp"
   >

    <RelativeLayout
        android:id="@+id/firstlayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textEnter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="hello" />

        <EditText
            android:id="@+id/editTextInput"
            android:layout_below="@+id/textEnter"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </RelativeLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/sw_refresh"
        android:layout_width="match_parent"
        android:layout_height="fill_parent">

    <!--layout which should be refreshed should come here-->
    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:listSelector="@drawable/list_selector"
        android:background="@drawable/customshape"
        android:fadeScrollbars="false"
        >
        </ListView>

    </android.support.v4.widget.SwipeRefreshLayout>

</RelativeLayout>

I had tried everything that was on my mind and in Android Studio designer there is error like Layout fidelity warning

A: Add just this line android:layout_below="@+id/firstlayout"
<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/sw_refresh"
    android:layout_width="match_parent"
    android:layout_below="@+id/firstlayout"
    android:layout_height="fill_parent">

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:listSelector="@drawable/list_selector"
    android:background="@drawable/customshape"
    android:fadeScrollbars="false" >
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>


text:
Q: is $dx$ (at least in integrals) a positive real number? Given the Riemann integral: $\int_a^b f(x)dx$
By definition: $dx = lim \frac{b-a}n$ as $n\rightarrow+\infty$. So, is it $dx$ a real number and a positive one as it seems apparent by defintion?
There seems to be a lot of confusion in literature about what $dx$ really is and none agrees that $dx$ is just a positive real number, but I really don't know why!

A: You can think of the $dx$ symbol as just part of the integral notation. The notation makes it looks like a number, because it takes the place of the actual small positive number $\Delta x$ that appears in each of the finite Riemann sums. But these $\Delta x$ values approach 0 in the limit, so there's no actual positive number that the $dx$ represents.


text:
Q: Reputation and badge counts are harder to read on the new top bar I'm finding it harder to read the reputation and badge counts on the new black top bar. The bold white text on the black background seems almost blurry. Also, I don't know if it is the 1px size difference or the new colors, but the badge counts are also slightly harder to read.

If you compare the design to the old top bar, the old reputation count is not bold, and it is much clearer. Also, the font size is 13px instead of 12px, and that one pixel does make a difference. The white colored text also stands out more than the silver or bronze colored text. (Sorry, I don't have a gold badge on Meta Stack Exchange yet, so my screenshot doesn't include any gold text :))

The new Stack Overflow top bar uses the same bold, colored and smaller text as the new black bar, but these changes don't seem as bad when on a white background. The bold black text and colored badge numbers are still clear on the white bar.


text:
Q: How to recover storage from "Videos" pseudo app? With the goal of recovering storage space, I attempted to delete the Apple TV App. This app was still taking up 490MB of "Documents and Data" storage after I deleted all videos I could manually delete (the TV app libray screen said "You don't have any videos.") However, deleting the TV app only changed it to "Videos" which still takes up 490MB of "Documents and Data" storage.
There is no option to delete this "Videos" pseudo app. As far as I can tell, there is no actual "Videos" app I can start from the home/search screens.
I also tried to locate the media file(s) taking up storage via iTunes. There was one file under "Movies." There was no option to delete this file from iTunes. I think I uploaded the file to my iPhone via CopyTrans Manager. So I tried deleting the file via CopyTrans.
Now the file does not show up in iTunes or CopyTrans, but the "Videos" app still consumes 490MB of storage. How do I recover the 490MB of storage taken up by the "Videos" app?
I have a feeling this file was orphaned somehow because it was uploaded a long time ago on different versions of iOS/iTunes/copyTrans before the Videos app became the TV app.
I read syncing may result in files that cannot be deleted. Since I manually manage the media on my iPhone, all sync settings have been set to disabled.

update: Now I have the same problem for the Music app: no files in library, but "documents and data" takes up 318MB of storage after I tried toggling the Movie sync on/off. Even though I only enabled syncing for movies there was a warning that the music would also be deleted since the library was empty. The music was deleted, but the storage was not...

A: So a system restore (I actually upgraded to iOS 13) fixed the problem. I had been trying to reduce the size of the backup before upgrading, but perhaps it would not have affected the backup size.
This article gives background info on why there might be "zombie" storage usage even after deleting the files: How to Delete Documents & Data on iPhone or iPad. (TDLR: "caches, app data, preferences, login details, and assorted other app-specific information")


text:
Q: looping nested lists in R I have a huge nested list of 15 levels. i need to replace empty lists occurring at any level with chr "". I tried lapply to loop through the list but it's not working. is there any easy way to do this?
nested_list<-list(a=list(x=list(),y=list(i=list(),j=list(p=list(),q=list()))),b=list())

lapply(nested_list,function(x) if(length(x)==0) "" else x)

the lapply is being applied to only first level, how do i recursively loop the entire nested list and perform this action?

A: Try the following recursion.
foo <- function(l){
    lapply(l, function(x) if(length(x)==0) "" else foo(x))
}
foo(nested_list)

EDIT: A better version
foo <- function(l){
    lapply(l, function(x) if(is.list(x) && length(x)==0) "" else if(is.list(x)) foo(x) else x)
}


text:
Q: Rails - storing search query/result I have a search page which finds candidates.
From this page you can click view to find more information about the candidate.
When on the candidate view you can click edit or do a number of other actions which would return you too the candidates view.
My problem is from the candidates view I need to add a button to go back to the search results.
I originally thought of using a JS button with history -1 but because the user can do other action from inside the view this won't work.
I am still quite new to rails so not sure of my options... I am thinking some sort of caching of the results and then maybe a hidden field to keep track of the location of the cache(don't think this is the best solution as keeping track of the hidden value could get abit messy!)
Thanks, Alex

A: You can include the parameters for the query on the subpage. Eg.: /foo/search?q=stuff displays search result. Each result then has a link like /foo/:id?q=stuff. And on the subpage, you will have the parameter available to link back to the main page.
This solution doesn't use any server side state, which is generally accepted as the better way to build web applications. Not only does it mean that you browser will behave as expected, with respect to bookmarks, multiple tabs etc., but it also ensures that proper caching can be employed. Further, it lowers the complexity of your application, making it easier to debug and extend.

A: You have a couple of options:
Cache the results, as you've suggested. The potential downsides to this are that it takes memory, and if new valid records get added, you won't see them. You could store the cache in Session, or in the database (though in the latter case, you don't gain much).
I'd suggest just remembering the last search term, either in session or using hidden fields. You end up re-running the query when you go to the search results page, but in a properly indexed DB, that shouldn't be a big deal.
Good luck!

A: I would probably use a session variable to store this information.
First, make sure your form that posts to the search page is a GET operation, this way the search details are in your query string.  Then in your search action, you can grab the request URL and store it in the session:
session[:search_results] = request.url

Now in your view for the results, you can do your "Back to search results" like this:
link_to "Back to search results", session[:search_results]

A: You could put the search results in a "search_results" table keyed by the user id.  Then when the user hits the page, always load from a query on that table.

A: If anybody does come across this page and you need a button that goes back to the previous page and still display those search results (just like the google chrome button), just use :back.....
<%= link_to(image_tag("back.svg"), :back, :class => 'back_btn') %>


text:
Q: Creating new instance of mongoose model in node - adding first item to one of the embedded arrays Here is my current code :
Assume I have the following mongoose model :
// This is the car model.

var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var Schema = mongoose.Schema;

//  Setup a mongoose model, and pass it to module.exports.

module.exports = mongoose.model('Car', new Schema({
    manufacturer: String,
    model: String,
    owners: [{type: ObjectId, ref: 'Owner'}]
}));

And I want to use it in my REST api as follows - In this code I am essentially trying to create an instance of the car object, and then have the current owner id which is passed in, be the first item in the array for the "list of owners"
app.post('/cars/create', function(req,res){

    if( req.body.manufacturer && req.body.model && req.body.ownerId)
    {
        newCar = new Car(
            manufacturer: req.body.manufacturer,
            model: req.body.model,
            owners: // NOT SURE WHAT TO DO HERE
        });
    }
});

A: owners : new Array(ObjectId.createFromHexString(req.body.ownerId))

Be careful not to rewrite it later on, just push. From there, it's business as usual... Feel free to populate, manipulate and save.
ObjectId can be obtained from Schema.types.ObjectId, IIRC. If you're using some older version of Mongo, you can also use fromHexString().


text:
Q: Fast way to get different lines from 2 big files in Java In Java, I have a method that reads two files, with each line being a GUID. The lines are unordered. The output is two new files with the lines that appear only on each file.
Example files:
| Input_1 | Input_2 |         | Output_1 | Output_2 |
| ------- | ------- |         | -------- | -------- |
| abcdef  | uvwxyz  |    >    | mnopqr   | uvwxyz   |
| ghijkl  | ghijkl  |
| mnopqr  | abcdef  |

I managed to do it fine with one Collection<String> for each file and some addAll() + removeAll() shenanigans, however the files are growing in size and this whole thing is taking some time now. Each file has about 600k lines.
Is there a fast way to improve this code just using another type of collection or I need to refactor my way of doing?
Code in question:
//Read two files
Collection<String> guidFile1 = readFileGuid(pathFile1);
Collection<String> guidFile2 = readFileGuid(pathFile2);

//Add file1 and remove file2
Collection<String> leftFromFile1 = new ArrayList<String>();
leftFromFile1.addAll(guidFile1);
leftFromFile1.removeAll(guidFile2);

//Add file2 and remove file1
Collection<String> leftFromFile2 = new ArrayList<String>();
leftFromFile2.addAll(guidFile2);
leftFromFile2.removeAll(guidFile1);

//Outputs
System.out.println("Leftover from file1: " + leftFromFile1.size());
System.out.println("Leftover from file2: " + leftFromFile2.size());

A: In your code, the removeAll is the most expensive operation.  If both files are 100 lines long, then removeAll would perform 20,000x operations.  If you include addAll, then it would perform a total of 20,200 operations.  What you want is 200 operations.  The way to do that is to use a Set.
  static HashSet<String> readFileGuid(String path) throws IOException{
      HashSet<String> guidFile = new HashSet<>();
      Scanner s = new Scanner(new File(path));
      while(s.hasNextLine())
        guidFile.add(s.nextLine());
      s.close();
      return guidFile;
  }

  static List<String> subtract(HashSet<String> s1, HashSet<String> s2){
      List<String> result = new ArrayList<>();
      Iterator<String> it = s1.iterator();
      while(it.hasNext()){
          String item = it.next();
          if (!s2.contains(item))
            result.add(item);
      }
      return result;
  }

  public static void main (String[]args) throws IOException{
      HashSet<String> guidFile1 = readFileGuid("input1.txt");
      HashSet<String> guidFile2 = readFileGuid("input2.txt");

      List<String> leftFromFile1 = subtract(guidFile1, guidFile2);
      List<String> leftFromFile2 = subtract(guidFile2, guidFile1);

      System.out.println("file1:" + leftFromFile1);
      System.out.println("file2:" + leftFromFile2);
  }


text:
Q: how to print array element from back side in increment loop let suppose I have an array var a = [1,2,3,4] and now I want to print this array from the back side like 4,3,2,1
I know this can we achieve by this
for(let i=a.length; i>= 0; i--) {
  console.log(a[i])
  // output is
  // 4
  // 3
  // 2
  // 1
}

but I want to print the output like 4,3,2,1 with the help of increment loop
for(let i=0; i < a.length; i++){
  console.log(a[i])
      // output should be
      // 4
      // 3
      // 2
      // 1
}

A: You need just take the length and subtract the actual loop value an one for zero based approach.

var a = [1, 2, 3, 4];

for (let i = 0; i < a.length; i++) {
    console.log(a[a.length - 1 - i]);
}

A: Another option is reversing the array prior.
a = a.reverse();
for(let i=0; i < a.length; i++){
  console.log(a[i])
  // output should be
  // 4
  // 3
  // 2
  // 1
}

A: Just while we are solving problems in the most backwards ways...

var arry = [1,2,3,4],
i = 1;
while (i <= arry.length) { console.log(arry[arry.length - i++]) }

A: I see some complicated answers around here.  Why not looping in reverse order?

var a = [1, 2, 3, 4];

for (let i = a.length - 1; i >= 0; i--) {
    console.log(a[i]);
}


text: Q: Android studio unistallation I was working with android studio 2.3.3. After an update I started getting gradle errors. I wanted to uninstall android studio completely. However android studio was not there in control panel programs. Is it already uninstalled or is there any other procedure?


text:
Q: WPF-MVVM: Handeling Event from within DataGrid Style I develop Prism+MEF application based on WPF+MVVM, where there are many DataGrids so i build DataGridStyle to be applied for all DataGrids in all modules. The style add Filter Text Box in the Columns Headers, and i used MVVM Light EventToCommand to trigger TextChanged event when the Text Box text is changed like this: (this code exist in DataGridStyle Resource Dictionary)
    <TextBox x:Name="filterTextBox"
         HorizontalAlignment="Right" MinWidth="25" Height="Auto"
         OpacityMask="Black" Visibility="Collapsed"
         Text=""
         TextWrapping="Wrap" Grid.Column="0" Grid.ColumnSpan="1">

            <i:Interaction.Triggers>
                <i:EventTrigger EventName="TextChanged">
                    <cmd:EventToCommand Command="{Binding DataContext.TextChangedCommand}"
                          PassEventArgsToCommand="True"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
   </TextBox>

Then i handled the TextChangedCommand in ViewModel (pertaining to View that contains the Data Grid)using Attached property:
#region TextChangedCommand----------------------------------------------------------------------------------------------

        static ICommand command; //1

        public static ICommand GetTextChangedCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(TextChangedCommandProperty);
        }

        public static void SetTextChangedCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(TextChangedCommandProperty, value);
        }

        // Using a DependencyProperty as the backing store for TextChangedCommand.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextChangedCommandProperty =
            DependencyProperty.RegisterAttached("TextChangedCommand",
                                                 typeof(ICommand),
                                                 typeof(SubsystemAllViewModel),
                                                 new UIPropertyMetadata(null, CommandChanged));

        static void CommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            var fe = obj as FrameworkElement;
            command = e.NewValue as ICommand;
            fe.AddHandler(TextBox.TextChangedEvent, new TextChangedEventHandler(ExecuteCommand));
        }

        static void ExecuteCommand(object sender, TextChangedEventArgs e)
        {
            //Some  Code
        }

        #endregion

And the View that contains the Grid:
 <DataGrid  ItemsSource="{Binding Subsystems,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                   SelectedItem="{Binding Path=SelectedSubsystem, Mode=TwoWay}"
                   Name="SubsystemAllDataGrid"
                   Style="{StaticResource DataGridStyle}"
                   Grid.Row="2">

            <DataGrid.Columns>
                <DataGridTextColumn Header="Serial" Binding="{Binding Path=Serial, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="Type" Binding="{Binding Path=Type, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="System" Binding="{Binding Path=System, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="SubsystemNo"  Binding="{Binding Path=SubsystemNo, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="Description" Binding="{Binding Path=Description, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="Scope" Binding="{Binding Path=Scope, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="Area" Binding="{Binding Path=Area, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="Priority" Binding="{Binding Path=Priority, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="DossierLocation" Binding="{Binding Path=DossierLocation, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="Parts" Binding="{Binding Path=Parts, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="Status" Binding="{Binding Path=Status, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="StatusDate" Binding="{Binding Path=StatusDate, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="MCDate" Binding="{Binding Path=MCDate, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="PlnMCDate" Binding="{Binding Path=PlnMCDate, Mode=TwoWay}"></DataGridTextColumn>
                <DataGridTextColumn Header="Remark" Binding="{Binding Path=Remark, Mode=TwoWay}"></DataGridTextColumn>

            </DataGrid.Columns>

        </DataGrid>

The problems are:
When i enter filter text in the text box in one of the columns headers of the data grid nothing happen and break points at following points not hit:
1-GetTextChangedCommand and SetTextChangedCommand
2-The CommandChanged() method.
i'm new to wpf so i'm sure there are faults in WPF or C# code..., so please help me fixing these faults.
Note: i don't use code behind.
Thanks in advance

A: Looks like your Command-Binding doesnt work. Try the following:
Command="{Binding Path=TextChangedCommand}"

or
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}} Path=DataContext.TextChangedCommand}"

A: Breakpoints not hit makes me thing binding issue.
The datacontext for you command needs to be set to where your command is defined.  SO if your command is defined in your viewmodel, you need to use the following but set the ansestor type to the type of object that binds to your viewmodel.  This is usually your view, not the datagrid:
 Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ViewType}} Path=DataContext.TextChangedCommand}"

So if your view is a window or user control then change the ViewType to the respective type.
You can also see if there are any binding errors generated for your command in the output window when you run your app.
EDIT 1:
Don't use dependency property, use relay command from MVVM-Light in your view model:
 this.YourRelayCommand = new RelayCommand( ExecuteYourCommand, CanYourCommandExecute);

  public RelayCommand YourRelayCommand{ get; private set; }

  public bool CanYourCommandExecute() {

    }

  public void ExecuteYourCommand() {
    //TODO: Do code here
    }


text:
Q: Projection makes query slower

I have over 600k of record in MongoDb.
my user Schema looks like this:
{
    "_id" : ObjectId,
    "password" : String,
    "email" : String,
    "location" : Object,
    "followers" : Array,
    "following" : Array,
    "dateCreated" : Number,
    "loginCount" : Number,
    "settings" : Object,
    "roles" : Array,
    "enabled" : Boolean,
    "name" : Object
}

following query:
db.users.find(
     {},
     {
         name:1,
         settings:1,
         email:1,
         location:1
     }
).skip(656784).limit(10).explain()

results into this:
{
    "cursor" : "BasicCursor",
    "isMultiKey" : false,
    "n" : 10,
    "nscannedObjects" : 656794,
    "nscanned" : 656794,
    "nscannedObjectsAllPlans" : 656794,
    "nscannedAllPlans" : 656794,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 5131,
    "nChunkSkips" : 0,
    "millis" : 1106,
    "server" : "shreyance:27017",
    "filterSet" : false
}

and after removing projection same query db.users.find().skip(656784).limit(10).explain()
results into this:
{
    "cursor" : "BasicCursor",
    "isMultiKey" : false,
    "n" : 10,
    "nscannedObjects" : 656794,
    "nscanned" : 656794,
    "nscannedObjectsAllPlans" : 656794,
    "nscannedAllPlans" : 656794,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 5131,
    "nChunkSkips" : 0,
    "millis" : 209,
    "server" : "shreyance:27017",
    "filterSet" : false
}

As far I know projection always increase performance of a query. So I am unable to understand why MongoDB is behaving like this. Can someone explain this. And when to use projection and when not. And how actually projection is implemented in MongoDB.

A: You are correct that projection makes this skip query slower in MongoDB 2.6.3. This is related to an optimisation issue with the 2.6 query planner tracked as SERVER-13946.
The 2.6 query planner (as at 2.6.3) is adding SKIP (and LIMIT) stages after projection analysis, so the projection is being unnecessarily applied to results that get thrown out during the skip for this query. I tested a similar query in MongoDB 2.4.10 and the nScannedObjects was equal to the number of results returned by my limit rather than skip + limit.
There are several factors contributing to your query performance:
1) You haven't specified any query criteria ({}), so this query is doing a collection scan in natural order rather than using an index.
2) The query cannot be covered because there is no projection.
3) You have an extremely large skip value of 656,784.
There is definitely room for improvement on the query plan, but I wouldn't expect skip values of this magnitude to be reasonable in normal usage. For example, if this was an application query for pagination with 50 results per page your skip() value would be the equivalent of page number 13,135.

A: Unless the result of your projection does something to produce an "index only" query, and that means only the the fields "projected" in the result are all present in the index only, then you are always producing more work for the query engine.
You have to consider the process:

*

*How do I match? On document or index? Find appropriate primary or other index.

*Given the index, scan and find things.

*Now what do I have to return? Is all of the data in the index? If not go back to the collection and pull the documents.
That is the basic process. So unless one of those stages "optimizes" in any way then of course things "take longer".
You need to look at this as designing a "server engine" and understand the steps that need to be undertaken. Considering none of your conditions met anything that would produce "optimal" on the specified steps you need to learn to accept that.
Your "best" case, is wher only the projected fields are the fields present in the chosen index. But really, even that has the overhead of loading the index.
So choose wisely, and understand the constraints and memory requirements for what you are writing our query for. That is what "optimization" is all about.


text:
Q: Empty version in List item version history I have a custom list and Problem is even if I am not changing the data and click on save the new versions are adding in my version history with out any changes..
Is there  solution/code that it should update the version history only if the item(list row) is changed when we click on save button.

A: Per my test, I cannot reproduce your issue. However the default behavior is the same as your expectation.
When the data is not changed, the version history is the same, while I change the data, the version history updates as shown below.
I'm using OOTB list , just some custom settings in my list.

My version settings:


text:
Q: PHP get which file included/required current file
Possible Duplicate:
PHP - retrieve name of script that included or required it

Is there a way in PHP to get which file required/included the current file? For example:
controller.php
<?php
  include("add-person.php");
?>

add-person.php
<?php
  echo get_parent(); //should return controller.php
?>

Execution
php -f controller.php

Basically, something like the made-up function get_parent(). Thanks.

A: I know of a "not so clean" way. Try going through the array debug_backtrace() gives you. Among other things it contains a hierarchy how the code processed through include files. Manual here.


text:
Q: Can't find my codeigniter website in my aws windows server 2012 R2 iis8.5 I already tried calling a simple text document and simple and normal html/php website (no MVC) and there is no problem, but when i call the folder with the codeigniter website 111.111.111.111/CODEIGNITERSITE
IN application/config/config.php: $config['base_url'] = 'http://111.111.111.111/CODEIGNITERSITE'; , $config['index_page'] = 'Inicio.php'; , (error log)$config['log_threshold'] = 4;(all messages)
IN application/config/routes.php: $route['default_controller'] = 'Inicio.php'; , gives me (codeigniter i guess) error 404.
it should give me the right direction: 111.111.111.111/CODEIGNITERSITE/Inicio/login (everithing works fine like this in my local pc (win8, xammp))
i read in a forum, someone that fix it "-changing index.php to index.php? in the config.php" but nothing different happens
and ,, if i enter the right  111.111.111.111/CODEIGNITERSITE/Inicio/login in the browser gives me the server error 404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.
but if i enter the address including '/?' like this before the controller name 111.111.111.111/CODEIGNITERSITE/?/Inicio/login i can successfully go to the login page,,, but no further (i think because the rest gives me directions without the '?/' and gives the server error 404)
and add '/?' to the base_url neither works ,,,
the new thing i tried, was add a web.config doc and remove the index.php and i get a new error with the suggestion to enable the directory browsing (i did it)and just show me the folders i have
someone have any other idea?
thanks for your help

A: thanks @VairaMuthu , i could fix the problem without removing the index.php
and all thanks to the @MonkeyZeus idea just delete the .php from the $route['default_controller']=
that make sense since this $route  must be a reference to a controller,, -_-'
(additionally i cleaned all the crazy things i tried like :
+return the directory browsing to disabled
+remove the web.config doc and bring back again the index.php)
if you still have problems with this try the step by step configuration from this youtube video: Windows 2012 - PHP Installation on IIS ( 8.5 )
 link
thanks guys (y)!!!


text:
Q: Finding links in text and checking if there are any whitespaces in it I am trying to parse html fragment to find if there are any whitespaces inside 'href' or 'src' attributes of tags.
So far i managed to come up with this regular expression:
(src|href)(\s*=\s*)(["'])(.+(?=\s).+)\3

But it can go false positive if there is a whitespace after closing quote symbol, which makes it kinda useless.
How can it be modified ?
Example: https://regex101.com/r/JXp6pZ/1

A: you could try this pattern:
(?:src|href)=.[^'"]*\s[^'"]*['"]

*we use . for the first double/single quote because we don't care which it is, thereby making a slightly simpler pattern to read


text:
Q: Flask-Admin | How to fix route to the image I have a question according to image path in Flask.
I have a DB model Image, that contains all necessary info about image, including path - '/animals/sometype/image.jpg'.
I'm using Flask-admin module, and the problem is the wrong path to the image in editing mode.
Here's a code:
class ImageView(ModelView):
    edit_template = 'image_edit.html'

    def _list_thumbnail(view, context, model, name):
        if not model.path:
            return ''
        return Markup('' % url_for('static', filename=('images' + model.path)))

column_formatters = {
    'path': _list_thumbnail
}

form_extra_fields = {
    'path': form.ImageUploadField('Image', base_path='static/images', url_relative_path='images/')
}

For column formatters path is correct, but for the extra fields is wrong,  resulting in 404 error: http://127.0.0.1:5000/static//animals/birds/the_bird-wallpaper-1366x768.jpg
How can I solve this?
Also, I was thinking about passing an image to the custom edit template, but I don't understand, how to do it in Flask-Admin.

A: I've found a solution to pass an image to the edit view in Flask-admin without ImageUploadField. The solution is simple, all I need is to pass an image id from DB and use it in Jinja template.
class ImageView(ModelView):
edit_template = 'image_edit.html'

@expose('/edit/', methods=['GET', 'POST'])
def edit_view(self):
    id = request.args.get('id')
    self._template_args['image'] = db.session.query(Image.path).filter(Image.id == id).first()[0]
    return super(ImageView, self).edit_view()

And HTML template:
{% extends "admin/model/edit.html" %}
{% block body %}

  {{ super() }}
{% endblock %}


text:
Q: Spring Boot Integration Test failes due to lucene lock when using Hibernate Search In my Spring Boot 1.5.10.Final project I use Hibernate Search ORM 5.6.4.Final. It works fine except of the integration tests. There is one test class with several
test methods to test the search logic. If I run just this test class every things works fine. Spring Boot is starting and creates the index. If I run this test class
together with all other integration tests, every test class will throw an LockObtainFailedException and the Hibernate Search tests will fail.
org.apache.lucene.store.LockObtainFailedException: Lock held by this virtual machine: ...LieferantEntity\write.lock
    at org.apache.lucene.store.NativeFSLockFactory.obtainFSLock(NativeFSLockFactory.java:127) ~[lucene-core-5.5.5.jar:5.5.5 b3441673c21c83762035dc21d3827ad16aa17b68 - sarowe - 2017-10-20 08:57:09]
    at org.apache.lucene.store.FSLockFactory.obtainLock(FSLockFactory.java:41) ~[lucene-core-5.5.5.jar:5.5.5 b3441673c21c83762035dc21d3827ad16aa17b68 - sarowe - 2017-10-20 08:57:09]
    at org.apache.lucene.store.BaseDirectory.obtainLock(BaseDirectory.java:45) ~[lucene-core-5.5.5.jar:5.5.5 b3441673c21c83762035dc21d3827ad16aa17b68 - sarowe - 2017-10-20 08:57:09]
    at org.apache.lucene.index.IndexWriter.<init>(IndexWriter.java:776) ~[lucene-core-5.5.5.jar:5.5.5 b3441673c21c83762035dc21d3827ad16aa17b68 - sarowe - 2017-10-20 08:57:09]
    at org.hibernate.search.backend.impl.lucene.IndexWriterHolder.createNewIndexWriter(IndexWriterHolder.java:126) ~[hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.search.backend.impl.lucene.IndexWriterHolder.getIndexWriter(IndexWriterHolder.java:92) ~[hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.search.backend.impl.lucene.AbstractWorkspaceImpl.getIndexWriter(AbstractWorkspaceImpl.java:117) ~[hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.search.backend.impl.lucene.AbstractWorkspaceImpl.getIndexWriterDelegate(AbstractWorkspaceImpl.java:203) ~[hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.search.backend.impl.lucene.LuceneBackendQueueTask.applyUpdates(LuceneBackendQueueTask.java:81) [hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.search.backend.impl.lucene.LuceneBackendQueueTask.run(LuceneBackendQueueTask.java:46) [hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.search.backend.impl.lucene.SyncWorkProcessor$Consumer.applyChangesets(SyncWorkProcessor.java:165) [hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.search.backend.impl.lucene.SyncWorkProcessor$Consumer.run(SyncWorkProcessor.java:151) [hibernate-search-engine-5.6.4.Final.jar:5.6.4.Final]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]

I use the default settings. If I set exclusive_index_use to false, then it works without failure but then the test execution is very slow.
For me it seems the index is initialized during the startup of Spring Boot and interferes between the tests.
Is it possible to use Spring Boot integration tests with Hibernate Search in a way so that locks are cleanly released between tests?
Alternativly I'm looking for a way to disable the Hibernate Search indexing for all integration tests not making use of Hibernate Search
I also tried already the property near-real-time and different lock factories as native, simple and single without luck.

A: First: do not use exclusive_index_use unless you are a Lucene guru. It is dangerous and probably will not behave as you want.
Now that we got that out of the way... As far as I understand, you are trying to execute integration tests in parallel on the same machine. This means integration tests will probably compete for access to the exact same index, and will write to the same index. This could lead to unpredictable results if your tests perform conflicting writes (one test erasing a document added by another test, before that test has completed).
If you really need to perform tests in parallel, I would recommend to execute each test in an isolated environment:

*

*Dedicated DB, or at least dedicated DB schema

*Dedicated Lucene index

*etc.

In the case of Hibernate Search, you will have to find a way to use a different physical index in each test execution.
There are two ways to do that:

*

*Just for tests, do not store the indexes on the filesystem, but directly in the heap, by setting hibernate.search.backend.directory.type to local-heap (Hibernate Search 6+) or hibernate.search.default.directory_provider to local-heap (Hibernate Search 5 and below).

It's super easy to implement, but there are a few disadvantages you should be aware of:

*

*your testing environment will not be exactly the same as your production environment anymore

*indexes will be lost after the tests have finished executing, which may make post-mortem debugging challenging (you won't be able to use Luke to inspect the state of the indexes anymore)

*if your integration tests store a lot of content in the index, you might get an OutOfMemoryError.

*If the disadvantages of solution 1 are too much for you, you can continue using the filesystem to store the indexes, but use a different configuration for each test execution, setting the index base path (hibernate.search.backend.directory.root for Hibernate Search 6+, or hibernate.search.default.indexBase for Hibernate Search 5 and below) to some unique path for each test execution. You will have to find how to do that in Spring, but I would be suprised to learn it's not possible. Maybe Spring allows you to use interpolation in the properties, something like hibernate.search.backend.directory.root = /tmp/it/#{testName}?

See the documentation about directory configuration (here for Hibernate Search 6+, or here for Hibernate Search 5 for more information on how to configure index storage.


text:
Q: pyinstaller stops in the middle of process I try to create a .exe from a .py script. I use Pyinstaller. The script runs fine with no errors in Pycharm. If I open the .exe my Tkinter opens I can choose the files etc.. And then in the middle of the process it stops at this line:
WARNING: org.esa.s2tbx.dataio.metadata.GenericXmlMetadata: Metadata: the path to element [granuleidentifier] does not exist.
This Warning makes usualy no problem.
Has anybody an idea? I am frustrated with that. I can't find the error.
I worked with the libraries:
import snappy
from snappy import ProductIO
from snappy import GPF
from snappy import jpy
from snappy import HashMap
from Tkinter import *
from tkFileDialog import askopenfilename, asksaveasfile
import numpy
import numpy.ma
from osgeo import gdal, ogr, osr

I can produce a exe from a predecessor project with the libraries and the package cx_freeze in the Osgeo4w shell:
from snappy import ProductIO
from snappy import GPF
from snappy import jpy
from snappy import HashMap
from Tkinter import *
from tkFileDialog import askopenfilename, asksaveasfile

The code was written in pycharm environment wit the python-qgis-ltr-dev.bat as python interpreter located in the bin folder of Osgeo4w.
With all libraries i get an error message that the sqlite3.dll file is missing in the Python27 Dlls folder. I placed the missing file into the desired folder and cx_freeze crates an exe which is not opening
If i work with pyinstaller i get an warning that the jvm.dll file can#t be conected- Pyinstaller creates a exe which is opening my GUI i can import all the files the process is starting but then crashing in.
I tried bbfreeze with the same result of missing dll's.
Py2exe created a exe which performs similar to the pyinstaller version. I had two insert two dll's to the python27 dlls folder.
My thoughts are that numpy is not compatible because i get for all trials an message that numpy is not imported.
Is it possible to insert a package in the setup file?


text:
Q: Pickuping the Common 1d sequence in 1d array's? How to pick the best uniformed 1d array from the 2d arrays ?
I have two 2d array of : 11 x 10
Example :
  4 8 12 12 12 14 16 18 4 1 0
  5 7 11 12 13 11 15 18 3 2 1
  8 3 12 14 18 19 20 21 8 5 4 ,
  8 2 11 12 17 17 19 20 7 4 3 ,
  4 7 11 11 11 15 17 19 5 1 1 ,
  3 8 11 13 11 15 14 17 4 1 0 ,
  4 7 12 13 13 14 16 19 3 1 1 ,
  5 9 11 12 13 15 17 19 5 0 1 ,
  9 7 25 22 24 18 23 17 3 3 3 ,
  4 8 13 13 13 15 17 17 5 2 0 ,

here we have 2d arrays of size 11x10 - Need to analysis and have to find out the common 1d array which has common like.
find the best closing number and its difference- and keep doing for all the corresponding columns in an array .
below  answer should be like - finding the corresponding very column and comparing with the next row column - if it has some difference below ( 5 ) take the both column of two rows are same and process for next column of the same row..process untill finding the 1 row where it has at least nearby matches of  5
4 8 11 12 13 13 15 18 4 1 0

A: why don't you do something like this
int[] count(int[][] array)
int result[11];

for(int x = o; x<= 11;x++)
{
int temp[10];
 for(int y = o; y<= 10;y++)
{
 temp[y] = array[y][x];
}
result[x] = getHighest(temp);
}
return result;
}

int getHighest(int[] array)
{
 int size = array.length;
 int[size][1] temp;

 for(int x; x<= size;x++)
{
 int z = array[x];
 temp[z][0]++;

}
int highest = -1;
for(int z; z<= size;z++)
{
 int z = array[x];
 int h = temp[z][0];
 if(h > highest)
 {
  highest = h;
 }
}
return highest;
}

Something like this, but my C++ has gotten a bit of rusty so sorry if there are any mistakes.


text:
Q: operator '-' cannot be applied to operands of type 'decimal' and 'Systems.Collections.Generic.IEnumerable I have this error that I am tying to solve.
Visual Studio 2010 gives the error as:
operator '-' cannot be applied to operands of type 'decimal' and 'Systems.Collections.Generic.IEnumerable<decimal>

My Code:
// Step 5: Retrieve MPR amount and deduct form Gross Tax Dictionary Per-Employee

                //Query database
                var taxtable = taxTableService.GetAllTaxTables();

                var mprAmount = (from tt in taxtable select tt.U_MPR_amount).Distinct();

                Dictionary<int, decimal> paye = new Dictionary<int, decimal>();

                grossTaxDictionary.ToList().ForEach(x =>
                {
                    var totalPAYE = x.Value - mprAmount;

                    paye.Add(x.Key, totalPAYE);

                });

In my database, the field U_MPR_amount is a decimal and so is x.Value.
Error shows up on the line x.Value - mprAmount;
What could be the problem? Any help appreciated.

A: According to your code, mprAmount is a list, you cannot subtract it from a single value.
If you are certain that the list contains just a single element then you can retrieve it using the Single method:
var totalPAYE = x.Value - mprAmount.Single();

Or, more likely:
var mprAmount = (from tt in taxtable select tt.U_MPR_amount).Single();

Notice that I've changed Distinct for Single. Using both makes no real sense.


text:
Q: sample code for change position of bitmap every milliseconds in android I want to create a bitmap in wallpaper service is fine,but i want to change  bitmap position every 5milliseconds [lease help me canvas.drawBitmap(bitmap, x, y, null);any one

A: Perhaps?
   while(true)
    {
    Thread.sleep(5);
    canvas.drawBitmap(bitmap, x, y, null);
    }

Not sure though.


text:
Q: python help me with this function I need a function that Asks the user for a Stock Symbol and Name pairing then adds it to the Names dictionary. but all I have so far is
def addname(x,y):
    dicname = {(x): (y)}
    return dicname;
stocksymbol = (input("what is the symbol of your stock"))
stockname = (input("what is the name of your stock"))
addname(stocksymbol, stockname)
dnames = {dicname}

thank you anyone who trys to help

A: This should work:
def addname(x,y):
    dicname = {(x): (y)}
    return dicname

stocksymbol = (raw_input("what is the symbol of your stock: "))
stockname = (raw_input("what is the name of your stock: "))
dnames = addname(stocksymbol, stockname)
print dnames

Output
what is the symbol of your stock: abc
what is the name of your stock: xyz
{'abc': 'xyz'}

A: Is this what you are after? Difficult to know from your question:
dictname = {}

def addname(x,y):
    global dictname
    dictname[x] = y

stocksymbol = input("what is the symbol of your stock: ")
stockname = input("what is the name of your stock: ")

addname(stocksymbol, stockname)

print(dictname)

Prints:
what is the symbol of your stock: some symbol
what is the name of your stock: some name
{'some symbol': 'some name'}


text:
Q: jqGrid setRowData fails I cannot update a cell from my grid row select handler.  The cell remains unchanged and the call to setRowData returns false.  What might cause this? I used code from another SO answer and read the online doco for jqGrid.
   var _handleRowSelectedInGrid = function( rowId ){
        var rowData = $('#attendantImagesTable').jqGrid( 'getRowData', rowId );
        // rowData looks good here!

        rowData.userLastName = 'HELLO';
        var success = $('#attendantImagesTable').jqGrid( 'setRowData', rowId, rowData );
        // success == false   why?
}

A: Based on your code snippet, it looks like the call to setRowData should have worked. You could try debugging using a non-minified version of jqGrid and step into the call to setRowData to see why it is failing.
Alternatively, if you are just setting data in a particular cell, it might be easier to use the setCell method.


text:
Q: wanted to drink vs was thirsty Can I use both examples or the second one is much better?

I wanted to drink and drank some water.

I was thirsty and drank some water.

If I change "water" to "beer", the first example will be much better to use, won't it?

A: Both sentences are grammatically correct and logically valid, whether you're talking about water or beer.
They don't mean exactly the same thing. You might want to drink without being thirsty. You might want to drink more water (or whatever fluid) for some health or medical reason. You might just have eaten some very spicy food and you want water to cool your mouth down. Especially if you're talking about something other than water, you might like the flavor of the drink. If you're talking about alcohol you might want to get the buzz. If you're talking about coffee you might want the caffeine hit. Etc.
In general I'd suppose that if someone says he is thirsty that that means he wants to drink, but not necessarily. He might be thirsty but decide he should not drink anything for some reason.

A: Both statements are very similar and grammatically valid, as @Jay described.  There are a couple additional differences though:
"I wanted to drink" sounds a little awkward. In most cases where either phrasing could apply, most native speakers will say "I was thirsty."
"I wanted to drink" also sounds very close to "I want a drink" which commonly implies a drink of alcohol specifically. The strength of that association can be changed by tone of voice and other context.


text:
Q: Problems with Doctrine 2 CRUD generator and identifier which isn't called "id" Here is the situation:
I'm kind of new to Symfony2 and liking all about it, but I'm having an issue with Doctrine's CRUD generator. I've generated entities with Doctrine starting from YAML files but can't generate their CRUD with the doctrine:generate:crud command line.
The problem:
For some reason I need to set an 'id' field and a getId() method, but it kind of ruins all the work I've done on class diagrams and relation schema…
My question is:
Is there a way to keep my field names as they are and get Doctrine to still generate my CRUDs?
A YAML example:
XXX\XXXBundle\Entity\Utilisateur:
 type: entity
 table: utilisateur
 id:
  pseudo:
   type: string
 fields:
  nom:
   type: string

I'm stuck with this… I've tried to change it for:
XXX\XXXBundle\Entity\Utilisateur:
 type: entity
 table: utilisateur
 fields:
  pseudo: # Le pseudo correspond au nom affiché pour identifier un utilisateur.
   type: string
   id: true

But it doesn't change any thing I always end up having this:
[RuntimeException]
The CRUD generator expects the entity object has a primary key field named "id" with a getId() method.

I'd be really grateful if anyone could help out a bit! Worst case scenario I'll have to modify all my entities to add a stupid ID field with an auto-generated integer…

A: No, it is not possible.
There is already a change request:
https://github.com/sensio/SensioGeneratorBundle/issues/57
It is hardcoded in DoctrineCrudGenerator.php on line 69 - 71:
if (!in_array('id', $metadata->identifier)) {
    throw new \RuntimeException('The CRUD generator expects the entity object has a primary key field named "id" with a getId() method.');
}


text:
Q: Application Request Routing server requirements I'm exploring the possibility of implementing ARR for a basic webfarm.  For the foreseeable future there will be at most 500-1000 users during peak usage.  The site is for OLTP -- no content streaming.  Can anyone provide some guidance as to what sort of system specs are required for that type of moderate load?  Or perhaps any benchmark results that you're aware of?
I've had trouble finding any data on CPU / memory usage for a dedicated ARR server.  Given limited resources,  I want to avoid spending on an unnecessarily powerful server so that I can sufficiently fund the web servers in the farm.

A: I've never seen sizing recommendations from Microsoft for ARR.
That being said, if you're not using caching in the ARR layer then the specs are minimal. Without caching, the ARR service isn't doing much. A single low-end server will probably handle your user load. Make sure that whatever NIC is in the server is known to work well with Receive Side Scaling. Also, if I had a choice between two small servers running NLB and ARR vs. one larger server, I would go for the two smaller servers for redundancy.
If you are using caching, I would recommend a single processor with lots of core and lots of fast RAM. If you get multiple processors then you will have to deal with NUMA affinity, which I don't think ARR's cache mechanism understands.


text:
Q: ALM Defects list failing with 'User defined type not defined' I wanted to extract list of defects using a filter criteria. I tried the VBA code from OTA here, but compile fails on the following declarations with User defined type not defined:
Dim BugFact As BugFactory
Dim BugFilter As TDFilter
Dim bugList As List
Dim theBug As Bug

Note: I do not have administrative privileges on ALM.
The full VBA code:
Sub BugFilter()

    Dim BugFact As BugFactory
    Dim BugFilter As TDFilter
    Dim bugList As List
    Dim theBug As Bug
    Dim i%, msg$

' Get the bug factory filter.
    'tdc is the global TDConnection object.
    Set BugFact = tdc.BugFactory
    Set BugFilter = BugFact.Filter

' Set the filter values.
    BugFilter.Filter("BG_STATUS") = "Closed"
    BugFilter.order("BG_PRIORITY") = 1
    MsgBox BugFilter.Text

'Create a list of defects from the filter
' and show a few of them.
    Set bugList = BugFilter.NewList
    msg = "Number of defects = " & bugList.Count & Chr(13)
    For Each theBug In bugList
       msg = msg & theBug.ID & ", " & theBug.Summary & ", " _
          & theBug.Status & ", " & theBug.Priority & Chr(13)
       i = i + 1
       If i > 10 Then Exit For
    Next
    MsgBox msg

End Sub

A: You need to add a reference to the OTA COM Type library (see here); otherwise your program will not know about the OTA types such as BugFactory and TDFilter.


text:
Q: Why was I blocked from chat for asking users to complete a survey for my computing GCSE homework? Why was I blocked from chat for asking users to complete a survey for my computing GCSE homework? I gave them a link to the survey, and they deleted it, so i reposted it and they marked me as spam, so i took it to another room, and now i cannot go on chat.

A: You were automatically suspended from chat because your link kept getting deleted. It was a 2-hour suspension. In the future, if they delete your link, it usually means they don't want it there, and posting it again is not a good way to solve the problem.


text:
Q: Flask-Mail not sending emails, no error is being reported All, I'm trying to setup flask-mail to send notifications to my email when a user registers.
I'm getting no error messages from the script used to send the email, but nothing is actually being sent, or at least, nothing is being received.
Is there a log file which can show if an email was sent, rejected, or maybe if there was even a problem logging onto the server? How does on track this problem?
Any ideas here?

A: tbicr has the most likely fix, check MAIL_SUPPRESS_SEND first.
What ended up burning me (being new to flask) is that when you instantiate your Mail() object, be sure it's after you've set your app.config values.  The Mail() object doesn't go back and look at these values after the fact, so they will default to bad values.  What's frustrating is that you won't see any errors when you try to send messages with the default/bad values.  At least not as of my posting.

A: I know this post is from a while ago, but I just ran into the same issue. Like @tbicr mentioned make sure that app.testing is set to False. As it states in the Flask-Maildocs here:
"If the setting TESTING is set to True, emails will be suppressed. Calling send() on your messages will not result in any messages being actually sent."
This was exactly my problem. I implemented Google reCAPTCHA into one of my forms and the app.testing was set to True so I did not have to hit the reCAPTCHA box every time. By removing the app.testing or by setting it to False, the emails were able to be sent.

A: Flask-Email use smtplib which can set debug level: https://github.com/mattupstate/flask-mail/blob/master/flask_mail.py#L139. You can set it with MAIL_DEBUG = True or DEBUG = True. Also check that MAIL_SUPPRESS_SEND = False and TESTING = False.
With debug I can see in stdout mail progress: success, fail, recipients and etc.
See details: http://pythonhosted.org/Flask-Mail/#configuring-flask-mail.


text:
Q: Is the ethernet port of my NAS defective? Can't negotiate gigabit speed This is my setup:
computer (gigabit) <--> router (gigabit) <--> NAS (gigabit)

The problem is, the NAS is not syncing at gigabit speed, but:
Speed: 100Mb/s
Duplex: Full

I tried switching the cable and the port on the router but nothing changed.
The full output of the ethtool on the NAS is:
Settings for eth0:
        Supported ports: [ TP MII ]
        Supported link modes:   10baseT/Half 10baseT/Full
                                100baseT/Half 100baseT/Full
                                1000baseT/Full
        Supported pause frame use: No
        Supports auto-negotiation: Yes
        Advertised link modes:  10baseT/Half 10baseT/Full
                                100baseT/Half 100baseT/Full
                                1000baseT/Half 1000baseT/Full
        Advertised pause frame use: No
        Advertised auto-negotiation: No
        Link partner advertised link modes:  10baseT/Half 10baseT/Full
                                             100baseT/Half 100baseT/Full
        Link partner advertised pause frame use: No
        Link partner advertised auto-negotiation: Yes
        Speed: 100Mb/s
        Duplex: Full
        Port: MII
        PHYAD: 1
        Transceiver: internal
        Auto-negotiation: on

I'm not sure I understand the part: Link partner advertised link modes, is that what the NAS thinks the router is advertising? Why would this happen? The router clearly support gigabit, every other device I connect to it successfully sync to gigabit.
I've tried forcing the NAS to sync at gigabit speed disabling auto-negotiation, but that resulted in the NAS unable to connect.
I've also tried to connect the NAS directly to the computer, but the computer doesn't even see anything on the ethernet port, like the cable wasn't plugged in at all. Only if I disable auto-negotiation (on the computer) and set the speed to anything up to 100 megabit full duplex (on the computer), the cable is seen as "connected" and the connection works, but if I try to set the speed to  gigabit OR I enable auto-negotiation, I get: "cable unplugged".
The NAS is a Synology DS214se, the router is a ASUS DSL-N55U_D1.
I'm not sure about the cables... I have five of them, one that came with the NAS (cat5e), one with the router, and other three. Tried them all with no success.
EDIT:
I've tried with a cat.7 cable, with no success...
The output for dmesg | grep eth0 is:
[...]
[ 5512.538960] :eth0: link up, full duplex, speed 1 Gbps
[ 5513.630155] :eth0: link down
[ 5516.560019] :eth0: link up, full duplex, speed 1 Gbps
[ 5517.659160] :eth0: link down
[ 5520.974534] :eth0: link up, full duplex, speed 1 Gbps
[ 5521.275674] :eth0: link down
[ 5523.379207] :eth0: link up, full duplex, speed 100 Mbps

It tries but eventually gives up, unless I force it to stick with 1 Gbps, in such case it tries forever. Synology support stays silent :(


text:
Q: How to authorization user in laravel? I have user table :
| id | username | password | role_id |
|:--:|:--------:|:--------:|:-------:|
| 1  |  user1   | password | 10      |
| 2  | user2    | password | 11      |

and the role table :
| id | name |
|:--:|:----:|
| 10 | admin|
| 11 | superadmin|

it is mean the user table should has relationship with role table.
I get confused how to make authorization with relation table, I have try to include this method in my user model, but is not working :
public function role()
{
    return $this->belongsTo(Role::class, 'role_id', 'id');
}

and this is my Gate in authserviceprovider :
public function boot()
{
    $this->registerPolicies();
    Gate::define('isSuperadmin', function ($admin) {
        return $admin->role == 'superadmin';
    });
}

A: When you go $admin->role it will return a model instance of the role, which is not a string, you should have
$admin->role->name === 'superadmin'
And a side note it makes more sense to me to call the admin var $user since it might be a regular user

A: Use spatie/laravel-permission package instead for roles/permissions management.


text:
Q: wrong number of arguments (given 0, expected 1) in rails when attempting to import .csv I'm trying to import a .csv to refill and complete many forms, rather than having to fill and create them one by one. I've followed a pretty nifty tutorial here:https://www.youtube.com/watch?v=W8pohTautj8 which has been really helpful. I then tweaked it for nested resources by this post here: https://gorails.com/forum/import-a-csv-with-associations
So far so good. I then made a few final tweaks to get where I was having issues with Authenticity tokens, NilClass errors and now I'm getting wrong number of arguments. All the stack overflow posts that also present this error that I've seen haven't been able to help.
Here's the code:
controller
def create
    @development = Development.find(params[:development_id])
    @lot = @development.lots.create(params.require[:lot].permit(:status, :lot_number ,:stage, :land_size, :price, :bed, :bath, :car, :rent))
    respond_to do |format|
      if @lot.save
        format.js
        format.html { redirect_to Development.find(params[:development_id]), notice: "Lot was successfully created." }
        format.json { render :show, status: :created, location: @lot }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @lot.errors, status: :unprocessable_entity }
      end
    end
  end

def import
    @development = Development.find(params[:development_id])
    @lot = @development.lots.create(params.require[:lot].permit(:status, :lot_number ,:stage, :land_size, :price, :bed, :bath, :car, :rent))
    Lot.import(@development, development_params[:lot])
    redirect_to development_path, notice: "Lots were successfully created."
  end

model
  def self.import(development, file)
    CSV.foreach(file.path, headers: true) do |row|
        development.lots.create! row.to_hash
    end
  end

_form partial
<%= form_tag import_development_lots_path, multipart: true, remote: true, authenticity_token: true do %>
                <%= file_field_tag :file %>
                <%= hidden_field_tag :authenticity_token, form_authenticity_token -%>
                <%= submit_tag "Upload csv" %>
                <% end %>

Note: This is additional to the regular, original form (both on the same _form partial) to create the object. It was my understanding that the original could stay as a means of creating data tables manually, one at a time, as another option to the mass csv import option. Please let me know if I need to add the code for the original form too. They seem to be fine to coexist on the same page together.
routes
resources :lots do
      collection { post :import }
      end

application.rb
require 'csv'

I believe that's everything related to the csv import; any help is greatly appreciated!
Edit:
Here's the error log as requested by Siim.
Started POST "/developments/2/lots" for ::1 at 2021-05-13 10:46:14 +1000
Processing by LotsController#create as HTML
  Parameters: {"authenticity_token"=>"s7EpVu4LymhZpm+nSxGF+yLXWY3GqHjwKSN0eccRCws7eTy1riGg9GplIciLIns7hlKYyRipA5tgMbGn0GTGow==", "file"=>"Test Lot.csv", "commit"=>"Upload Stocklist", "development_id"=>"2"}
  Development Load (1.3ms)  SELECT "developments".* FROM "developments" WHERE "developments"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  ↳ app/controllers/lots_controller.rb:71:in `get_development'
  CACHE Development Load (0.0ms)  SELECT "developments".* FROM "developments" WHERE "developments"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  ↳ app/controllers/lots_controller.rb:25:in `create'
Completed 500 Internal Server Error in 14ms (ActiveRecord: 1.3ms | Allocations: 1798)

ArgumentError (wrong number of arguments (given 0, expected 1)):

app/controllers/lots_controller.rb:26:in `create'

A: According to your error backtrace (from comments), the error is on the following line:
@lot = @development.lots.create(params.require[:lot].permit(:status, :lot_number ,:stage, :land_size, :price, :bed, :bath, :car, :rent))

If you would break that apart to multiple lines you would get an even more accurate error message to find it out yourself, but I can already see it.
require is a method that requires an argument. You are calling it without arguments and then accessing it as an array/hash by calling [] on it.
Use params.require(:lot) instead of params.require[:lot].


text:
Q: Unbinding USB Interface to use Chrome Web USB API How can I unbind an USB interface?
Found multiple pages like this one: Manual driver binding and unbinding or this one: How to unbind/bind a usb device as normal user?
Which suggest to use the following command:
sudo echo -n "1-1:1.0" > /sys/bus/usb/drivers/usb/unbind

This gives me the following response:

echo: write error: No such device

But the folder is available inside my file system:

lsusb gives me:
Bus 001 Device 047: ID 0483:1234 STMicroelectronics USB2CAN converter

and usb-devices:
T:  Bus=01 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#= 47 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=ff(vend.) Sub=ff Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=0483 ProdID=1234 Rev=01.00
S:  Manufacturer=8Devices
S:  Product=USB2CAN converter
S:  SerialNumber=5D2C531E
C:  #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=100mA
I:  If#=0x0 Alt= 0 #EPs= 4 Cls=ff(vend.) Sub=ff Prot=ff Driver=usb_8dev

Also if I try to use 'sudo echo -n "0-1:1.0" > /sys/bus/usb/drivers/usb/unbind' or 'sudo echo -n "1-0:1.0" > /sys/bus/usb/drivers/usb/unbind' it gives me:
echo: write error: No such device

What works is:
sudo echo -n "1-1" > /sys/bus/usb/drivers/usb/unbind

But if I try to connect like this via Chrome:
navigator.usb.requestDevice({ filters: [{}] })
.then(selectedDevice => {
   device = selectedDevice;
console.log(device);
   return device.open()
    .then(() => device.reset())
    .then(() => device.selectConfiguration(1))
    .then(() => device.claimInterface(device.configuration.interfaces[0].interfaceNumber))
 });

it still gives me:

DOMException: Unable to claim interface.

Also unlike this person How to claim interface using WebUSB? I can select the device.
tl;dr:
I would like to connect to an USB device with the WebUSB API but it's giving me

DOMException: Unable to claim interface.

A: So basically you have to do this for "8devices".
/sys/bus/usb/drivers/usb_8dev$ echo "1-1:1.0" > unbind

in long:
cd /sys/bus/usb/drivers/usb_8dev
echo "1-1:1.0" > unbind

You will find a file called something similar to "1-1:1.0" in /sys/bus/usb/drivers/usb_8dev so just do a ls to get the correct file and then exchange "1-1:1.0" for this value.
Also don't forget to set sudo chmod -R -v 777 ./ to the driver(ex. usb_8dev) folder.
Also recommended: Disconnect and reconnect ttyUSB0 programmatically in Linux


text:
Q: Materialize Modals Not Working I am building a simple blogging application in php and html, and when i generate my modals (using the javascript fetch() command) with database data, the modal trigger does not work. Here is the generation code:
Javascript:
function RetrieveArticles() {
  fetch('blog-php/inc/blogOverview/retrieveArticles.php').then(response => response.text()).then(data => {
    document.getElementById('container-articles').innerHTML = data;
  })
}

Php:
require('../../settings.php');

  try{
    /* Create a new PDO object */
    $connect = new PDO("mysql:host=$databaseHost;dbname=$databaseName",
    $databaseUser, $databasePassword);
    /* set the PDO error mode to exception */
    $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  } catch(PDOException $e){
    /* Redirect the user with errorcode 1: "Database settings are incorrect" */
    header('location: ../pages/error.php?errcode=1');
    exit();
  }

  $stmnt = $connect->prepare("SELECT * FROM blog_articles NATURAL JOIN article_text;");
  $stmnt->execute();
  $result = $stmnt->fetchAll(PDO::FETCH_ASSOC);
  if(count($result) > 0){
    foreach($result as $data){
      echo "
";
        echo "
";
          echo "";
            echo "
"."".$data['article_name'].""."
"."By ".$data['article_user'].", ".$data['article_made']."
";
          echo "";
        echo "
";
      echo "
";
      echo "
";
        echo "
";
          echo "
".$data['article_name']."
";
          echo "
".$data['article_text']."
";
        echo "
";
        echo "
";
          echo "

";
          echo "<button type='button' class='modal-close btn left indigo darken-3'>"."Close Article"."</button>";
        echo "
";
      echo "
";
    }
  }else{
    echo "
"."No Articles Found"."
";
  }

And this is how i gets displayed in the webbrowser:

Test Modal 1
By GuylianWasHier, 2018-06-01 20:21:39

Test Modal 1

This is a simple modal test

<button type="button" class="modal-close btn left indigo darken-3">Close Article</button>

12
By GuylianWasHier, 2018-06-01 20:26:42

12

12

<button type="button" class="modal-close btn left indigo darken-3">Close Article</button>

1234
By GuylianWasHier, 2018-06-01 20:26:46

1234

1243

<button type="button" class="modal-close btn left indigo darken-3">Close Article</button>

23
By GuylianWasHier, 2018-06-01 20:35:14

23

23

<button type="button" class="modal-close btn left indigo darken-3">Close Article</button>

Create New Article

The modals get initialized by a script that has the auto-init function from materialize in it (Which loads correctly into the webpage because a modal that has not been generated by php works fine).
Does anyone know how to fix this?.
If you want to have a better look at the code, here is the github repo: https://github.com/GuylianWasHier/Blog.php

A: You have to reinitialize modals after document.getElementById('container-articles').innerHTML = data;
Try this
function RetrieveArticles() {
 fetch('blog-php/inc/blogOverview/retrieveArticles.php').then(response => response.text()).then(data => {
  document.getElementById('container-articles').innerHTML = data;
  // you can destroy previous instances instance.destroy();
  var elems = document.querySelectorAll('.modal');
  var instances = M.Modal.init(elems, {});
 })
}


text:
Q: Splitting array into two arrays once an certain elements values equal 20 I am stuck with an issue that I cannot work out how to approach. i'm hoping someone can help me solve this.
I have an array which could change depending on items in a shopping cart:
Array
(
    [0] => Array
        (
            [product_id] => 17134
            [quantity] => 7
            [text] => 1.5
            [category_id] => 46
        )

    [1] => Array
        (
            [product_id] => 1001
            [quantity] => 1
            [text] => 1.5
            [category_id] => 46
        )

    [2] => Array
        (
            [product_id] => 18468
            [quantity] => 1
            [text] => 2
            [category_id] => 40
        )

    [3] => Array
        (
            [product_id] => 156
            [quantity] => 1
            [text] => 1
            [category_id] => 40
        )

    [4] => Array
        (
            [product_id] => 17557
            [quantity] => 1
            [text] => 5
            [category_id] => 43
        )

    [5] => Array
        (
            [product_id] => 11865
            [quantity] => 1
            [text] => 7.5
            [category_id] => 49
        )

    [6] => Array
        (
            [product_id] => 15322
            [quantity] => 1
            [text] => 1
            [category_id] => 42
        )

    [7] => Array
        (
            [product_id] => 16239
            [quantity] => 1
            [text] => 3
            [category_id] => 42
        )

)

I want to split the array into two arrays by looping over array's text, but at the same time multiplying the text by its corresponding quantity until the text would equal 20. Once it equals 20, I want to split the array up, so for example the result would look something like:
Old array:
Array
(
    [0] => Array
        (
            [product_id] => 17134
            [quantity] => 7
            [text] => 1.5
            [category_id] => 46
        )

    [1] => Array
        (
            [product_id] => 1001
            [quantity] => 1
            [text] => 1.5
            [category_id] => 46
        )

    [2] => Array
        (
            [product_id] => 18468
            [quantity] => 1
            [text] => 2
            [category_id] => 40
        )

    [3] => Array
        (
            [product_id] => 156
            [quantity] => 1
            [text] => 1
            [category_id] => 40
        )

    [4] => Array
        (
            [product_id] => 17557
            [quantity] => 1
            [text] => 5
            [category_id] => 43
        )

    )

New array:
Array
(
    [0] => Array
        (
            [product_id] => 11865
            [quantity] => 1
            [text] => 7.5
            [category_id] => 49
        )

    [1] => Array
        (
            [product_id] => 15322
            [quantity] => 1
            [text] => 1
            [category_id] => 42
        )

    [2] => Array
        (
            [product_id] => 16239
            [quantity] => 1
            [text] => 3
            [category_id] => 42
        )

)

Is this achievable?
Thank you for your time.

A: Check this:
    $i=0;
    $y=0;
    $countValue = 0;
    $newCartsArray = [];

    // $cart is your array
    foreach($cart as $index => $product):
            $countValue += $product['quantity'] * $product['text'];
            if($countValue >= 20){ // if you are sure it will always exactly reach 20 use == instead >=
                    $newCartsArray[$y] = array_slice($cart, $index-$i, $i+1);
                    $i=0;
                    $y++;
                    $countValue = 0;
            }
            $i++;
    endforeach;

    // This will add the last elements into $newCartsArray
    if($i!=1){
            $newCartsArray[$y] = array_slice($cart, count($cart)-($i-1), $i-1);
    }

Let me know if it works for you!


text:
Q: why python multiprocessing initialize same values? Here is an example
import multiprocessing
import numpy as np

def inner_function(idx, return_dic, N):
    c = np.random.choice(N)
    return_dic[idx] = c

if __name__ == '__main__':
    manager = multiprocessing.Manager()
    return_dic = manager.dict()
    jobs = []

    for index in range(10):
        p = multiprocessing.Process(
            target=inner_function, args=(index,return_dic, 10)
        )
        jobs.append(p)
        p.start()

    for proc in jobs:
        proc.join()

    print(return_dic)

the outcome would be the same (e.g., {0: 4, 1: 4, 2: 4, 3: 4, 4: 4, 5: 4, 6: 4, 7: 4, 8: 4, 9: 4}). How to generate random number with multiprocessor?
Edited: Problem solved. It seems numpy would treat multiprocessors identically if we want to generate random values. So we would get identical values even we call random functions. We need to manually set the random seed for each processor.


text:
Q: Using an array of indices for `values_at` method's selectors I'm looking to return elements of an array with the indices in another array. For example:
array = ["h", "y", "R", "X", "y", "u", "w", "o", "q"]
indices_array = [1, 3, 7, 8]

Normally I would use:
array.values_at(1, 3, 7, 8)

I need to do something more like this (because my indices_array is quite long)
array.value_at(indices_array) # => ["y", "X", "o", "q"]

A: You can use the splat operator:
array.values_at(*indices_array)

Example output:
array = ["h", "y", "R", "X", "y", "u", "w", "o", "q"]
indices_array = [1, 3, 7, 8]
array.values_at(*indices_array)
# => ["y", "X", "o", "q"]

A: thomthom already gave the right suggestion, but to define the method you wanted,
class Array
  def value_at(a)
    values_at(*a)
  end
end


text:
Q: PostgreSQL shutdown tracking PG shutdowns are taking time.
I am using the "smart" shutdown process by sending SIGINT signal to the PG process. So, it waits for the child processes to die gracefully before exiting. Can I somehow know what is the child process kill where it is stuck/taking time?
I cannot find a documentation on what steps are included in a "smart" shutdown. I am guessing we take checkpoints and wait for WAL writers and archivers to finish. I want to track how much time each of these is taking to finish its task and exit.

A: There are only two things that normally can take a long time during a smart shutdown: waiting until all client connections have disconnected on their own, and then the shutdown checkpoint.
To monitor the latter, set log_checkpoints = on. The former can take forever – you are at the mercy of the client application. For that reason, it is usually smarter to use the default "fast" shutdown mode that forcibly disconnects the clients.


text:
Q: useEffect как componentDidUpdate Есть ли возможность в функциональных компонентах React отслеживать момент только повторных изменений props. Те аналогично методу componentDidUpdate в классовых компонентах? Если вторым аргументом передавать список зависимостей props, то хук useEffect запустится также при первом рендеренге, а этого не хотелось бы. Делать проверку с использованием флага - также кажется не лучшим решением. Что посоветуете?
useEffect(() => {
       console.log('hook');
   }, [props.counter]);

A: Итак, начальное значение counter появляется в state родителя и приходит через props (или context) в дочерний. Оно так и продолжает это делать.
По ходу дела дочерний свой counter меняет, кладя себе в стейт.
Там, где counter используется, вызывается функция, дающая один из 2-х с приоритетом дочернего.

Альтернатива:
Можно использовать аргумент useState(initial), но это менее гибко.
Т. к. с первым вариантом можно, например, учитывать время/версии: дочерний поменял, но родитель позже решил, что он правее со своим новым значением.


text:
Q: is it a good practice to use K-Fold cross validation instead of training, validation and test set? i have a Dataset of 5000 samples for a regression problem, now with this number of samples can i and is it better to use K-Fold cross validation instead of the validation set as an alternative?
if not i've been splitting data as 70% 15% 15%, but it doesn't seem the distribution of splits are exactly the same, i mean depending on the split i would get very different predictions, for example in split i tune the model with validation set and get 0.75 $R^2$ for validation set and then get a $R^2$ if 0.88 for test set, and in another instance its the exact opposite.
if i do a few random splits and find a few splits that the model structure is not very different in each split, can i just use one of these splits? wouldn't that defeat the purpose of the randomness of splits? out of these splits i chose two random splits, now after training, tuning and all the other steps, for one of the splits i would get the following $R^2$ for train, dev and test set: 0.91, 0.92, 0.90 and for the other one i would get these:  0.93, 0.88, 0.85. can i use the first one that gave me the best result? is it valid? i mean depending on the split it seems my final test score would be totally different.

A: Your experience with split-dependent differences in your modeling and performance estimates is a reason why cross validation is often preferred in all but extremely large data sets. Repeated cross validation or bootstrapping might be even better.
With the separate training/validation/test approach, your estimate of the generalizability of your model's performance on new data comes from the test set, which is set aside until initial training and tuning are done on the training and validation sets. Say that you want to estimate the error in model predictions made on your test set. You are then trying to estimate a variance, which can require a surprisingly large number of cases to estimate precisely.
But if you set aside more cases for the test set so that you have a better measure of generalizability, you have fewer cases available for training and validation, which may limit your ability to generate a useful model in the first place.
The chapter on cross validation and related methods in The Elements of Statistical Learning (2nd edition, p. 222) puts it like this:

The methods in this chapter are designed for situations where there is insufficient data to split it into three parts. Again it is too difficult to give a general rule on how much training data is enough; among other things, this depends on the signal-to-noise ratio of the underlying function, and the complexity of the models being fit to the data.

So cross validation is a useful approach in cases where you don't have a "large enough" data set to accomplish your goals. Your question suggests that you might be in such a situation despite having 5000 cases.
In practice, a single run of cross validation can give imprecise results. Frank Harrell recommends repeated runs of cross validation or, better, bootstrapping to take advantage of all the data most efficiently in building and evaluating a model. See for example this answer, with a link to further reading in a comment. His rms package provides tools for building, validating, and calibrating models.

A: In addition to the accepted answer, which is right, I would like to point that you don't need to choose between k-fold cross validation and training, validation and test set, because you can have both with nested cross validation.
In short:

*

*You split your data in several test sets (just like in k-fold cross validation).

*After taking aside each test set, you optimize your model using k-fold cross validation with the remaining data.

*You test each optimized model against the each test set.


text: Q: Excel on Android I am working with an web application which lets users downloads excel files using open xml documents/API. When I click on the link on my desktop (windows 7/office 13) it works fine and documents open up without any errors/popups. However, if I run the same workflow on my android phone the document downloads but excel complains that the document is corrupt when I try to open the document on my desktop as well as mobile. Any help?


text:
Q: Как на Макбуке через VPN подключиться к другому компьютеру? Подключаюсь по VPN в определенную сеть, теперь нужно скопировать папку с проектом но она находиться на другом компьютере под управление Windows но в той же сети.
Как посредством Макбука/Линукса зайти и скопировать папку?

A: Тогда включить на W10 sshd и
scp -r remote_user@w10_vpn_ip:/path/to/project /local/path/to/project
Или без заморочек расшарить папку с проектом на W10 и через finder на Mac
Cmd+K (откроется строка подключения)
smb://w10_vpn_ip/sharename и скопировать проект.

Но это все в случае если Вам нужно просто забрать копию проекта.
  Если нужно работать с проектом и поддерживать копию на win10 в актуальном состоянии, тогда нужно настраивать git или другую систему контроля версий.
И естетственно и в том и другом случае понадобятся логин пароль учетной записи w10


text:
Q: create menu with ionic 2 and angular 2 I am developing a mobile application with ionic 2, and I need a menu as shown in the image,this menu is not like the menu side
Page View

A: You will need to scaffold a new project with ionic2 cli using
$ionic start myApp sidemenu

which will give you the basic hamburger menu after which it is all on how you style it.


text:
Q: Error adding parameters to sql execution from c# Sorry if someone has already given an answer to this, I have been browsing the site and trying tips and bits of code for hours, to no avail.
I have a stored procedure which basically retrieves the id of an element, if this element exists, and zero if it doesn't.
Here we go:
PROCEDURE [dbo].[ChecksProductExistence]
        @Product_Name varchar(50),
        @Return_Value Int output
AS
BEGIN
    IF EXISTS (SELECT prod.ProductID
               FROM dbo.Products prod
               WHERE prod.ProductName = @Product_Name)
        SET @Return_Value = 1;
    ELSE
        SET @Return_Value = 0;
END

Okay, so far so good. Execute that in my database, and it works like a charm... not that it's such complex code.
Then, in Visual Studio, I coded the following:
private static bool checkExistingProduct(ShoppingListContext ctx, Product product)
{
    var cmd = ctx.Database.Connection.CreateCommand();
    cmd.CommandText = "[dbo].[ChecksProductExistence]";

    ctx.Database.Connection.Open();
    int bla = 0;

    SqlParameter inParameter = new SqlParameter();
    inParameter.ParameterName = "@Product_Name";
        inParameter.SqlDbType = SqlDbType.NVarChar;
        inParameter.Direction = ParameterDirection.Input;
        inParameter.Value = product.ProductName;

    SqlParameter outParameter = new SqlParameter();
        outParameter.ParameterName = "@Return_Value";
        outParameter.SqlDbType = SqlDbType.Int;
        outParameter.Direction = ParameterDirection.Output;

    cmd.Parameters.Add(inParameter);
    cmd.Parameters.Add(outParameter);

    bla = cmd.ExecuteNonQuery();

    Console.WriteLine(outParameter.Value);

    Console.ReadLine();

    if ((int)outParameter.Value == 1) return true; else return false;
}

As you can see... simple enough. I create a command, add parameters, execute it, try some decision making on the output.
But... I get an error on the
cmd.ExecuteNonQuery();

line. I have changed it to ExecuteScalar, for example, but still no luck. I have executed it without the "bla = ...", and still the same.
The error I get is

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Procedure or function 'ChecksProductExistence' expects parameter '@Product_Name', which was not supplied.

But then again, not only can you see clearly in the code that I AM IN FACT SUPPLYING IT, but also on the debug session I can explore the cmd object and browse the parameters, and I can see that IT IS THERE, and the values are correct...
So what else can I do?? Am I making some silly mistake I can't see...?

A: As stated in the documentation for SqlCommand.CommandType you have to set it to CommandType.StoredProcedure and set the CommandText to the name of the stored procedure.  It defaults to CommandType.Text where you have to include the named parameters in the text of the query.

When you set the CommandType property to StoredProcedure, you should
  set the CommandText property to the name of the stored procedure. The
  command executes this stored procedure when you call one of the
  Execute methods.
The Microsoft .NET Framework Data Provider for SQL
  Server does not support the question mark (?) placeholder for passing
  parameters to a SQL Statement or a stored procedure called with a
  CommandType of Text. In this case, named parameters must be used. For
  example:
SELECT * FROM Customers WHERE CustomerID = @CustomerID

So, just add the following
cmd.CommandType = CommandType.StoredProcedure;

somewhere before executing it.