text:
Q: How to call parent non virtual function in c++ multi inheritance? class VA {
 public:
  virtual void print() = 0;
};
class VB : public VA {
 public:
  virtual void bprint() = 0;
};
class SA : public VA {
 public:
  void print() override { std::cout << "SA" << std::endl; };
};
class SB : public SA, public VB {
 public:
  virtual void bprint() { std::cout << "SB" << std::endl; };
};
int main() {
  SB sb;
  sb.bprint();
  sb.print();
}

What is the correct way to call sb.print()?
class SB : public SA, public VB {
 public:
  virtual void bprint() { std::cout << "SB" << std::endl; };
  void print() override { SA::print(); };
};

I know this kind of override will work, but I am considering is there a way that no extra code in class SB?

A: It looks like you are trying to make VA an interface in Java sense: no data, only some methods which have to be implemented only once in the hierarchy.
Short version: use virtual inheritance for VA: : public virtual VA.
Long version follows.
Multiple inheritance in C++ by default creates independent paths to all base objects. In your case, SB actually has two VA bases: one from SA, and one from VB. The former has an implementation of print, the latter does not, hence the first compilation error:
a.cpp: In function 'int main()':
a.cpp:20:6: error: cannot declare variable 'sb' to be of abstract type 'SB'
   20 |   SB sb;
      |      ^~
a.cpp:15:7: note:   because the following virtual functions are pure within 'SB':
   15 | class SB : public SA, public VB {
      |       ^~
a.cpp:5:16: note:     'virtual void VA::print()'
    5 |   virtual void print() = 0;
      |                ^~~~~
a.cpp:22:6: error: request for member 'print' is ambiguous
   22 |   sb.print();
      |      ^~~~~
a.cpp:5:16: note: candidates are: 'virtual void VA::print()'
    5 |   virtual void print() = 0;
      |                ^~~~~
a.cpp:13:8: note:                 'virtual void SA::print()'
   13 |   void print() override { std::cout << "SA" << std::endl; };
      |        ^~~~~

However, there is also the second error. It becomes more visible if you implement print both in SA and VB: there are actually two prints:
a.cpp: In function 'int main()':
a.cpp:23:6: error: request for member 'print' is ambiguous
   23 |   sb.print();
      |      ^~~~~
a.cpp:5:16: note: candidates are: 'virtual void VA::print()'
    5 |   virtual void print() = 0;
      |                ^~~~~
a.cpp:10:8: note:                 'virtual void VB::print()'
   10 |   void print() override { std::cout << "VB" << std::endl; };  // Tried to add another implementation
      |        ^~~~~
a.cpp:14:8: note:                 'virtual void SA::print()'
   14 |   void print() override { std::cout << "SA" << std::endl; };
      |        ^~~~~

In C++ corresponding mechanics is provided by virtual inheritance: every base which should be deduplicated should be marked as virtual:
#include <iostream>

class VA {
 public:
  virtual void print() = 0;
};
class VB : public virtual VA {  // 'virtual' ~ 'please ensure there is only one VA base'
 public:
  virtual void bprint() = 0;
};
class SA : public virtual VA {  // 'virtual' ~ 'please ensure there is only one VA base'
 public:
  void print() override { std::cout << "SA" << std::endl; };
};
class SB : public SA, public VB {
 public:
  virtual void bprint() { std::cout << "SB" << std::endl; };
};
int main() {
  SB sb;
  sb.bprint();
  sb.print();
}

Now the compiler knows that there is only one VA base, and successfully finds its print implementation unambiguously in SA. It's important that SA is derived from VA, though, otherwise SA::print won't have any connection to VA::print whatsoever.


text:
Q: SenderID validation using java based email filter I am using jSPF to validate SPF records for incoming email addresses.
Now I need to support Sender-ID too.
Is it possible to use the same code of jSPF or with some patches I could use it for validating Sender-ID too?
I had checked the jSPF code but they only support SPF RFC-4408 only.
I am ready to write the patch by myself in java if I could not find any existing SenderID validation library in java,
moreover I tried to read RFC 4406 and RFC 4408 to implement SenderID in java but the RFC confused me further regarding the right implementation path as it refers SPF RFC's and formatting's too.
Please help.
Thanks in advance

A: FYI: Perhaps there are also webservices to do this.
For example: http://www.microsoft.com/mscorp/safety/content/technologies/senderid/wizard/default.aspx
shows if there are entries for domain xy. Perhaps you can parse and use them. But please check out if you are allowed to use this webservices.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convergence of Integrands and Integrals Suppose $E \subset \mathbb{R}$ is compact. Is it possible to find a sequence of positive continuous functions $f_n: E \to \mathbb{R}$ such that for every $x \in E$ we have
$$f_n(x) \to f(x)$$
for some $f \in L^\infty(E)$ and
$$\int_E \! f_n(x) \, dx \to C < \infty$$
but
$$C \neq \int_E \! f(x) \, dx?$$
I would think not, but none of the standard convergence theorems seem to do the trick. All integrals are supposed to be Lebesgue integrals.

A: Let $f$ be any nonnegative continuous function with support contained in $[0,1]$, and $$f_n(x)=nf(nx).$$
To get a positive function, just add something like $e^{-x^2}$ to each $f_n$.


text:
Q: Expand Collapse buttons in AngularJS I intend to create multiple expand/collapse button at the bottom of each article that I display in a stream using AngularJS.
This is what my page structure looks like:

Heading of the Page

Some very long text goes here.

            <icon name="expand">E</icon>

            <icon name="share">S</icon>

I have multiple item-content-blocks and I want to expand and collapse each block using AngularJS (Please DO NOT use jQuery anywhere).
Since there will be multiple blocks, with same Class names and everything, a scalable code will be needed.
I am just beginning with AngularJS, so any help will be appreciated. Thanks!

A:
Since there will be multiple blocks, with same Class names and everything, a scalable code will be needed.

you essentially should have each block driven off an item in your view model. Just an an expanded (boolean) option to each item. Then you can drive css classes off of it using ngClass.
More
https://docs.angularjs.org/api/ng/directive/ngClass


text:
Q: flutter saves the file in the directory selected by the user I use file_picker to get the directory path and permission_handler to get the storage permission, but when I finally save the file, it still fails. I don't know where the problem is, I use Android
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as path;

        onPressed: () async {
          var storageStatus = await Permission.storage.status;
          if (storageStatus != PermissionStatus.granted) {
            storageStatus = await Permission.storage.request();
            if (storageStatus != PermissionStatus.granted) {
              return;
            }
          }

          var dpath = await FilePicker.platform.getDirectoryPath();
          if (dpath != null) {
            var p = path.join(dpath, 'test.jpg');
            try {
              var r = await http.readBytes(
                  'https://i.loli.net/2019/12/07/vVfLEsQy7TbehrW.jpg');
              try {
                await File(p).writeAsBytes(r);
              } catch (er) {
                print('save error: ' + er.message); // save error: Cannot open file
                print('save path: ' + p); // save path: /storage/emulated/0/.Android/test.jpg
                print(er); // FileSystemException: Cannot open file, path = '/storage/emulated/0/.Android/test.jpg' (OS Error: Permission denied, errno = 13)

              }
            } catch (er) {
              print('download errro: ' + er.message);
            }
          }
        },

pubspec.yaml:
environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  path:
  file_picker: 2.0.7
  permission_handler: ^5.0.1+1
  http:

flutter doctor -v
[√] Flutter (Channel stable, 1.22.4, on Microsoft Windows [Version 10.0.19041.630], locale zh-CN)
    • Flutter version 1.22.4 at D:\my-tools\flutter
    • Framework revision 1aafb3a8b9 (12 days ago), 2020-11-13 09:59:28 -0800
    • Engine revision 2c956a31c0
    • Dart version 2.10.4
    • Pub download mirror https://pub.flutter-io.cn
    • Flutter download mirror https://storage.flutter-io.cn

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
    • Android SDK at D:\my-tools\Android\sdk
    • Platform android-30, build-tools 29.0.3
    • ANDROID_HOME = D:\my-tools\Android\sdk
    • Java binary at: D:\my-tools\Android\AndroidStudio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    X Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/windows#android-setup for more details.

[!] Android Studio (version 4.1.0)
    • Android Studio at D:\my-tools\Android\AndroidStudio
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)

[√] Connected device (1 available)
    • SM G8750 (mobile) • c5976a52 • android-arm64 • Android 10 (API 29)

A: I carefully checked the document of permission_handler, and changed the compileSdkVersion and targetSdkVersion in "android/app/build.gradle" file to 28, and it can work normally when I run it again


text:
Q: Read records from large xlsx/csv files and post it to azure service bus topic We receive large feed files(excel/csv) of ~5gb size every night, need to read and have to post one record after another from the file to azure service bus topic. Is it possible using Azure Data Factory, if yes, how? or any other better azure based solution available? please suggest.

A: Data Factory doesn't support Azure Service Bus topic. So it's impossible to using Azure Data Factory

For more details, please see : Supported data stores and formats.
I think Azure Function may can help you achieve it.
You can reference :

*

*Azure Blob storage bindings for Azure Functions.
This article explains how to work with Azure Blob storage bindings in Azure Functions. Azure Functions supports trigger, input, and output bindings for blobs. The article includes a section for each binding: Blob trigger, Blob input binding,Blob output binding.

*Azure Service Bus bindings for Azure Functions. This article explains how to work with Azure Service Bus bindings in Azure Functions. Azure Functions supports trigger and output bindings for Service Bus queues and topics
Here is a blog about Copy data from Azure Service Bus Topic to a Storage Account inside Azure.
We don't know how much time it will take. Azure Functions has two kinds of pricing plans:Consumption plan and App Service plan.
Azure Functions in a Consumption plan are limited to 10 minutes for a single execution. In the Premium plan, the run duration defaults to 30 minutes to prevent runaway executions. However, you can modify the host.json configuration to make this unbounded for Premium plan apps.
For more details, please reference: Azure Functions Premium plan.
Maybe Azure Function is not fit for this long process, but can help you execute this long process.
Hope this helps.


text:
Q: Upgrading to latest Wakanda Enterprise: decipher error codes? I am trying to move to the latest version of Wakanda Enterprise and my solution, originally created in V10 enterprise, won't even launch. Below are the error codes. I searched for some kind of index to look up the codes but I could not find one.
2016-09-28 13:50:33 [wakanda.PlannerTool2.PlannerTool2.xbox] ERROR - [614] "{newname}" is an invalid name for file {path}., task #1299
2016-09-28 13:50:33 [wakanda.PlannerTool2.PlannerTool2.iasv] ERROR - [1054] Cannot post 'applicationWillStart' message to services, task #1299
2016-09-28 13:50:33 [wakanda.PlannerTool2.PlannerTool2.xbox] ERROR - [650] Directory not found (dirNFErr)., task #1299
I tried this on 2 different machines (both Mac) and am an admin on one of them-- both had the same error codes.
I am trying to upgrade to 11.197492 and the same exact errors happen when I try to launch using 11.196912
My .waProject file:
<?xml version="1.0" encoding="UTF-8"?>
<project>
`<folder path="./Widgets/">`
    `<tag name="widgets"/>`
`</folder>`
`<folder path="./Themes/">`
    `<tag name="themes"/>`
`</folder>`
`<file path="./Model.waModel">`
    `<tag name="catalog"/>`
`</file>`
`<file path="./Settings.waSettings">`
    `<tag name="settings"/>`
`</file>`
`<file path="./Permissions.waPerm">`
    `<tag name="permissions"/>`
`</file>`
`<file path="./bootstrap.js">`
    `<tag name="bootStrap"/>`
`</file>`

</project>


text:
Q: uszipcode Windows command prompt: ImportError: DLL load failed: The specified module could not be found I have been working with the module uszipcode without problem in anaconda, but
when moving to Windows command prompt, I get an error failing the DLL load.
I am using python3 in Windows 10
>>> uszipcode.__version__
'0.2.2'

>>> sys.version
'3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)]'

>>> import uszipcode
>>> uszipcode.SearchEngine()
Traceback (most recent call last):
  File "C:\Users\user\Anaconda3\lib\site-packages\sqlalchemy\dialects\sqlite\pysqlite.py", line 334, in dbapi
    from pysqlite2 import dbapi2 as sqlite
ModuleNotFoundError: No module named 'pysqlite2'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\user\Anaconda3\lib\site-packages\uszipcode\search.py", line 82, in __init__
    engine = connect_to_simple_zipcode_db()
  File "C:\Users\user\Anaconda3\lib\site-packages\uszipcode\db.py", line 49, in connect_to_simple_zipcode_db
    return engine_creator.create_sqlite(path=simple_db_file_path.abspath)
  File "C:\Users\user\Anaconda3\lib\site-packages\uszipcode\pkg\sqlalchemy_mate\engine_creator.py", line 51, in create_sqlite
    return create_engine(_create_sqlite(path), **kwargs)
  File "C:\Users\user\Anaconda3\lib\site-packages\sqlalchemy\engine\__init__.py", line 425, in create_engine
    return strategy.create(*args, **kwargs)
  File "C:\Users\user\Anaconda3\lib\site-packages\sqlalchemy\engine\strategies.py", line 81, in create
    dbapi = dialect_cls.dbapi(**dbapi_args)
  File "C:\Users\user\Anaconda3\lib\site-packages\sqlalchemy\dialects\sqlite\pysqlite.py", line 339, in dbapi
    raise e
  File "C:\Users\user\Anaconda3\lib\site-packages\sqlalchemy\dialects\sqlite\pysqlite.py", line 337, in dbapi
    from sqlite3 import dbapi2 as sqlite  # try 2.5+ stdlib name.
  File "C:\Users\user\Anaconda3\lib\sqlite3\__init__.py", line 23, in <module>
    from sqlite3.dbapi2 import *
  File "C:\Users\user\Anaconda3\lib\sqlite3\dbapi2.py", line 27, in <module>
    from _sqlite3 import *
ImportError: DLL load failed: The specified module could not be found.

Any help would be appreciated. Thanks

A: I have created an environment with python 3.6 and the issue has been solved.


text:
Q: setValues on the first empty row in a specific column I am building a script that will take a table with student's names and their first, second, and so on choices for an activity and then put them into a class roster by grade. I have got everything working in my test except that it won't setValues next to each other. I know this is because of the .getLastRow that I am using but I can't think of any other way. Secondly, I am forced to use separate for loops or it will just place the names wherever in the loop it finds them and makes a mess.
Here is my code:
function StreamRoster2() {

  var grade = 2;
  var name = 1;
  var choice1 = 3;
  var fifth = SpreadsheetApp.openById("1prA4_1z_8JGsjKHGLOQKj0FCo1pF7tDCxdR_nHkBqq8").getSheetByName("Fifth");

  var data = SpreadsheetApp.openById("1prA4_1z_8JGsjKHGLOQKj0FCo1pF7tDCxdR_nHkBqq8").getSheetByName("Results").getDataRange().getValues();

  for (var i = 2; i < data.length; i++) {
    if (data[i][grade] === 'Fifth' && data[i][choice1] === 1) {
       fifth.getRange(fifth.getLastRow()+1, 1).setValue(data[i][name]);
    }
  }

  for (var i = 2; i < data.length; i++) {
    if (data[i][grade] === 'Fifth' && data[i][choice1] === 2) {
       fifth.getRange(fifth.getLastRow()+1, 2).setValue(data[i][name]);
     }
    }
  for (var i = 2; i < data.length; i++) {
    if (data[i][grade] === 'Fifth' && data[i][choice1] === 3) {
        fifth.getRange(fifth.getLastRow()+1, 3).setValue(data[i][name]);
     }
    }

   SpreadsheetApp.flush();
   Browser.msgBox("Classes Created");
  }

Any help will be appreciated. Thanks
What it looks like in the spreadsheet

A: Create a counter and only increment it if there is a match:
var foundCounter = 0;

for (var i = 2; i < data.length; i++) {
  if (data[i][grade] === 'Fifth' && data[i][choice1] === 1) {
    foundCounter +=1;
    fifth.getRange(foundCounter, 1).setValue(data[i][name]);
  }
}


text:
Q: Relation between covariance and bandwidth in gaussian_kde I'm trying to implement a 2D parzen window on a cluster of data to estimate the PDF. I'm doing this for school and one of the requirements is to use a Gaussian window with covariance σ^2=400.
I decided to use the gaussian_kde class provided by SciPy.stats. However, I'm not sure what value of bandwidth to provide. I see documentation about Scott's rule and Silverman's rule but I was wondering how to incorporate the σ^2=400 requirement into this parameter.
In other words, what is the relationship between the covariance of the Gaussian parzen window and the bandwidth parameter of the gaussian_kde class?


text:
Q: Generate maven archetype from project and variable replacement I'm trying to generate an archetype from a project, but I have some issues to solve.
First of all, I've a file like this:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: ${artifactId}
....

Then, I use the command:
mvn clean archetype:create-from-project -Darchetype.filteredExtentions=* -Darchetype.postPhase=install

But, when I try to generate a new project from the installed archetype, the result of this operation is this:
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: ${symbol_dollar}{artifactId}
  ...

Is there a way to obtain a file in which the property "${artifactId}" is replaced during the new project creation?
Thanks all


text:
Q: Keyboard Pressing Application Imagine that problem. When you play some games, sometimes happens situations like "press quickly the X key to escape from ropes" or "press quickly the X key to fill the rage gauge", etc.
Of course, that kind of game destroy keyboards, joysticks, mouses, etc.
I would like to know about programs (preferentially free) that, by example, will press the 'x' key in intervals of, by example, 300ms.
Remember that the built in Windows "keyboard repeat rate" doesn't works for games. When you press (and hold) somekey in the game, the key is not repeated as in default Windows Applications.
Thanks!

A: AutoPressKey will do it for you I believe.


text:
Q: Java BigInteger pow with an int base I'm probably missing something and kinda rusted out this sort of thing, I was wondering what is the best way to implement 2^Biginteger into a variable? I'm sure it's a simple question. This is to aid in figuring out a 2-pseudoprime. (Basically to see if 2^N-1 = 1 mod N or not).

A: So if I understand you, you want to do something like this:
 BigInteger bigExp = ...  some really large value
 BigInteger pow = BigInteger.valueOf(2).pow(bigExp);

Unfortunately, that won't work.
As you noted, there is no pow overload that takes a BigInteger argument.  And when you think about it, such a method would be problematic.
The value of 2N is a value with N significant bits when represented in binary.  If is larger than will fit into an int, then that means N is 231 or more.  Or converting to bytes, that is 228 bytes or 0.25 Gigabytes.  For a single number.
That isn't impossibly large.  It should be possible to represent numbers that big, even in a 32 bit JVM.  The problem is that any BigInteger arithmetic operation is liable to generate another one of these monsters.  Just creating a number of this size is going to copy 0.25 Gigabytes, and operations like multiplication and division ... which are O(N^2) for N bit numbers ... are going to take "forever".
Having said that, there would be ways to generate numbers that size.  For example, you could allocate a huge byte array (which default initializes to zero), set the appropriate byte to contain a 1 bit, and then use BigInteger(byte[]) to construct the monster number.

A: As @StephenC points out, these numbers will be too unwieldy.
But

to see if 2^N-1 = 1 mod N or not

You don't need to calculate 2^X.  You can calculate 2^X mod N. A much smaller number.
 BigInteger.valueOf(2).modPow(n.subtract(ONE), n);


text:
Q: Install BIOS for Dell Inspiron 1564 my labtob doesn't power on (when i click the power button the lamp flashes and it doesn't power on), i went to a technician and he said that the bios is corrupted, and he want to install a new bios not update.
please advise how can i install a new bios, because all the files i found was for updating bios not installing a new one, and to update the bios i need to power on the laptop first.

A: You could try to unplug the battery and remove the power-cord and press the power-button for a few seconds (10 should do).
This will reset the BIOS to default. I know this is over a year old thread, but maybe it helps some other people.
I had the similar problem few days ago and this did a good job ;)


text:
Q: Basic authentification ignoring password validation I configure WebSecurityConfig, create user in memory
@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("username")
                .password(passwordEncoder().encode("password"))
                .authorities("READ_ORDERS")
                .roles("USER");
    }

configure WebSecurityConfig
@Configuration
    @Order(1)
    public static class BasicAuthenticationAdapter extends WebSecurityConfigurerAdapter {

        private final AuthenticationEntryPoint authEntryPoint;

        @Autowired
        public BasicAuthenticationAdapter(AuthenticationEntryPoint authEntryPoint) {
            this.authEntryPoint = authEntryPoint;
        }

        protected void configure(HttpSecurity http) throws Exception {
            http
                    .antMatcher("/orders**")
                    .authorizeRequests()
                    .anyRequest().hasRole("USER")
                    .and()
                    .csrf().disable()
                    .httpBasic().authenticationEntryPoint(authEntryPoint)
                    .and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    }

When i try to Authorise with invalid credentials first time - 401 exception, it's ok.
But after successful authorization, when i use invalid username and password,
i also authorised.
What can be the problem ?

A: That is how basic authentication works. As soon as you have logged in successfully the valid credentials will always be posted.
Spring security works with SessionCreationPolicy, and default policy is IF_REQUIRED. It means spring creates session if it does not have and is required.
In order to solve your issue you have to change this policy.
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

Restart your server and try again.


text:
Q: Update Image source in data template long list selector WP8 My problem is :
In my long list selector, when my list items loaded and i click on edit button  to activate/inactive items
When  i active / d-activate the top items then on scrolling down long list selector the some- where middle items where automatically got selected.

Please suggest something to me to get rid of this issue:
MainPage.xaml
<phone:PhoneApplicationPage
    x:Class="longlistselector.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">
    <phone:PhoneApplicationPage.Resources>
        <phone:JumpListItemBackgroundConverter x:Key="BackgroundConverter"/>
        <phone:JumpListItemForegroundConverter x:Key="ForegroundConverter"/>

        <DataTemplate x:Key="CustomHeaderTemplate">
            <StackPanel Background="DarkKhaki" Orientation="Horizontal" Width="450" >
                <TextBlock Text="{Binding Name}"
                                    FontSize="36"
                                    FontFamily="{StaticResource PhoneFontFamilySemiLight}"/>
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="CustomExpanderTemplate">
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Image}" Stretch="None"/>

            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="CustomItemTemplate">
            <StackPanel Background="BlueViolet" Margin="0,0,0,10" Height="55" Orientation="Horizontal"  Width="412">
                <Border BorderThickness="1" CornerRadius="10" Background="White" Width="280" Height="50">
                    <TextBlock Text="{Binding UnitName}" Foreground="Black" FontWeight="Bold" />
                </Border>
                <StackPanel Margin="0,6,15,0">
                    <Image  Height="32" Width="32"  Source="/Assets/Images/edit.png"></Image>
                </StackPanel>
                <StackPanel Margin="0,6,15,0">
                    <Image  Height="32" Width="32"   Source="/Assets/Images/trash.png"></Image>
                </StackPanel>
                <StackPanel  Margin="0,6,15,0">
                    <Image  Height="32" Width="32"  Source="{Binding ImageSource}"></Image>
                </StackPanel>

            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="CustomNonExpandableHeaderTemplate">
            <StackPanel Orientation="Vertical">
                <TextBlock Text="{Binding Name}"
                                    FontSize="{StaticResource PhoneFontSizeExtraLarge}"
                                    FontFamily="{StaticResource PhoneFontFamilySemiLight}"/>
            </StackPanel>
        </DataTemplate>
    </phone:PhoneApplicationPage.Resources>
    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
            <TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

            <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <phone:LongListSelector x:Name="GroupListBox" Width="Auto" Background="#D1EEFC" BorderThickness="1"   IsGroupingEnabled="False" LayoutMode="List" HideEmptyGroups="True" VerticalAlignment="Stretch" >
     <phone:LongListSelector.ItemTemplate>
                    <DataTemplate>

                        <StackPanel  Background="White" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="Auto" Height="Auto">
                            <Grid x:Name="SubGrid"  Width="Auto" HorizontalAlignment="Stretch">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition x:Name="SubGridCol"/>
                                    <ColumnDefinition Width="80"/>
                                </Grid.ColumnDefinitions>

                                <StackPanel Grid.Column="0" Name="Subpnl" Orientation="Horizontal" HorizontalAlignment="Stretch" Width="Auto" MaxHeight="200" MinHeight="100">

                                    <TextBlock TextWrapping="Wrap"  HorizontalAlignment="Left" Height="Auto" Width="250"  TextAlignment="Left"  Foreground="Black" FontSize="25"  VerticalAlignment="Center" Text="{Binding Name}"  Style="{StaticResource PhoneTextNormalStyle}" FontFamily="{StaticResource PhoneFontFamilySemiBold}" />
                                </StackPanel>
                                <StackPanel Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Center" Background="Transparent" >
                                    <Image Source="{Binding Content}" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" Width="Auto" Visibility="{Binding ControlVisibility}" Tap="ActiveInactiveImage_Tap_1">

                                    </Image>
                                </StackPanel>
                            </Grid>
                            <Rectangle Fill="Gray" Height="1" HorizontalAlignment="Stretch" Width="1000" />
                        </StackPanel>
                    </DataTemplate>
                </phone:LongListSelector.ItemTemplate>
            </phone:LongListSelector>

        </Grid>

    </Grid>
    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar Mode="Default"  Opacity="1.0" IsMenuEnabled="True" IsVisible="True">

            <shell:ApplicationBarIconButton Click="ApplicationBarIconButton_Click_1" IconUri="/Assets/AppBar/edit.png" Text="Edit"/>

        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>
</phone:PhoneApplicationPage>

MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using longlistselector.Resources;
using System.Windows.Media.Imaging;
using System.Collections.ObjectModel;

namespace longlistselector
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        List<GroupClass> List = new List<GroupClass>();
        ObservableCollection<GroupClass> DataList = null;
        static bool IsEditable = false;
        public MainPage()
        {
            InitializeComponent();

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();

            List.Add(new GroupClass() { Name = "Temp", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 1 });
            List.Add(new GroupClass() { Name = "Temp1", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 2 });
            List.Add(new GroupClass() { Name = "Temp2", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 3 });
            List.Add(new GroupClass() { Name = "Temp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 4 });
            List.Add(new GroupClass() { Name = "Aemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 5 });
            List.Add(new GroupClass() { Name = "Aemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 6 });
            List.Add(new GroupClass() { Name = "Aemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 7 });
            List.Add(new GroupClass() { Name = "Bemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 8 });
            List.Add(new GroupClass() { Name = "Bemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 9 });
            List.Add(new GroupClass() { Name = "Bemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 10 });
            List.Add(new GroupClass() { Name = "Cemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 11 });
            List.Add(new GroupClass() { Name = "Cemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 12 });
            List.Add(new GroupClass() { Name = "Cemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 13 });
            List.Add(new GroupClass() { Name = "Demp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 14 });
            List.Add(new GroupClass() { Name = "Demp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 15 });
            List.Add(new GroupClass() { Name = "Demp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 16 });
            List.Add(new GroupClass() { Name = "Eemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 17 });
            List.Add(new GroupClass() { Name = "Eemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 18 });
            List.Add(new GroupClass() { Name = "Eemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 19 });
            List.Add(new GroupClass() { Name = "Eemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 20 });
            List.Add(new GroupClass() { Name = "Femp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 21 });
            List.Add(new GroupClass() { Name = "Femp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 22 });
            List.Add(new GroupClass() { Name = "Gemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 23 });
            List.Add(new GroupClass() { Name = "Gemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 24 });
            List.Add(new GroupClass() { Name = "Hemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 25 });
            List.Add(new GroupClass() { Name = "Hemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 26 });
            List.Add(new GroupClass() { Name = "Jemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 27 });
            List.Add(new GroupClass() { Name = "Jemp3", IsActive = false, IsCustom = false, IsEditable = false, UnitGroupID = 28 });

            DataList = new ObservableCollection<GroupClass>(List);
            this.GroupListBox.ItemsSource = DataList;

        }

        private void ActiveInactiveImage_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {

            Image imgobj = sender as Image;
            GroupClass gcobj = (GroupClass)imgobj.DataContext;
            if (gcobj != null)
            {
                gcobj.IsActive = !gcobj.IsActive;

                imgobj.DataContext = gcobj;

                DataList.FirstOrDefault(x => x.UnitGroupID == gcobj.UnitGroupID).IsActive = gcobj.IsActive;

                imgobj.Source = new BitmapImage(new Uri(gcobj.IsActive ? "/Assets/Images/Active.png" : "/Assets/Images/Inactive.png", UriKind.Relative));

            }

            GroupListBox.ItemsSource = DataList;
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            IsEditable = !IsEditable;
            foreach (var obj in DataList)
            {
                obj.IsEditable = IsEditable; obj.IsChecked = false;

            }
            this.GroupListBox.ItemsSource = null;
            this.GroupListBox.ItemsSource = DataList;

        }
    }
}

GroupClass.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace longlistselector
{
    class GroupClass
    {

        public string ImageSource
        {
            get;
            set;
        }
        public string Content
        {
            get { return IsActive ? "/Assets/Images/Active.png" : "/Assets/Images/Inactive.png"; }

        }
        public string Name
        {
            get;
            set;
        }
        public long UnitGroupID
        {
            get;
            set;
        }
        public bool IsActive
        {
            get;

            set;

        }

        public bool IsCustom
        {
            get;
            set;
        }
        public bool IsChecked
        {
            get;
            set;
        }
        public bool IsEditable
        {
            get
           ;
            set;

        }

        public Visibility ControlVisibility
        {
            get { return IsEditable? Visibility.Visible : Visibility.Collapsed; }
        }

    }
}

A: Finally after struggling for 2 day, i solve this issue and fix it.
Replace the groupclass.cs with this code:
groupclass.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace longlistselector
{
    class GroupClass : INotifyPropertyChanged
    {

        public string ImageSource
        {
            get;
            set;
        }

        public string Content
        {
            get;
            set;
        }
        public string Name
        {
            get;
            set;
        }
        public long UnitGroupID
        {
            get;
            set;
        }
        private bool isActive;
        public bool IsActive
        {
            get { return isActive; }
            set
            {
                isActive = value;
                Content = isActive ? "/Assets/Images/Active.png" : "/Assets/Images/Inactive.png";
                OnPropertyChanged("IsActive");
                OnPropertyChanged("Content");

            }

        }

        public bool IsCustom
        {
            get;
            set;
        }
        public bool IsChecked
        {
            get;
            set;
        }
        private bool isEditable;
        public bool IsEditable
        {
            get { return isEditable; }
            set
            {
                if (value != isEditable)
                {
                    isEditable = value;

                    OnPropertyChanged("IsEditable");
                    ControlVisibility = isEditable ? Visibility.Visible : Visibility.Collapsed;
                    OnPropertyChanged("ControlVisibility");
                }
            }

        }
        public Visibility IsCustomControlVisibility
        {
            get { return IsEditable & IsCustom ? Visibility.Visible : Visibility.Collapsed; }
        }
        public Visibility ControlVisibility
        {
            get;
            set;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

We just need to call the INotifyPropertyChanged at couple of more places in the code.

A: You need implement INotifyPropertyChanged in GroupClass
public class GroupClass : INotifyPropertyChanged
{
    private bool _isActive;
    private string _content;
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual bool Set<T>(ref T field, T newVal, [CallerMemberName] string propertyName = null)
    {
        if (Equals(field, newVal)) return false;
        field = newVal;
        if(PropertyChanged!=null)
        PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        return true;
    }

    public string Content
    {
        get { return _content; }
        set { Set(ref _content, value); }
    }

    public bool IsActive
    {
        get { return _isActive; }
        set
        {
            if(Set(ref _isActive, value))
            Content = _isActive ? "/Assets/Images/Active.png" : "/Assets/Images/Inactive.png";
        }
    }
}

In your code behind:
private void ActiveInactiveImage_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {

            Image imgobj = sender as Image;
            GroupClass gcobj = (GroupClass)imgobj.DataContext;
            if (gcobj != null)
            {
                gcobj.IsActive = !gcobj.IsActive;
            }
        }


text:
Q: How to load an entire html file as a pop up using ui-dialog in jquery? I want to load an html file as a pop up window (like a lightbox) using ui-dialog. I tried the following code, but the js functions inside the loaded html page do not get triggerred. I only get the page content and the images.
$('#lightbox_link').click(function(){

     $('#lightbox_popup').load('new_lightbox.html').dialog({
                                            resizable: false,
                                                height:650,
                                                width:980,
                                                dialogClass:'noTitle',
                                                modal: true
                                });
    });
 });

Also I need to know, if ui-dialog would support if the html link is created dynamically? Now I have given a static link. But suppose the link is genereated and returned by the server, then would the page be loaded as a pop up with all the js functions in my page being triggered? Thanks for the help.

A: If you want to reuse same dialog box on page for number of links try this
Html:
Load
Load

Javascript:
$(document)ready(function(){
    $('#content').dialog({
             resizable: false,
             height: 300,
             width: 500,
             dialogClass: 'noTitle',
             modal: true
          });
     $('#load').click(function (){
         $("#content-holder").load($(this).attr("href"));
         $("#content").dialog('open');
         return false;
     })

}

A: Try this and see if it works for you
$('#load').click(function () {

   $('#content').load('load.htm', function (content) {
      $('#content').dialog({
         resizable: false,
         height: 300,
         width: 500,
         dialogClass: 'noTitle',
         modal: true
      });
      $('#content').dialog('show');
   });

});

Load.htm

    Content

Page
Load

If the links are dynamic then replace the $('#load').click with
$('body').delegate('#load', 'click', function () { ..... }


text:
Q: how to alter ScrollView scrollTo scrolling speed? I've been working with Scrollview which contains a list view containing  page indicators as numbers. When I click on them, I want them to scroll so that the selected number is in the center
like

4 5 6 [7] 8 9

7 is selected number here ,
when I click on 9 here
the scrollview scrolls left so that view comes as

7 8 [9] 10 11

I'm using scrollTo(x : calculated  , y : 0 , animated : true)
however the scroll is too slow. I want the scroll to be fast or controllable by a parameter, I've tried duration in scrollTo but that doesn't work.

A: This is a pretty neat solution that uses the scrollview's content height to scroll an entire view (on mount). However, the same trick can be used (add a listener to an animated value) to create a scroll function that can be triggered by some event at any given moment (to any given value).

import { useEffect, useRef, useState } from 'react'
import { Animated, Easing, ScrollView } from 'react-native'

const SlowAutoScroller = ({ children }) => {
  const scrollRef = useRef()
  const scrollAnimation = useRef(new Animated.Value(0))
  const [contentHeight, setContentHeight] = useState(0)

  useEffect(() => {
    scrollAnimation.current.addListener((animation) => {
      scrollRef.current &&
        scrollRef.current.scrollTo({
          y: animation.value,
          animated: false,
        })
    })

    if (contentHeight) {
      Animated.timing(scrollAnimation.current, {
        toValue: contentHeight,
        duration: contentHeight * 100,
        useNativeDriver: true,
        easing: Easing.linear,
      }).start()
    }
    return () => scrollAnimation.current.removeAllListeners()
  }, [contentHeight])

  return (
    <Animated.ScrollView
      ref={scrollRef}
      onContentSizeChange={(width, height) => {
        setContentHeight(height)
      }}
      onScrollBeginDrag={() => scrollAnimation.current.stopAnimation()}
    >
      {children}
    </Animated.ScrollView>
  )
}

A: This is currently not possible. A call of scrollTo results in a call of scrollResponderScrollTo, which then calls either the ios implementation or the android implementation. This would be the points where one would have to implement the scroll speed.


text:
Q: ViewChild binding with compiler checking I use ViewChild in the following way:
@Component({
    selector: 'demo',
    template: `<input type="text" #firstnameCtrl [(ngModel)]="firstname" />`
})
export class DemoComponent {
    public firstname: string;
    @ViewChild('firstnameCtrl') firstElementCtrl: ElementRef;
}

If someone changed in the template the exported variable #firstnameCtrl to #firstnameElement the application is broken, but no compiler was raised (also not in AOT).
So is there a prefered approach to bind ViewChild in a saver way?
Thanks!

A: https://angular.io/api/core/ViewChild
shows an example of binding a child via an object.
Copying the code here, in case link becomes invalid in future:
You can use ViewChild to get the first element or the directive matching the selector from the view DOM. If the view DOM changes, and a new child matches the selector, the property will be updated.
View queries are set before the ngAfterViewInit callback is called.
Metadata Properties:
selector - the directive type or the name used for querying.
read - read a different token from the queried elements.
import {Component, Directive, Input, ViewChild} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
   @Input() id: string;
}

@Component({
  selector: 'example-app',
  template: `
    <pane id="1" *ngIf="shouldShow"></pane>
    <pane id="2" *ngIf="!shouldShow"></pane>

    <button (click)="toggle()">Toggle</button>

Selected: {{selectedPane}}

  `,
})
export class ViewChildComp {
  @ViewChild(Pane)
  set pane(v: Pane) {
    setTimeout(() => { this.selectedPane = v.id; }, 0);
  }
  selectedPane: string = '';
  shouldShow = true;
  toggle() { this.shouldShow = !this.shouldShow; }
}


text:
Q: javascript sort array of string by value after special character I want to sort by array which contains value having colon (:)
This is the below input
[
  'Severity',
  'Name',
  'U1A_Shift SCM: UPTT-Pressure (Bara)',
  'U1A_Shift SCM: DPTT-Pressure (Bara)',
  'U3B SCM: APTT-Pressure (Bara)',
  'U3B SCM: UPTT-Pressure (Bara)',
  'U1B SCM: DPTT-Pressure (Bara)',
  'U1B SCM: UPTT-Pressure (Bara)',
  'U3B SCM: DPTT-Pressure (Bara)',
  'U1A_Shift SCM: UPTT-Temp (DegC)',
  'U1A_Shift SCM: DPTT-Temp (DegC)',
  'U3B SCM: APTT-Temp (DegC)',
  'U3B SCM: UPTT-Temp (DegC)',
  'U1B SCM: DPTT-Temp (DegC)',
  'U1B SCM: UPTT-Temp (DegC)',
  'U3B SCM: DPTT-Temp (DegC)',
  'U1B SCM: PCV-CHOKE status - Control position',
  'U3B SCM: PCV-CHOKE status - Control position',
  'U1A_Shift SCM: PCV-CHOKE status - Control position',
  'Alarms',
  'Advisories',
  '__row_index'
]

I want to sort / group it by the value after colon (:)
This should be below output
[
    'Severity',
    'Name': 'U3B',
    'U1A_Shift SCM: UPTT-Pressure (Bara)',    // grouped by UPTT-Pressure (Bara)
    'U3B SCM: UPTT-Pressure (Bara)',
    'U1B SCM: UPTT-Pressure (Bara)',
    'U1A_Shift SCM: DPTT-Pressure (Bara)',    //grouped by DPTT-Pressure (Bara)
    'U1B SCM: DPTT-Pressure (Bara)',
    'U3B SCM: DPTT-Pressure (Bara)',
    'U3B SCM: APTT-Pressure (Bara)', // grouped by APTT-Pressure (Bara)
    'U1A_Shift SCM: UPTT-Temp (DegC)', // grouped by UPTT-Temp (DegC)
    'U3B SCM: UPTT-Temp (DegC)',
    'U1B SCM: UPTT-Temp (DegC)',
    'U1A_Shift SCM: DPTT-Temp (DegC)', // grouped by DPTT-Temp (DegC)
    'U1B SCM: DPTT-Temp (DegC)',
    'U3B SCM: DPTT-Temp (DegC)',
    'U3B SCM: APTT-Temp (DegC)', // grouped by APTT-Temp (DegC)
    'U1B SCM: PCV-CHOKE status - Control position', // grouped by PCV-CHOKE status - Control position
    'U3B SCM: PCV-CHOKE status - Control position',
    'U1A_Shift SCM: PCV-CHOKE status - Control position',
    'Alarms',
    'Advisories',
    '__row_index',
]

I need to sort this array value which lies after ":" Eg: APTT-Temp (DegC)
How can i sort / group array values
Any help would by highly appreciated :)

A: You could collect all groups and single values and return a flat array.

const
    data = ['Severity', 'Name', 'U1A_Shift SCM: UPTT-Pressure (Bara)', 'U1A_Shift SCM: DPTT-Pressure (Bara)', 'U3B SCM: APTT-Pressure (Bara)', 'U3B SCM: UPTT-Pressure (Bara)', 'U3B SCM: DPTT-Pressure (Bara)', 'U1A_Shift SCM: UPTT-Temp (DegC)', 'U1A_Shift SCM: DPTT-Temp (DegC)', 'U3B SCM: APTT-Temp (DegC)', 'U3B SCM: UPTT-Temp (DegC)', 'U1B SCM: DPTT-Temp (DegC)', 'U1B SCM: UPTT-Temp (DegC)', 'U3B SCM: DPTT-Temp (DegC)', 'U1B SCM: PCV-CHOKE status - Control position', 'U3B SCM: PCV-CHOKE status - Control position', 'U1B SCM: DPTT-Pressure (Bara)', 'U1B SCM: UPTT-Pressure (Bara)', 'U1A_Shift SCM: PCV-CHOKE status - Control position', 'Alarms', 'Advisories', '__row_index'],
    map = data.reduce((m, s) => {
        const group = s.split(/:\s*/)[1] || m.size;
        return m.set(group, [...(m.get(group) || []), s]);
    }, new Map),
    grouped = Array.from(map.values()).flat(),
    counts = Array
        .from(map, ([k, { length }]) => [k, typeof k === 'string' && length])
        .filter(([, length]) => length);

console.log(counts);
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: jquery tablesorter2: How to sort the content of the generated Dropdown I use the jquery tablesorter2 (https://mottie.github.io/tablesorter/docs/index.html) with the filter widget.
Now I want to change the sort order of the values in the generated dropdowns (NOT the table-values) form asc to desc.
I have made a jsFiddle for this:
http://jsfiddle.net/ru5zLjk8/
Here you can find a discount column. I would like to have its values sorted desc, so that the biggest discount is first in the dropdown.
There are some options, but nothing seems to fit:
  // each option has an associated function that returns a boolean
  // function variables:
  // e = exact text from cell
  // n = normalized value returned by the column parser
  // f = search filter input value
  // i = column index

Maybe this is completely the wrong place to do it?
How to achive this?

A: You can use the filter_selectSource option to target that column (demo)
filter_selectSource: {
  5: function(table, column, onlyAvail) {
    // get an array of all table cell contents for a table column
    var array = $.tablesorter.filter.getOptions(table, column, onlyAvail);
    return array.sort(function(a, b) {
      return a === b ? 0 : parseFloat(b) > parseFloat(a) ? 1 : -1
    });
  }
}

You will also need to add a "filter-select-nosort" class to the header to prevent internal sorting of the data.
I think I'll make this easier by adding a "filter-select-desc-sort" class to change the sort.


text:
Q: C# Sending Email with attached file (image) My method sends an email using a SMTP Relay Server.
Everything works fine (the email gets sent), except for that the attached file (the image) is somehow compressed/notexistent and not able to retrieve from the email.
The method looks like this:
public static bool SendEmail(HttpPostedFileBase uploadedImage)
        {
            try
            {
                var message = new MailMessage() //To/From address
                {
                    Subject = "This is subject."
                    Body = "This is text."
                };

                    if (uploadedImage != null && uploadedImage.ContentLength > 0)
                    {
                        System.Net.Mail.Attachment attachment;
                        attachment = new System.Net.Mail.Attachment(uploadedImage.InputStream, uploadedImage.FileName);
                        message.Attachments.Add(attachment);
                    }
                message.IsBodyHtml = true;

                var smtpClient = new SmtpClient();
                //SMTP Credentials
                smtpClient.Send(message);
                return true;
            }
            catch (Exception ex)
            {
            //Logg exception
                return false;
            }
        }

*

*The uploadedImage is not null.

*ContentLength is 1038946 bytes (correct size).

However, the email that is being sent contains the image as an attachment with correct filename, although it's size is 0 bytes.
What am I missing?

A: The second parameter of constructor of System.Net.Mail.Attachment is not the file name. It's the content type.
And perhaps ensure your stream position is 0 before to create attachment

A: @ChrisRun,

*

*You should change the parameter HttpPostedFileBase as byte[] for example. This way you could re-use your class in more places.

*Try changing FileName for ContentType and add the  MediaTypeNames.Image.Jpeg.

*Also, add the using directive for dispose the MailMessage and SmtpClient
    using (var message = new MailMessage
    {
        From = new MailAddress("from@gmail.com"),
        Subject = "This is subject.",
        Body = "This is text.",
        IsBodyHtml = true,
        To = { "to@someDomain.com" }
    })
    {
        if (imageFile != null && imageFile.ContentLength > 0)
        {
            message.Attachments.Add(new Attachment(imageFile.InputStream, imageFile.ContentType, MediaTypeNames.Image.Jpeg));
        }

        using (var client = new SmtpClient("smtp.gmail.com")
        {
            Credentials = new System.Net.NetworkCredential("user", "password"),
            EnableSsl = true
        })
        {
            client.Send(message);
        }
    }

Cheers


text:
Q: Finding a biggest (in terms of dimension) vector space in a finite set I previously asked a similar question to this but noticed that the formulation was slightly different than what I am interested in, therefore I ask for any useful information on this problem (by any useful information I mean any mention of this problem in literature, lower bounds to complexity, complexity analysis and even intuitions on how to efficiently approach this problem).
The formulation of the problem I am interested in is as follows (pay attention that any information on a more general version of this problem is also welcome, such as by considering a generic field instead of GF(2)):
Let $X \subseteq \{0,1\}^n$ be a nonempty set of vectors of length $n \geq 1$ with binary components such that the zero vector $\vec{0}$ having all components equal to $0$ belongs to $X$. Along with the sum $\oplus$ defined as the component-wise xor (modulo 2 sum) of two vectors (i.e. consider the usual GF(2) field), i.e. let $x_i, y_i$ be the $i$-th component of $\vec{x}, \vec{j}$ respectively, then
$$
(\vec{x} \oplus \vec{y})_i :=\quad  x_i + y_i\quad\text{(mod 2)}
$$
Find: a subset of $X$ which is a vector space and has maximum size (in terms of cardinality, or equivalently, dimension).
A few things to note:

*

*The existence of a solution is trivial, since the set $X$ is finite and the vector space $\{\vec{0}\}$ is contained in $X$.

*There might be multiple subsets which have the same maximal cardinality (i.e. the solution might not be unique), if that is the case, picking any such set is enough.

One approach to giving a lower bound to the solutions' size is by observing that whenever $|X| \geq 2$ then any solution $S$ is such that $|S| \geq 2$, since at least one vector space with dimension 1 is guaranteed to be contained in $X$. This approach can probably be extended to a general bound but I feel this gives a very loose lower bound on the size of the solution.
My belief is that this problem might be NP-hard, I tried to find a reduction from some known problems (CLIQUE, SAT) but with no success. I also find it strange that while the "dual" problem asking for the smallest vector space containing a given set is well known in literature, this one has no mentions (afaik).
As a final remark on how this problem differs from the previous one, intuitively, one subset of $X$ might be such that it cannot be "expanded' with any new element of $X$, but still have a cardinality smaller than some other subset which constitutes a vector space, that is, is maximal in terms of set inclusion, but not in terms of dimension.


text:
Q: how to combine rows in a dataFrame based on a condition in pyspark I have to process a dataframe containing logs (entry and exit) for an application
The data is given below:
USER | DATETIME        | IN_OUT
---------------------------------
0002  2018/08/28 12:00   IN

0002  2018/08/28 12:20   OUT

0003  2018/08/28 13:00   IN

0003  2018/08/28 14:20   OUT

0003  2018/08/28 15:00   IN

0003  2018/08/28 16:00   OUT

How can the rows containing 2 session be combined to produce
USER | DATETIMEIN       | DATETIMEOUT        | SESSIONTIME[Minutes]
-------------------------------------------------------
0002    2018/08/28 12:00   2018/08/28 12:20        20

0003    2018/08/28 13:00   2018/08/28 14:30        90

0003    2018/08/28 15:00   2018/08/28 16:00        60

A: if you can ensure that an IN is always followed by an OUT event, you can use the following code (I included a check for IN and OUT, but it will not work if IN and OUT are not alternating).
from pyspark.sql.window import Window as W
test_df = spark.createDataFrame([
    (2,datetime.datetime(2018,8,28,12,00), "IN"),(2,datetime.datetime(2018,8,28,12,20), "OUT"),(3,datetime.datetime(2018,8,28,13,00), "IN"),(3,datetime.datetime(2018,8,28,14,20), "OUT"),(3,datetime.datetime(2018,8,28,15,00), "IN"),(3,datetime.datetime(2018,8,28,16,00), "OUT")
    ], ("USER", "DATETIME", "IN_OUT")) # creation of Dataframe

w = W.partitionBy("USER").orderBy("DATETIME") #order by datetime and process every user separately
get_in= when((lag("IN_OUT", 1).over(w) == "IN") & (col("IN_OUT")=="OUT"), lag("DATETIME",1).over(w)).otherwise(None) # apply the window and if the previous event was IN preserve the time

test_df.withColumn("DATETIMEIN",get_in.cast("timestamp")).withColumn("DATETIMEOUT",col("DATETIME")).filter((col("DATETIMEIN").isNotNull())).withColumn("SESSIONTIME[Minutes]",(col("DATETIME").cast("long")-col("DATETIMEIN").cast("long"))/60).select("USER","DATETIMEIN", "DATETIMEOUT", "SESSIONTIME[Minutes]").show() #apply the function and compute the difference to previous IN_TIME

Result:

+----+-------------------+-------------------+--------------------+
|USER|         DATETIMEIN|        DATETIMEOUT|SESSIONTIME[Minutes]|
+----+-------------------+-------------------+--------------------+
|   3|2018-08-28 13:00:00|2018-08-28 14:20:00|                80.0|
|   3|2018-08-28 15:00:00|2018-08-28 16:00:00|                60.0|
|   2|2018-08-28 12:00:00|2018-08-28 12:20:00|                20.0|
+----+-------------------+-------------------+--------------------+


text:
Q: Executing spark sql in aws glue returns the column name in the queries rather than values running spark sql in aws glue returns the column name in the queries
data:

product,price,quantityinKG

mango,100,1

apple,200,3

peach,200,2

mango,200,2

My Test Query
         eg : select product,sum(price)

              from myDataSource

              group by product

The output of the query should be
            product, sum(price)

            mango, 300

but output is :
            product, "sum(price)"

            mango,

There is nothing in the sum(price) column it only has the  product nane , please can you help me with this behaviour of glue

A: First of all, create or replace a local temporary view with your dataframe and then use the sql query
data.createOrReplaceTempView('data_table')
spark.sql("select product, sum(price) as sum_price from data_table group by product").show()

If you are using the glue dynamic dataframe, then first convert it into a spark dataframe using toDF() function before creating the temp view.


text:
Q: XML : faxterxml can't deserialize xml element with ignoring xml attribute I'm trying to deserialize XML with fasterxml library and I encounter an error during the parsing of the xml attribute as below.
the bean :
@XmlAccessorType(XmlAccessType.FIELD)
@Data
public class Product {
    public int id;
    public int id_manufacturer;
}

the xml :
<product>
   <id><![CDATA[1]]></id>
   <id_manufacturer xlink:href="http://localhost:8080/api/manufacturers/1"><![CDATA[1]]></id_manufacturer>
</product>

the dependency :
implementation group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.7.4'

the execution :
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
System.out.println(xmlMapper.readValue(XML_STRING, Product.class));

the exception :
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `int` from Object value (token `JsonToken.START_OBJECT`)
 at [Source: (File); line: 4, column: 81] (through reference chain: come.has.you.are.Product["id_manufacturer"])

Any ideas ?
Of course, I've tried the annotation @JsonIgnoreProperties(ignoreUnknown = true)

A: Here is your problem:
CDATA is a String value, not an int value.
Note: CDATA is short for "Character Data".
Option 1: Change your Product class.  For example,
@XmlAccessorType(XmlAccessType.FIELD)
@Data
public class Product2
{
    public String id;
    public String id_manufacturer;
}

Option 2: Add String setters
@XmlAccessorType(XmlAccessType.FIELD)
@Data
public class Product
{
    public int id;

    @JsonProperty("id_manufacturer")
    public int idManufacturer;

    public void setId(final String value)
    {
        if (StringUtils.isNumeric(value))
        {
            id = Integer.valueOf(value).intValue();
        }
    }

    public void setIdManufacturer(final String value)
    {
        if (StringUtils.isNumeric(value))
        {
            idManufacturer = Integer.valueOf(value).intValue();
        }
    }
}

Note: id_manufacturer is a tag name,
but is not a java field name.


text:
Q: Uniqueness condition for Hamilton-Jacobi equation? Let $f= f(t,x) : \mathbb{R}_+ \times \mathbb{R}^d \to \mathbb{R}$ be a Lipschitz function such that
$$
\partial_t f - |\nabla f|^2 = 0 \qquad \text{almost everywhere in } \mathbb{R}_+ \times \mathbb{R}^d.
$$
As is well-known, this condition does not determine the function $f$ uniquely in terms of the initial condition $f(0,\cdot)$; but uniqueness is restored if we impose in addition that for every $t \ge 0$, the mapping $x \mapsto f(t,x)$ is convex (or locally semiconvex). I want to assume instead that, for every $t \ge 0$, the mapping $x \mapsto f(t,x)$ is concave. Under this condition, is the function $f$ determined uniquely in terms of $f(0,\cdot)$? The answer is "no", because for instance (say in $d = 1$) the function $(t,x) \mapsto t-|x|$ satisfies the required properties, but one can check that this is not the solution given by the Hopf-Lax formula. However, I struggle to find a counter-example if there is no kink in the initial condition to start with. So here is my question.

Assume that $f$ is a Lipschitz function that satisfies the equation above at every point of differentiability of $f$; that for every $t \ge 0$, the mapping $x \mapsto f(t,x)$ is concave; and that the mapping $x \mapsto f(0,x)$ is smooth. Does the initial condition $f(0,\cdot)$ determine the function $f$ uniquely?

A: Proposition A.2 of https://arxiv.org/abs/2104.05360 shows that the answer is "yes". In fact, this is also valid for a general nonlinearity in the equation in place of the squared norm here.


text:
Q: Android emulator device does not open devices with google play sign in it Android emulator device does not open devices with google play sign in it, it opens devices without google play sign. But the problem stays in black screen when I open devices with google play sign
enter image description here


text:
Q: GC collects a still referenced object I need to solve a mathematical model for concentration in a particle and excel is the UI for the parameters.
I made a dll library in vb.net that has 3 classes: Particle, ParticleMix
InteropParticleMix.
Particle based on it's properties have a sub that calculates the concentration in the next step by a simple euler method.
ParticleMix is a class that have a dictionary of Particle, double representing the mass fraction of each particle in the mixture and properties calculating the weighted average of the properties.
InteropParticleMix inherits ParticleMix, it creates 3 Particles on creation saving them on 3 fields. In a Sub called Load I add the 3 particles on the dictionary with respective fractions. And last but not least, a function that loops n times calling the next step by a simple euler method saving the concentration of each particle and the average in an array.
Now from VBA-excel I create a new InteropParticleMix, insert every property and call the iterative method storing in a variable that makes a plot.
Everything great with the mathematics and info flow, but 30% of the time the returned value goes nuts. The firsts elements of the array always work, but a random particle goes in a random point to 6553500. I'm assuming this is caused by the GC collecting one of the particles during the iteration. This behavior is for the same input parameters so it's not a divergence or rounding problem.
Already used GC.KeepAlive method on every particle before, inside and after the loop. Any lights?

A: Found it. For better performance some of the properties in the classes were using a parallel.foreach loop to calculate a weighted arithmetic mean on a dictionary of Keys, weight. Example:
Public ReadOnly Property Test As Double
    Get
        Dim dblTest As Double = 1

        Parallel.ForEach(MassFractions.Keys, Sub(s)
                                                 dblTest += s.Test * MassFractions(s)
                                             End Sub)
        Return dblTest
    End Get
End Property

But for some reason, this leads to some unexpected behaviour on event listeners and references. Changing to a not parallel loop solved the issue. Solved example:
    Public ReadOnly Property Test As Double
    Get
        Dim dblTest As Double = 0

        For Each s As Substance In MassFractions.Keys
            dblTest += s.Test * MassFractions(s)
        Next

        Return dblTest
    End Get
End Property


text:
Q: How to validate Array of Objects in Mongoose I need to validate the array of objects in my schema
Schema:
user: [{
name: String,
Age: String,
Contact: Number
}]

How to validate name, age and contact.

A: I assume your user array is inside another schema.
Let's say we have a Course model with users like this:
const mongoose = require("mongoose");

const courseSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  users: [
    {
      name: { type: String, required: [true, "Name is required"] },
      age: { type: Number, required: [true, "Age is required"] },
      contact: { type: Number, required: [true, "Contact is required"] }
    }
  ]
});

const Course = mongoose.model("Post", courseSchema);

module.exports = Course;

To validate this in a post route you can use mongoose model validateSync method:
const Course = require("../models/course");

router.post("/course", async (req, res) => {
  const { name, users } = req.body;

  const course = new Course({ name, users });

  const validationErrors = course.validateSync();

  if (validationErrors) {
    res.status(400).send(validationErrors.message);
  } else {
    const result = await course.save();
    res.send(result);
  }
});

When we send a requset body without required fields like age and contact:
(you can also transform validationErrors.errors for more useful error messages.)
{
    "name": "course 1",
    "users": [{"name": "name 1"}, {"name": "name 2", "age": 22, "contact": 2222}]
}

The result will be like this:
Post validation failed: users.0.contact: Contact is required, users.0.age: Age is required

A: It will be similar to the usual validation but inside an array, you need to make a validator function as so:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

//the custom validation that will get applied to the features attribute.
var notEmpty = function(features){
    if(features.length === 0){return false}
    else {return true};
}

var CarSchema = new Schema({
    name: {
        type: String,
        required: true,
    },
    features: [{
        type: Schema.ObjectId,
        ref: Feature
        required: true; //this will prevent a Car model from being saved without a features array.
        validate: [notEmpty, 'Please add at least one feature in the features array'] //this adds custom validation through the function check of notEmpty.
    }]
});

var FeatureSchema = new Schema({
    name: {
        type: String,
        required: true //this will prevent a Feature model from being saved without a name attribute.
    }
});

mongoose.model('Car', CarSchema);
mongoose.model('Feature', FeatureSchema);

A: By using type key/property:
var breakfastSchema = new Schema({
  eggs: {
    type: Number,
    min: [6, 'Too few eggs'],
    max: 12
  },
  bacon: {
    type: Number,
    required: [true, 'Why no bacon?']
  },
  drink: {
    type: String,
    enum: ['Coffee', 'Tea'],
    required: function() {
      return this.bacon > 3;
    }
  }
});


text:
Q: Ubuntu 19.10 Grub options not shown I just installed ubuntu 19.10 today. it's succesfully installed and i can enter ubuntu and windows 10. however, the options for the menut not shown. I have to press a down arrow and enter in blank screen to enter windows (it means the grub option is running but there is no disply).
What I have done:

*

*boot repair

*Change GRUB_TIMEOUT_STYLE=menu and GRUB_TIMEOUT=10

*use this bcdedit /set "{bootmgr}" path \EFI\ubuntu\grubx64.efi  in windows

but nothing change...
do you have another suggestion how to show grub menu
Thank you

A: I have the same problem, it seems like the signed version of grub shimx64.efi can't load any font. To show the menu I renamed the file unicode.pf2 in /boot/efi/EFI/ubuntu/fonts. This way grub2 will use system font, the drawback is that you will see question marks in place of extended chars. The unsigned version of grub grubx64.efi works well but it can't load unsigned kernels even though secure boot is disabled.

A: I have the problem also.
On the very same machine I have a hard disk with Ubuntu 18.04 installed on it alongside same copy of Windows also. This disk is fine when used and the Grub menu shows.
if I switch disks, no more menu...
I will try to see what is the font problem by checking both fonts on both disks.
BTW, I have another machine running also secure boot and 19.10 and the menu displays fine (but the machine is a different make and different EFI Bios)
Update :
As I have some machines running Ubuntu 18-04 and Secure Boot, I checked the file unicode.pf2. They are different in 18.04 and 19.10.
I tried to use the file from 18.04 in lieu of the file which came from 19.10. Same result.
So for now, rename /boot/grub/unicode.pf2 to something else and also /boot/grub/fonts/unicode.pf2 and the menu will show. Albeit with an ugly face.
Next step is to see what Grub2 package is used in 18-04 and 19-10 and see if we can safely switch from the new back to the old....


text:
Q: can't get correct results from this jquery object I have the following bit of javascript and have tried a number of different ways to get the text from the div with the class dvservicestitle, and any li tags in the div with the dvservicescontent class. Neither work and I'm not sure why. Anyone have an idea what's wrong with this code?
if (html == "") html = "
Our Services

";

var title = $(html).find(".dvservicestitle");
var elements = $("dvservicescontent li", $(html));

A: you can use:
var title = $(".dvservicestitle").text();
var elements = $(".dvservicescontent li").text();

A: The reason is because the find() method finds children nodes on the current node. Your HTML variable IS the div that you are looking for so the find() method doesn't find it. You need to wrap it in another container.
html = "
Our Services

";
$(html).find(".dvservicestitle")
>> []

$(html).hasClass("dvservicestitle")
>> true

html = "

Our Services

"

$(html).find(".dvservicestitle")
>> [
Our Services
]

A: .find searches descendants which you don't have. The div to search exists at top level, so it is one of the elements in the jQuery object.
Use .filter to filter the correct element:
$(html).filter(".dvservicestile").text();

A: var title = $(html).find(".dvservicestitle").html();
var elements = $(html).find('.dvservicescontent ul').children();


text:
Q: HTML Tables, Table Headers I have an array of size n. Each element of the array is a table header:
<th> "array[0]" </th>

<th> "array[1]" </th>

...

<th> "array[n]" </th>

How can I automatically create n table headers without LITERALLY writing all that? Like a loop that goes over the array and create a table header with each element of the array.

A: Using PHP as your comment indicated, you can do something like this:
foreach ($array as $header) {
    echo "<th>$header</th>";
}

See this site for a more complex tutorial: http://www.tizag.com/phpT/forloop.php
and here for more on foreach: http://www.php.net/manual/en/control-structures.foreach.php


text:
Q: Building Flink application mode without using Flink base image I found Flink's application deployment is opinionated and inflexible. For example:

*

*Some dependencies need to be marked as provided since they are bundled within the Docker image or the Flink's base image.

*If I want to change log4j layout type, I need to change Flink client's local file.

*Environment variables and k8s secrets need to be passed in via the deployment command's options, which can get very long.

How do I build a Flink application to run on application mode without using Flink as base image? Ideally, an application where all dependencies are managed in 1 place, log configuration is baked into the app and k8s deployment yaml where env vars and secrets can be specified and the base image provides only JDK/JRE.


text:
Q: Override the compiler prefix generated by autotools I have a suite of small programs and libraries that run on several embedded systems running different platforms that our company uses. One of the platforms uses a gcc 2.95.3 compiler with gcc being ppc_405-gcc, which obviously doesn't match the conventional modern naming scheme for gcc cross compilers (e.g. i686-pc-linux-gnu). I want to use autotools to create a new program to target these PowerPC boards running an old version of BusyBox linux running a 2.4 series kernel. The flags I use are : --build=i686-pc-linux-gnu --host=powerpc-none-linux  --target=powerpc-none-linux and when Autotools runs it searches for powerpc-none-linux-g++ et al. Is there any way to override the tool prefix so that it searches for ppc_405-gcc et al ?

A: You can just tell it:
./configure CC=ppc_405-gcc CXX=ppc_405-g++ LD=ppc_405-ld STRIP=ppc_405-strip ...


text:
Q: error installing graphviz 2.40.1 app on mac os 10.13.6 with xcode 10 Here is the terminal log. Any suggestions?

Last login: Tue Sep 18 18:31:24 on console Marks-MacBook-Pro:~
  markklein$ brew uninstall graphviz Error: No such keg:
  /usr/local/Cellar/graphviz Marks-MacBook-Pro:~ markklein$ brew install
  graphviz --with-app
  ==> Downloading https://www.mirrorservice.org/sites/distfiles.macports.org/graph
  Already downloaded:
  /Users/markklein/Library/Caches/Homebrew/downloads/1c469743457f48b96f1f3fca3f9444a15736b2840413f31cc7e5f4a6bb5c8510--graphviz-2.40.1.tar.gz
  ==> ./configure --prefix=/usr/local/Cellar/graphviz/2.40.1 --without-qt --with-q
  ==> make install
  ==> xcodebuild SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/MacO Last
  15 lines from
  /Users/markklein/Library/Logs/Homebrew/graphviz/03.xcodebuild:    25
  libdyld.dylib                       0x00007fff55528015 start + 1  26
  ???                                 0x0000000000000015 0x0 + 21 )
  libc++abi.dylib: terminating with uncaught exception of type
  NSException Command CompileXIB failed with a nonzero exit code
** BUILD FAILED **
The following build commands failed:  CompileXIB
  /tmp/graphviz-20180918-1135-ze21bq/graphviz-2.40.1/macosx/English.lproj/MainMenu.xib
    CompileXIB
  /tmp/graphviz-20180918-1135-ze21bq/graphviz-2.40.1/macosx/English.lproj/Export.xib
    CompileXIB
  /tmp/graphviz-20180918-1135-ze21bq/graphviz-2.40.1/macosx/English.lproj/Document.xib
    CompileXIB
  /tmp/graphviz-20180918-1135-ze21bq/graphviz-2.40.1/macosx/English.lproj/Attributes.xib
  (4 failures) /usr/local/Homebrew/Library/Homebrew/utils/fork.rb:49:in
  write': Broken pipe (Errno::EPIPE)   from
  /usr/local/Homebrew/Library/Homebrew/utils/fork.rb:49:inputs'   from
  /usr/local/Homebrew/Library/Homebrew/utils/fork.rb:49:in rescue in
  block (3 levels) in safe_fork'    from
  /usr/local/Homebrew/Library/Homebrew/utils/fork.rb:31:inblock (3
  levels) in safe_fork'     from
  /usr/local/Homebrew/Library/Homebrew/utils/fork.rb:30:in fork'   from
  /usr/local/Homebrew/Library/Homebrew/utils/fork.rb:30:inblock (2
  levels) in safe_fork'     from
  /usr/local/Homebrew/Library/Homebrew/utils/fork.rb:27:in open'   from
  /usr/local/Homebrew/Library/Homebrew/utils/fork.rb:27:inblock in
  safe_fork'    from
  /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/tmpdir.rb:89:in
  mktmpdir'    from
  /usr/local/Homebrew/Library/Homebrew/utils/fork.rb:26:insafe_fork'
    from /usr/local/Homebrew/Library/Homebrew/formula_installer.rb:719:in
  build'   from
  /usr/local/Homebrew/Library/Homebrew/formula_installer.rb:311:in
  install'     from
  /usr/local/Homebrew/Library/Homebrew/cmd/install.rb:321:in
  install_formula'     from
  /usr/local/Homebrew/Library/Homebrew/cmd/install.rb:253:inblock in
  install'  from
  /usr/local/Homebrew/Library/Homebrew/cmd/install.rb:251:in each'
    from /usr/local/Homebrew/Library/Homebrew/cmd/install.rb:251:in
  install'     from /usr/local/Homebrew/Library/Homebrew/brew.rb:89:in
  `'
READ THIS: https://docs.brew.sh/Troubleshooting
Marks-MacBook-Pro:~ markklein$

A: Try this:
-update Xcode from App store
-open Xcode from the applications and accept any new terms
-brew upgrade
-brew uninstall graphviz
-brew install graphviz --with-app


text:
Q: Application linked to msvcp140d instead of msvcp140 In short, Question is how to link application towards MSVCP140.dll instead of MSVCP140D.dll ?
Description:
While porting application to Windows XP encountered the following issue:
Application failed to start because MSVCP140D.dll was not found.
Target is Windows XP Professional 2002 SP 3 with Microsoft Visual C++ Redistributable for Visual Studio 2017 installed
Host is Windows 10 with Visual Studio 2017
I verified that MSVCP140D.dll is missed on target, but MSVCP140.dll is present.
I tried both Release|Debug Configuration and also MDd|MD Runtime Library configurations.
Platform Toolset is set to v141_xp


text:
Q: Git branch experiment Here's an interesting experiment with using Git. Think of Github's 'pages' feature: I write a program in one branch (e.g. master), and a documentation website is kept in another, entirely unrelated branch (e.g. gh-pages).
I can generate documentation in HTML format from the code in my master-branch, but I want to publish this as part of my documentation website in the gh-pages branch.
How could I intelligently generate my docs from my code in master, move it to my gh-pages branch and commit the changes there? Should I use a post-commit hook or something? Would this be a good idea, or is it utterly foolish?

A: You could 'git stash' your generated files and apply then on the relevant branch
git checkout master
#generate doc
git stash save
git checkout gh-pages
git stash pop

Update August 2016: Simpler GitHub Pages publishing now allows to keep your page files in a subfolder of the same branch (no more gh-pages needed):

You can now keep your doc up-to-date with your code in a subfolder of the same branch.

A: What would be the advantage of having generated files under version control? And if you insist on this, what would be the advantage of having generating and generated files in the same repository? git's branching support is fantastic, but I am sure it wasn't designed to do what you are trying to do.


text:
Q: B is significant correlated with Y, but not a significant predictor of Y in a multiple regression. What can it mean? I'm working on a paper and I have some problems explaining some of my findings. I have four independent variables, let's call them A,B,C,D. And i have one dependent variable, let's call it Y.
In my correlation analysis I have these correlations between the dependent variable (Y) and the four independent (A,B,C and D).
Y -- A=0.54*, B=0.29* C=0.44* D=-.08
I then did a multiple regression analysis, where i used the four independent variables to predict the dependent variable. My model was significant, and with a high F value. But my Standardized coefficient estimates between the variables are different.
Y-- A=.40* B=.08 C=.22* D=-.13*
As you can see D is now a significant predictor of Y, and at the same time B is not. I have checked for multicollinearity, and all looks good (to the best of my knowledge). I understand that there most be some underlying relationship between the independent variables, but how do you find it and explain it?
Note: I have read some similar questions here, but I don't find them covering the same question I have.

A: It appears that your predictors share a particular type of multi-colinearity known as suppression. Suppression refers to a pattern of multi-colinearity that results in a larger or reversed effect in multiple regression compared to simple regression. Since the partial correlation of D is larger (and sig.) in the multiple regression case than in the simple regression case we know that the unique effect of D that is not shared with the other predictors was being "suppressed" in the simple regression case.
Remember that whereas simple regression presents a "total" effect of your single predictor, multiple regression yields the "unique" effect of each predictor after partialing out any shared explanatory power. For example, if we wanted to estimate children's weights from their heights and ages, height and age likely explain a lot of the same variability in weight because taller children tend to be older.
To illustrate suppression, let's say we wanted to predict children's weights using age and number of hours involved in organized sports to predict weight. What we might imagine is that older children tend to be involved in more sports (i.e. age and # hours are positively correlated). We might also reason that children who are involved in more organized sports tend to weigh less than children who are not involved in organized sports. However, since age and involvement in organized sports are positively correlated, some part of the # hours-weight relationship is really driven by the relationship between age and weight (which is positive). Since both this positive correlation and negative correlation are going into the overall correlation between # hours and weight, the total effect may appear smaller than the partial effect. Here is a visual representation of this:

Each circle represents one of the variables in the example. The dotted line within the two predictor circles separates out the portion of that predictor that shares explanatory power with the other predictor. The small portion of the # hours circle is the portion of explanatory power that is is shared with age. The dotted lines represent the portion of the total effect of a predictor that is really driven by the other predictor. For example, the dotted line with the + symbol is the part of the # hours simple relationship that is really driven by child age. The solid lines represent the partial correlation of that predictor with the outcome over and above any shared explanatory power of the two predictors. The total effect would be a combination of the dotted and solid lines stemming from the same predictor variable. As we can see, the + and - relationships would sort of wash each other out. Thus, the partial correlation would be stronger than the simple correlation. The way that suppression works with more than 2 predictors gets a bit more complicated, but I bet there is some overall relationship among your predictors. If you calculate (or ask the computer to calculate) tolerance, this should help you know what's going on. Tolerance varies from 0 to 1 and tells you the extent to which your predictors are orthogonal. 1 indidicates that there is no multicollinearity and 0 indicates that there is complete multicolinearity (fun fact, if you regressed D on A, B and C the $R^2$ you would obtain would be 1-tolerance). Since there are more than 2 predictors, the multi collinearity issue is more complex than just, "are there simple relationships among my predictors". As such, I think tolerance would be a better measure of this. In terms of explaining why such suppression exists, I would think about the simple example above and consider whether it would make sense that such a phenomenon is happening with your own data.  Hope this is helpful!
A tolerance of .67 means that something like 33% of the variability in one of your predictors is explained by the other 3 predictors. This seems, to me, like a non trivial amount of redundancy.

A: Are the results that you show for the multiple regression really correlations? or are they the coefficient estimates?
With your check on multicolinearity, what did you see?  was there some relationship, just not enough to worry you? or was there really no relationship?
Remember that correlations and simple linear regressions are interpreted very differently from a multiple regression and even moderate relationships between predictor (independent) variables can lead to very different results in coefficient estimates and significance.  If Y is strongly related to the difference between say A and D, then it could be that the relationship between Y and D is not significant without A in the model, but with both A and D in the model, that difference is now part of the model and D becomes significant.  Additionally if B is somewhat related to that difference then you may see that when only B is in the model, but with both A and D in the model, B becomes redundant to the difference and is no longer significant.
Here is a simple example in R that shows with moderate correlation, neither x1 or x2 alone is a significant predictor of y, but including both is very significant:
set.seed(1)
x1 <- rnorm(25)
x2 <- rnorm(25, x1)
y <- x1-x2 + rnorm(25)
pairs( cbind(y,x1,x2) )
cor( cbind(y,x1,x2) )
summary(lm(y~x1))
summary(lm(y~x2))
summary(lm(y~x1+x2))


text:
Q: How to make a search filter in flutter So I'm using an API for the search filter which means that all the logic of the search filter is in the API, My job is to call the search filter API. I have tried to call the search API in the textfield on the onChange event. But the search API won't recognize any single alphabets on the textcontroller. The Search perfectly works, I have tested it, but it didn't work when I display the list.
TextField(

             controller:searchQuery,
               onChanged:(string)
            {
                  setState(() {
                _provider.getSearch(searchQuery.toString());
              });
            },
            decoration: InputDecoration.collapsed(
            hintText: ''
           ),
          ),
         )

It's empty when I tried to search

It actually reads the input that I type when I debug,

When I manually input the parameter it display all the list
Container(
           margin: EdgeInsets.symmetric(vertical: 10,horizontal: 10),
           child:TextField(

             controller:searchQuery,
               onChanged:(string)
            {
                  setState(() {
                _provider.getSearch("r");
              });
            },
            decoration: InputDecoration.collapsed(
            hintText: ''
           ),
          ),
         )

A: searchQuery.toString() to searchQuery.text or use string variable of onChanged method.


text:
Q: using .htaccess to block tor servers I have a large list of tor servers, maybe 2,000+ servers that I would like to ban from registering accounts on my site. Is it viable to block the entire list I have in an .htaccess file or will this cause the server to slow down in the same way having thousands of hosts in iptables will?
Is there another alternative? I have captcha already but bots aren't the problem. The problem is users using tor to circumvent bans.

A: You can use your htaccess file
order deny,allow
deny from x.x.x.x
deny from x.x.x.
allow from all

The alterative (and probably best) way is adding a DROP rule in your iptables firewall, which will keep the IP addressess away from your server.


text:
Q: Sum the first dimension of a 3D numpy array I have the following 3D numpy.array of shape (2,3,3):
import numpy as np

arr = np.array(((((1,2,3),(9,8,7),(6,5,4))),
                (((10,20,30),(90,80,70),(60,50,40)))))

I want to sum the first dimension and get one 2D array of shape (3,3).
Expected output:
array([[11, 22, 33],
       [99, 88, 77],
       [66, 55, 44]])

I know I can iterate over the elements in the first dimension and sum, with something like this:
for el in range(len(arr)):
    if el == 0:
        arr_sum = arr[el]
    else:
        arr_sum += arr[el]

But there is another option to do this?
Thanks in advance.

A: You can use, NumPy.sum method.
import numpy as np
arr = np.array(((((1,2,3),(9,8,7),(6,5,4))),(((10,20,30),(90,80,70),(60,50,40)))))

print(np.sum(arr, axis=0))


text:
Q: Angular ngrx and Resolver. Find Observable object from observable array by property value I have a resolver that needs to return Organization details from the api service. At the same time we are using ngrx to store the details of all organizations.
I want my resolver to look into the ngrx store:
- populate it with list of Organizations if it is empty
- find Organization with specific id from the ngrx store and return it.
The way i am trying to do it now:
resolve(route: ActivatedRouteSnapshot): Observable<Organization> {

const organizationId = route.paramMap.get(RouterHelperService.urlParam.organizationId);
this.initOrganizationsData();

const company = this.store.select(store => store.companies)
  .filter(state => state && state.length > 0 && state.filter(c => c.id === organizationId).length > 0)
  .take(1)[0];

return company;
}

and here is the method initOrganizationsData():
private initOrganizationsData(): void {
this.store.take(1).subscribe(store => {
  if (store.companies.length === 0) {
    this.organizationService.getOrganizations().subscribe(data => {
      this.store.dispatch(new companyActions.LoadCompaniesSuccessAction(data));
    });
  }
});

}
At the moment I always get the the result Company is undefined.
Can anyone point me into the right direction. What is wrong? How to get Observable<Organization> from Observable<Organization[]> with specific value?


text:
Q: Find a string and get the numerical value to the right of it I am trying to create a VBA code that when runs, find a certain string in column x but then gets the value to the right of the string in column y. If anyone could help that would be great thanks

A: You will need to adapt this but I see two ways of doing.  Without knowing the answer, you could just use formulas.
Formula
Use a VLOOKUP ... Cell D2 = =VLOOKUP(D1,$A$1:$B$20,2,FALSE)

VBA
You need to change the column you want to search and the amount of columns you want to offset by to get the value.
You also need to adapt it to your solution.  I've merely given you the approach and a couple of samples.
Using MATCH ...
Public Sub FindStringAndOffset()
    Dim strToSearchFor As String, lngRow As Long, objSheet As Worksheet
    Dim varValue As Variant, strColToSearchIn As String, lngOffset As Long

    strToSearchFor = "Lookup 8"
    strColToSearchIn = "A"
    lngOffset = 1

    Set objSheet = Sheet1

    With objSheet
        On Error GoTo ExitGracefully:

        lngRow = WorksheetFunction.Match(strToSearchFor, .Range(strColToSearchIn & ":" & strColToSearchIn), 0)
        varValue = .Range(strColToSearchIn & lngRow).Offset(0, lngOffset).Value

        Debug.Print varValue
    End With

ExitGracefully:

End Sub

... or using a VLOOKUP ...
Public Sub FindStringAndOffsetv2()
    Dim strToSearchFor As String, objSheet As Worksheet
    Dim varValue As Variant, strColToSearchIn As String, lngOffset As Long
    Dim strColumnWithOffset As String

    strToSearchFor = "Lookup 8"
    strColToSearchIn = "A"
    lngOffset = 1

    Set objSheet = Sheet1

    With objSheet
        On Error GoTo ExitGracefully:

        strColumnWithOffset = Split(.Range(strColToSearchIn & "1").Offset(0, lngOffset).Address, "$")(1)
        varValue = WorksheetFunction.VLookup(strToSearchFor, .Range(strColToSearchIn & ":" & strColumnWithOffset), lngOffset + 1)

        Debug.Print varValue
    End With

ExitGracefully:

End Sub

There are a heap of ways to skin that cat.


text:
Q: Transparent Context in IOS? I'm displaying an image in a UIScrollView but I want it to blend with a UIImageView which is laid behind the UIScrollView.
I'm currently trying to override - (void)drawRect:(CGRect)rect in a subclass of UIView created to display the image inside the scrollview, using either the method drawInRect:blendMode:alpha: or CGContextSetBlendMode but none worked. I think the reason is that the current context is opaque but I cannot find a workaround.

A: You can add UIImageView as a subclass of UIView (parent view of your scroll view).
You can change opacity of your UIImageView to match your criteria. If you just want a image as a background of your UIView you can set up background of your view and as a colour you can use [UIColor colorWithPatternImage:Your UIImage here].
Is it something you need?
//EXTENDED
I try it and both of the example below set the image as a background and when I scroll the image is not moving:
Example 1:
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"newtons_cradle.jpg"]]];
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    [scrollView setContentSize:CGSizeMake(self.view.bounds.size.width, 1000.0f)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 300, 50)];
    [label setBackgroundColor:[UIColor whiteColor]];
    [label setText:@"Label Test Text"];
    [scrollView addSubview:label];
    [self.view addSubview:scrollView];

Example 2:
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
[imageView setImage:[UIImage imageNamed:@"newtons_cradle.jpg"]];
[self.view addSubview:imageView];

UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
[scrollView setContentSize:CGSizeMake(self.view.bounds.size.width, 1000.0f)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 300, 50)];
[label setBackgroundColor:[UIColor whiteColor]];
[label setText:@"Label Test Text"];
[scrollView addSubview:label];

[self.view addSubview:scrollView]

;


text:
Q: How to $_GET array element from URL I have this url:

search.htm?postSearchForm=1&mediaTypes[3]=3

I need to get mediaTypes[3] with $_GET method
This code doesn't work:
$value = $_GET[mediaTypes[3]];

A: You should write
 $value = $_GET['mediaTypes'][3];

And don't forget to filter the data, for example
 if (ctype_digit($_GET['mediaTypes'][3]))
    $value = $_GET['mediaTypes'][3];