text:
Q: Is there any particular font family which can be used for displaying different languages in tcpdf? I am trying to generate a pdf file which contains different languages at the same time(like English, French, Chinese, Malay, Thai etc)using PHP and tcpdf. But as I tried, it work for only some languages. Font-family I used is freesans. Can I anybody help me, how can I achieve this?

A: Noto is a Google free font which is designed for more than 800 languages. Here is a Guidelines for Using Noto. And here is a stackoverflow post for how to add custom fonts in tcpdf.


text:
Q: How to switch from tailwind CSS Play CDN to production build? I am using Tailwind CSS Play CDN for local development, and would like to use PostCSS to build a production version
Basically every time I need to manually replace the following line in index.html
<script src="https://cdn.tailwindcss.com"></script>
with
<link href="/dist/main.css" rel="stylesheet">
before pushing to production site
What is the best way to do that automatically each time I publish the website?

A: Quotes from tailwind docs

Use the Play CDN to try Tailwind right in the browser without any build step. The Play CDN is designed for development purposes only, and is not the best choice for production.

So you need to use build tools like webpack, Rollup, Vite, and Parcel

*

*Tailwind CSS with Parcel

*Using Postcss

redpajama_set_name: RedPajamaStackExchange


text:
Q: Whether the type of application affects the unit per minute cost? I know that characteristic and numbers of virtual servers or amount of memory we use or region where we run VM influence cost, but question to a specialist.
Is there a type of application that we run that affects unit per minute cost?
Thanks in advance!

A: Google cloud runs a per minute billing model. For applications the billing is factored on the environment you are using.
There are two: standard environment and app engine flexible environment.  Standard environment billing is cheaper than flexible app environment billing.
These quite depends on the resources you are provisioning.  Also I think legacy apps too could be a factor to what you will be billed

A: While other cloud providers charge for services by the hour, Google charges for all services per second, which can add up to major savings when instances are frequently started and stopped.Pricing is different for apps in the standard environment and the flexible environment. Apps in both environments may also incur charges from other Google Cloud products, depending on which products they use in addition to App Engine.
Apps in the standard environment have a free tier for App Engine resources. Any use of App Engine resources beyond the free tier incurs charges, To estimate costs for App Engine resources in the standard environment, use the pricing calculator.
App Engine does not provide a free tier in the flexible environment.Apps running in the flexible environment are deployed to virtual machine types that you specify. These virtual machine resources are billed on a per-second basis with a 1 minute minimum usage cost.
Billing for the memory resource includes the memory your app uses plus the memory that the runtime itself needs to run your app. This means your memory usage and costs can be higher than the maximum memory you request for your app.
Refer to the link  for more information about pricing.


text:
Q: ubuntu 14.04 getting freezeed I have installed ubuntu 14.04 on laptop (toshiba setellite c) with core i3, 2gb ram.
Please give me solution on this or suggest any other best version.
Thanks.

A: You can install Lubuntu. It based on Ubuntu but using LXDE (desktop environment). LXDE have low-system-requirement for older PC and laptop with low RAM like you laptop.


text:
Q: smell some bad smell Someone farts in the class.
Jack noticed that and said, "What's that smell?"
Keith haven't smelled that and asked Jack, "Smell, I didn't smell anything."
Jack said, "I smell stinks." or "I smell some bad smell."
Smell can be verb and noun, how do we used it?

A: It can also be an adjective:
Noun:

"What is that smell? It stinks!"

Verb:

"Can you smell that? It stinks!"

or

"Smell this. It smells good."

Adjective:

"It's very smelly in here. In fact, it stinks."

A: I don't think it's right to say "I smell stinks"; "I smell something stinky" would be OK. While "smell" can be a noun or a verb, "stink" is only a verb.


text:
Q: setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (SequencerActivity) back.setOnClickListener(this); I want to display an image on button click, but I have three errors in my code. What's wrong?

*

*class name "SequencerActivity"

The type SequencerActivity must implement the inherited abstract method DialogInterface.OnClickListener.onClick(DialogInterface, int).

*next.setOnClickListener(this);

The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (SequencerActivity).

*onClick(View v)

The method onClick(View) of type SequencerActivity must override or implement a supertype method.
Here's the code giving those errors:
public class SequencerActivity extends Activity implements OnClickListener
{
private int imageCounter = 0;
private ImageView imageLoader;

private int[] imageList = {R.drawable.f03, R.drawable.f04, R.drawable.f05, R.drawable.f06};

@Override
public void onCreate(Bundle savedInstanceState)
{
    setContentView(R.layout.main);//this one is the common parent layout for all image views
    super.onCreate(savedInstanceState);

    /*requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);*/

    //int image1 = R.drawable.image_w_lbl_0;

    imageLoader = (ImageView) findViewById(R.id.imageLoader);
    //imageLoader.setImageResource(image1);

    Button next = (Button) findViewById(R.id.next);
    Button back = (Button) findViewById(R.id.back);
    next.setOnClickListener(this);
    back.setOnClickListener(this);
    back.setEnabled(false);
    //show the default image
    this.loadImage(imageList[imageCounter]);

}
@Override
public void onClick(View v)
{
    int imagePath = 0;
    // TODO Auto-generated method stub
    switch (v.getId())
    {
    case R.id.next:
        Log.i("Tag","tag");
        if(imageCounter < imageList.length)
        {
            imageCounter++;
            imagePath = imageList[imageCounter];
            if (imageCounter==(imageList.length)-1)
            {
                {
                    ImageButton next=(ImageButton)findViewById(R.id.next);
                    next.setEnabled(false);
                }
            }
            else
            {
                ImageButton back=(ImageButton)findViewById(R.id.back);
                back.setEnabled(true);
            }
        }
        break;
    case R.id.back:
        if(imageCounter > 0)
        {
            imageCounter--;
            imagePath = imageList[imageCounter];
            if (imageCounter==0)
            {
                ImageButton back=(ImageButton)findViewById(R.id.back);
                back.setEnabled(false);
            }
            else
            {
                ImageButton next=(ImageButton)findViewById(R.id.next);
                next.setEnabled(true);
            }
        }
        break;
    }
    this.loadImage(imagePath);

}

private void loadImage(int imagePath)
{
    imageLoader.setImageResource(imagePath);

}

}

A: The OnClickListener that you implement is not correct,
try to implement View.OnClickListener and not DialogInterface.OnClickListener.
You can see that in your import
import View.OnClickListener
instead of
import DialogInterface.OnClickListener

A: The OnClickListener you're implementing is the wrong one. It says it's DialogInterface.OnClickListener, while you probably want View.OnClickListener. You can correct that in the corresponding import statement.

A: Just do only One thing. Use "import android.view.View.OnClickListener" statement at the top of the program.

A: you need to import import android.view.View.OnClickListener;

So your code look like
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener{
  // Your oncreate() and rest of all code
}
// you should have method as below
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    if(v.getId() == R.id.editText1) // just for instance
    {
        .. your onclick handle code
    }
}

A: Still you are not able to resolve the error type import View.OnClickListener; then move the cursor on the View in import View.OnClickListener; It will open up pop-up then choose the Organize imports option.
Use simply import View.OnClickListener; at the top.

A: Do one thing
remove import android.content.DialogInterface.OnClickListener;
and import
android.View.View.OnClickListener
this will solve the problem
Happy Coding

A: Implement View.view.onClickListener


text:
Q: Возможно ли создать круговой Progress Bar на PyQt5 без .png заготовок? Прогресс загрузки неопределённый, либо определённый, неважно. Основная потребность узнать как это работает.
Видел как люди используют метод PyCircularProgress. Я тоже попробовал такой подставить вместо QProgressBar, но IDE подсвечивает что такой модуль не найден.
В документации по PyQt5 я тоже ничего не нашёл кроме QProgressBar и QProgressDialog.
Возможно его нужно как то стилизовать через setStyleSheet?

A: Возможно, пробуйте и выбирайте что вам больше нравится.
import sys
from PyQt5.QtCore    import pyqtProperty, QSize, Qt, QRectF, QTimer
from PyQt5.QtGui     import QColor, QPainter, QFont
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QSlider, \
    QApplication

class PercentProgressBar(QWidget):
    MinValue    =   0
    MaxValue    = 100
    Value       =   0
    BorderWidth =   8
    Clockwise       = True   # По часовой стрелке или против часовой стрелки
    ShowPercent     = True   # Отображать ли процент
    ShowFreeArea    = False  # Показывать позади остальных
    ShowSmallCircle = False  # Покажите небольшой круг с головой
    TextColor       = QColor(255, 255, 255)  # Цвет текста
    BorderColor     = QColor(24, 189, 155)   # Цвет пограничного круга
    BackgroundColor = QColor(70, 70, 70)     # Цвет фона

    def __init__(self, *args, value=0, minValue=0, maxValue=100,
                 borderWidth=8, clockwise=True, showPercent=True,
                 showFreeArea=False, showSmallCircle=False,
                 textColor=QColor(255, 255, 255),
                 borderColor=QColor(24, 189, 155),
                 backgroundColor=QColor(70, 70, 70), **kwargs):
        super(PercentProgressBar, self).__init__(*args, **kwargs)

        self.Value    = value
        self.MinValue = minValue
        self.MaxValue = maxValue
        self.BorderWidth     = borderWidth
        self.Clockwise       = clockwise
        self.ShowPercent     = showPercent
        self.ShowFreeArea    = showFreeArea
        self.ShowSmallCircle = showSmallCircle
        self.TextColor       = textColor
        self.BorderColor     = borderColor
        self.BackgroundColor = backgroundColor

    def setRange(self, minValue: int, maxValue: int):
        if minValue >= maxValue:
            return
        self.MinValue = minValue
        self.MaxValue = maxValue
        self.update()

    def paintEvent(self, event):
        super(PercentProgressBar, self).paintEvent(event)
        width = self.width()
        height = self.height()
        side = min(width, height)

        painter = QPainter(self)
        painter.setRenderHints(QPainter.Antialiasing |
                               QPainter.TextAntialiasing)
        # координатный центр - средняя точка
        painter.translate(width / 2, height / 2)
        # 100x100 масштабирование
        painter.scale(side / 100.0, side / 100.0)
        self._drawCircle(painter, 50)
        # Нарисуйте дугу
        self._drawArc(painter, 50 - self.BorderWidth / 2)
        # Текст
        self._drawText(painter, 50)

    def _drawCircle(self, painter: QPainter, radius: int):
        radius = radius - self.BorderWidth
        painter.save()
        painter.setPen(Qt.NoPen)
        painter.setBrush(self.BackgroundColor)
        painter.drawEllipse(QRectF(-radius, -radius, radius * 2, radius * 2))
        painter.restore()

    def _drawArc(self, painter: QPainter, radius: int):
        # Нарисуйте дугу
        painter.save()
        painter.setBrush(Qt.NoBrush)
        # Изменить кисть
        pen = painter.pen()
        pen.setWidthF(self.BorderWidth)
        pen.setCapStyle(Qt.RoundCap)

        arcLength = 360.0 / (self.MaxValue - self.MinValue) * self.Value
        rect = QRectF(-radius, -radius, radius * 2, radius * 2)

        if not self.Clockwise:
            # против часовой стрелки
            arcLength = -arcLength

        # Нарисуйте оставшуюся прокрутку
        if self.ShowFreeArea:
            acolor = self.BorderColor.toRgb()
            acolor.setAlphaF(0.2)
            pen.setColor(acolor)
            painter.setPen(pen)
            painter.drawArc(rect, (0 - arcLength) *
                            16, -(360 - arcLength) * 16)

        # Нарисуйте текущую прокрутку
        pen.setColor(self.BorderColor)
        painter.setPen(pen)
        painter.drawArc(rect, 0, -arcLength * 16)

        # Нарисуйте небольшой круг перед дугой прогресса
        if self.ShowSmallCircle:
            offset = radius - self.BorderWidth + 1
            radius = self.BorderWidth / 2 - 1
            painter.rotate(-90)
            circleRect = QRectF(-radius, radius + offset,
                                radius * 2, radius * 2)
            painter.rotate(arcLength)
            painter.drawEllipse(circleRect)

        painter.restore()

    def _drawText(self, painter: QPainter, radius: int):
        painter.save()
        painter.setPen(self.TextColor)
        painter.setFont(QFont('Arial', 25))
        strValue = '{}%'.format(int(self.Value / (self.MaxValue - self.MinValue)
                                    * 100)) if self.ShowPercent else str(self.Value)
        painter.drawText(QRectF(-radius, -radius, radius * 2,
                                radius * 2), Qt.AlignCenter, strValue)
        painter.restore()

    @pyqtProperty(int)
    def minValue(self) -> int:
        return self.MinValue

    @minValue.setter
    def minValue(self, minValue: int):
        if self.MinValue != minValue:
            self.MinValue = minValue
            self.update()

    @pyqtProperty(int)
    def maxValue(self) -> int:
        return self.MaxValue

    @maxValue.setter
    def maxValue(self, maxValue: int):
        if self.MaxValue != maxValue:
            self.MaxValue = maxValue
            self.update()

    @pyqtProperty(int)
    def value(self) -> int:
        return self.Value

    @value.setter
    def value(self, value: int):
        if self.Value != value:
            self.Value = value
            self.update()

    @pyqtProperty(float)
    def borderWidth(self) -> float:
        return self.BorderWidth

    @borderWidth.setter
    def borderWidth(self, borderWidth: float):
        if self.BorderWidth != borderWidth:
            self.BorderWidth = borderWidth
            self.update()

    @pyqtProperty(bool)
    def clockwise(self) -> bool:
        return self.Clockwise

    @clockwise.setter
    def clockwise(self, clockwise: bool):
        if self.Clockwise != clockwise:
            self.Clockwise = clockwise
            self.update()

    @pyqtProperty(bool)
    def showPercent(self) -> bool:
        return self.ShowPercent

    @showPercent.setter
    def showPercent(self, showPercent: bool):
        if self.ShowPercent != showPercent:
            self.ShowPercent = showPercent
            self.update()

    @pyqtProperty(bool)
    def showFreeArea(self) -> bool:
        return self.ShowFreeArea

    @showFreeArea.setter
    def showFreeArea(self, showFreeArea: bool):
        if self.ShowFreeArea != showFreeArea:
            self.ShowFreeArea = showFreeArea
            self.update()

    @pyqtProperty(bool)
    def showSmallCircle(self) -> bool:
        return self.ShowSmallCircle

    @showSmallCircle.setter
    def showSmallCircle(self, showSmallCircle: bool):
        if self.ShowSmallCircle != showSmallCircle:
            self.ShowSmallCircle = showSmallCircle
            self.update()

    @pyqtProperty(QColor)
    def textColor(self) -> QColor:
        return self.TextColor

    @textColor.setter
    def textColor(self, textColor: QColor):
        if self.TextColor != textColor:
            self.TextColor = textColor
            self.update()

    @pyqtProperty(QColor)
    def borderColor(self) -> QColor:
        return self.BorderColor

    @borderColor.setter
    def borderColor(self, borderColor: QColor):
        if self.BorderColor != borderColor:
            self.BorderColor = borderColor
            self.update()

    @pyqtProperty(QColor)
    def backgroundColor(self) -> QColor:
        return self.BackgroundColor

    @backgroundColor.setter
    def backgroundColor(self, backgroundColor: QColor):
        if self.BackgroundColor != backgroundColor:
            self.BackgroundColor = backgroundColor
            self.update()

    def setValue(self, value):
        self.value = value

    def sizeHint(self) -> QSize:
        return QSize(100, 100)

class Window(QWidget):
    def __init__(self, *args, **kwargs):
        super(Window, self).__init__(*args, **kwargs)

        layout = QHBoxLayout(self)
        self._value   = 0
        self._widgets = []
        self._timer   = QTimer(self, timeout=self.updateValue)

        self._widgets.append(PercentProgressBar(self))
        layout.addWidget(self._widgets[0])

        self._widgets.append(PercentProgressBar(self, clockwise=False))
        layout.addWidget(self._widgets[1])

        self._widgets.append(PercentProgressBar(self, showPercent=False))
        layout.addWidget(self._widgets[2])

        self._widgets.append(PercentProgressBar(self, showFreeArea=True))
        layout.addWidget(self._widgets[3])

        self._widgets.append(PercentProgressBar(self, showSmallCircle=True))
        layout.addWidget(self._widgets[4])

        self._widgets.append(PercentProgressBar(self, styleSheet="""
            qproperty-textColor: rgb(255, 0, 0);
            qproperty-borderColor: rgb(0, 255, 0);
            qproperty-backgroundColor: rgb(0, 0, 255);
        """))
        layout.addWidget(self._widgets[5])

        rWidget = QWidget(self)
        layout.addWidget(rWidget)

        vlayout = QVBoxLayout(rWidget)
        self.staticPercentProgressBar = PercentProgressBar(self)
        self.staticPercentProgressBar.showFreeArea = True
        self.staticPercentProgressBar.ShowSmallCircle = True
        vlayout.addWidget(self.staticPercentProgressBar)
        vlayout.addWidget(QSlider(self, minimum=0, maximum=100,
                                  orientation=Qt.Horizontal,
                                  valueChanged=self.staticPercentProgressBar.setValue))
        self._timer.start(100)

    def updateValue(self):
        for w in self._widgets:
            w.value = self._value
        self._value += 1
        if self._value > 100:
            self._value = 0

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())


text:
Q: Compass Navigation With ArcGIS SDK for iOS There's a sample provided by esri named GpsSample (I can't find a way to upload it here)
Anyway, the sample includes multiple selections for mapview's locationDisplay autoPanMode property
I'm trying to implement it in a similar way, my code is the same, difference is I'm creating the UI controls dynamically (mapview included) without relying on static XIBs
Debugging the code, the autoPanMode property for the map changes correctly but the mapview still wouldn't be automatically rotated like in the provided sample
Finally, I set mapview's allowRotatingByPinching to YES, the map and attached compass image are rotating correctly via pinching. But still wouldn't automatically rotate itself.

A: Try setting the autoPanMode property to either AGSLocationDisplayAutoPanModeNavigation or AGSLocationDisplayAutoPanModeCompassNavigation because, according to the docs, those should rotate the map.
Also beware that panning or zooming the map will turn off autoPanMode.

A: I found out what was wrong
I set locationDisplay.dataSource.Delegate to self, and it was causing all these issues
Using the locationDisplayDataSourceDelegate methods, I was receiving location and heading updates without any trouble. Yet it appears that I also had to implement a way to draw the symbol and handle the map view responses to the autoPanMode
I think it'll be easier to keep it this way and create another location manager instance to receive location data.


text:
Q: CSS list gradual fade in with unknown amount I was trying to make a gradual fadein using normal CSS and no jquery on a list so it can fade in one-by-one. However, I only know how to do it in a limited amount of list. How do I loop the css so no matter how much list I have it still works.
Here is what I have done:

.ladder {
  opacity: 0;
  -webkit-animation: fadeIn 0.9s 1;
  animation: fadeIn 0.9s 1;
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

.ladder:nth-child(5n+1) {
  -webkit-animation-delay: 0.2s;
  animation-delay: 0.2s;
}

.ladder:nth-child(5n+2) {
  -webkit-animation-delay: 0.4s;
  animation-delay: 0.4s;
}

.ladder:nth-child(5n+3) {
  -webkit-animation-delay: 0.6s;
  animation-delay: 0.6s;
}

.ladder:nth-child(5n+4) {
  -webkit-animation-delay: 0.8s;
  animation-delay: 0.8s;
}

.ladder:nth-child(5n+5) {
  -webkit-animation-delay: 1.0s;
  animation-delay: 1.0s;
}

@-webkit-keyframes fadeIn {
  0% {
    opacity: 0.0;
  }
  100% {
    opacity: 1.0;
  }
}

@keyframes fadeIn {
  0% {
    opacity: 0.0;
  }
  100% {
    opacity: 1.0;
  }
}

A

B

C

D

E

My question: How to make the css to work on no matter how much list there is.

A: Here is an idea using CSS variable that allow you to reduce the code. It's not generic but it's more easier to append a simple inline CSS to each li than writing complex CSS:

.ladder {
  opacity: 0;
  animation: fadeIn 1s var(--d) forwards;
}

@keyframes fadeIn {
  100% {
    opacity: 1;
  }
}

A

B

C

D

E

Here is another idea where you can apply an animation on the ul:

ul {
  position:relative;
}
ul:before {
  content:"";
  position:absolute;
  top:-20px;
  bottom:0;
  left:0;
  right:0;
  background:linear-gradient(to bottom,transparent,#fff 20px);
  animation:fadeIn 2s forwards
}

@keyframes fadeIn {
  0% {
    top:-10px;
  }
  100% {
    top: 100%;
  }
}

A

B

C

D

E


text:
Q: How in adminer to increase current session on login? Using adminer-4.7.7 with plugin login-password-less.php
I found a way how to enter adminer without credentials entered.
But entering adminer I would like to keep the current session as far as possible(including
current db and table opened), even after browse closed/opened next day...
Has adminer session time parameter/tools?
That is for my home laptop ( kununtu18, apache 2, php 7.4), so security breaks are ignored...
apache config decisions also possible.
How can I do it ?
MODIFIED :
I tried to increase gc_maxlifetime as in Jasar Orion code, but failed
I modified session block in adminer/include/bootstrap.inc.php  as:
global $adminer, $connection, $driver, $drivers, $edit_functions, $enum_length, $error, $functions, $grouping, $HTTPS, $inout, $jush, $LANG, $langs, $on_actions, $permanent, $structured_types, $has_token, $token, $translations, $types, $unsigned, $VERSION; // allows including Adminer inside a function

if (!$_SERVER["REQUEST_URI"]) { // IIS 5 compatibility
   $_SERVER["REQUEST_URI"] = $_SERVER["ORIG_PATH_INFO"];
}
if (!strpos($_SERVER["REQUEST_URI"], '?') && $_SERVER["QUERY_STRING"] != "") { // IIS 7 compatibility
   $_SERVER["REQUEST_URI"] .= "?$_SERVER[QUERY_STRING]";
}
if ($_SERVER["HTTP_X_FORWARDED_PREFIX"]) {
   $_SERVER["REQUEST_URI"] = $_SERVER["HTTP_X_FORWARDED_PREFIX"] . $_SERVER["REQUEST_URI"];
}
$HTTPS = ($_SERVER["HTTPS"] && strcasecmp($_SERVER["HTTPS"], "off")) || ini_bool("session.cookie_secure"); // session.cookie_secure could be set on HTTP if we are behind a reverse proxy

@ini_set("session.use_trans_sid", false); // protect links in export, @ - may be disabled
if (!defined("SID")) {
   session_cache_limiter(""); // to allow restarting session
   session_name("adminer_sid"); // use specific session name to get own namespace
// $params = array(0, preg_replace('~\?.*~', '', $_SERVER["REQUEST_URI"]), "", $HTTPS);
   if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
      $params[] = true; // HttpOnly
   }
    $lifetime = time() + 97 * 24 * 60 * 60;
    $params = array($lifetime, preg_replace('~\?.*~', '', $_SERVER["REQUEST_URI"]), "", $HTTPS);

    ini_set('session.gc_maxlifetime', 99600);
   call_user_func_array('session_set_cookie_params', $params); // ini_set() may be disabled

    session_set_cookie_params(99600);

    session_start();
}

It is invalid way? Which way is valid?
Thanks!

A: If you open file adminer/adminer/include/bootstrap.inc.php:57 you could see the following code:
call_user_func_array('session_set_cookie_params', $params); // ini_set() may be disabled

According to documentation this methods sets session lifetime. By default it set to 0, which means that session will be destroyed when browser is closed.
I suppose, you could set another value you want:
$lifetime = time() + 7 * 24 * 60 * 60;
$params = array($lifetime, preg_replace('~\?.*~', '', $_SERVER["REQUEST_URI"]), "", $HTTPS);

A: This could be a problem of permission,
can you check in your phpinfo() the value of "session.save_path", if you are working on localhost this is normally C:\xampp\tmp.
If you are working on ubuntu the session folder should be /var/lib/php/session, if the folder session doesn't exist you should navigate to /var/lib/php/ and create the folder with:
mkdir session

then you need to extend the permission to user www-data, with:
sudo chown -R www-data:www-data /var/lib/php/session

Good luck!

A: Session timeout is a notion that has to be implemented in code if you want strict guarantees; that's the only way you can be absolutely certain that no session ever will survive after X minutes of inactivity.
If relaxing this requirement a little is acceptable and you are fine with placing a lower bound instead of a strict limit to the duration, you can do so easily and without writing custom logic.
Convenience in relaxed environments: how and why
If your sessions are implemented with cookies (which they probably are), and if the clients are not malicious, you can set an upper bound on the session duration by tweaking certain parameters. If you are using PHP's default session handling with cookies, setting session.gc_maxlifetime along with session_set_cookie_params should work for you like this:
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);

// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);

session_start(); // ready to go!

This works by configuring the server to keep session data around for at least one hour of inactivity and instructing your clients that they should "forget" their session id after the same time span. Both of these steps are required to achieve the expected result.

*

*If you don't tell the clients to forget their session id after an hour (or if the clients are malicious and choose to ignore your instructions) they will keep using the same session id and its effective duration will be non-deterministic. That is because sessions whose lifetime has expired on the server side are not garbage-collected immediately but only whenever the session GC kicks in.
GC is a potentially expensive process, so typically the probability is rather small or even zero (a website getting huge numbers of hits will probably forgo probabilistic GC entirely and schedule it to happen in the background every X minutes). In both cases (assuming non-cooperating clients) the lower bound for effective session lifetimes will be session.gc_maxlifetime, but the upper bound will be unpredictable.

*If you don't set session.gc_maxlifetime to the same time span then the server might discard idle session data earlier than that; in this case, a client that still remembers their session id will present it but the server will find no data associated with that session, effectively behaving as if the session had just started.
Certainty in critical environments
You can make things completely controllable by using custom logic to also place an upper bound on session inactivity; together with the lower bound from above this results in a strict setting.
Do this by saving the upper bound together with the rest of the session data:
session_start(); // ready to go!

$now = time();
if (isset($_SESSION['discard_after']) && $now > $_SESSION['discard_after']) {
    // this session has worn out its welcome; kill it and start a brand new one
    session_unset();
    session_destroy();
    session_start();
}

// either new or old, it should live at most for another hour
$_SESSION['discard_after'] = $now + 3600;

Session id persistence
So far we have not been concerned at all with the exact values of each session id, only with the requirement that the data should exist as long as we need them to. Be aware that in the (unlikely) case that session ids matter to you, care must be taken to regenerate them with session_regenerate_id when required.


text:
Q: Why can Twitter API Authorization data be sent through GET or POST params instead of HTTP headers? I'm using oauth.js and sha1.js in a Greasemonkey script:
// ==UserScript==
// @name        twitter_api
// @namespace   twitter
// @include     *
// @version     1
// @require http://oauth.googlecode.com/svn/code/javascript/oauth.js
// @require http://pajhome.org.uk/crypt/md5/sha1.js
// ==/UserScript==

var url = "https://api.twitter.com/1.1/statuses/update.json";
var accessor = {
  token: "XXX",
  tokenSecret: "XXX",
  consumerKey : "XXX",
  consumerSecret: "XXX"
};
var message = {
  action: url,
  method: "POST",
  parameters: {status: "apitest"}
};
OAuth.completeRequest(message, accessor);
OAuth.SignatureMethod.sign(message, accessor);
var authorization = "OAuth oauth_consumer_key=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_consumer_key) + "\""
            + ", oauth_nonce=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_nonce) + "\""
            + ", oauth_signature=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_signature) + "\""
            + ", oauth_signature_method=\"HMAC-SHA1\""
            + ", oauth_timestamp=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_timestamp) + "\""
            + ", oauth_token=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_token) + "\""
            + ", oauth_version=\"1.0\"";

Using Authorization header with POST request:
GM_xmlhttpRequest({
  method: "POST",
  url: url,
  data: "status=apitest",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": authorization
  },
  onload: function(response) {
    alert(response.responseText);
  }
});

Using GET params only with POST request:
GM_xmlhttpRequest({
  method: "POST",
  url: url + '?' + OAuth.formEncode(message.parameters),
  onload: function(response) {
    alert(response.responseText);
  }
});

Using POST params only with POST request:
GM_xmlhttpRequest({
  method: "POST",
  url: url,
  data: OAuth.formEncode(message.parameters),
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  onload: function(response) {
    alert(response.responseText);
  }
});

Why do this 3 AJAX requests work when Twitter clearly says you have to send an Authorization header?
https://dev.twitter.com/docs/auth/authorizing-request
If both GET, POST, HTTP header Authorization are accepted, why should I prefer HTTP header, is it more secure or maybe it doesn't matter since it's an API call?


text:
Q: JavaScript chrome automation Im trying to create a shortcut on chrome by console but I do know anything about JS.
The shortcut receive the key then click in some coordinate.
What`s the problem with my code?
$(document).on('keydown', function(e)
{
  console.log(e.which); // Retur the number of key code
  if (e.which === 67))
  {
      document.elementFromPoint(x, y).click();
  }
}


text:
Q: how to match abbreviations with their meaning with regex? I'm looking for a regex pattern that matches the following string:

Some example text (SET) that demonstrates what I'm looking for. Energy system models (ESM) are used to find specific optima (SCO). Some say computer systems (CUST) are cool. In the summer playing outside (OUTS) should be preferred.

My goal is to match the following:
Some example text (SET)
Energy system models (ESM)
specific optima (SCO)
computer systems (CUST)
outside (OUTS)

The important part is that it's not always exactly three words and their first letter. Sometimes the letters used for the abbreviation are merely contained in the preceding words. That's why I started looking into the positive lookbehind. However, it is constrained by length, which can be worked around by combining it with a positive lookahead. So far I couldn't come up with a robust solution though.
What I've tried so far:
(\b[\w -]+?)\((([A-Z])(?<=(?=.*?\3))(?:[A-Z]){1,4})\)

This works reasonable well but matches include too many words:
Some example text (SET)
Energy system models (ESM)
are used to find specific optima (SCO)
Some say Computer systems (CUST)
In the summer playing outside (OUTS)

I have also tried to use a reference to the first letter of the abbreviation at the start of the first group. That didn't work at all though.
Things I have looked at but didn't find useful:

*

*regex for catching abbreviations

*Match Acronym and their Meaning with Python Regex
Useful resources:

*

*something on lookbehinds

*something on lookarounds in general

A: I suggest using
import re
def contains_abbrev(abbrev, text):
    text = text.lower()
    if not abbrev.isupper():
        return False
    cnt = 0
    for c in abbrev.lower():
        if text.find(c) > -1:
            text = text[text.find(c):]
            cnt += 1
            continue
    return cnt == len(abbrev)

text= "Some example text (SET) that demonstrates what I'm looking for. Energy system models (ESM) are used to find specific optima (SCO). Some say computer systems (CUST) are cool. In the summer playing outside (OUTS) should be preferred. Stupid example(s) Stupid example(S) Not stupid example (NSEMPLE), bad example (Bexle)"
abbrev_rx = r'\b(([A-Z])\w*(?:\s+\w+)*?)\s*\((\2[A-Z]*)\)'
print( [x.group() for x in re.finditer(abbrev_rx, text, re.I) if contains_abbrev(x.group(3), x.group(1))] )

See the Python demo.
The regex used is
(?i)\b(([A-Z])\w*(?:\s+\w+)*?)\s*\((\2[A-Z]*)\)

See the regex demo. Details:

*

*\b - word boundary

*(([A-Z])\w*(?:\s+\w+)*?) - Group 1 (text): an ASCII letter captured into Group 2, then 0+ word chars followed with any 0 or more occurrences of 1+ whitespaces followed with 1+ word chars, as few as possible

*\s* - 0+ whitespaces

*\( - a ( char

*(\2[A-Z]*) - Group 3 (abbrev): same value as in Group 2 and then 0 or more ASCII letters

*\) - a ) char.

Once there is a match, Group 3 is passed as abbrev and Group 1 is passedas text to the contains_abbrev(abbrev, text) method, that makes sure that the abbrev is an uppercase string and that the chars in abbrev go in the same order as in text, and are all present in the text.

A: Just regex won't be enough .. looks like you might a python script for this...
this should handle all your scenarios:
import re
a="Some example text (SET) that demonstrates what I'm looking for. Energy system models (ESM) are used to find specific optima (SCO). Some say computer systems (CUST) are cool. In the summer playing outside (OUTS) should be preferred.";
b=re.findall("(\((.*?)\))",a)
a=a.replace(".","")
i=a.split(' ')
for c in b:
   cont=0
   m=[]
   s=i.index(c[0])
   l=len(c[1])
   al=s-l
   for j in range(al,s+1):
       if i[j][0].lower() == c[1][0].lower():
            cont=1
       if cont == 1:
            m.append(i[j])
   print(' '.join(m))

Output:
Some example text (SET)
Energy system models (ESM)
specific optima (SCO)
computer systems (CUST)
outside (OUTS)


text:
Q: Canon LiveView: image convertion to OpenCV Mat I'm trying to show LiveView image in real time. I use EDSDK 2.14 + Qt5 + opencv+mingw32 under Windows. I'm not very sophisticated in image processing so now I have the following problem. I use example from Canon EDSDK and all was ok until this part of code:
//
// Display image
//
I googled a lot of examples but all of them was written on C# or MFC or VB. Also I found advise to use libjpegTurbo for decompressing image and then showing it using opencv. I tried to use libjpegTurbo but failed to undestand what to do :(. Maybe somebody here have code example of the conversion LiveView stream to opencv Mat or QImage (because I use Qt)?

A: Here is what worked for me after following the SAMPLE 10 from the Canon EDSDK Reference. It's a starting point for a more robust solution.
In the downloadEvfData function, I replaced the "Display Image" part by the code bellow:
unsigned char *data = NULL;
EdsUInt32 size = 0;
EdsSize coords ;

// get image coordinates
EdsGetPropertyData(evfImage, kEdsPropsID_Evf_CoordinateSystem, 0, sizeof(coords), &coords);

// get buffer pointer and size
EdsGetPointer(stream, (EdsVoid**)&data);
EdsGetLenth(stream, &size);

//
// release stream and evfImage
//

// create mat object
Mat img(coords.height, coords.width, CV_8U, data);
image = imdecode(img, CV_LOAD_IMAGE_COLOR);

I've also changed the function signature:
EdsError downloadEvfData(EdsCameraRef camera, Mat& image)

And in the main function:
Mat image;
namedWindow("main", WINDOW_NORMAL);
startLiveView(camera);
for(;;) {
    dowloadEvfData(camera, image);
    imshow("main", image);
    if (waitkey(10) >= 0);
        break;
}

A: Based on the Canon EDSDKs example, you may append your EdsStreamRef 'stream' data  with its correct length into a QByteArray. Then, use for example the following to parse the raw data from the QByteArray as a JPG into a new QImage:
QImage my_image = QImage::fromData(limagedata,"JPG"); Once it's in a QImage you can convert it into a OpenCV cv::Mat (see How to convert QImage to opencv Mat)

A: Well it depends on the format of the liveview-stream.
There must be some kind of delimiter in it and you need then to convert each image and update your QImage with it.
Check out this tutorial for more information: Canon EDSDK Tutorial in C#

A: QImage img = QImage::fromData(data, length, "JPG");

m_image = QImageToMat(img);

// -----------------------------------------
cv::Mat MainWindow::QImageToMat(QImage& src)
{
     cv::Mat tmp(src.height(),src.width(),CV_8UC4,(uchar*)src.bits(),src.bytesPerLine());
     cv::Mat result = tmp.clone();
     return result;
}

// -------------------------
void MainWindow::ShowVideo()
{
    namedWindow("yunhu",WINDOW_NORMAL);
    while(1)
    {
        requestLiveViewImage();
        if(m_image.data != NULL)
        {
            imshow("yunhu", m_image);
            cvWaitKey(50);
        }
    }
}


text:
Q: Where can one find source archives of old SQLite versions? The downloads page on www.sqlite.org appears to only have links to the current version, and I would like to get a previous version.  I cannot see any obvious links to historical versions on the site and (unless I'm missing something obvious) there does not appear to be a sourceforge project.
Can someone point me at an archive of old SQLite source releases if such a thing exists?
Nigel.

A: Direct Access To The Sources
Also, if you want to compile yourself.  Access to all SQLite source code is maintained in a CVS repository that is available for read-only access by anyone. You can interactively view the repository contents and download individual files by visiting this link
Also
www.sqlite.org/src/timeline?t=release will show when every sqlite version was released.
Checkout from cvs from the date you want and compile. Instruction how to checkout from cvs are here
Note: Use the -D option to checkout by date

A: The idea from TomWitt2 is fantastic (I had spent hours to find solution) but now the links seems to be have modified so follow below steps to get your archived version:

*

*Get the latest version link from the download page here http://www.sqlite.org/download.html

*Get your normalized 7 digit number as mentioned in answer by TomWitt2

*Just replace the number in the link and you are ready to go

A: I've tried a few solutions on this page and elsewhere, all that I've seen seem outdated and no longer work. I've done the steps below as of 5/4/2016 with success.

*

*Go to http://system.data.sqlite.org/index.html/finfo?name=www/downloads.wiki to view the history of the SQLite downloads wiki.

*Search (ctrl+f) for the version you want (ex. 1.0.91.0)

*Select the commit ID and it will open that old version of the page complete with download links to source code as well as precompiled binaries and setups.

You won't always find the version in a search (ex. 1.0.98.0), but it should be reasonably easy to find the correct page by the surrounding versions/commits.
You can also check archive.org for the downloads page:
http://web.archive.org/web/20150101000000*/http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki
Find the date that your desired version was released on from the SQLite news page (you may need to pick the next archive date after that). Select your desired link (sometimes the download page was archived, more ofter it seems like it was not). If the download page was not archived, edit the address bar to remove the archive.org-related info and you should be able to navigate directly to the SQLite download page for that version.

A: I found this in their old message list archives. Hopefully this helps:

Older version of SQLite are aviable
  from the website, but there are no
  direct links on the web pages. You
  need to manually edit the links to
  get the file you need.
The 2.1 version of the database file
  implies that it was created with a
  2.X.Y version of SQLite. You should get the latest version which is
  2.8.17 (I believe).
If you go the download page
  http://www.sqlite.org/download.html
  and the  right click on the link to
  download the latest Windows binary
  file, then
select Copy Link Location (at least
  using Firefox, in IE the command is
  Copy Shortcut). Now open a new tab or
  window and paste the link into the
address bar. You can edit the link and
  replace the version number with  the
  version you want to download. In your
  case you need to change
  http://www.sqlite.org/sqlitedll-3_5_6.zip
  to
  http://www.sqlite.org/sqlitedll-2_8_17.zip
  and then press enter to start

A: I know this question is kind of old but there's an easier way to get the URL to the older zip files.
Using a combination of answers here, you can calculate the download URL of the zip file for the specific version you want.

*

*Determine the version number you want to get  (we'll use 3.8.7.4 as an example)

*Look on the timeline (http://www.sqlite.org/src/timeline?t=release) to figure out the year in which your desired version was released (3.8.7.4 was released in 2014)

*Normalize the version number into exactly 7 digits.  Expand each piece into 2 digits with leading zeroes except for the initial 3 which should remain 1 digit.   For example 3.8.7.4  becomes 3080704.  3.13.0 becomes 3130000.  (If there is no 4th period delimited piece, use 00)

*Using your normalized version number, plug it into one of these formats, depending on what you're looking for (Replace the text '7DIGITS' in the urls below with your normalized version number, replace the text YEAR with the year in which the version was released
Source:       http://www.sqlite.org/YEAR/sqlite-src-7DIGITS.zip
Amalgamated:  http://www.sqlite.org/YEAR/sqlite-amalgamation-7DIGITS.zip
So our example versions become
http://www.sqlite.org/2014/sqlite-src-3080704.zip and http://www.sqlite.org/2014/sqlite-amalgamation-3080704.zip
I haven't tried this for every version but my 3 test versions worked. I would imagine the other download types (like precompiled binaries, documentation, etc) work as well.

A: Follow this link to the official website and under "3.0 Obtaining Code Directly From the Version Control System" you can read further directions:

*

*get the list of release check-ins (this link)

*choose the required check-in

*download source code archive

The oldest release available now is from
2007-08-13.

A: You are correct to point out that https://www.sqlite.org/download.html only links to the most recent release, but a page always linking the current release combined with Wayback Machine preserving every (well, hopefully) version of said page, is all you need to download your favorite release:
http://web.archive.org/web/*/https://www.sqlite.org/download.html
Given that the binaries themselves have not been removed, of course, but fortunately they seem intact to me.
In fact, I just downloaded SQLite 3.9.2 through this page:
http://web.archive.org/web/20151231190003/https://www.sqlite.org/download.html

A: You can get all release of SQLite from https://www.sqlite.org/chronology.html, this page contains the history of SQLite releases


text:
Q: Opening multiple files (OpenFileDialog, C#) I'm trying to open multiple files at once with the OpenFileDialog, using FileNames instead of FileName. But I cannot see any examples anywhere on how to accomplish this, not even on MSDN. As far as I can tell - there's no documentation on it either. Has anybody done this before?

A: You must set the  OpenFileDialog.Multiselect Property value to true, and then access the OpenFileDialog.FileNames property.
Check this sample
private void Form1_Load(object sender, EventArgs e)
{
    InitializeOpenFileDialog();
}

private void InitializeOpenFileDialog()
{
    // Set the file dialog to filter for graphics files.
    this.openFileDialog1.Filter =
        "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
        "All files (*.*)|*.*";

    //  Allow the user to select multiple images.
    this.openFileDialog1.Multiselect = true;
    //                   ^  ^  ^  ^  ^  ^  ^

    this.openFileDialog1.Title = "My Image Browser";
}

private void selectFilesButton_Click(object sender, EventArgs e)
{
    DialogResult dr = this.openFileDialog1.ShowDialog();
    if (dr == System.Windows.Forms.DialogResult.OK)
    {
        // Read the files
        foreach (String file in openFileDialog1.FileNames)
        {
            // Create a PictureBox.
            try
            {
                PictureBox pb = new PictureBox();
                Image loadedImage = Image.FromFile(file);
                pb.Height = loadedImage.Height;
                pb.Width = loadedImage.Width;
                pb.Image = loadedImage;
                flowLayoutPanel1.Controls.Add(pb);
            }
            catch (SecurityException ex)
            {
                // The user lacks appropriate permissions to read files, discover paths, etc.
                MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
                    "Error message: " + ex.Message + "\n\n" +
                    "Details (send to Support):\n\n" + ex.StackTrace
                );
            }
            catch (Exception ex)
            {
                // Could not load the image - probably related to Windows file system permissions.
                MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
                    + ". You may not have permission to read the file, or " +
                    "it may be corrupt.\n\nReported error: " + ex.Message);
            }
        }
    }

A: You can use this method for text files:
OpenFileDialog open = new OpenFileDialog();
open.Filter = "All Files *.txt | *.txt";
open.Multiselect = true;
open.Title = "Open Text Files";

if (open.ShowDialog() == DialogResult.OK)
{
    foreach (String file in open.FileNames)
    {
         string temp = YourRichTextBox.Text;

         YourRichTextBox.LoadFile(file, RichTextBoxStreamType.PlainText);

         YourRichTextBox.Text += temp;
    }
}


text:
Q: Subscribe function is not trigger when I call function next on BehaviourSubject I have 2 components and one service shared between the 2 components, let's say ComponentA and ComponentB. One component in for the toolbar of the app (Comp. A) and the other one, component B,  is routed with the routing module. This is the HTML:

<router-outlet></router-outlet>

It is in this way because I want to always have the toolbar present, fixed, at the top.
In the HTML for component A, I have a select to select the language of the app. In Component B I have some content that comes from backend depending on the selected language.I want that when the user changes the language, the content came from server, to be rendered.I am using the service to call the backend and render the new content. Here comes my problem, the call to server is done and is ok, but it never enters to the subscription function. I have tried to use a shared module (with or without forRoot()), I tried to make the service a provider for a module, and import the module(AppRoutingModule) in the other module(AppModule). In this moment I got to the point where I have  the "No provider for Service!" error in console. The code for service and components:
Service:
@Injectable()
export class SharedService extends GlobalHttpService<HomeSection> {
  private sectionsSubject: BehaviorSubject<HomeSection[]>;
  constructor(private http: HttpClient) {
    super("api/path", new GlobalSerializer(HomeSection), http);
    this.sectionsSubject = new BehaviorSubject<HomeSection[]>([]);
  }

  load() {
    this.list().subscribe(res => {
      this.sectionsSubject.next(res);
    });
  }
  get content() {
    return this.sectionsSubject.asObservable();
  }
}

AppModule
@NgModule({
 imports:[AppRoutingModule]
})
export class AppModule {}

AppRoutingModule
export function SharedServiceFactory(http: HttpClient){
  return new SharedServiceFactory(http);
}

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [
    {
      provide: SectionService,
      useFactory: SectionServiceFactory,
      deps: [HttpClient]
    }
  ]
})
export class AppRoutingModule {}

ComponentA:
@Component({
  selector: "a",
  templateUrl: ".a.component.html",
  styleUrls: ["./a.component.scss"]
})
export class AComponent implements OnInit {
  constructor(
    public authentificationService: AuthenticationService,
    private languagesService: LanguagesService,
    private sharedService: SharedService
  ) {
  }
 ngOnInit() {
//other logic;
}

updateLanguage(event) {
// other logic;
this.sharedService.load();
}

ComponentB
@Component({
  selector: "app-b",
  templateUrl: "./b.component.html",
  styleUrls: ["./b.component.scss"]
})
export class BComponent implements OnInit {
  constructor(
    private sharedService: SharedService,
  ) {}

ngOnInit() {
 this.sharedService.load();
 this.sharedService.content.subscribe(s => {
 // logic
 });
}

How can I make to have a single instance of the SharedService or can I include one module in another?

A: Try to do this in your service:
@Injectable({ providedIn: 'root' })

And remove providing of this service from AppRoutingModule.
If you use providedIn: 'root' you do not need to provide it somewhere else. It will inject the service at very top of Angular tree, so you will always have the same instance. Another benefit from it - it makes services tree-shakeable.

A: First import the service in the AppModule:
AppModule
@NgModule({
 imports:[AppRoutingModule],
 providers: [SharedService]
})
export class AppModule {}

OR:
@Injectable({ providedIn: 'root' })
export class SharedService extends GlobalHttpService {
...
}
Then, you don't have to create a method in the SharedService to return the Observable event, you can just create a property and instance once in the constructor.
SharedService
@Injectable()
export class SharedService extends GlobalHttpService<HomeSection> {
  private sectionsSubject: BehaviorSubject<HomeSection[]>;
  public content$: Observable<HomeSection[]>;
  constructor(private http: HttpClient) {
    super("api/path", new GlobalSerializer(HomeSection), http);
    this.sectionsSubject = new BehaviorSubject<HomeSection[]>([]);
    this.content$ = this.sectionsSubject.asObservable();
  }

  load() {
    this.list().subscribe(res => {
      this.sectionsSubject.next(res);
    });
  }
}

Finally in your component B:
@Component({
  selector: "app-b",
  templateUrl: "./b.component.html",
  styleUrls: ["./b.component.scss"]
})
export class BComponent implements OnInit {
  constructor(
    private sharedService: SharedService,
  ) {}

ngOnInit() {
 this.sharedService.load();
 this.sharedService.content$.subscribe(s => {
     // logic
 });
}


text:
Q: Background service doesn't stop in iOS I'm using socket.io-client in react-native to start a chat room, when the app enters in background mode the socket keeps working, no problem, but when I disconnect the socket yet the foreground mode still stays active. I have tried a lot of ways but none deactivated the background service.
Follow the code who call the socket:
socket = null;

socketConnection = (url) => {
    socket = io(url, { forceNew: true });

    socket.on('connect', () => {
        console.warn("Connected: ", socket.connected);
    });
    socket.on('disconnect', () => {
        console.warn("Disconnected: ", socket.disconnected);
    });
}

socketDisconnect = () => {
    socket.disconnect();
    socket.off("connect");
    socket.off("disconnect");
}

A: I solved that by call exit(EXIT_SUCCESS) in applicationDidEnterBackground method directly in Objective-C code.


text:
Q: Using typeclasses wtih multiple type parameters I'm trying to use symulacrum's @typeclass to avoid writing Ops/Syntax boilerplate. I have a trait parameterized with effect and a type:
@typeclass trait Close[F[_], T]{
    def close(t: T): F[Unit]
}

With the intention to be used as follows:
trait Stream[F[_], Pipe]{
    def open(): F[Pipe]
    def drain(): F[Unit]
}
object App{
    def runApp[F[_], Pipe: Close[F, ?]](implicit stream: Stream[F, Pipe]) = {
        for{
            pipe <- stream.open()
            _ <- stream.drain(pipe)
            _ <- pipe.close()
        } yield ()
    }
}

The reason I decided to put Close[F[_], T] away was that some Pipes in my application are inherently unclosable so it is kind of wierd to put
close method for all Pipes
This is the error I get:
Error:(32, 4) @typeclass may only be applied to types that take a single type parameter
  @typeclass trait Close[F[_], T]

QUESTION: In case of a trait has multiple type parameters (like Close[F[_], T]) do I have to write all the Ops/Syntax boilerplate on my own and symulacrum's @typeclass cannot help here?

A: On your own.
https://github.com/mpilquist/simulacrum#known-limitations

Known Limitations

*

*Only type classes that abstract over a proper type or a unary type constructor are currently supported.


text:
Q: Get top sites favicon - browser extension I'm using the topSites API to get a list of the user most visited websites.
browser.topSites.get().then( (mostVisitedURL) => {
  console.log(mostVisitedURL);
});

Is possible to get also the favicons for each website? I see that in forefox there is the ability to set options but this isn't available in chrome.


text:
Q: Calculate the uncertainty in components of composite model in Lmfit I have a model defined as
gmodel=Model(a)+Model(b)
result=gmodel.fit(data,...)
I use this model to fit the data, which gives me the parameters and their error estimates. Using the result.eval_components(), I could access the component a and component b of the model function. Also, using result.eval_uncertainty(), I could access the 1-sigma uncertainties in the model functions, which would be two lines. Now I want to know each component a and b in that 1-sigma uncertainty lines.Is there a easy way of doing this.

A: There is not currently "an easy way of doing this" - the eval_uncertainty method belongs to the lmfit.ModelResult, not the lmfit.Model itself, at least partly because it needs the resulting covariance matrix.
But: I think eval_uncertainty method could probably calculate the uncertainty in any component models too.  I would suggest raising an Issue and/or using the lmfit mailing list to discuss making this change.


text:
Q: Line not rendered with data in variable but rendering with array data I have a method which renders a line graph with Highcharts. The data in the graph is an array in the avg_rates variable, which has these values:
[0.8936e2, 0.8901e2, 0.9015e2, 0.9043e2, 0.8994e2, 0.9105e2, 0, 0, 0, 0, 0, 0]

When I use the variable it doesn't render the line:
f.series(
  name: "Average rates",
  data: avg_rates
)

When I use the array it does render the line:
f.series(
  name: "Average rates",
  data: [0.8936e2, 0.8901e2, 0.9015e2, 0.9043e2, 0.8994e2, 0.9105e2, 0, 0, 0, 0, 0, 0]
)

I have no ideay why this is happening? Here is the method in full:
def create_avg_rates_chart(avg_rates)
    months = ['jan','feb','mar','apr','mei','jun','jul','aug','sep','okt','nov', 'dec']
    min = avg_rates[0] - 5
    max = avg_rates[0] + 5

    avg_rates_chart = LazyHighCharts::HighChart.new('graph') do |f|
      f.chart(type: 'line', height: '150', width: '1000')
      f.pane(size: '100%')
      f.colors(['#0092C9'])
      f.xAxis(
        categories: months.map{ |m| [m] },
        labels: {
          style: { "fontSize": "12px" }
        }
      )
      f.yAxis(
        title: {
            text: 0
        },
        min: min,
        max: max
      )
      f.plotOptions(
        line: {
          dataLabels: {
              enabled: true,
              padding: 10
          },
          enableMouseTracking: false,
          lineWidth: 4,
          marker: {
            radius: 5
          }
        }
      )
      f.series(
        name: "Average rates",
        data: avg_rates
      )
      f.legend(enabled: false)
    end
  end

A: This most likely happens because when you copied the contents from the array variable you don't copy the actual object but just the console representation (aka the result of #inspect).
The array avg_rates most likely happens to contain BigDecimals:
# avg_rates comes in from outside the function, the line below is a mock.
avg_rates = %w[89.36 89.01 90.15 90.43 89.94 91.05 0 0 0 0 0 0].map(&:to_d)

These values are represented in the console using the #inspect method and produce the following visual output:
#=> [0.8936e2, 0.8901e2, 0.9015e2, 0.9043e2, 0.8994e2, 0.9105e2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

This visual output is also perfectly valid Ruby code. However if you type 0.8936e2 into the console you'll instantiate a Float and not a BigDecimal. This can be seen if you look at the return value of just entering the the representation of the array:
avg_rates_repr = [0.8936e2, 0.8901e2, 0.9015e2, 0.9043e2, 0.8994e2, 0.9105e2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
#=> [89.36, 89.01, 90.15, 90.43, 89.94, 91.05, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

avg_rates.map(&:class).uniq
#=> [BigDecimal]
avg_rates_repr.map(&:class).uniq
#=> [Float]

As you said the graph doesn't render when using the avg_rates variable, but does with the copying the representation. This means that LazyHighCharts::HighChart doesn't accept BigDecimals but does accept Floats. So your solution should be to convert the values to Floats before passing them to the :data option of #series.
data: avg_rates.map(&:to_f)


text:
Q: Exclude css from parent application(angular) from applying into child(react) in single-spa-application I have made a single-spa application where I am using angular as a parent project and put react bundle into it. Now the problem coming is that react is picking up the CSS of the angular project. I have excluded that particular CSS in webpack.config file of react project. But that isn't working in the way I wanted. S what should be done?

A: Nothing about single-spa changes the nature of how CSS works. It is the exact same as you would do without single-spa, namely, using techniques like CSS Modules, or scoped/prefixed styles. Using component styles is the most common approach in angular for this: https://angular.io/guide/component-styles


text:
Q: Max pooling backpropagation using Numpy I'm implementing a CNN using Numpy and I can't find a way to implement backpropagation for max-pooling efficiently as I did for forward-propagation.
This is what I did in the forward propagation:
def run(self, x, is_training=True):
    """
    Applying MaxPooling on `x`
    :param x: input - [n_batches, channels, height, width]
    :param is_training: a boolean indicating whether training or not
    :return: output of the MaxPooling on `x`
    """
    n_batch, ch_x, h_x, w_x = x.shape
    h_poolwindow, w_poolwindow = self.pool_size

    out_h = int((h_x - h_poolwindow) / self.stride) + 1
    out_w = int((w_x - w_poolwindow) / self.stride) + 1

    windows = as_strided(x,
                         shape=(n_batch, ch_x, out_h, out_w, *self.pool_size),
                         strides=(x.strides[0], x.strides[1],
                                  self.stride * x.strides[2],
                                  self.stride * x.strides[3],
                                  x.strides[2], x.strides[3])
                         )
    out = np.max(windows, axis=(4, 5))

    if is_training:
        self.cache['X'] = x
    return out

My current implementation of the backpropagation:
def backprop(self, dA_prev):
    """
    Backpropagation in a max-pooling layer
    :return: the derivative of the cost layer with respect to the current layer
    """
    x = self.cache['X']
    n_batch, ch_x, h_x, w_x = x.shape
    h_poolwindow, w_poolwindow = self.pool_size

    dA = np.zeros(shape=x.shape)  # dC/dA --> gradient of the input
    for n in range(n_batch):
        for ch in range(ch_x):
            curr_y = out_y = 0
            while curr_y + h_poolwindow <= h_x:
                curr_x = out_x = 0
                while curr_x + w_poolwindow <= w_x:
                    window_slice = x[n, ch, curr_y:curr_y + h_poolwindow, curr_x:curr_x + w_poolwindow]
                    i, j = np.unravel_index(np.argmax(window_slice), window_slice.shape)
                    dA[n, ch, curr_y + i, curr_x + j] = dA_prev[n, ch, out_y, out_x]

                    curr_x += self.stride
                    out_x += 1

                curr_y += self.stride
                out_y += 1
    return dA

Can I vectorize it?

A: I managed to solve it by changing the forward propagation to:
windows = as_strided(x,
                     shape=(n_batch, ch_x, out_h, out_w, *self.pool_size),
                     strides=(x.strides[0], x.strides[1],
                              self.stride * x.strides[2],
                              self.stride * x.strides[3],
                              x.strides[2], x.strides[3])
                     )
out = np.max(windows, axis=(4, 5))

maxs = out.repeat(2, axis=2).repeat(2, axis=3)
x_window = x[:, :, :out_h * self.stride, :out_w * self.stride]
mask = np.equal(x_window, maxs).astype(int)

if is_training:
    self.cache['X'] = x
    self.cache['mask'] = mask
return out

and changing the backpropagation to:
mask = self.cache['mask']
dA = dA_prev.repeat(h_poolwindow, axis=2).repeat(w_poolwindow, axis=3)
dA = np.multiply(dA, mask)
pad = np.zeros(x.shape)
pad[:, :, :dA.shape[2], :dA.shape[3]] = dA
return pad


text:
Q: How to create a completely immutable tree hierarchy? Construction chicken and egg I like to make data classes immutable to make concurrent programming easier.  But making a completely immutable hierarchy seems problematic.
Consider this simple tree class:
public class SOTree {
    private final Set<SOTree> children = new HashSet<>();
    private SOTree parent;

    public SOTree(SOTree parent) {
        this.parent = parent;
    }

    public SOTree(Set<SOTree> children) {
        for (SOTree next : children)
            children.add(next);
    }

    public Set<SOTree> getChildren() {
        return Collections.unmodifiableSet(children);
    }

    public SOTree getParent() {
        return parent;
    }
}

Now, if I want to create a hierarchy of these, when I construct it, either the parent has to exist before the current node, or the children have to exist first.
    SOTree root = new SOTree((SOTree)null);
    Set<SOTree> children = createChildrenSomehow(root);
    //how to add children now?  or children to the children?

or
    Set<SOTree> children = createChildrenSomehow(null);
    SOTree root = new SOTree(children);
    //how to set parent on children?

Without forcing this to be a singly linked tree, is there any clever way to construct such a tree and still have all the nodes completely immutable?

A: You've correctly stated your problem as one of chicken and egg. Another way of restating the problem that might shed a solution is that you want to grow a tree (root, trunk, leaves and all - all at once).
Once you accept that the computer can only process things step by step, a series of possible solution emerges:

*

*Have a look at how Clojure creates immutable data structures. In Clojure's case, each operation on a tree (such as adding a node) returns a new tree.

*Make tree creation atomic. You can create a special format and then deserialize the tree. Since all serialization methods are internal, you do not have to expose any mutable methods.

*Just before the factory returns a constructed tree, lock it down with a flag first. This is an analog of atomic operation.

*Use package level methods to construct the tree. This way the mutation methods on nodes couldn't be accessed by external packages.

*Create nodes on the fly when they are accessed. This means your internal tree representation can never be changed, since changing the nodes have no effect on your tree structure.

A: I recently faced a similar problem - https://medium.com/hibob-engineering/from-list-to-immutable-hierarchy-tree-with-scala-c9e16a63cb89
The approach is to build the tree bottom-up, having the bottom nodes constructed first, then go up towards the top node(s).
Phase 1 - Sort by depth
In order to start from the bottom, the algorithm sorts the nodes by their depth in the hierarchy (There's an O(n) way of doing it as you'll see in the link).
Phase 2 - Build the tree from the bottom
Bottom nodes have no children, so the algorithm constructs the bottom nodes.
Then, go one layer up and construct the nodes who have children with the nodes that were processed a layer before.
The algorithm continues until it reaches the top node(s).

A: Building efficient, immutable data structures can be challenging.  Fortunately, there are folks who have figured out how to implement many of these already.  Take a look here for a discussion of large variety of immutable data structures.
This is an area that I'm still trying to bring myself up to speed on as well, so I'm not able to recommend the exact subset of these structures you should be looking at, but one data structure for working with trees that can be very useful is Zippers.

A:
Without forcing this to be a singly linked tree, is there any clever way to construct such a tree and still have all the nodes completely immutable?

Keep your interfaces and implementations decoupled, and don't restrict your nodes of the tree to being the same class as the tree itself.
One solution to this issue is to store the node hierarchy in some other immutable representation, and when a caller calls getChildren() or getParent() whatever, it lazily constructs the child nodes from that immutable representation. If you want node.getChildren().get(i).getParent() == node to be true (rather than .equals(node) -- i.e. identity rather than equality), then you'll have to cache the node objects so you can redeliver them accordingly.

A: The proper approach for constructing an immutable tree would be to have the constructor of each node invoke the child nodes' constructors with itself as a parameter, with the provisos that the child node's constructor must not cause a a rooted reference to itself to be stored anywhere, nor use the passed-in parameter for any purpose except to initialize a field which the constructor would use for no purpose except to accept such initialization.  Additionally, the parent node's constructor should avoid using any members of the child node which would dereference the "parent" field.
Although such a technique would seem to violate the rule that the constructors of immutable objects should not the fledgeling objects as parameters to other routines, the "real" rule is that the constructor of an immutable object should not allow a reference to the fledgeling object to be used in such fashion as to directly or indirectly access any fields which have not yet attained their final value.  In general, if a fledgeling object exposes a reference to itself to the outside world, it will have no control over what outside code may do with it.  In the particular case of calling a child node constructor, however, assuming the code for the child node honors the above requirements, there will be no rooted reference to the parent node, except through the parent node itself.  Consequently, there will be no danger that any code that would do anything unexpected with the fledgeling node will get a reference to it.

A: Eric Lippert recently blogged about this problem.  See his blog post Persistence, Facades and Roslyn's Red-Green Trees.  Here's an excerpt:

We actually do the impossible by keeping two parse trees. The "green" tree is immutable, persistent, has no parent references, is built "bottom-up", and every node tracks its width but not its absolute position. When an edit happens we rebuild only the portions of the green tree that were affected by the edit, which is typically about O(log n) of the total parse nodes in the tree.
The "red" tree is an immutable facade that is built around the green tree; it is built "top-down" on demand and thrown away on every edit. It computes parent references by manufacturing them on demand as you descend through the tree from the top. It manufactures absolute positions by computing them from the widths, again, as you descend.

A: Two thoughts:

*

*Use some sort of tree factory.  You could describe the tree using mutable structures, then have a factory that would assemble an immutable tree.  Internally, the factory would have access to the fields of the different nodes and so could rewire internal pointers as necessary, but the produced tree would be immutable.

*Build an immutable tree wrapper around a mutable tree.  That is, have the tree construction use mutable nodes, but then build a wrapper class that then provides an immutable view of the tree.  This is similar to (1), but doesn't have an explicit factory.
Hope this helps!

A: Since you want them to be immutable, you'd have to just do it at construction. Make one constructor that takes both parent and children, instead of two separate constructors.


text:
Q: C# Null References while serializing When serializing, how do you handle backer variables? Mine keep on turning up null, as in the following example:
[DataContract]
public Person
{
     public Person()
     {
         //a break point here doesn't get called in time - I try to use _myList and get an exception first. :(
         _myList = new string[3];
     }

    private string[] _myList {get; set;} = new string[3];  // Will be filled: {"Bob", "The", "Builder"};

    [DataMember]
    public string Occupation
    {
        get { return _myList[2]; }
        set {_myList[2] = value; }
    }

}

SerializeFunction(Person Bob, string filePath = @"C:\Temp\BobTheBuilder.xml")
{
     DataContractSerializer serializer = new DataContractSerializer(typeof(Person));
     using(XmlWriter xmlwriter = XmlWriter.Create(filePath))
     {
         serializer.WriteObject(xmlWriter, bob);
         xmlWriter.Flush();
     }
     using(XmlReader reader = XmlReader.Create(filePath))
     {
         // This throws an exception, because _myList is null
         Person readInBob = deserializer.ReadObject(xmlReader);
     }
}

I get an exception when I try to read Bob back in, because the backer property _myList doesn't get initialized. How do you guys handle situations like this?

A: When you do new List<int>(3), you are setting the initial capacity, not the number of elements. There are still zero elements, so _myList[0] etc will all fail until you Add the appropriate number of elements. This contrasts to arrays, as new int[3] always has exactly 3 elements (which will be null initially).
Frankly, there's no need for a list here at all, if you are trying to hard-code them to positions - just use simple properties:
[DataMember]
public string Occupation {get;set;}

A: If you implement IXmlSerializable, you gain the control to do whatever you need to. Replace the person class above with:
public Person : IXmlSerializable
{
    private string[] _myList {get; set;} = new string[3];

    public string Occupation
    {
        get { return _myList[2]; }
        set {_myList[2] = value; }
    }

    XmlSchema IXmlSerializable.GetSchema() => null;

    void IXmlSerializable.ReadXml(XmlReader reader)
    {
         //THIS IS THE KEY LINE:
         _myList = new string[3];// you can do any initialization you need before actually reading.

        while(reader.Read())
        {
            if(reader.NodeType != XmlNoteType.Element)
                continue;

            string propertyName = reader.Name; // we have arrived at an element.
            reader.Read(); // we have the property name, now get it's value

            switch(propertyName)
            {
                case nameof(Occupation):
                    Occupation = reader.Value; // for an int, you could do: int.Parse(reader.Value);
                    break;
                case "ComplicatedClass": // if you need to serialize complicated class member then you could do this:
                    // you'd have to not do the reader.Read() above...
                    // DataContractSerializer complicatedClassSerializer = new DataContractSerializer(typeof(ComplicatedClass));
                    // ComplicatedClass foo = complicatedClassSerializer.ReadObject(reader) as ComplicatedClass;
                    break;
            }
        }
    }

    void IXmlSerializable.WriteXml(XmlWriter writer)
    {
         writer.WriteElementString(nameof(Occupation), Occupation.ToString());

         //for a more complicated  type than string, int etc:
         //DataContractSerializer complicatedClassSerializer = new DataContractSerializer(typeof(complicatedClass));
         //complicatedClassSerializer.WriteObject(writer, new ComplicatedClass());
    }
}


text:
Q: Android - HorizontalScrollView scrolls to the right when keyboard is opened I have a general layout for my app in place, which includes a horizontal scroll view.
What I'm doing is adding 32 fragments to the scroll view (which inflates into a vertical linear layout with two buttons and an editText. They're going to be controls for an equalizer).
The problem is, when I try to edit one of the editText's, the scrollview scrolls all the way to the right - so you're unable to see what you're typing into, and have to scroll all the way back to that entry to view it.
Here's the main xml layout. It splits the screen up into 4 quadrants, with the horizontal scroll view going in the bottom right:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity"
    android:focusable="true"
    android:focusableInTouchMode="true">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:padding="4dp"
        android:orientation="vertical"
        android:layout_weight="2"
        >
        <TextView android:text="Hello World!" android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="4"
        android:padding="4dp"
        android:orientation="vertical"
        android:background="#FF0000"
        >
        <TextView android:text="Hello World!"      android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <HorizontalScrollView
            android:id="@+id/hsv_eqControls"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="2dp"
            android:background="#FFFFFF"
            android:descendantFocusability="beforeDescendants"
            android:focusable="true"
            android:focusableInTouchMode="true"
            >

            <LinearLayout
                android:id="@+id/layout_eqControls"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="horizontal">

            </LinearLayout>

        </HorizontalScrollView>
    </LinearLayout>

</LinearLayout>

And this is what I'm adding into the scrollview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="3dp"
    android:orientation="vertical">
    <Button
        android:id="@+id/btn_eqUp"
        android:layout_width="60dp"
        android:layout_height="60dp" />
    <EditText
        android:id="@+id/etext_eq"
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal|numberSigned"
        android:textAlignment="center"
        android:layout_gravity="center_horizontal"
        android:background="#EEEEEE"
        android:hint="32dB"/>
    <Button
        android:id="@+id/btn_eqDown"
        android:layout_width="60dp"
        android:layout_height="60dp" />
    <TextView
        android:id="@+id/vtext_eqLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:layout_gravity="center"
        android:text="1"/>
</LinearLayout>

This is the code I'm running to fill the scrollview:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // View eqControls = findViewById(R.id.hsv_eqControls);

        FragmentTransaction ft = getFragmentManager().beginTransaction();
        for(int i = 1; i < 33; i++)
        {
            ft.add(R.id.layout_eqControls, new FragmentEQ(), "ch"+i);
        }

        ft.commit();
        getFragmentManager().executePendingTransactions();
        for(int i = 1; i < 33; i++)
        {
            FragmentEQ feq = (FragmentEQ) getFragmentManager().findFragmentByTag("ch"+i);
            if(feq != null)
                feq.setChannel(i);
        }

    }
}

And this is the code for my fragment:
public class FragmentEQ extends Fragment {
    protected int _channel = 0;
    protected ViewGroup _parent;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.activity_fragment_eq, container, false);
        TextView label = (TextView) view.findViewById(R.id.vtext_eqLabel);

        label.setText(Integer.toString(_channel));
        return view;
    }

    public int getChannel() { return _channel; }

    public void setChannel(int i)
    {
        _channel = i;
    }
}

I've tried creating a custom HorizontalScrollView, and overriding scrollTo() and onRequestFocusInDescendants() as blank methods that do nothing, but this changes nothing.
public class EQScrollView extends HorizontalScrollView {

    public EQScrollView( Context context, AttributeSet attrs)
    {
        super(context, attrs);
        setSmoothScrollingEnabled(false);
    }

    @Override
    public void scrollTo(int x, int y)
    {

    }

    @Override
    public boolean onRequestFocusInDescendants(int x, Rect y)
    {

        return false;
    }

}

A: Using "setRawInputType":
setRawInputType(InputType.TYPE_CLASS_NUMBER);

solved the issue for me at first. After realizing that some number keyboards don't provide decimal input I ended up using standard text input for EditText, extending HorizontalScrollView and overriding "onRequestFocusInDescendants", "requestChildRectangleOnScreen" and "getFocusables" like so:
public class HorizontalScrollViewEx extends HorizontalScrollView {
    public HorizontalScrollViewEx(Context context) {
        super(context);
    }

    public HorizontalScrollViewEx(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HorizontalScrollViewEx(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public HorizontalScrollViewEx(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
        return true;
    }

    @Override
    public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
        return true;
    }

    @Override
    public ArrayList<View> getFocusables(int direction) {
        return new ArrayList<View>();
    }
}

A: I have just encountered this problem and for me the scrolling to the end only happens when android:inputType is not set in the EditText. If you remove this then the issue should vanish.
FYI even using .setInputType(InputType.TYPE_CLASS_NUMBER); produces this error.
Admittedly this isn't a fix but it's worth noting the cause.

A: HorizontalScrollView always scroll to the right when I try to click the EditText
I have fixed the similar by the way below:
In my scenario
    <HorizontalScrollView
        android:id="@+id/id_HorizontalScrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/border_left_black_bold">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/id_RecyclerView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
    </HorizontalScrollView>

*

*RecyclerView's item view:

<LinearLayout>
    <EditText
        android:id="@+id/id_edit"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@drawable/border_right_black"
        android:gravity="center"
        android:inputType="number" />
<LinearLayout/>

*

*Solution in my way:

Customize HorizontalScrollView and override the requestChildRectangleOnScreen method
    @Override
    public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
        return true;
    }
    @Override
    protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
        return 0;
    }

root causes
Let's back to the Android source code.

*

*when the soft keyboard pop up. the size of layout changed View.java protected void onLayout(boolean changed, int left, int top, int right, int bottom)
    /**
     * Called from layout when this view should
     * assign a size and position to each of its children.
     * ....
     */
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    }

*Then HorizontalScrollView.java protected void onLayout(boolean changed, int left, int top, int right, int bottom)
In this method, mIsLayoutDirty = false;

*HorizontalScrollView.java public void requestChildFocus(View child, View focused)

*HorizontalScrollView.java private void scrollToChild(View child)

*HorizontalScrollView.java
int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
if(scrollDelta!=0){
    scrollBy(scrollDelta, 0);
}


text:
Q: SIFR 3.0 - Font Size I have been working with SIFR 3.0 for some time now and the font-size never seems to work correctly.  I understand the most basic concepts behind SIFR.  SIFR runs when you load the page. It does some calculations one the size of the HTML rendered font and then replaces it with a flash movie that is roughly equal to that size.  Because of this, you want to style your HTML font to match the size of your SIFR font as close as possible.
My problem always comes up when trying to style these two font sizes to match.  Let's say I want to use a SIFR font of Helvetica Neue Lt at about 32px.  The HTML equivalent is something like Arial Narrow at about 36px with some negative letter spacing.  So here is what I do.
In sifr.css I'll write:
@media screen {
  .sIFR-active h1 {
      visibility: hidden;
      z-index: 0 !important;
      font-size: 36px;
  }
}

Great, that gets the default HTML font the size I need.  Now I need to update the flash SIFR font size.  So I go into sifr-config.js and write something like this:
sIFR.replace(HelveticaNeueThinCond, {
  selector: 'h1',
  css: '.sIFR-root { color: #762123; font-size: 32px; line-height: 1em; }',
  transparent: true
});

So right now everything is working great.  That is until my h1 text wraps more than one line.  For some reason, when the text wraps it only shows the first line.  It seems calculates the height wrong.  This is very weird because I ran some tests.  I took "visibility: hidden" off of "sIFR-active h1" to make sure that the HTML rendered text was the right size.  It is, it takes up two lines. However, when the Flash replaces this text it gives it a min-height of one line of text. Odd.
The only way I could find to fix this wrapping problem was to remove "font-size: 32px;" from "sIFR.replace(HelveticaNeueThinCond" in sifr-config.  The problem I run into then is that it inherits the font-size set in sifr.css. Now the problem is that my HTML text is bigger then the SIFR text.  So occasional my HTML text will wrap to a new line before my SIFR text leaving a big white space.
So, how do I set two different font-size (one for my HTML text and one for my SIFR) without losing the wrapping.
The only time I have been able to use the successfully is when I have a SIFR font that is so similar to a web safe font that they can share the same font-size attribute.
Thanks

Thanks Mark.  As explained, if I remove the font-size from sIFR.replace it will default to use the font-size declared in .sIFR-active.  I am declaring two different font sizes for a reason, I want sIFR.replace to have a font-size of 32px and sIFR-active to have a font-size of 26px.  This way they match as closely as possible.  Is there no way to have you flash font (sifr.replace) be a different size then the HTML font (sifr-active)?
Is it mandatory to have them be the same font size?  Doesn't make much sense if that is true.  How else would you be able to fine tune the two fonts to get them to take up the same letter spacing/lines?

A: You seem to be doing all the right things with the .sIFR-active class and negative letter spacing. Remove the font size and line height from the sIFR.replace and you should be fine…

A: Actually, I never thought of using two different font sizes, sIFR is simply designed to use the font size from the CSS.
You can use http://wiki.novemberborn.net/sifr3/Ratio+Calculation though to help sIFR sort out the height of the Flash movie, and of course tweak the letter-spacing to sort out the width of the text.


text:
Q: Indexing from a list of strings in C? Obvious newbie question, I'm trying trying to write something that you put in an int and it gives you the month. Here is a function python version:
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
def get_month(mon):
    return months[mon]

In C, I have done this:

#include <stdio.h>
char *months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

int main()
{
char get_month(int m)
{
    return *months[m];
}

for (int i = 0; i < 12; i++)
{
    char    this_month = get_month(i);
    printf ("Month %d is %c\n", i, this_month);
}

return 0;
}

I get this output
Month 1 is J
Month 2 is F
Month 3 is M
Month 4 is A
Month 5 is M
Month 6 is J
Month 7 is J
Month 8 is A
Month 9 is S
Month 10 is O
Month 11 is N
Month 12 is D

I think I have to somehow account for  the length of the strings (or are they technically chars?) in *months[12] but I don't know how. If I change it to *months[12][3] I get
warning: returning 'char *' from a function with return type 'char' makes integer from pointer without a cast [-Wint-conversion]

Also, what if they were not all the same length (i.e. the months were written out fully)?

A: Defining a function within another function is not a standard C feature.
You need to move the definition of the function get_month above main.
Elements of the array monhts have the type char *.
char *months[12] = { /*... */ };

So the function get_month that returns element of the array must have the same return type as the type of the array elements.
char * get_month(int m)
{
    return months[m];
}

So within the for loop in main you need to write
char   *this_month = get_month(i);
printf ("Month %d is %s\n", i, this_month);

As for this expression *months[m] then it yields the first character of the string pointed to by the pointer months[m] because you have an array pf pointers.

A: *

*The function:

char get_month(int m)  // this declares function which returns a single char
{
    return *months[m]; // months is array of pointers. months[m] gives pointer to string. *months[m] dereferences that pointer giving the first character of the month name.
}

it has to be:
char *get_month(int m)  // this declares function which returns pointer to the char array.
{
    return months[m]; // months is array of pointers. months[m] gives pointer to the char array containing the month name
}

*Do not define functions inside other functions.

Move your function definition outside the main function.

*Your variable has to type of pointer to char as strings in C are arrays of chars : char *this_month = get_month(i);

*Use correct printf format:
printf ("Month %d is %s\n", i, this_month);

*Use correct main definition. If it does not take parameters it had to be int main(void)

*Format your code properly
#include <stdio.h>
char *months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

char *get_month(int m)
{
    return months[m];
}

int main()
{
    for (int i = 0; i < 12; i++)
    {
        char    *this_month = get_month(i);
        printf ("Month %d is %s\n", i, this_month);
    }
    return 0;
}

A: in your method the return type is char instead char* so you can only return a single character instead of a string.
char get_month(int m)
{
    return *months[m];
}

The next problem is that you dereference the value which is looked up from the array
so instead a pointer to the string you get the value at the start address of that string, which is the first letter.
Try this instead:
char* get_month(int m)
{
    return months[m];
}


text:
Q: How do I update VMs in place with new image versions in ARM? If I deploy VM from my own image and I iterate and deploy new version number of image, how do I in place upgrade VM which is already deployed. I can not make those properties AFAIK, so I would not be able to use ARM on it's own to perform this operation and would require complex logic to first check if deployed image is correct version, and if it's not then delete VM and submit new ARM deployment afterwards. Is there a better way to accomplish this task?

A: I end up with just using Azure Virtual Machine Scale Sets with instance count of 1 and disabling "overprovision" feature, this way I always have 1 instance running at a time and it's allows to update image.


text:
Q: Ratio between the surface areas of two cones, given the areas of the bases. If you have a cone with a base of 10 square cm and another cone with a base of 5 square cm, what is the ratio between the surface areas, given that the angle of the sloped sides is 60 degrees. When I calculated the two areas using trigonometry I found that the ratio was 2, however, intuitively I thought the area scale factor would be the linear scale factor (2) squared, giving a ratio of 4. Where is the flaw in my logic?

A: You incorrectly stated that the linear scale factor is 2. Instead, the linear scale is $\sqrt2$. This is because the ratio of the two given base areas is $\frac{10}{5}=2$, which translates into the linear ratio of $\sqrt2$.
Thus, the area ratio of the two cones is 2.


text:
Q: Fail to delete API Management service I made 'API Management service' but I can't delete it.
I tried to delete it in the portal, I got this message.

9:47 PM
Succeeded: 0, Failed: 1, Canceled: 0.
Error details
az532test3: The API Service az532test3 is transitioning at this time.
Please try the request again later. (Code: ServiceLocked)

and, if I click the api management service, there is delete button unavailable...
Please help me to find a way to delete it.

A: Any chance it is still provisioning? An API Management service can take up to an hour to provision/deploy.

A: The message is self-explanatory. You cannot delete api management service while it is in a transitioning state like activation, updating or upgrading. You have to wait until it back to active state.
Based on the logs, I guess you were trying to delete while your service was getting activated. It took 38 mins for activation to complete.


text:
Q: Confusion about a conditional probability question?
Music and Math are said to be two subjects that are closely related in
  the way the students think as they learn. At the local high school,
  the probability that a student takes math and music is 0.25. The
  probability that a student is taking math is 0.85. What is the
  probability that a student that is in music is also choosing math?

Here I am not able to undersatnd what probability, Do I have to calculate?
Do I have to calculate P(Math|Music) or P(Music|Math)?
Accoding to the last line of this question-

What is the
  probability that a student that is in music is also choosing math?

Please correct me if I am wrong- It means a studen is already in music and I have to calculate P(Math) given that a stduent is already in music.
But when I checked the answer it is other way around. Please help me to figure out.

A:

What is the probability that a student that is in music is also choosing math?

Please correct me if I am wrong- It means a student is already in music and I have to calculate $\rm P(Math)$ given that a student is already in music.

No, you are not wrong; if that was the question asked, then you've interpreted it correctly.   That is asking you to calculate the conditional probability that a student is taking math, given that that student is taking music.   That is: $\mathsf P({\rm Math}\mid {\rm Music})$ .
However, you have only been given $\mathsf P({\rm Math}\cap{\rm Music})=0.25$ and $\mathsf P({\rm Math})= 0.85$ .   So you can't get to there from here.
Thus the reason the book gave the answer it did would appear to be because the book asked the wrong question.


text:
Q: print files with java using lpr I'm writing an lpr client on java to send files (PDF, doc, etc) to a printer (hp laser-jet 4250dtn)
Both client and server are running UNIX
The printer is on a server (that's why I'm using lpr) Everything is all right and I indeed managing  to open the socket, sending the control file(according to RFC 1179) and sending the file itself.
the file is getting to the printer "queue".
My problem is when I want to print the file from the printer, it's comes out wrong and not understandable at all (can't see any text just weird symbols).
My question is what file type shout I give or make (change the file to postscript??) in order that the printer will understand me? Or am I doing anything else wrong?
Im attaching the code here so you can see and highlighted the line in which im opening the file from the file-path
Socket socketLpr = getSocket(hostName);
    socketLpr.setSoTimeout(30000);
    OutputStream sOut = socketLpr.getOutputStream();
    InputStream sIn = socketLpr.getInputStream();

    //Open printer
    s = "\002" + printerName + "\n";
    sOut.write(s.getBytes());
    sOut.flush();
    acknowledge(sIn, "lpr Failed to open printer");

    //Send control file
    controlFile += "H" + hostName + "\n";
    controlFile += "P" + userName + "\n";
    controlFile += ((printRaw) ? "o":"p") +"dfA" + strJobNumber + hostName + "\n";
    controlFile += "UdfA" + strJobNumber + hostName + "\n";
    controlFile += "N" + documentName + "\n";

    s = "\002" + (controlFile.length()) + " cfA" + strJobNumber + hostName + "\n";
    sOut.write(s.getBytes());

    acknowledge(sIn, "lpr Failed to send control header");

    buffer = controlFile.getBytes();
    sOut.write(buffer);
    buffer[0] = 0;
    sOut.write(buffer, 0, 1);
    sOut.flush();

    acknowledge(sIn, "jLpr Failed to send control file");

    //Send print file
    **f = new File(fileName);** // <- here is when im oppening the file(pdf,word,etc)
    if (!(f.exists() && f.isFile() && f.canRead())) {
        throw new IOException("jLpr Error opening print file");
    }
    s = "\003" + (f.length()) + " dfA" + strJobNumber + hostName + "\n";
    sOut.write(s.getBytes());
    sOut.flush();
    acknowledge(sIn, "jLpr Failed to send print file command");

    FileInputStream fs = new FileInputStream(f);

    int readCounter;
    do {
        readCounter = fs.read(buffer);
        if (readCounter>0) {
            sOut.write(buffer, 0, readCounter);
        }
    } while (readCounter>0);
    buffer[0] = 0;
    sOut.write(buffer,0,1);
    sOut.flush();
    acknowledge(sIn, "jLpr Failed to send print file");

    socketLpr.close();
}


text:
Q: How to convert Python code to executable? So I have a python code now that I want other folks to use. They don't have Python installed on their computers.
I have seen people convert their code to .exe so others can use it even if they don't have Python on their machines.
How can I do this? Is there a special software needed for this?
Thank you

A: Use the pyinstaller library. Then you can create the file with
pyinstaller --onefile yourFileName.py