text:
Q: Android automated Integration Testing with Semaphoreci. How to properly set up? https://semaphoreci.com
I have an Android project I'm working on I'm trying to set up automated integration testing on every PR against my master branch on GitHub with semaphoreci.
The question I have is, how can I run the gradle tasks if there is no Android SDK? Do I have to push my Android SDK (really don't wanna)? Or can I point to a compiled Android SDK on a server (possibly Google)?
So far I have it set up semaphoreci to run these commands:
gradle wrapper // Fails here
./gradlew clean
./gradlew build

I get this error
FAILURE: Build failed with an exception.
[0K
* What went wrong:
A problem occurred configuring project ':app'.
> SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

A: I know this is an old topic, but I've recently set this up, myself and figured I'd post the solution here in case someone stumbles upon this post in the future and needs help.
The solution is to install the Android SDK command-line tools. Place the following in the commands: section of your Semaphore script. All of this below may not be strictly necessary, but it works for me when building my own React-Native Android app. Make sure you grab the latest version of the command-line toolset listed here: https://developer.android.com/studio#command-tools. On Semaphore, you want the Linux toolset. The first line of the script installs some suggested prerequisites before grabbing and installing the Android SDK CLI. Then just carry on with the rest of your commands to do whatever else you need to test/build your app.
- echo y | sudo apt-get install libc6-dev-i386 lib32z1 openjdk-8-
- wget https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip
- unzip sdk-tools-linux-4333796.zip
- export ANDROID_HOME=`pwd`
- yes | tools/bin/sdkmanager --update || exit 0
- yes | tools/bin/sdkmanager "platform-tools" "platforms;android-28" || exit 0
- yes | tools/bin/sdkmanager --licenses || exit 0


text:
Q: Reading Files/Folders from disk with FAT12 in Own OS I am developing an OS, I am trying to Implement FAT12 Filesystem from an Other's OS Source Code, Finally, I can Mount a FAT12 Formatted disk and Get its FAT12 Information.
It can Read DriveName ( When 'Location = 0' ).
But When I am trying to List Directories from disk, It is not Working!
Here, This is My Code to Get Directories,
void FAT12_PrintDirectories(uint32_t Location, uint32_t numEntries, uint8_t DriveNum)
{

   uint8_t read[((numEntries*32)/4096)+1];

   AHCI::Port* port = AHCI::GlobalAHCI->ports[0];

   port->Configure();

   port->buffer = (uint8_t*)GlobalAllocator.RequestPage();

   memset(port->buffer, 0, ((numEntries*32)/4096)+1);

   port->Read(Location /* If I write here '0' Instead of Location, then Output is Image2 */, Location+((numEntries*32)/4096)+1, port->buffer);

   for (int n = 0; n < sizeof(port->buffer); n++)
   {
        GlobalRenderer->PutChar(port->buffer[n]);
        read[n] = port->buffer[n];
   }

   char drivename[12];

   memset(&drivename, 0, 12);

   memcpy(drivename, read, 8);

    if(read[9] != ' ')
    {

        drivename[8] = '.';

        memcpy(drivename + 9, read + 8, 3);

    }

    drivename[11] = 0;

    // Print test read

    GlobalRenderer->Next();

    for (int n = 0; n < sizeof(read); n++)
    {
        GlobalRenderer->Print("=");
        GlobalRenderer->Print(to_string((uint64_t)read[n]));
    }

    GlobalRenderer->Next();
    GlobalRenderer->Print("Listing Dirs!");

    GlobalRenderer->Next();
    GlobalRenderer->Print("DriveName : ");
    GlobalRenderer->Print(drivename);
    GlobalRenderer->Next();

    uint8_t *reads = read;

    GlobalRenderer->Print("Dirs : ");
    GlobalRenderer->Next();

    for (unsigned int i = 0; i < numEntries; i++)
    {

        if(!reads[11] & 0x08 || reads[11] & 0x02 || reads[0] == 0 || reads[0] == 0xE5)
        {

            // Print FileName
            for (uint8_t j = 0; j < 11; j++)
            {

                if(j == 8 && reads[j] != ' ')
                {
                    GlobalRenderer->Print(".");

                }

                if(reads[j] != 0x20)
                {
                    GlobalRenderer->Print(to_string((uint64_t)reads[j]));

                }

                if(reads[11] & 0x10 && j == 10)
                {

                    GlobalRenderer->Print("/");

                }

                uint32_t nextCluster = (reads[27] << 8) | reads[26];

                uint32_t size = *(uint32_t *)&reads[28];

            }

            reads += 32;

        }

        GlobalRenderer->Print("-");

    }

}

Here It is my Calling Code for that function FAT12_PrintDirectories(dirOff, 32, 0);
This time dirOff = 2097153
Output :
After 'Dirs' text - Image1

Image2

Location =          ((FAT12_MOUNT *)getDiskMount(numActiveMounts).mount)->RootDirectoryOffset*512+1;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating OCaml binding from C++ with Swig I am creating a C++ package with just about everything being wrapped in a class and am testing out using Swig to create different bindings for my project. Right now I am looking into the process for OCaml using the documentation here as the main point of reference. I am fairly new to OCaml and Swig but I was able to successfully create the binding for Python with no hiccups but when trying for OCaml I am running into issues with using camlp4(I believe this is the default for swig so I did not bother with camlp5). I am running into issues specifically when running the following:
$ ocamlmktop -custom swig.cmo -I `camlp4 -where` camlp4o.cma swigp4.cmo example_wrap.o example.cmo -o example

I get the error
Error: Module `Dynlink' is unavailable (required by `Camlp4')

Before trying to use the Camlp4 util in my Swig process I was running the following to successfully compile the OCaml module:
    swig -c++ -ocaml -co swigp4.ml
    swig -c++ -ocaml example.i
    for file in swig.mli swig.ml swigp4.ml ; do swig -ocaml -co $$file ; done
    swig -ocaml -co swig.mli ; swig -ocaml -co swig.ml
    ocamlc -c swig.mli ; ocamlc -c swig.ml
    cp example_wrap.cxx example_wrap.c
    ocamlc -c -ccopt -xc++ example_wrap.c
    ocamlc -c example.mli
    ocamlc -c example.ml

The issue with this was trying to figure out calling the objects of my class within the top level. Since I am a beginner in the land of OCaml and functional programming as a whole, I am of course curious how to go about calling class methods of my original C++ code in OCaml after complete the Swig binding process (without camlp4)
Does anyone have experience with the C++->OCaml binding process using Swig have some pointers on how to properly perform this?


text:
Q: Remove item from ComboBox (DropDownList) Winforms I have a dropdownlist which has been populated
ddlNumbers.DisplayMember = "PhoneNumber";
ddlNumbers.DataSource = mobileList;
ddlNumbers.SelectedItem = null;

When a button is clicked I want to remove an item from it.
ddlMobileNumbers.Items.RemoveAt(i);

But get the exception. 'Items collection cannot be modified when the DataSource property is set...'
I have also tried re-assigning a collection to the DataSource
ddlNumbers.DataSource = myNewList

But does not work.
What am I doing wrong here?

A: You can't remove an item from a list when its bound to a control, You can temporarily null the data source of the bound control and remove the item from list and then set the data source again.
Something like,
//Null the datasource
Combobox1.Datasource = null;

//Remove the item
ddlMobileNumbers.Items.RemoveAt(i);

//Set the source again
Combobox1.Datasource = ddlMobileNumbers;


text:
Q: Как обновлять recyclerView смещая его ниже самого progres view. Подобному как в инстаграм. Пример обновления в инстаграме.

A: SwipeRefreshLayout из библиотеки Android support — «потяните чтобы обновить»
Он добавляет функционал, который один мой коллега называет «резинка от трусов», а остальные знают этот UI-паттерн под названием «потяни, чтобы обновить». Он бывает нужен, когда есть какой-то контент, который пользователь хочет часто обновлять, и может это сделать, просто потянув контент жестом вниз, а потом отпустив.
Очень похоже, что компонент был создан для GoogleNow, а потом перекочевал в support lib (очень похожа анимация).
Алгоритм простой.
Компонент «оборачивается» вокруг View или Layout, для которого нужно сделать обновление и может содержать только одного потомка (похоже на ScrollView).
Устанавливается OnRefreshListener с одним единственным методом onRefresh(). Как на него реагировать — решаем сами.
Когда нужно показать, что идет обновление (и запустить анимацию), вызываем метод setRefreshing(boolean) и передаем ему true. Наиболее логичным кажется вызов метода внутри onRefresh().
Когда обновление закончено, вызываем метод setRefreshing(boolean) и передаем ему false.
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="@+id/container"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical" />

Логику можете написать тут:
mSwipeRefreshLayout.setOnRefreshListener(new    SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            // Do some logic
            // if (refresh is ok)
            Toast.makeText(getContext(), "Refresh", Toast.LENGTH_SHORT).show();
        }
     });


text:
Q: Reference std::basic_string specialization of string with custom allocator as a constant object of std::string without overhead? Given an object of class std::basic_string<char, std::char_traits<char>,my_allocator<char> >, how would you pass it to a third-party function that expects a constant reference to an object of class std::string without making any copies?
What I am thinking is if we assume a stateless allocator, then, theoretically, two types should be exactly the same in runtime. Therefore, one could simply re-interpret cast the type, for example:
// my_allocator template is some place else...
typedef std::basic_string< char, std::char_traits<char>,
                           my_allocator<char> > my_string;

void third_party_foo(const std::string &s);

int main()
{
    const my_string str = "Hello, world!";
    third_party_foo(*(const std::string *)&str);
}

Given an allocator that has a state (which we can have since C++11), I would assume this is a lot more dangerous since sizes and layout of those classes in runtime could be different. If I am right thus far, let's say that sizes of the object of two classes are the same, in that case I could assume that allocator state fits, say, into some area that would have otherwise been padded, in which case the first approach can work.
How much do I put myself in danger with this approach, practically speaking? Are there any  alternatives that do not carry any runtime overhead (and of course do not require changing third-party interface and/or giving up a string with custom allocator)?

A: You don't. By using a custom allocator, you're using a different type from std::string. And there's no (legitimate) way in C++ to convert this without a copy. Anything you think might work will not be guaranteed by the C++ standard.
So you have to accept that you need a copy.


text:
Q: Djagno: Getting objects via ManyToMany "through" model in a single database query Given these models:
class Places(models.Model):
    #...

class Tour(models.Model):
    places = ManyToManyField(A, through='TourPlaces')

class TourPlaces(models.Model):
    tour = ForeignKey(Tour, on_delete=models.CASCADE)
    place = ForeignKey(Place, on_delete=models.CASCADE)
    #...

How can I build a Queryset so that I can get the Tours a Places belongs to on the SQL side without hitting the database repeatedly? Pseudo example:
for place in Places.objects.(some kind of annotation maybe?):
    print(place.tours[0])

Instead of
for place in Places.objects.all():
    print(TourPlaces.objects.get(place=place).tour[0])

Context: My REST Framework ModelSerializer for Places, using the code above in a SerializerMethodField, is too slow.

A: class Places(models.Model):
    first_field = models.CharField(max_length=50)
    second_field = models.CharField(max_length=50)

class Tour(models.Model):
    places = ManyToManyField(A, through='TourPlaces')

class TourPlaces(models.Model):
    tour = ForeignKey(Tour, on_delete=models.CASCADE)
    place = ForeignKey(Place, on_delete=models.CASCADE)

then :
TourPlaces.objects.filter(place__first_field = 'some')

A: I solved this and improved performance a lot by using prefetch_related with the reverse set:
for place in Places.objects.prefetch_related('tour_set').all():
    print(str(place.tour_set.first()))

See https://docs.djangoproject.com/en/2.1/ref/models/querysets/#prefetch-related
My REST view set and model serializer look like this now:
class PlaceViewSet(viewsets.ModelViewSet):
    parser_classes = (JSONParser,)
    serializer_class = PlaceSerializer
    queryset = Place.objects.prefetch_related('tour_set')

class PlaceSerializer(serializers.ModelSerializer):
    tour = serializers.SerializerMethodField('_tour')

    def _tour(self, obj):
        try:
            return str(obj.tour_set.first())
        except:
            return ""

    class Meta:
        model = Place
        fields = (
            '...',
            'tour',
        )


text:
Q: How to change this code in vb.net to show just the time how to convert this code in vb.net to show only time instead of date and time in vb.net
            Dim UTCTime As Date = Date.UtcNow
            Dim IndianTime As DateTime = UTCTime.AddHours(5.5)
            TextBox1.Text = IndianTime

A: Dim UTCTime As Date = Date.UtcNow
Dim IndianTime As DateTime = UTCTime.AddHours(5.5)
TextBox1.Text = IndianTime.ToString("T")
TextBox2.Text = Now.ToString("T")

A: TextBox1.Text = IndianTime.ToString("hh:mm") 'For 12 hr format
TextBox1.Text = IndianTime.ToString("HH:mm") 'For 24 hr format

A: Dim formatString As String = String.Format("{0,HH:mm:ss}", IndianTime)

String.Format reference

A: Try this code
    Dim UTCTime As Date = Date.UtcNow
    Dim IndianTime As DateTime = String.Format("{0:hh:mm}", UTCTime.AddHours(5.5))
    TextBox1.Text = IndianTime
    TextBox2.Text = Now

A: Use a format specifier in ToString() eg:
IndianTime.ToString("hh:mm tt")

Should output the Time only (in 12 hour clock, with AM or PM).
More examples of custom formatting here, and there's a very useful list of Date Time format patterns with examples here.
Whole thing:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim UTCTime As DateTime = DateTime.UtcNow
    Dim IndianTime As DateTime = UTCTime.AddHours(5.5)
    TextBox1.Text = IndianTime.ToString("hh:mm tt")
    TextBox2.Text = Now.ToString("hh:mm tt")
End Sub


text:
Q: Prevent user from returning to previous screen StackNavigator I want to do a simple task: after a successful login redirect the user to his home page. I use react-navigation's StackNavigator for that purpose:
// App.js

class App extends Component {
  render() {
    return (<RootStack />);
  }
}

const RootStack = createStackNavigator(
  {
    Login: { screen: Login, navigationOptions: { header: null }},
    Home: { screen: Home, navigationOptions: { header: null }}
  },
  {
    initialRouteName: 'Root'
  }
)

How do I prevent user from returning to Login screen after login? To prevent use back button in android, I would use this one:
// Home.js

import React, { Component} from 'react';
import { ... , BackHandler } from 'react-native';

class Home extends Component {
    constructor(props) {
        super(props);
        BackHandler.addEventListener('hardwareBackPress', this.onBackButtonPressAndroid);
    }
    onBackButtonPressAndroid = () => {
        return true;
    }
}

But doing this way, I disable back button at all. Is there another way to achieve the goal?

A: The react native documentation has an excellent page on how to make an authentication flow.

You may not be familiar with SwitchNavigator yet. The purpose of SwitchNavigator is to only ever show one screen at a time. By default, it does not handle back actions and it resets routes to their default state when you switch away. This is the exact behavior that we want from the authentication flow: when users sign in, we want to throw away the state of the authentication flow and unmount all of the screens, and when we press the hardware back button we expect to not be able to go back to the authentication flow. We switch between routes in the SwitchNavigator by using the navigate action. You can read more about the SwitchNavigator in the API reference.

According to the documentation, this SwitchNavigator is implemented like this:
import { createSwitchNavigator, createStackNavigator } from 'react-navigation';

// Implementation of HomeScreen, OtherScreen, SignInScreen, AuthLoadingScreen
// goes here.

const AppStack = createStackNavigator({ Home: HomeScreen, Other: OtherScreen });
const AuthStack = createStackNavigator({ SignIn: SignInScreen });

export default createSwitchNavigator(
  {
    AuthLoading: AuthLoadingScreen,
    App: AppStack,
    Auth: AuthStack,
  },
  {
    initialRouteName: 'AuthLoading',
  }
);

So, to achieve what you are looking for, you would want to change your RootStack to the following (note i have not tested this code):
const RootStack = createSwitchNavigator(
  {
    Loading: ,//put your loading screen here
    Auth: { screen: Login, navigationOptions: { header: null }},
    App: { screen: Home, navigationOptions: { header: null }}
  },
  {
    initialRouteName: 'Loading'
  }
)

Then, in your loading screen, you would fetch whatever state is needed to determine if the user is already signed in and you would call either this.props.navigation.navigate('App'); to skip the login screen and take the user directly to your app, or this.props.navigation.navigate('Auth'); to send your user to the login page. the SwitchNavigator automatically handles disabling back navigation for you.


text:
Q: How to use android cam as security surveillance cam for live video streaming like IP Cam app I wanna build an app that will use android camera video and stream it to another android phone or on the web. I don't wanna do it through my Wifi, but i want the cam streaming to be broadcast live anywhere in the world.
Can anyone help me getting an overview of the android classes or APIs that will be helpful doing this task?

A: You can't stream live video from a phone directly to another phone, there are just too many possible differences between any two given devices.
To do this you will need to have a publicly accessible server, (that you have control of) running a streaming engine, such as Woza: https://www.wowza.com/products/streaming-engine The source phone sends video to the server, and the destination phone receives video from the server.


text:
Q: How do i name my index column of the attached dataset? enter image description herePlease i am trying to name the index column but I can't. I want to be a able to name it such that I can reference it to view the index values which are dates. i have tried
df3.rename(columns={0:'Date'}, inplace=True) but it's not working.
Please can someone help me out? Thank you.

A: As there is no example data frame that you are on, I am listing an arbitrary example to demonstrate the idea.
import datetime as dt
import pandas as pd

data = {'C1'     : [1, 2],
        'Date'  : [dt.datetime.now().strftime('%Y-%m-%d'),dt.datetime.now().strftime('%Y-%m-%d')]}
df = pd.DataFrame(data)
df.index = df["Date"]
del df["Date"]

print(df.index.name) # this will give you the new index column

print(df) #print the dataframe

A: Note that the dataframe index cannot be accessed using df['Date'],
I fyou want rename the index, you can use DataFrame.rename_axis:
df=df.rename_axis(index='Date')

if you want to access it as a column then you have to transform it into a column using:
df=df.reset_index()

then you can use:
df['Date']

otherwise you can access the index by:
df.index


text:
Q: Adding dns entry for subdomain in another subdomain I have a now created a subdomain - api.domain.com.
Now I want to create 1.api.domain.com, 2.api.domain.com.
Each pointing to different servers.
Is that possible?
I want to make this happen in aws route 53.

A: Of course you can. 1.api.example.com. is a different name than api.example.com., so all the three can have their own A records.
With AWS Route 53 you can have all of these in the same example.com zone. You'll just use 1.api in the name field.


text:
Q: Метод простой перестановки Как зациклить функцию на столько раз, сколько символов в переменной "key"?
Дан следующий код, где две функции: одна шифрует, другая расшифровывает. Функция "cryp" зашифровывает слово. Функция "encryp" должна расшифровывать, но она ещё не готова. Такая идея: сделать в функции "encryp" цикл, который будет использовать внутри себя функцию "cryp" столько раз, сколько символов в переменной "key" минус один.
Что делает функция "cryp":
Вход:
cif
246531
абсолютность
Выход:
боюлсансьтот
Что должна делать функция "encryp":
Вход:
decif
246531
боюлсансьтот
Выход:
абсолютность
Внутри цикла:
key = 246531
длина key = 6, значит нужно 5 циклов
При первом цикле вывод - 'оласюбсттоьн',
При втором - 'лсбюаотоньтс',
При третьем - 'сюоаблоьстнт',
При четвёртом - 'юалбосьттнсо',
При пятом - 'абсолютность' (Это идёт на выход)
print("Будем шифровать или расшифровывать? cif/decif") #print cif for encryption or decif for decryption
cipher=input()
print("Введите, пожалуйста, ключ: ") #print some int number
key=input()
print("Введите, пожалуйста, ваше предложение: ") #print your sentence for en\decryption
text=input()

def cryp(key, text):
    key_length = len(key)          #отсюда начинается перечисление всего того, что будет задействовано
    q = 0
    i = 0
    j = 0
    x = str()
    ret = []
    p = len(text)//len(key)
    if len(text)%len(key) != 0:
        p=p+1
    matrix = [[0 for x in range(key_length)] for y in range(p)]           #до этого места
    for x in text:              #отсюда идет шифровка
        matrix[i][j] = x
        j = j+1
        if j%key_length == 0:
            j=0
            i=i+1
    i = 0
    j = 0
    while q != p:
        for n in key:
            ret += matrix[q][(int(n))-1]
        q=q+1                     #до этого места
    sret = ''.join(ret)           #здесь перевод массива в строку
    return sret

def encryp(key, text):
    key_length = len(key)           #отсюда начинается перечисление всего того, что будет задействовано
    q = 0
    i = 0
    j = 0
    l = 0
    x = str()
    ret = []
    p = len(text)//len(key)
    if len(text)%len(key) != 0:
        p=p+1
    matrix = [[0 for x in range(key_length)] for y in range(p)]
    txt = text                       #до этого места
    while l != key_length:
        for x in txt:
            matrix[i][j] = x
            j = j+1
            if j%key_length == 0:
                j=0
                i=i+1
        i = 0
        j = 0
        while q != p:
            for n in key:
                ret += matrix[q][(int(n))-1]
            q=q+1
        sret = ''.join(ret)
        txt = sret
        l=l+1
        sret = None
    sret = txt
    return sret

if cipher == "cif":
    print(cryp(key, text))
elif cipher == "decif":
    print(encryp(key, text))
else:
    print("Прошу прощения, но, видимо, где-то ошибка. Надеюсь, вы правильно всё написали. Приношу извинения за сбой!")
#Here is an apology for the fact that you or the program made a mistake somewhere

A: Решил сам
def encryp(key, text):
    key_length = len(key)
    if (key_length % 2) == 1:
        l = 2
    else:
        l = 1
    while l != key_length:
        txt = cryp(key, text)
        l=l+1
        text = txt
    return txt


text: Q: Quiver algebras whose modules have a distributive submodule lattice Is there a classification (by quiver and relations) of finite dimensional quiver algebras such that every indecomposable right module has a distributive submodule lattice?


text:
Q: Getting Data from a DataGrid I'm populating a C# DataGrid with some values, and I'd like to retrieve a value from a cell when I click on that.  How do I go about doing that with the .NET 1.1 Framework?
datagridview1 is not available in .net1.1
only for windows applications

A: If you are talking about a web/ASP.Net 1.1 DataGrid:

*

*Use myDataGrid.Items to get a row

*Use row.Cells[x] to get a column in that row

*Use (TextBox)cell.FindControl("TextBox1") to get a control inside the cell

For more info, see Accessing a Control's Value from DataGrid in ASP.NET

A: Does the following work:
string strCell = (string)dataGridView1.CurrentCell.Value;

A: Here is an excerpt from http://www.jigar.net/articles/viewhtmlcontent4.aspx, also found as a link in Eric Lathrop's answer. This covers most of the common scenarios.
Bear in mind that in the following example, dataGridItem is an alias for MyDataGrid.Items[x], where x is the (row) index. This is because the following example is using a foreach loop, so if skimming keep that in mind.

Iterating through Rows of a DataGrid
  We have to iterate through rows of our DataGrid to get values of controls within that row, so
  let's do that first. The DataGrid control has a property called Items,
  which is a collection of object DataGridItem that represents the
  individual item in a DataGrid control, and we can use this property to
  iterate through DataGrid rows by following these six steps.
foreach(DataGridItem dataGridItem in MyDataGrid.Items){

}

Getting the Value from a Bound Column in DataGrid
Our first column is a bound column, and we need to get a value written
  in that column. DataGridItem has a property named Cells of which is
  the collection of the TableCell object that represents the cells of
  the row. The Text property of TableCell gives us the value written in
  that particular cell.
//Get name from cell[0]
String Name = dataGridItem.Cells[0].Text;

Getting the Value of a TextBox Control in DataGrid Now our second column contains a TextBox control, and we need to get a Text property
  of that object. We use the FindControl method of the DataGridItem to
  get a reference for the TextBox.
//Get text from textbox in cell[1]
String Age =
((TextBox)dataGridItem.FindControl("AgeField")).Text;

Getting the Value from CheckBox Control in DataGrid
Our third column
  in DataGrid contains a CheckBox Web control that we need to check if
  the Checked property of that control is true or false.
//Get Checked property of Checkbox control
bool IsGraduate =
((CheckBox)dataGridItem.FindControl
("IsGraduateField")).Checked;

Getting the Value from CheckBoxList Web Control in DataGrid
This case
  differs from the previous one because the CheckBoxList may return more
  then one value selected. We have to iterate through the CheckBoxList
  items to check if the user has selected a particular item.
// Get Values from CheckBoxList
String Skills = "";
foreach(ListItem item in
((CheckBoxList)dataGridItem.FindControl("CheckBoxList1")).Items)
{
  if (item.Selected){
      Skills += item.Value + ",";
  }
}
Skills = Skills.TrimEnd(',');

Getting the Value from a RadioButtonList Web Control in a DataGrid
We use the FindControl method of the DataGridItem to get a reference for
  RadioButtonList and then the SelectedItem property of the
  RadioButtonList to get the selected item from RadioButtonList.
//Get RadioButtonList Selected text
String Experience =
((RadioButtonList)dataGridItem.FindControl("RadioButtonList1"))
    .SelectedItem.Text;

Getting the Value from a DropDownList Web Control in a DataGrid
This is similar to a RadioButtonList. I have used this control just to show
  that it works the same way as any other ListControls. Similarly, you
  can work with a ListBox Web control as we did with the CheckBoxList
  control.
//Get DropDownList Selected text
String Degree =
((DropDownList)dataGridItem.
FindControl("DropDownList1")).SelectedItem.Text;


text:
Q: Show part of a very large image to user without downloading the whole image file - php I have very large images of plants (about 40MB) and want to show these to users.
But here is the question: If the user wants to see only part of an image (e.g. only the root of a plant) how to tell browser to download only that part not the full size image.
I think about something like Google maps that shows a very large image of the world without the details, but when you are zooming on a part of the map you only download that part.

A: You could follow the google maps approach by creating a grid from the image.
With imagemagick you could split the image in a grid of multiple images. From each image you create a thumbnail so you can combine it to a small image.
When the user clicks on one of these thumbnails in your composed small picture, you link them to the corresponding big image part.


text:
Q: Ubuntu 18.04 and Windows 10 not booting after dual boot installation I tried to install Ubuntu 18.04 as a second OS, but now neither of them is booting anymore. While boot "System BootOrder not found. Initializing defaults. Boot System." is displayed. See the screenshot below.

Boot error
I followed this guide and created two (/ and /home) partitions like in the screenshot below:

Partitions
Beause it did not work and displayed this:
grub-efi-amd64-signed failed installation /target/

I found this solution to create a third FAT32 boot/esp partition to successfully install grub and Ubuntu, but now I can't boot either of them.
Some more screenshots:

Boot menu

UEFI boot settings
Did I mess with the bootloader/MBR, and why did I need to create the esp/boot partition to install grub?
Additional information:
Secure boot configuration


text:
Q: performance problem sql server 2005 update sentence I have a table "OFICIAL3" with 500k rows. and 30 columns. and table INSIS with 150k rows and 20 columns.
OFICIAL3.NUMERO_TITULO has an index.
INSIS.NumeroDocumento has an index too.
update sentence take long time. this process will take 9 hours in my machine
my machine is a core 2 duo 2.GHZ and 2GB RAM
ALTER PROCEDURE [dbo].[CompletarDatos] AS
declare @cantidad int;
declare @CONTADOR int;
declare @NRO_TITULO VARCHAR(600);
declare @POYECTO VARCHAR(200);
DECLARE @I_PROYECTO VARCHAR(500);
DECLARE @I_AREA_INT VARCHAR(500);

SET NOCOUNT ON
BEGIN

SET @cantidad =(select count(*) from OFICIAL3)
SET @CONTADOR=1

declare CURSORITO cursor for
select NUMERO_TITULO from OFICIAL3
open CURSORITO

 fetch next from CURSORITO
into @NRO_TITULO

 while @@fetch_status = 0
 begin

        SET @CONTADOR=@CONTADOR+1
        PRINT 'ROW='+CONVERT(NVARCHAR(30),@CONTADOR)+' NRO TITULO='+@NRO_TITULO

        SET @I_PROYECTO = (SELECT  PROYECTO FROM INSIS WHERE NumeroDocumento=@NRO_TITULO)
        SET @I_AREA_INT = (SELECT  I_AREA_INTERVENCION FROM INSIS WHERE NumeroDocumento=@NRO_TITULO)

        UPDATE OFICIAL3 SET PROYECT=@I_PROYECTO , COD_AREA=@I_AREA_INT WHERE NUMERO_TITULO=@NRO_TITULO

        fetch next from CURSORITO   into @NRO_TITULO

end

 -- cerramos el cursor
  close CURSORITO
  deallocate CURSORITO

END

A: Assuming OFICIAL4 is a typo, this should work as a single update:
UPDATE  o
SET     PROYECT = i.PROYECTO,
        COD_AREA = i.I_AREA_INTERVENCION
FROM    OFICIAL3 o
        INNER JOIN
                INSIS i
                ON o.NUMERO_TITULO = i.NumeroDocumento

As others have commented, an approach that avoids the CURSOR is vastly preferable from a performance point of view. Another thought is that a covering index on `INSIS (NumeroDocumento, PROYECTO, I_AREA_INTERVENCION) would speed things up further for this query.

A: Is there any way you can do this without a cursor?  Removing the iteration should help it considerably.


text:
Q: FFMpeg convert VOB to H264 and multi language I try to convert VOB files to H264. I know it seems to be crazy to do that but the goal is to use it with the Apple TV.
To just converting a VOB file to mp4 with the right audio stream is not really a problem.
The problem is when the VOB file contains multi-sequences in different languages. For example, in the mp4's file I will have 3 seconds of video including for example a book on the screen in english, then, the same 3 seconds with the book in french and so on...
But with the VOB file I will have only the 3 seconds in the right language.
When I check the VOB file, I only see one stream #0.0 for the video.
So my question is, how can I avoid to include the differents videos sequences with these different languages ?
Thx for your help.

A: In that VOB, all the video sequences are concatenated with the DVD authoring that tells the player which portions to play depending on the language choice.
So, in order to extract just a coherent single language video, you will have to examine the VOB and note down the timecodes of the language you want. Then using, probably, the concat demuxer, extract the segments and join them.
e.g. if the timecodes for English for 14-17 seconds and then 3m 34sec to 6m 20 sec, you would create a text file like this
file 'input.vob'
inpoint 14
outpoint 17
file 'input.vob'
inpoint 214
outpoint 380

(times are in seconds)
and then
ffmpeg -f concat -i list.txt out.mp4


text:
Q: How to fix this error in Spring Boot using Spring Data JPA and MySQL I'm try to connect to a MySQL database using Spring Data JPA (in a Spring Boot application) and always the same error:
java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)

My application.properties looks like:
spring.datasource.url=jdbc:mysql://localhost:3306/demographics
spring.datasource.data-username=root
spring.datasource.data-password=root
spring.jpa.hibernate.ddl-auto=update

I know the url, username and password are good.

A: The problem is with creating connection with the database itself due to authentication.
Execute this with command line or some tool like mysql workbench.
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '%root%' WITH GRANT OPTION;

A: The Spring documentation for "Common Application Properties" states that spring.datasource.data-username is the user to execute DML scripts (if different). I think you are looking for:
spring.datasource.username = root
spring.datasource.password = root

Notice you don't need the data- part of the key.
Keep in mind that if you need different credentials for both, you must specify them accordingly, unless they are the same. Also, just make sure the user have the correct/required privileges to access the schema you are using.

A: it seems your account in the database does not require password so just put empty password in your property
spring.datasource.data-password=


text:
Q: How do I perform custom error reporting in ANTLR using python? I'm writing a simple parser for my compilers class (just a proof of concept that I can get the tools working) and am using ANTLR with python bindings.  I've gotten our trivial grammar to properly tokenize and parse, but I want to also handle the errors in a custom way.  According to the ANTLR documentation (more specifically: http://www.antlr.org/wiki/display/ANTLR3/Error+reporting+and+recovery), I can put the following code in my grammar file to do so:
@members {
    private List<String> errors = new LinkedList<String>();
    public void displayRecognitionError(String[] tokenNames,
                                        RecognitionException e) {
        String hdr = getErrorHeader(e);
        String msg = getErrorMessage(e, tokenNames);
        errors.add(hdr + " " + msg);
    }
    public List<String> getErrors() {
        return errors;
    }
}

However, this is a Java example that I can't seem to replicate in python (I can replicate the code, but just can't really seem to get it to run).  Does anyone know how I might go about doing so?

A: I managed to find a solution to my problem:
@members {
def displayRecognitionError(self, tokenNames, e):
    # do something
    pass

antlr3.BaseRecognizer.displayRecognitionError = displayRecognitionError
}


text:
Q: launching command line handling escape characters I have command line argument (launched in C#):
 fijiCmdText = string.Format("/C \"\"{0}\" -macro \"{1}\" \"{2}\" {3} \"{4}\" {5} {6}", _fijiExeFile, _ijmFile, _inputDir, redirStr, _logFile, headlessOption, resStr);

where string is built in strings, and the only problem is from the third and forth strings: _inputDir, redirStr. They are actually
_inputDir = "D:\\fiji\\blobimg\\";
redirStr = ">";
_logFile = "D:\\fiji\\blobimg\\log.txt";

If the command argument is like above, then the actual _inputDir received by the script, which is launched by this command line, will be
D:\fiji\blobimg"

but if I change the argument to
 fijiCmdText = string.Format("/C \"\"{0}\" -macro \"{1}\" \"{2} {3} \"{4}\" {5} {6}", _fijiExeFile, _ijmFile, _inputDir, redirStr, _logFile, headlessOption, resStr);

the actual string received will be (problem here is the third string interferes with the forth string, which it should not)
D:\fiji\blobimg\ > D:\fiji\blobimg\Output\log.txt

I really want to have, neither without the ", nor messed up with the string following.
D:\fiji\blobimg\

so how should I change the argument of the command line to make it work?
EDIT: Hope this is useful info
fijiCmdText = string.Format("/C \"{0}\"", _fijiExeFile);
will run,
but
fijiCmdText = string.Format("/C \"{0}\" -macro \"{1}\" \"{2}\", _fijiExeFile, _ijmFile, _inputDir);
will not run. I have no idea why. Very strange. I think I follow all the rules, but it did not work.

A: I think your problem is an extra \" right before your first place holder.
Try:
var fijiCmdText = string.Format("/C \"{0}\" -macro \"{1}\" \"{2}\" {3} \"{4}\" {5} {6}", _fijiExeFile, _ijmFile, _inputDir, redirStr, _logFile, headlessOption, resStr);

Looking at this fiddle the logged text looks about right to me for a command line.
/C "foo" -macro "bar" "D:\fiji\blobimg\" > "D:\fiji\blobimg\log.txt" headless resStr


text:
Q: Firefox: input field number min max not working I'm facing the issue for input field's attributes min and max values in Firefox (v_30.0) browser.
This works
<input name="year" type="number" placeholder="YYYY" required min="1" max="12"/>

But this does not
<input name="year" type="number" placeholder="YYYY" required min="1990" max="20014"/>

it displays 1 on input box and does not move further.

A: Just set the starting value and it will work
<input name="year" type="number"  min="1990" max="2014" value="1990" required />

http://jsfiddle.net/ywq6dq93/
EDIT:
As another user previously pointed out, this will not show the placeholder but instead the starting value of 1990. In Chrome it works to not set the value and still show the placeholder and achieve the desired functionality, however it seems that in FF you would need to set the value by javascript when focusing on the input field, if you want to show a placeholder instead of a starting value.
Demo for this: http://jsfiddle.net/1pg5727f

A: Firefox (unlike Chrome) seems to follow the HTML5 definition for stepping up the value of an input type=number element. When the value is not set, as it here isn't initially, it is interpreted as 0, so the result of incrementing is 1. Since it is outside the range, it is an invalid value, and further stepping is not possible.
This means that input type=number is intended for use with quantities for which an initial value can be set (or the default initial value of 0 can be accepted). After all, stepping up and down is really the reason for using this element type, and it needs to start somewhere.
Consequently, there is not much point in using required for such an element, unless the implicit default of 0 is acceptable and within the bounds set.
If you still want to use input type=number, you need to set some initial value with the value attribute that is within the bounds. Technically, this means that the pattern attribute has no effect.
To read a required 4-digit number when no default value is set, optionally with a placeholder, you can use a text input field with suitable attributes (but you cannot express a range requirement in HTML, in any reasonable way, in this approach):

<input name="year" type="text" placeholder="YYYY"
  size="4" maxlength="4" pattern="\d[4}" required
  style="font-family: Consolas, monospace">

A:

<input type="number" step="1" min="1"  name="product_qty" value="1" title="Qty" class="input-text" size="4" maxlength="10" pattern="\d*" required />

A: if you still looking for the answer you can use input type="number".
min max work if it set in that order:
1-name
2-maxlength
3-size
4-min
5-max
just copy it
<input  name="X" maxlength="3" size="2" min="1" max="100" type="number" />


text:
Q: Why won't the else statement in my while loop execute when the conditions in the if statement aren't met? I'm making a game called 'Game of Nim' in Netbeans. Basically, a random amount of stones between 15-30 is generated and a computer and a player take turns taking 1-3 stones until there are none left. The player to take the last stones loses. I'm coding this in a jframe form. I want to make sure the player doesn't enter a number bigger than 3, less than 1 and bigger than the total stones, so I made a while loop with an if statement for the input that meets the requirements and an else statement if they aren't met. My problem is that when a player does enter numbers that shouldn't be entered, no error message appears and the game continues as normal.
Here is where I think the problem is:
    public int playerInput(){
        // Getting the user input and converting it into an integer
        int userIn = Integer.parseInt(txtIn.getText());
        //
        boolean input = false;

        // Do this while the input isn't between 1-3 and higher than the total amount of rocks
        while(!input){
            //
            if (userIn < 3 || userIn > 1 || userIn < totalStone){
                //
                input = true;
            }
                //
                else{
                    // Output an error message
                    txtaOut.setText(txtaOut.getText() +"\nEnter a number between 1 - 3 and less than the amount of stones left.");
                }
        }
        // return the amount of rocks the user takes
        return userIn;
}

Here is most of the code for the game (I am going to use the random slashes for commenting):
    public void computerMove() {
    // Generating a number for the computer's move
    int comIn = (int)(Math.random() * 2) + 1;

    // If number generated is bigger than the total stones,
    if (comIn > totalStone){
        // Get the difference between the total and the random number
        int totalComDiff = Math.abs(totalStone - comIn);
        // Subtract the difference from the random number
        comIn -= totalComDiff;
        // Substract the rocks taken from the total
        totalStone -= comIn;
        // Display a message of the rocks taken and the rocks left
        txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");
        }
            // Otherwise, if the random number is smaller than the total,
            else if (comIn < totalStone){
                // Substract the rocks taken from the total
                totalStone -= comIn;
                // Display a message of the rocks taken and the rocks left
                txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");

            }
             // If the total equals amount the computer takes,
            else if (totalStone == comIn){
                // Substract the rocks taken from the total
                totalStone -= comIn;
                // Display a message of the rocks taken and the rocks left
                txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");
                // Display a message that says the player wins
                txtaOut.setText(txtaOut.getText() +"\nThere are no more stones left. The player wins!");
            }

            // Otherwise, if the amount of stones is 0,
            else if (totalStone == 0){
                // Display an end game message
                txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
            }

}
public void playerMove(){
    // If there are no more stones left,
    if (playerInput() == totalStone){
        // Subtracting how much the player took from the total amount of rocks
        totalStone -= playerInput();
        // Displaying how many rocks were taken and how many are left
        txtaOut.setText(txtaOut.getText() +"\nYou picked up " +playerInput() +" stone(s). There are " +totalStone +" stones left.");

        // Display a message that says the computer wins
        txtaOut.setText(txtaOut.getText() + "\nThere are no more stones left. The computer wins.");
    }
        //
        else if (playerInput() != totalStone){
            // Subtracting how much the player took from the total amount of rocks
            totalStone -= playerInput();
            // Displaying how many rocks were taken and how many are left
            txtaOut.setText(txtaOut.getText() +"\nYou picked up " +playerInput() +" stone(s). There are " +totalStone +" stones left.");

        }
        //
        else if (totalStone <= 0){
            //
            txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
            }
}
    private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {
    //
    if (totalStone > 0){
        // Display how many rocks there are
        txtaOut.setText(txtaOut.getText() +"\nThere are " +totalStone +" stones.");
        // The player does their move
        playerMove();

    }

    //
    if (totalStone > 0){
        // Computer does a turn
        computerMove();
    }

        //
        else if (totalStone == 0){
            //
            txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
        }
}
    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {
    // Generating another random number
    totalStone = (int)(Math.random() * 15) + 15;

    // Clearing all the textfields
    txtIn.setText("");
    txtaOut.setText("");

    // Outputting the number of starting stones
    txtaOut.setText(txtaOut.getText() +"There are " +totalStone +" stones. It's your turn.");

}

A: your if needs to look like this:
while (!input) {
    if (!(userIn < 3 && userIn > 1 && userIn < totalStone)) {
       // Output an error message
       txtaOut.setText(txtaOut.getText() +"\nEnter a number between 1 - 3 and less than the amount of stones left.");
       // Prompt the user again
       userIn = Integer.parseInt(txtIn.getText());
    } else {
       input = true;
    }
}

And, it will work.
It is better to check if conditions are not valid first, and then if the verification is passed do the normal flow in else block.
The way you wrote it, the if condition would always be true since || represents 'or' so you're asking weather userIn is less then 3 or greater then 1 or lesser than totalStone which is always true.
On the other hand && represents 'and' and '!' represents not. So, you basically want all the conditions to be fulfilled and checking if they aren't by putting them into the brackets and putting ! (negation) in front
You also need to prompt the user again if the condition is not met. Otherwise it's gonna run forever and freeze the ui.

A: If the user enters an incorrect number, they should then be prompted to enter a new one. In your code, it will be stuck in the loop forever.
You should also be checking that all conditions are satisfied using &&.
You need a number that is (<=3) AND (>=1) AND (<=totalStones)
public int playerInput () {

    int userIn;

    do {

        System.out.println("Enter a number between 1 - 3 and less than the amount of stones left.")

        userIn = Integer.parseInt (txtIn.getText ());

    } while (!(userIn <= 3 && userIn >= 1 && userIn <= totalStone));

This will continue to loop while the conditions are not satisfied.


text:
Q: How to efficiently remove redundant linear constraints for optimization? My optimization problem involves thousands of linear constraints. I want to reduce the complexity of my problem by finding redundant constraints, e.g. 3 * x + 4 * y < 10 would be redundant if I already have a constraint that is 4 * x + 5 * y < 10 (and x and y are >= 0, which is the case for my problem).
So, I have a numpy array that holds all the coefficients, and it looks like this, for example:
[[0.1, 3.0, 4.8, 0.2],
 [1.0, 4.7, 5.3, 0.1],
 [2.2, 4.3, 5.2, 1.1]]

representing the constraints:
0.1 * w + 3.0 * x + 4.8 * y + 0.2 * z < 10
1.0 * w + 4.7 * x + 5.3 * y + 0.1 * z < 10
2.2 * w + 4.3 * x + 5.2 * y + 1.1 * z < 10

How do I efficiently find out which one are redundant?
My common sense tells me to do a loop (pseudo-codeish):
for i, row1 in enumerate(array):
    for j, row2 in enumerate(array):
        if j > i:
            if all(row1 > row2):
                delete row

But this slow for thousands of constraints. Any way to speed it up?

A: You can think of each constraint as a hyperplane, intercepting each axis at (sum constraint constant) / (coefficient for that axis); if the coefficient is 0, the hyperplane is parallel to that axis (== "intercepts at infinity").
Trivially, if the axis-intercepts for one hyperplane are all equal to or greater than the corresponding intercepts for another, that hyperplane is redundant.
In order to cull as many constraints as early as possible, you want to start by comparing against ones whose hyperplane is (a) as close to the origin as possible and (b) parallel to as few axes as possible, as it can only cull other hyperplanes also parallel to that axis. [A hyperplane not parallel to a given axis may be able to cull one parallel to that axis, but the inverse is never true.]
I suggest you sort the list by (number of axis-parallel axes) then (sum of non-infinite axis intercepts).

A: I think for speed up this problem you can use backtracking for ex you can check out coefficients in arrays one by one ! if you find an index that is less than other index you can stop checking and delete the row !


text:
Q: Plotting any number of images in MATLAB I want to plot random number of images. Means i have searched images related to my query, the images can be 5,6 or more based on the query given. Is there any way to plot them automatically based on the number of images matched.
Here is my code so far:
for k = 1:length(textfiles)
    file = [sdirectory '/' textfiles(k).name];
    file1 = [sdirectory1 '/' imgfiles(k).name];
    fid=fopen(file,'r');
    tline = fgetl(fid);

    while ischar(tline)
         line_string = sprintf('%s',tline);
         x = get(handles.edit1,'String');
         u=strfind(line_string,x);
         tline = fgetl(fid);

         if u>0
              file2=imread(file1);
              figure,imshow(imresize(file2,0.5)),title(file1);
              break;
         end
    end
    fclose(fid);
end

A: You can concatenate them into a multiframe/multipage image (4D matrix), and display them with montage.
mframe = cat (4, img1, img2, img3);
montage (mframe)

Since you don't know the number of images to plot, you can throw them all into a cell array first:
mframe = cell (); % if you know in advance the number of images...
for ...
  ## whatever code you have to pick the right images
  mframe{end+1} = img;
endfor
mframe = cat (4, mframe{:});
montage (mframe)

This assumes that images are all of the same size, all RGB or grayscale, and same class, If they are not, you can pad them easily with padarray, and convert them to the same class with im2uint8, im2double, etc...


text:
Q: Read iframe url after changed used iframe to load a payment page in my html page. Then i used  contentWindow.location.href to read iframe page url when after it loaded. After payment process and transaction completed, url will changed. I want to read the url after transaction completed. Suffix of that returned url they mentioned COMPLETED or CANCELED. how to read that.
my.html

script
 var url = document.getElementById("iframe_mercury").contentWindow.location.href;

mercurywindow.html

    <form name=frmCheckout method=Post action="https://hc.mercurydev.net/mobile/mCheckout.aspx">
       <input name=PaymentID type=hidden value="28ff0296-d36d-476e-9a58-60e58241bb7b">
    </form>

A: Try with -
$('#iframe_mercury').prop('src');

Or
$('#iframe_mercury').attr('src');

A: There is no way you can read the frame URL if it's pointing to a different domain.
Ref. http://en.wikipedia.org/wiki/Same-origin_policy


text:
Q: Gatsby build failed with promise.finally is not a function I am able to run gatsby develop successfully but when I run gatsby build it throws me promise.finally is not a function.
I was referring this link to try to multiple solutions but did not get much success with it.
https://github.com/gatsbyjs/gatsby/issues/23542
Gatsby info return this details
System:
    OS: macOS 10.14.6
    CPU: x64 Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 12.16.1 - ~/.nvm/versions/node/v12.16.1/bin/node
    Yarn: 1.22.4 - /usr/local/bin/yarn
    npm: 6.13.4 - ~/.nvm/versions/node/v12.16.1/bin/npm
  Browsers:
    Chrome: 83.0.4103.116
    Firefox: 56.0.2
    Safari: 12.1.2
  npmPackages:
    gatsby: ^2.18.25 => 2.23.22
    gatsby-image: ^2.2.31 => 2.4.12
    gatsby-plugin-google-analytics: ^2.1.34 => 2.3.10
    gatsby-plugin-google-fonts: ^1.0.1 => 1.0.1
    gatsby-plugin-google-tagmanager: ^2.1.24 => 2.3.10
    gatsby-plugin-manifest: ^2.2.33 => 2.4.17
    gatsby-plugin-offline: ^3.0.19 => 3.2.16
    gatsby-plugin-react-helmet: ^3.1.14 => 3.3.9
    gatsby-plugin-sharp: ^2.2.37 => 2.6.18
    gatsby-source-contentful: ^2.1.69 => 2.3.24
    gatsby-source-dev: ^0.1.4 => 0.1.4
    gatsby-source-filesystem: ^2.1.36 => 2.3.18
    gatsby-transformer-json: ^2.2.17 => 2.4.10
    gatsby-transformer-sharp: ^2.3.3 => 2.5.10
  npmGlobalPackages:
    gatsby-cli: 2.12.59

A: Finally, I got resolved by downgrading my gatsby version from 2.23.22 to 2.20.28
My current gatsby info shows below information
 System:
    OS: macOS 10.14.6
    CPU: x64 Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 12.16.1 - ~/.nvm/versions/node/v12.16.1/bin/node
    Yarn: 1.22.4 - /usr/local/bin/yarn
    npm: 6.13.4 - ~/.nvm/versions/node/v12.16.1/bin/npm
  Browsers:
    Chrome: 83.0.4103.116
    Firefox: 56.0.2
    Safari: 12.1.2
  npmPackages:
    **gatsby: 2.20.28 => 2.20.28**
    gatsby-image: ^2.2.31 => 2.4.12
    gatsby-plugin-google-analytics: ^2.1.34 => 2.3.10
    gatsby-plugin-google-fonts: ^1.0.1 => 1.0.1
    gatsby-plugin-google-tagmanager: ^2.1.24 => 2.3.10
    gatsby-plugin-manifest: ^2.2.33 => 2.4.17
    gatsby-plugin-offline: ^3.0.19 => 3.2.16
    gatsby-plugin-react-helmet: ^3.1.14 => 3.3.9
    gatsby-plugin-sharp: ^2.2.37 => 2.6.18
    gatsby-source-contentful: ^2.1.69 => 2.3.24
    gatsby-source-dev: ^0.1.4 => 0.1.4
    gatsby-source-filesystem: ^2.1.36 => 2.3.18
    gatsby-transformer-json: ^2.2.17 => 2.4.10
    gatsby-transformer-sharp: ^2.3.3 => 2.5.10


text:
Q: how to set a progress Dialog till server response ?? i'm trying but it shows error at show method of progress dialog #Json #Volley #StringRequest how to set a progress Dialog till server response ?? i'm trying but it shows error at show method of progress dialog Json Volley StringRequest
public class Loginn extends Activity {
Button btn1,btn2,btn3;
EditText et1,et2;
TextView waittv;
SharedPreferences sp;
CheckBox cb1;
ProgressDialog pd;
ProgressDialog progressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    btn1=(Button)findViewById(R.id.btn1);
    btn2=(Button)findViewById(R.id.btn2);
    btn3=(Button)findViewById(R.id.regbtn);
    waittv=(TextView)findViewById(R.id.waittv);
    et1=(EditText)findViewById(R.id.et1);
    et2=(EditText)findViewById(R.id.et2);
    cb1=(CheckBox)findViewById(R.id.cb1);

    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final String mobile = et1.getText().toString();
            String pword = et2.getText().toString();
            if (mobile.isEmpty()) {
                et1.setError("please enter Mobile no.");
            } else if (pword.isEmpty()) {
                et2.setError("please enter password");
            } else {
                //progressDialog= new ProgressDialog(getApplicationContext());
                //progressDialog.setTitle("Wait for login ...");
                //progressDialog.setMessage("if it takes much time,then check your internet connectivity...");
                //progressDialog.show();
                Response.Listener<String> listener=new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {

                            JSONObject jsonResponse =new JSONObject(response);

                            boolean success=jsonResponse.getBoolean("success");

                            if(success){
                                String fname=jsonResponse.getString("first_name");
                                String lname=jsonResponse.getString("last_name");
             Toast.makeText(getApplicationContext(),"Login Success", Toast.LENGTH_LONG).show();

                                //progressDialog.dismiss();

                                Intent intent=new Intent(getApplicationContext(),Profile.class);

                                Loginn.this.startActivity(intent);
                            }
                            else
                            {                                   Toast.makeText(getApplicationContext(),"Incorrect mobile/password", Toast.LENGTH_LONG).show();
                                pd.dismiss();
                                //progressDialog.dismiss();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };

                LoginRequest loginRequest=new LoginRequest(mobile,pword,listener);
                RequestQueue queue= Volley.newRequestQueue(getApplicationContext());
                queue.add(loginRequest);
            }
        }
    });
}

error's like:
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
                      at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
                      at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
                      at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
                      at android.app.Dialog.show(Dialog.java:319)
                      at android.app.ProgressDialog.show(ProgressDialog.java:116)
                      at android.app.ProgressDialog.show(ProgressDialog.java:99)
                      at android.app.ProgressDialog.show(ProgressDialog.java:94)

A: I think you should fix changing the Context you pass to the ProgressDialog constructor :
progressDialog= new ProgressDialog(Loginn.this);

the rest remains unchanged.


text:
Q: Why all layers shows on top (in layout) in OrCAD? I'm in trouble with Orcad Layout Plus 10.3.0.
All layers (SST, SSB, BOT, ...) shows on top when i generate gerber files, and view them with Gerbtool. But everything looks ok, when i open the .max file in Layout.
I hope that i don't need to create the PCB again, because i need to send it for fabrication tomorrow. Any ideas?
Update: Here's the screenshot.

A: From your description, it sounds like the gerber files show up in a wrong Z-order in GerbTool.  That doesn't sound like a sign of a problem, which would manifest itself during PCB fabrication, as long ans you correctly indicate to the fab which gerber file corresponds to which layer.


text:
Q: How do I roll a random number once to be used on multiple classes? I am a beginner C# programmer in general, attempting to create a Japanese falling word typing game in Unity where the word / letter shown on screen will be in Hiragana, but the requested input is in Romaji (alphabetical) letters.
Currently, I am stuck in a rut attempting to figure out how to generate a random number once per words.Add (word) is executed. For instance, when a Word object is created, generate a random number. Then, that random number is used on classes that depend on it, such as getWord_Hiragana, and getWord_Romaji. Most typing games existing on the internet are shown only a single object (English), so I couldn't find what I need.
// WordManager.cs
public class WordManager : MonoBehaviour {

    public List<Word> words;

    public WordSpawner wordSpawner;

    public void AddWord ()
    {
        Word word = new Word (WordGenerator.GetWord_Romaji(), wordSpawner.SpawnWord());

        words.Add (word);
    }
}

// WordGenerator.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WordGenerator : MonoBehaviour {

    public static string[] wordList_Hiragana = {    "あ", "い", "う", "え", "お" };

    public static string[] wordList_Katakana = {    "ア", "イ", "ウ", "エ", "オ" };

    public static string[] wordList_Romaji = {      "a", "i", "u", "e", "o" };

    public static int GetIndex ()
    {
        int index = Random.Range (0, wordList_Romaji.Length - 1);   // Get Random number which has the same index for Hiragana, Katakana, and Romaji arrays

        Debug.Log ("Index #" + index + ": " + wordList_Hiragana[index] + " " + wordList_Katakana[index] + " " + wordList_Romaji[index]); // Debug Log

        return index; // Returns the result of the random as a guidance.
    }

    public static string GetWord_Hiragana ()    // A function to return the result of GetIndex as Hiragana word to be used on WordManager and in turn, displays that Hiragana.
    {
        int index = GetIndex ();

        string getWord_Hiragana = wordList_Hiragana [index];
        return getWord_Hiragana;
    }

    public static string GetWord_Romaji ()
    {
        int index = GetIndex ();
        string getWord_Romaji = wordList_Romaji [index];

        return getWord_Romaji;
    }
}

// Word.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Word {

    public string word;
    private int typeIndex; // Checks for current letter

    WordDisplay display;

    public Word (string _word, WordDisplay _display)  // Displays the word as Hiragana / Katakana
    {
        word = _word;

        display = _display;
        display.SetWord (word);
    }

    public char GetNextLetter ()
    {
        return word[typeIndex]; // Gets the next letter of the Romaji array
    }

    public void TypeLetter ()
    {
        typeIndex++;
    }

    public bool WordTyped ()
    {
        bool wordTyped = (typeIndex >= word.Length); // Checks if the whole word has been typed
        if (wordTyped)
        {
            display.RemoveWord (); // Remove the whole object on screen
        }
        return wordTyped;
    }
}

The expected result is for GetIndex to roll a random number once per Word object. When getWord_Romaji is executed, it grabs the return value of GetIndex. The same goes when getWord_Hiragana is executed. Right now, GetIndex is executed twice and generates a random number twice in each Word object, causing the word that appeared on Debug to be different compared to what appears on the game screen. How do I make this work?
If the code above is not enough to solve the problem, the project is posted here.

A: Without seeing the implementation of Word I'ld say from your example it actually does call GetIndex() only exactly once ... namely for GetWord_Romaji() ...
Anyway a quick simple fix could be
private static int randomizedIndex;

public static void NewRandomIndex()
{
    randomizedIndex = Random.Range (0, wordList_Romaji.Length - 1);

    Debug.Log("Index #" + randomizedIndex + ": " + wordList_Hiragana[randomizedIndex] + " " + wordList_Katakana[randomizedIndex] + " " + wordList_Romaji[randomizedIndex]);
}

public static string GetWord_Hiragana()
{
    return wordList_Hiragana[randomizedIndex];
}

public static string GetWord_Romaji ()
{
    return wordList_Romaji[randomizedIndex];
}

and call it
public void AddWord ()
{
    WordGenerator.NewRandomIndex();

    Word word = new Word(WordGenerator.GetWord_Romaji(), wordSpawner.SpawnWord());
    words.Add (word);
}

If you rather want to be able to later "translate" the words between those arrays then you should in Word instead of retrieved string rather store the used randomizedIndex and get the string value for it "on the fly".

A: I would change your Word class constructor to the below:
public class Word
{

    public string word;
    private int typeIndex; // Checks for current letter

    private int wordIndex; // index of word used from WordGenerator

    WordDisplay display;

    public Word(WordDisplay _display)  // Displays the word as Hiragana / Katakana
    {
        wordIndex = WordGenerator.GetIndex(); // now it will only be called ONCE per instance
        word = _WordGenerator.wordList_Romaji[wordIndex];

        // you can get the equivalent? letters similarly...with something like:
        word = _WordGenerator.wordList_Hiragana[wordIndex];

        display = _display;
        display.SetWord(word);
    }

    // ... other existing code ...

}

Note that I've added another field to store the index selected for that particular word instance.


text:
Q: Does oracle ODI delete all options in IKM sql incremental update have transaction? I am using oracle ODI to sync tables.
I am using IKM SQL Incremental Update,and i set DELETE_ALL to TRUE.
The source data has about 60000+ rows,because it's readonly, i cannot use cdc.
The problem is,when i run this mapping,the target table data will be deleted,when i select,there shows no data.After completed,the data can be seleted.
In my opinion,i think delete and insert should in same transaction,whenever i select ,there should have data.
Is my understand right? Or am i using the wrong way?

A: This might be the default order for steps, but oracle made it very easy to customise it. I recommend you to make another copy from the IKM, modify it, give it a suitable name and then use the new copy.

A: The aim is to sync a small table. So i shoule use "Control Append" mode.But in this question,i use "Incremental Update" mode,this is wrong.


text:
Q: android How DialogFragment displays the words on the status bar on a white background? Before loading,The font of the status bar of the normal page is displayed
After loading 'Why is the font in the status bar invisible?'
The project theme background is white, the status bar is transparent, and the words in the status bar of the loading page using DialogFragment are not visible. How to solve this?
My expectation is that only the middle loading box appears, the words on the status bar are displayed normally, and the entire DialogFragment is completely transparent; thank you
class LoadingDialog(var message: String? = null) : DialogFragment() {

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?,
): View {
    val binding = LoadingViewBinding.inflate(inflater, container, false)
    val tvContent = binding.loadingViewTvContent
    if (!message.isNullOrEmpty()) {
        tvContent.text = message
    }
    dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    dialog?.window?.setDimAmount(0f)  //完全透明
    return binding.root
}

override fun onStart() {
    super.onStart()
    isCancelable = false    //点击外部不可取消
    val dm = DisplayMetrics()
    this.activity?.windowManager?.defaultDisplay?.getMetrics(dm)
    this.dialog?.window?.setLayout(dm.widthPixels, dm.heightPixels)
}  }

A: Check your code:
this.activity?.windowManager?.defaultDisplay?.getMetrics(dm)
this.dialog?.window?.setLayout(dm.widthPixels, dm.heightPixels)

When the dialog is created you set the layout size according to the device height & width. So, logially the dialog will shown up as fullscreen.
Also, you can show the LoadingDialog with Dialog only.
Follow this code: https://github.com/rommansabbir/ResultShowDialog-Android/blob/master/app/resultshowdialog/src/main/java/com/rommansabbir/resultshowdialog/ResultShowDialog.kt and change it according to your requirement.


text:
Q: How can I put colors in console output with Robot Framework I would like to put some colors in the console output of RobotFramework.
I tried to use the console color codes like:
${message}=  Set Variable  hello world!
Log To Console  \\e[0;36;49m${message}\\e[0;39;49m

(In a linux console, echo -e "\e[0;36;49mHello world!\e[0;39;49m" print Hello world! in cyan)
(I also tried with one \ and also \033[31m, \033[0m, ... codes)
But it doesn't work...
So, is it possible to do something like:
${message}=  Set Variable  hello world!
Log To Console ${message.red}

I found this module but I didn't found anything on how to use it :(
I tried:
Log To Console ${message.red}  robot.output.console.highlighting

and
${message}=  Evaluate  ${message}.red  robot.output.console.highlighting
Log To Console ${message}

But none works :'(

A: Because of Robot Framework interpretation of '\', Log To Console  \\033[31mRed Text\\033[0m doesn't color the output.
To solve this problem, you have to Evaluate the variable before to log in to console:
${message}=  Evaluate  "\\033[31mRed Text\\033[0m"
Log To Console  ${message}

I ended up with the below solution, which I find quite "clean":
*** Variables ***
${BLACK}  "\\033[30m"
${RED}    "\\033[31m"
# More colors ANSI codes...

*** Keywords ***
Initialize Colors
  ${black}=  Evaluate  ${BLACK}
  Set Test Variable  ${black}
  ${red}=  Evaluate  ${RED}
  Set Test Variable  ${red}
  # More colors...

Then, you just have to use the previous keyword in a Suite/Test Case Setup and you can colorize your outputs like below:
Log To Console  ${cyan}Some Text in cyan and a ${red}${variable}${cyan} in red${default}

A: can I ask your overall goal here?  Is it just to output random text in different colours?
Here's what I do to easily signal PASS/FAIL etc on different test cases to make them stand out:
--monitorcolors ansi

In your command to run your test suite, include the above toward the beginning of the command.


text:
Q: ExpressionEngine on MAMP I am trying to run a legacy 1.6.8 EE install on MAMP. I can see the index page but the expression engine tags are rendered to the browser rather than being parsed and running DB queries. I'm also not seeing any styling (images, css etc) on the front end or in the control panel.
In addition, I cannot install a fresh version of 1.6.8 as I get the error:
Error: Unable to perform the SQL queries needed to install this program. Please make sure your MySQL account has the proper GRANT privileges: CREATE, DROP, ALTER, INSERT, and DELETE
I do this as root which has the relevant privileges. I have tried switching off MYSQL STRICT mode (both in my.cnf and by running SET @@global.sql_mode= '';
Does anyone know what might be causing either of these problems? I have already tried official EE support

A: Installing ExpressionEngine 1.x on any version of MAMP 1.9.5 or later is a known-issue, and causes the following error during the EE installation process:

Error: Unable to perform the SQL queries needed to install this
  program. Please make sure your MySQL account has the proper GRANT
  privileges: CREATE, DROP, ALTER, INSERT, and DELETE

Unfortunately, the error message isn't indicative of the actual problem, as 'root@localhost' has full MySQL privileges.
The solution is to downgrade to MAMP v1.9.4 (162 MB Download).
MAMP v1.9.5 (released 2011-03-11) upgraded MySQL from v5.1.44 to v5.5.9, which according to EllisLab is problematic with EE 1.x — all versions of EE 2.x do not have this problem.


text:
Q: Can I upgrade to Windows 10 from my OEM Windows 7 Pro Dell without install media which is currently running Ubuntu 14.04 I received this computer from work for free, its a Dell Vostro 3550 it came with the HD wiped of Windows 7 Pro, which was fine as I wanted a Linux machine. Now I am thinking I'd Like to install Windows 10 and be able to use the OEM product stickers to upgrade to 10. It is running Ubuntu 14.04 right now. Can I do this? Ultimately I'd like to dual boot Win10 and Trusty

A: You need to understand how the PC was originally purchased and how Windows was licensed.
If the PC came with a license for W7 Pro and has a sticker with the code on it, you should be OK to use that code for the upgrade. The OEM license is only valid for that PC anyway.


text:
Q: What's the input space and auxiliary space in this code block? public static void main(String[] args){
    int n;
    Scanner in = new Scanner(System.in);
    n=in.nextInt();
    int[] arr = new int[n];
    for(int i=0; i<=n; i++){
        arr[i]=i*2;
    }
}

I'm just confused about what is the input in space or time complexity.


text:
Q: Stylus empty text variable How to create stylus EMPTY text variable?
$cross(prop)
  prop = shift(arguments)
  -webkit-{prop} arguments
  -moz-{prop} arguments
  -ms-{prop} arguments
  -o-{prop} arguments
  {prop} arguments

$transition()
  attrs = shift(arguments)
  if length(arguments)
    str = ????WTF???
    for arg in arguments
      if length(str)
        str += \,
      str += arg attrs
    $cross (transition) (str)

I want to create transition mixin:
$transition((.4s ease out), opacity, visibility)

A: Unfortunately, the length bif can only be used for lists/hashes. It always returns 1 for other nodes. You can write something like this instead:
$transition()
  attrs = shift(arguments)
  if length(arguments)
    str = ''
    for arg in arguments
      if str != ''
        str += ', '
      str += arg, attrs
    $cross (transition) unquote(str) // unquote to remove quotes

Or you can write a custom function to get string length:
str-length.js
module.exports = function() {
  return function(stylus) {
    stylus.define('str-length', function(str) {
      return str.val.length;
    });
  };
};

test.styl
use('str-length.js')

$cross(prop)
  prop = shift(arguments)
  -webkit-{prop} arguments
  -moz-{prop} arguments
  -ms-{prop} arguments
  -o-{prop} arguments
  {prop} arguments

$transition()
  attrs = shift(arguments)
  if length(arguments)
    str = ''
    for arg in arguments
      if str-length(str)
        str += ', '
      str += arg attrs
    $cross (transition) unquote(str) // unquote to remove quotes

body
  $transition((.4s ease out), opacity, visibility)


text:
Q: Number of Edges in a Subset Graph of a Power Set Given a set $A$ of cardinality $n$, let $\mathbb{P}(A)$ be the power set of $A$. What is the number of edges of the intersection graph of the powerset of $A$. I.e how many pairs of sets $x,y$ have the property that $x,y \in \mathbb{P}(A) \land x \bigcap y \neq \varnothing$. Let's call this number $f(n)$.
If $A = \{1\}$ then $f(1) = 0$. If $A = \{1,2\}$, then $f(2) = 2$ (since $\{1\},\{1,2\}$ and $\{2\},\{1,2\}$ are connected). If $A = \{1,2,3\}$, then $f(3) = 15$, see this to see why. I tried counting $f(4)$ and $f(5)$ and got $f(4) = 80, f(5) = 1652$. It seems like the formula is
$$
\frac{1}{2}\left(4^n - 3^n - 2^n + 1\right)
$$
But I can't see why. Any help or direction would be appreciated $:)$.

A: To specify an ordered pair $(x,y)$ with $x,y \in \mathbb P(A)$, we can go through all $n$ elements $i \in A$ and decide whether $i \in x$ and whether $i \in y$: $4$ choices at each step, for $4^n$ total.
To eventually get an edge out of such a pair $(x,y)$, we impose some additional restrictions (subtracting some terms from $4^n$):

*

*We want $x \cap y \ne \varnothing$. So we eliminate $3^n$ pairs for which we never chose both $i \in x$ and $i \in y$ for the same $i$, because in that case $x$ and $y$ wouldn't actually intersect.

*We want $x\ne y$. So we eliminate $2^n$ pairs for which we always either chose $i \in x, i \in y$ or $i \notin x, i \notin y$, because in that case $x$ and $y$ would be equal and we wouldn't get an edge of the graph.

*There is one pair which violates both of the above restrictions: the pair $(\varnothing, \varnothing)$.

By the inclusion-exclusion principle, there are $4^n - 3^n - 2^n + 1$ pairs $(x,y)$ obeying both restrictions: pairs where $x \ne y$ and $x\cap y \ne \varnothing$.
Finally, we divide by $2$ because edges of the graph are unordered pairs $\{x,y\}$, getting $$\frac{4^n - 3^n - 2^n + 1}{2}.$$

A: Although not as conceptually clear as the other answer, another approach is to use induction. Suppose that the count is correct for $A = \{1,\ldots, n-1\}$ and consider the graph corresponding to $A \cup \{n\}$.
First, if $x, y \subseteq A$ were connected, then you get three edges in the graph for $A \cup \{n\}$, namely the ones between $(x, y)$, $(x \cup \{n\}, y)$, and $(x, y \cup \{n\})$. So we have $3 \times f(n-1)$ edges of this type. (We count $(x \cup \{n\}, y \cup \{n\})$ in the next step.)
You are adding $2^{n-1}$ new nodes, all of which contain $n$ and are therefore connected, for a total of
$$
\binom{2^{n-1}}{2} = \frac{2^{n-1}(2^{n-1} - 1)}{2} = \frac12\left(4^{n-1} - 2^{n-1}\right)
$$
edges.
Finally, for every $x \subseteq A$, there is an edge between $x$ and $x \cup \{n\}$, except when $x = \emptyset$, which gives another $2^{n-1} - 1$ edges.
Hence we get:
$$
f(n) = 3\times \frac12 \times \left(4^{n-1} - 3^{n-1} - 2^{n-1} + 1\right) + \frac12\left(4^{n-1} - 2^{n-1}\right) + 2^{n-1} - 1,
$$
and simply grouping powers of $2, 3, 4$ together shows that this is what we expected for $f(n)$.


text:
Q: How to reload Django models without losing my locals in an interactive session? I'm doing some research with an interactive shell and using a Django app (shell_plus) for storing data and browsing it using the convenient admin.
Occasionally I add or change some of the app models, and run a syncdb (or South migration when changing a model). The changes to the models don't take effect in my interactive session even if I re-import the app models. Thus I'm forced to restart the shell_plus and lose my precious locals() in the process.
Is there any way to reload the models during a session?
Thanks!!

A: You can use this snippet to rebuild the AppCache. Do not forget to remove all *.pyc files if any by using something like:
find . -name "*.pyc" -exec rm {} \;

Otherwise the reload() will ignore your changes in your models.py file.


text:
Q: Assigning string as a variable Is it possible to assign a string containing variable names to a variable in R?
For example imagine I have the string "log(p_n) + log((1 - p_n)) + log(p_n * p_b) + log(p_n * (1 - p_b)) + log((1 - p_n) * p_g)". I'd like to make this function:
formula_function = function(p_n, p_b, p_g){
  x <- log(p_n) + log((1 - p_n)) + log(p_n * p_b) + log(p_n * (1 - p_b)) + log((1 - p_n) * p_g)
  return(x)
}

I have a function which generates the formula strings and I'm just copy-pasting them by hand at the moment, is there a more 'program-y' way of doing it?

A: 1) body Assuming you know the parameters:
x <- "log(p_n) + log((1 - p_n)) + log(p_n * p_b) + log(p_n * (1 - p_b)) + log((1 - p_n) * p_g)"

f <- function(p_n, p_b, p_g) {}
body(f) <- parse(text = x)
f
## function (p_n, p_b, p_g)
## log(p_n) + log((1 - p_n)) + log(p_n * p_b) + log(p_n * (1 - p_b)) +
##    log((1 - p_n) * p_g)

2) as.function The gsubfn package has a function for converting formulas to functions.  The order of the formal arguments will be in the order encountered in x or you can specify the order.  Convert the string to a formula using reformulate and then use as.function.
library(gsubfn)

# args are in order encountered
f <- as.function(reformulate(x))
f
## function (p_n, p_b, p_g)
## log(p_n) + log((1 - p_n)) + log(p_n * p_b) + log(p_n * (1 - p_b)) +
##    log((1 - p_n) * p_g)

# specify order of args
f <- as.function(reformulate(x, "p_n + p_g + p_b"))
f
## function (p_n, p_g, p_b)
## log(p_n) + log((1 - p_n)) + log(p_n * p_b) + log(p_n * (1 - p_b)) +
##     log((1 - p_n) * p_g)

3) match.funfn gsubfn also has match.funfn that is like match.fun in R except it also translates arguments passed as formulas to functions.  e.g.
library(gsubfn)

myfun <- function(a, b, c, fun) {
  f <- match.funfn(fun)
  f(a, b, c)
}
myfun(0.1, 0.1, 0.1, reformulate(x, "p_n + p_g + p_b"))
## [1] -11.82901

4) fn$ gsubfn also provides fn which when prefixed to an arbitrary function will interpret formulas as functions.  See the help file ?fn for details.  Note that sapply was not specially written for this but it works anyways.
library(gsubfn)

fn$sapply(1:3, ~ x^2)
## [1] 1 4 9


text:
Q: StringCases with string replace and with escape characters I want to extract url address of all css files inside HTML source.
First output is as expected. But why second and third outputs are different? Notice that only "href" was removed from beginning of the first searching string and then "href=", but Shortest[x__] should remain same, so I would expect all outputs to be the same.
What I am doing wrong?
str="\"/><link rel=\"stylesheet\" type=\"text/css\" href=\"/some/path/to/css/name.min.css";
StringCases[str,"href=\""~~Shortest[x__]~~y:".css"->x~~y]
StringCases[str,"=\""~~Shortest[x__]~~y:".css"->x~~y]
StringCases[str,"\""~~Shortest[x__]~~y:".css"->x~~y]
Clear[str]

(* {"/some/path/to/css/name.min.css"} *)
(* {"stylesheet\" type=\"text/css\" href=\"/some/path/to/css/name.min.css"} *)
(* {"/><link rel=\"stylesheet\" type=\"text/css\" href=\"/some/path/to/css/name.min.css"} *)

Update:
First I thought it has something to do with escape characters used inside strings but here is a simple example:
StringCases["A---A--A____B-A_B-A---A______B---AAAAB","A"~~Shortest[x__]~~"B"->x]

(* {"---A--A____","_","---A______","AAA"} *)

But I believe correct result should be:
(* {"____","_","______"} *)

A: It is just a consequence of how the lazy quantifier in regular expression works. Online test gives the same result.
You should understand that string expressions are first converted to regular expressions by Mathematica. You can see the result with StringPattern`PatternConvert:
StringPattern`PatternConvert[#][[1]] & /@ {"href=\"" ~~ Shortest[x__] ~~ y : ".css",
  "=\"" ~~ Shortest[x__] ~~ y : ".css", "\"" ~~ Shortest[x__] ~~ y : ".css"}

{"(?ms)href=\"(.+?)(\\.css)", "(?ms)=\"(.+?)(\\.css)", "(?ms)\"(.+?)(\\.css)"}

Hence you shouln't be fooled by the name Shortest: it has no relation to Mathematica's own patter matcher's Shortest, which behaves differently.
Further reading:

*

*https://mathematica.stackexchange.com/a/72293/280

*https://mathematica.stackexchange.com/a/108399/280

*https://mathematica.stackexchange.com/a/121855/280

*https://mathematica.stackexchange.com/a/139878/280

UPDATE
On this page, several techniques to overcome this feature of the lazy quantifier are provided, including the most general (but not the most efficient) Tempered Greedy Token Solution. It can be applied as follows for making an equivalent of what could be called a true shortest BlankNullSequence string expression*:
Clear[shortest]
shortest[start_, end_, "IncludeBoundaries" -> True] :=
  RegularExpression[
   StringTemplate["`START`(?:(?!`START`)(?!`END`).)*`END`"][<|"START" -> start,
     "END" -> end|>]];
shortest[start_, end_] := shortest[start, end, "IncludeBoundaries" -> True]
shortest[start_, end_, "IncludeBoundaries" -> False] :=
  RegularExpression[
   StringTemplate["(?<=`START`)(?:(?!`START`)(?!`END`).)*(?=`END`)"][<|"START" -> start,
     "END" -> end|>]];

Testing:
front = "A";
back = "B";
str = "A---A--A____B-A_B-A---A______B---AAAAB";
StringCases[str, shortest[front, back, "IncludeBoundaries" -> False]]

{"____", "_", "______", ""}

front = "href=\"";
back = "\\.css";
str = "\"/><link rel=\"stylesheet\" type=\"text/css\" \
href=\"/some/path/to/css/name.min.css";
StringCases[str, shortest[front, back, "IncludeBoundaries" -> False]]
front = "=\"";
StringCases[str, shortest[front, back, "IncludeBoundaries" -> False]]
front = "\"";
StringCases[str, shortest[front, back, "IncludeBoundaries" -> False]]

{"/some/path/to/css/name.min"}

{"/some/path/to/css/name.min"}

{"/some/path/to/css/name.min"}

*As the OP shows in the comments, this method fails miserably in more complicated cases:
front = "tomato";
back = "iconic";
str = "gffghtomatomato12345iconiconictomatomatoiconiconic";
StringCases[str, shortest[front, back, "IncludeBoundaries" -> False]]

{"mato12345", "mato", ""}

This result is wrong. The expected result is {"12345",""}.
Here is another version which gives the desired result:
Clear[shortest2]
shortest2[str_, start_, end_] :=
  StringCases[str,
   RegularExpression[
     StringTemplate["(?!.{1,`len`}`START`)`START`((?:(?!`START`)(?!`END`).)*)`END`"][<|
       "len" -> StringLength[start], "START" -> start, "END" -> end|>]] -> "$1"];

front = "tomato";
back = "iconic";
str = "gffghtomatomato12345iconiconictomatomatoiconiconic";
shortest2[str, front, back]

{"12345", ""}

However, in some special cases this method also fails:
front = "NotEnd";
back = "End";
str = "NotEndNotEnd1234NotEnd";
shortest2[str, front, back]

{}

Hence the approach suggested by the OP should be preferred.

UPDATE 2
It seems that I managed to find a really universal solution through regular expressions:
Clear[ShortestStringBetween]
Options[ShortestStringBetween] = {"IncludeBoundaries" -> False,
   "BoundaryOverlaps" -> False};
ShortestStringBetween[str_String, start_String, end_String, OptionsPattern[]] :=
  Module[{bInclude = OptionValue["IncludeBoundaries"],
    bOvelap = OptionValue["BoundaryOverlaps"]},
   Which[
    bInclude && Not[bOvelap],
    StringCases[str, RegularExpression[
      StringTemplate["`START`(?:(?!`END`).(?<!`START`))*`END`"][
       <|"START" -> start, "END" -> end|>]]],
    Not[bInclude] && Not[bOvelap],
    StringCases[str, RegularExpression[
       StringTemplate["`START`((?:(?!`END`).(?<!`START`))*)`END`"][
        <|"START" -> start, "END" -> end|>]] -> "$1"],
    Not[bInclude] && bOvelap,
    StringCases[str, RegularExpression[
      StringTemplate["(?<=`START`)(?:(?!`END`).(?<!`START`))*(?=`END`)"][
       <|"START" -> start, "END" -> end|>]]],
    bInclude && bOvelap,
    StringCases[str, match : RegularExpression[
        StringTemplate["(?<=`START`)(?:(?!`END`).(?<!`START`))*(?=`END`)"][
         <|"START" -> start, "END" -> end|>]] :> StringJoin[start, match, end]]
    ]];

Note that the start and end parameters are directly inserted into RegularExpression and therefore must be regular expressions in the Mathematica format. And since PCRE (on which RegularExpression is based) doesn't support infinite repetition within a lookbehind, the start parameter must be a fixed-length regexp or contain alternations of different but pre-determined lengths (for example, "cat|raccoon"). The end parameter has no such restriction. But I haven't tested how this implementation behaves with non-fixed length parameters.
It works correctly in the all test cases:
front = "tomato";
back = "iconic";
str = "gffghtomatomato12345iconiconictomatomatoiconiconic";
ShortestStringBetween[str, front, back]

{"12345", ""}

front = "NotEnd";
back = "End";
str = "NotEndNotEnd1234NotEnd";
ShortestStringBetween[str, front, back]
ShortestStringBetween[str, front, back, "BoundaryOverlaps" -> True]

{"Not"}

{"Not", "1234Not"}

A: This finds shortest strings inside str that are between strings front and back (including empty string).
shortest[str_,front_,back_]:=Module[{p1,p2,p},
p1={#,1}&/@StringPosition[str,front][[All,2]];
p2={#,2}&/@StringPosition[str,back][[All,1]];
p={1,-1}+#&/@SequenceCases[Sort[Join[p1,p2]],{{_,1},{_,2}}][[All,All,1]];
StringTake[str,p]
]

front="A";
back="B";
str="A---A--A____B-A_B-A---A______B---AAAAB";
shortest[str,front,back]
Clear[front,back,str]

(* {"____", "_", "______", ""} *)

front="href=\"";
back=".css";
str="\"/><link rel=\"stylesheet\" type=\"text/css\" href=\"/some/path/to/css/name.min.css";
shortest[str,front,back]
front="=\"";
shortest[str,front,back]
front="\"";
shortest[str,front,back]
Clear[front,back,str]

(* {"/some/path/to/css/name.min"} *)
(* {"/some/path/to/css/name.min"} *)
(* {"/some/path/to/css/name.min"} *)


text:
Q: Is MemoryStore express middleware still leaking? I'm planning to use MemoryStore in production. My application doesn't care about lost session data after server restart & is small enough so there is no need for scaling. Taking that in count there is only one concern that I have left - warning that says: MemoryStore is not designed for a production environment, as it will leak memory, and will not scale past a single process.
Here is a suggestion of how it can be worked around: https://stackoverflow.com/a/10761522/4446128
Please note, at the time of writing, there is no answer to my question in linked question & I can't ask there because it requires 50 reputation which I don't have.
I set interval to log all sessions (.all method on MemoryStore) & I see that sessions are being cleaned up after expiration date - so I don't think that leak is happening, but not 100% sure. Can someone confirm that it is not an issue anymore or tell me that I'm wrong & leak is still happening? If leak can still happen, please explain why.
Also not 100% sure that is relevant, but I'm using passport for authentication, so maybe it is cleaning up sessions?
Thank you.


text:
Q: Can "AddInProcess.exe has stopped working" be suppressed? I am attempting to sandbox potentially malicious code by executing it within a MAF plugin launched in its own process:
    var x = token.Activate<Ix>(new AddInProcess(), AddInSecurityLevel.Internet);

This seems to work well except that when handling a StackOverflowException a dialog is shown:  "AddInProcess.exe has stopped working".  This makes it very hard to test
    [TestMethod]
    public void TestStackOverflow() {
        var host = new Host(Environment.CurrentDirectory
            + "/../../../build/pipeline");
        host.Run("foo");
        host.Tick();
        Thread.Sleep(1000);
        host.Monitors.Count.Should().Be(0);
        host.Shutdown();
    }

If I click the "close" button before the Sleep expires, the test succeeds, otherwise it fails.  This indicates that the process does not exit until the "close" button is pressed.  Given I am expecting the process to terminate, how can I make sure it does so without raising this dialog?  I have tried setting my OS to "never check for solutions" but the dialog still comes up.  Setting it to "automatically check for solutions" avoids the dialog but takes up to ten seconds which is not desirable... and I would rather avoid an OS setting.

A: You can call SetErrorMode somewhere inside the addin process like so:
    [Flags]
    enum ErrorModes : uint {
        SYSTEM_DEFAULT = 0x0,
        SEM_FAILCRITICALERRORS = 0x0001,
        SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
        SEM_NOGPFAULTERRORBOX = 0x0002,
        SEM_NOOPENFILEERRORBOX = 0x8000
    }

    [DllImport( "kernel32.dll" )]
    static extern ErrorModes SetErrorMode( ErrorModes uMode );

    var em = SetErrorMode( 0 );
    SetErrorMode( em | ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOOPENFILEERRORBOX );


text:
Q: Проблема с console.log в прототипе конструктора Подскажите пожалуйста причину, по которой после f.call(console, x) итерация не прерывается (а должна вообще после f.call() прерывается) и выполняется следующий код.
function rangeTwo(from, to)
{
    this.from = from;
    this.to = to;
}

rangeTwo.prototype = {

    foreach: function(f) {
        for (var x = Math.ceil(this.from); x <= this.to; x++) {
            if (f == console.log) {
                f.call(console, x);
                continue;
            }
            f(x); // Без continue выполняется
        }
    }

};

Костыль подставил в виде continue. Если убрать его, то отваливается с ошибкой, понимаю почему...для log значение this должно указывать на console.

A: а что собственно не правильно: jsbin - не должна она прерываться. f.call - это просто способ вызвать функцию с нужным контекстом, он не прерывает выполнение цикла или прочего асинхронного кода.