text:
Q: Sufficient condition for $f(z)$ to be polynomial I think it suffices to exhibit a sequence $\{R_n\}$ of positive real numbers such that $R_n \to \infty$ with $f(z) \neq 0,$ whenever $|z|=R_n$ and $\begin{align} \left|\int_{|z|=R_n}\dfrac{f'(z)}{f(z)}dz \right|\end{align} \leq M, \forall n$.
But I am loss at how to continue from here. Appreciate if someone could advise me.  Thank you.

A: I wouldn't use that approach personally (I doubt it would work as you have no information on $f'$). The theme of my approach is; first observe if $f$ had no zeroes, $1/f$ would be entire and bounded, hence constant by Liouville's theorem. What we can do in this case is multiply $1/f$ by a polynomial to make it entire, then use an extended version of Liouville's theorem that says polynomially bounded entire functions are polynomials, to get that it's a polynomial.
First observe that $f$ has at most finitely many zeroes; if it had infinitely many, you could make a sequence of them, and as this sequence would be contained in closed ball of radius 1, which is compact, it'd have a convergent subsequence. This implies the set of zeroes of $f$ has an accumulation point; a contradiction, as $f$ cannot be identically zero.
Now, let $p(z)$ be the polynomial with the same zeroes as $f$ (with the same multiplicities). I claim $$F(z) = p(z)/f(z)$$ is entire. It's holomorphic at all points $z$ with $f(z) \neq 0$ by the quotient rule. For each zero of $f$, say $z_0$ with multiplicity $m$, we can find an open neighbourhood of $z_0$ where we can write $f(z) = (z-z_0)^m h(z)$ with $h$ analytic and $h(z) \neq 0$ for all $z$ in the neighbourhood, and $p(z) = (z-z_0)^m q(z)$ with $q$ a polynomial. Then on this neighbourhood, $F(z) = q(z)/ h(z)$, showing it's analytic on the neighbourhood, hence at $z_0$.
We now apply this extended version of Liouville's theorem:

Suppose $f: \mathbb{C} \rightarrow \mathbb{C}$ is entire, and there exists $c,C>0$ and $R >0$ and $n\in \mathbb{N}$ such that for $|z| > c$, $\vert f(z) \vert < C \vert z \vert ^n$. Then, $f$ is a polynomial of degree at most $n$.

This applies to $F$ because when $|z|>1$, $|F(z)| < \frac{|p(z)|}{1}$. So $F$ is a polynomial, hence $f$ is rational. Then because $f$ is entire, it has to be a polynomial.

A: You could consider the holomorphic function $$g:D\setminus\lbrace0\rbrace\to D,\quad z\mapsto g(z)=f\left(\frac1z\right)^{-1}$$ where $D$ is the open unit disk of $\Bbb C$. By hypothesis, it is bounded by $1$, hence it extends holomorphically to $0$. Define $m\in\Bbb N$ by
$$g(z)=z^mh(z)$$
with $h$ holomorphic and $h(0)\neq 0$. Then $\frac{f(z)}{z^m}$ is converges to $\frac1{h(0)}$ as $|z|$ tends to infinity, and a standard consequence of Liouville's theorem mentioned in Matt Rigby's answer implies that $f$ is a polynomial of degree $m$.


text:
Q: Handlebars: How pass @index as parameter to custom helper Setup:

*

*I'm using Handelbars.PHP, but maybe a solution with Handlebars.js in mind can help me.

*A custom helper content that expects two parameters a collection and an index.

*An #each helper invocation that calls to #content helper, like this:
{{#each data}}
     {{#content ../parent_options @index}}{{/content}}
{{/each}}
The issue:
Inside the content helper definition I want to access the @index value, say 0,1,2,... but I'm only getting a string!
How can pass as a parameter and access inside the content helper definition the value of @index?

A: As everplays commented and boukeversteegh commented in the official project repo:

Handlebars.PHP doesn't parse arguments of helpers, it's your job to
  parse and give meaning to them (I'm talking about third parameter that
  gets passed to helpers, _helper_each($template, $context, $args,
  $source)). But in your case, there's no need to parse arguments, you
  can simply access it by $context->lastIndex().

Full comments at https://github.com/XaminProject/handlebars.php/issues/27
Final custom helper for reference:
    /**
     * Handlebars Helper Content. Return object->Alphabet[index].
     *
     * @param $template
     * @param $context
     * @param $args
     * @param $source
     *
     * @return Handlebars_String
     * @throws InvalidArgumentException
     */
    public static function _helper_content($template, $context, $args, $source) {
        $Alphabet = range('A', 'Z');

        $tmp = explode(' ', $args);
        $buffer = '';

        $object = $context->get($tmp[0]);

        if (count($tmp) < 2 || $tmp[1] == '@index') {
            $last_index = $context->lastIndex();
            $letter = $Alphabet[$last_index];
        }
        else {
            $index = $context->get($tmp[1]);
            $letter = $Alphabet[$index];
        }

        $buffer .= $object->$letter;

        return new Handlebars_String($buffer);
    }

A: Herebelow is some boilerplate code you can use to create powerful templates with custom helpers, while still using but a minimal amount of code.
It contains two helpers :

*

*One to change a string to uppercase. A @key value is passed to it in the demo code.

*One to increment a numeric value. An @index value is passed to it in the demo code.

Template table.hbs :
{{#if table}}

            #
            {{#each table.0}}

                {{uppercase @key}}

            {{/each}}

        {{#each table}}

            {{increment @index}}
            {{#each this}}
            <input type="text" value="{{this}}" />
            {{/each}}

        {{/each}}

{{#if paginator}}

        {{#each paginator}}

{{@key}}

        {{/each}}

{{/if}}
{{else}}

No data found!

{{/if}}

The view :
// Create handlebars object
$template_engine = new \Handlebars\Handlebars;

// Get helpers object
$helpers = $template_engine->getHelpers();

// Add 'camelize' helper
$helpers->add('uppercase', function($template, $context, $args, $source) {
    return ucwords($context->get($args));
});

// Add 'increment' helper
$helpers->add('increment', function($template, $context, $args, $source) {
    return $context->get($args) + 1;
});

// Render template
echo $template_engine->render(file_get_contents(__DIR__ . '/table.hbs'), array(
    'table' => array(
        array('name' => 'John', 'profession' => 'programmer', 'city' => 'Leuven'),
        array('name' => 'Sam', 'profession' => 'designer', 'city' => 'Aarschot'),
        array('name' => 'Tom', 'profession' => 'owner', 'city' => 'Leuven'),
        array('name' => 'Steve', 'profession' => 'copywriter', 'city' => 'Brussels'),
        array('name' => 'Thomas', 'profession' => 'designer', 'city' => 'Antwerp')
    ),
    'paginator' => array(
        'first' => 'http://www.test.com/first',
        '1' => 'http://www.test.com/1',
        '2' => 'http://www.test.com/2',
        '3' => 'http://www.test.com/3',
        'last' => 'http://www.test.com/last'
    )
));

The output :

            #

                Name

                Profession

                City

            1
            <input type="text" value="John" />
            <input type="text" value="programmer" />
            <input type="text" value="Leuven" />

            2
            <input type="text" value="Sam" />
            <input type="text" value="designer" />
            <input type="text" value="Aarschot" />

            3
            <input type="text" value="Tom" />
            <input type="text" value="owner" />
            <input type="text" value="Leuven" />

            4
            <input type="text" value="Steve" />
            <input type="text" value="copywriter" />
            <input type="text" value="Brussels" />

            5
            <input type="text" value="Thomas" />
            <input type="text" value="designer" />
            <input type="text" value="Antwerp" />

first

1

2

3

last

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parse Push Notification not working on REAL Device but working on Emulator i am working on a project, Currently using parse Push Notification, When i run the app on emulator, The notification works perfectly but Not working on my Samsung galaxy Note 11 and other android devices.
What could be the cause of the problem?
Here is my Permission :
 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission
        android:name="com.packageName.www.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.packageName.www.permission.C2D_MESSAGE" />

Here is my Receiver Tags
<service android:name="com.parse.PushService" />

        <receiver android:name="com.parse.ParseBroadcastReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.USER_PRESENT" />
            </intent-filter>
        </receiver>
        <receiver
            android:name="com.parse.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="com.packageName.www" />
            </intent-filter>
        </receiver>

A: You are missing one more configuration:
<receiver android:name="com.parse.ParsePushBroadcastReceiver" android:exported="false">
  <intent-filter>
    <action android:name="com.parse.push.intent.RECEIVE" />
    <action android:name="com.parse.push.intent.DELETE" />
    <action android:name="com.parse.push.intent.OPEN" />
  </intent-filter>
</receiver>


text:
Q: Emulator Images in android studio and real device images do not match i'm developing an app to manipulate image taken by camera in real time. Though when i run the same code in android studio emulator i get the colors i need. Though when i do it in real device the colors are shifted.
for example Dark blue in emulator is slightly lighter. Red in emulator is lighter in real device. i tried it in several real devices. In all cases colors are lighter than expected.
Why this is happening?? Is there any differences in webcam in a laptop which emulator pickup the image and real device cameras??
How can i make the colors same as the images in webcam pictures in emulator?

A: Found an answer for my issue. Just needed to adjust the contrast of my laptop's webcam. All working as expected.


text:
Q: sandbox Activation / login is just hanging and not connecting I have quite strange behavior . I could not connect to any dev or sandboxes . Login form just freez when i try to get activation code or login even to new devbox . I have try different devices and reset dns and network cache, reboot router. I see just pending post request for 2-4 minutes .

A: This is usually a connection or computer/device problem.
Try the following:

*

*Try getting to other websites to make sure that it's isolated to just salesforce.com. If you're having general intermittent problems, it's either your connection or your device.

*Try pinging the salesforce.com servers. See the online help for your operating system on how to ping.

*Try clearing your cache. Most browsers now support Ctrl-Shift-Del as a keyboard shortcut to clear your cache. Follow the online help for your browser of choice. This can often resolve problems.

*Try the recommended browser settings in Help & Training (Google "salesforce.com recommended browsers").

*Rarely, there's a problem with your "instance". Check Salesforce Trust to see if you're affected.


text:
Q: Spring Security and complex method-based rules needing db request I'm having I think a design problem. I'm starting to need to implement method-based security to ensure my users don't try anything funny.
I have users "owning" a certain business object who can add other users "owning" children of this business object. What I'd like is to check that the user trying to create the new user is indeed the owner of the father of the object for which the new user will be added.
It's not very clear, but here is my question: is it a very bad design when it means that I need to query my database to check for things in a PermissionEvaluator ? And if not, is it even possible ? I can't seem to be able to inject Spring components (@Service beans for exemple) in a PermissionEvaluator used by a SpEL @PreAuthorize rule.

A: To determine permissions on the fly based on database tables, spring security ACL is the safest choice. But as an alternative, you can create a custom access decision manager that has a custom voter that queries the database.
Check this answer for an example, in your case you would need a unanymous based access decision voter, with an AuthenticatedVoter to check that the user is logged in and a custom DBPermissionsVoter to decide if the user has permissions based on reference data.
The voters are spring beans, so you can inject any DAOs or services you need in them.


text:
Q: OneHotEncoder categorical_features deprecated, how to transform specific column I need to transform the independent field from string to arithmetical notation. I am using OneHotEncoder for the transformation. My dataset has many independent columns of which some are as:
Country     |    Age
--------------------------
Germany     |    23
Spain       |    25
Germany     |    24
Italy       |    30

I have to encode the Country column like
0     |    1     |     2     |       3
--------------------------------------
1     |    0     |     0     |      23
0     |    1     |     0     |      25
1     |    0     |     0     |      24
0     |    0     |     1     |      30

I succeed to get the desire transformation via using OneHotEncoder as
#Encoding the categorical data
from sklearn.preprocessing import LabelEncoder

labelencoder_X = LabelEncoder()
X[:,0] = labelencoder_X.fit_transform(X[:,0])

#we are dummy encoding as the machine learning algorithms will be
#confused with the values like Spain > Germany > France
from sklearn.preprocessing import OneHotEncoder

onehotencoder = OneHotEncoder(categorical_features=[0])
X = onehotencoder.fit_transform(X).toarray()

Now I'm getting the depreciation message to use categories='auto'. If I do so the transformation is being done for the all independent columns like country, age, salary etc.
How to achieve the transformation on the dataset 0th column only?

A: As of version 0.22, you can write the same code as below:
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
ct = ColumnTransformer([("Country", OneHotEncoder(), [0])], remainder = 'passthrough')
X = ct.fit_transform(X)

As you can see, you don't need to use LabelEncoder anymore.

A: transformer = ColumnTransformer(
    transformers=[
        ("Country",        # Just a name
         OneHotEncoder(), # The transformer class
         [0]            # The column(s) to be applied on.
         )
    ], remainder='passthrough'
)
X = transformer.fit_transform(X)

Reminder will keep previous data while [0]th column will replace will be encoded

A: Dont use the labelencoder and directly use OneHotEncoder.
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import make_column_transformer
A = make_column_transformer(
    (OneHotEncoder(categories='auto'), [0]),
    remainder="passthrough")

x=A.fit_transform(x)

A: There is a way that you can do one hot encoding with pandas.
Python:
import pandas as pd
ohe=pd.get_dummies(dataframe_name['column_name'])

Give names to the newly formed columns add it to your dataframe. Check the pandas documentation here.

A: There is actually 2 warnings :

FutureWarning: The handling of integer data will change in version
  0.22. Currently, the categories are determined based on the range [0, max(values)], while in the future they will be determined based on the
  unique values. If you want the future behaviour and silence this
  warning, you can specify "categories='auto'". In case you used a
  LabelEncoder before this OneHotEncoder to convert the categories to
  integers, then you can now use the OneHotEncoder directly.

and the second :

The 'categorical_features' keyword is deprecated in version 0.20 and
  will be removed in 0.22. You can use the ColumnTransformer instead.
  "use the ColumnTransformer instead.", DeprecationWarning)

In the future, you should not define the columns in the OneHotEncoder directly, unless you want to use "categories='auto'". The first message also tells you to use OneHotEncoder directly, without the LabelEncoder first.
Finally, the second message tells you to use ColumnTransformer, which is like a Pipe for columns transformations.
Here is the equivalent code for your case :
from sklearn.compose import ColumnTransformer
ct = ColumnTransformer([("Name_Of_Your_Step", OneHotEncoder(),[0])], remainder="passthrough")) # The last arg ([0]) is the list of columns you want to transform in this step
ct.fit_transform(X)

See also : ColumnTransformer documentation
For the above example;

Encoding Categorical data (Basically Changing Text to Numerical data i.e, Country Name)

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
#Encode Country Column
labelencoder_X = LabelEncoder()
X[:,0] = labelencoder_X.fit_transform(X[:,0])
ct = ColumnTransformer([("Country", OneHotEncoder(), [0])], remainder = 'passthrough')
X = ct.fit_transform(X)

A: I had the same issue and the following worked for me:
OneHotEncoder(categories='auto', sparse=False)

Hope this helps

A: Use the following code :-
from sklearn.preprocessing import OneHotEncoder

from sklearn.compose import ColumnTransformer

columnTransformer = ColumnTransformer([('encoder', OneHotEncoder(), [0])], remainder='passthrough')

X = np.array(columnTransformer.fit_transform(X), dtype = np.str)

print(X)

A: from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
...
onehotencorder = ColumnTransformer(
   [('one_hot_encoder', OneHotEncoder(), [0])],
   remainder='passthrough'
)

X = onehotencorder.fit_transform(X)

A: # Data Preprocessing Template

# Importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,3].values

# Splitting the dataset into the Training set and Test set
#from sklearn.preprocessing import Imputer
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer = imputer.fit(X[:,1:3])
X[:,1:3] = imputer.transform(X[:,1:3])

#encoding Categorical Data
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer

labelencoder_X = LabelEncoder()
X[:,0] = labelencoder_X.fit_transform(X[:,0])
onehotencoder = ColumnTransformer([("Country", OneHotEncoder(), [0])], remainder = "passthrough")
X = onehotencoder.fit_transform(X)

labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)

A: from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
transformer = ColumnTransformer([('one_hot_encoder', OneHotEncoder(), [0])],remainder='passthrough')
x = py.array(transformer.fit_transform(x), dtype=py.float)

onehotencoder = oneHotEncoder(categorical_features=[0])

This code should solve the error.

A: When updating the code from this:
one_hot_encoder = OneHotEncoder(categorical_features = [0, 1, 4, 5, 6])
X_train = one_hot_encoder.fit_transform(X_train).toarray()

To this:
ct = ColumnTransformer([('one_hot_encoder', OneHotEncoder(), [
                       0, 1, 4, 5, 6])], remainder='passthrough')
X_train = np.array(ct.fit_transform(X_train), dtype=np.float)

Note that I had to add dtype=np.float to fix the error message TypeError: can't convert np.ndarray of type numpy.object_.
Where my colums were [0, 1, 4, 5, 6] and 'one_hot_encoder' is anything.
My imports were:
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
import numpy as np


text:
Q: Split a Table into 2 or more Tables based on Column value I have a Table called "MIVTable" which has the following records,
    MIVID      Quantity         Value
   ------     ----------       --------
      14           10             3000
      14           20             3500
      14           15             2000
      15           20             3000
      15           50             7500
      16           25             2000

Here, I need to store the above Table into two tables such as "HeaderTbl" and "DetailTbl" based on the MIVID as follows:
HeaderTbl:
   HID      MIVID       TotalQuantity    TotalValue
  -----    -------      -------------    -----------
    1         14               45           8500
    2         15               70          10500
    3         16               25           2000

Here HID is the Primary Key with Identity Column.
DetailTbl:
  HID        MIVID        Quantity        Value
 -----      -------     ------------     -------
   1           14             10           3000
   1           14             20           3500
   1           14             15           2000
   2           15             20           3000
   2           15             50           7500
   3           16             25           2000

Suppose, if the MIVTable contains 4 different MIVID means, then 4 row should be created based on the MIVID on the HeaderTbl. How to do this?

A: To insert records in HeaderTbl from MIVTable use this: (HID should be auto increment)
INSERT INTO HeaderTbl
    ([MIVID], [TotalQuantity], [TotalValue])
SELECT MIVID, SUM(Quantity), SUM(Value) FROM MIVTable GROUP BY MIVID;

To insert records in DetailTbl from HeaderTbl and MIVTable use this:
INSERT INTO DetailTbl
([HID], [MIVID], [Quantity], [Value])
    SELECT H.HID, M.*
      FROM HeaderTbl H
INNER JOIN MIVTable M
        ON H.MIVID = M.MIVID;

Look at this SQLFiddle
Here you need to use INSERT INTO SELECT statement to insert data from one table to another. You can also use JOIN in such statement as I did it for DetailTbl.

A: You would generate the HeaderTbl using RANK() SQL Server function, as follows:
SELECT RANK() OVER (ORDER BY MIVID) as HID, MIVID, TotalQuantity, TotalValue
FROM
(
SELECT
    MIVID,
    SUM(Quantity) as TotalQuantity,
    SUM(Value) as TotalValue
FROM MIVTable GROUP BY MIVID
) AS A

and the Detail table using the ROW_NUMBER() SQL Server function, as follows:
SELECT
    ROW_NUMBER() OVER (ORDER BY MIVID) AS HID,
    MIVID,
    Quantity,
    Value
FROM MIVTable


text:
Q: Using testfor to give a potion effect How do you use a testfor command to give you a potion effect? I want a command that makes it so when you hold a stick called "Flashlight", you get night vision.
Can anyone help?

A: /testfor will not be useful as it simply outputs if there was a match and will not allow you to target the one(s) who matched.
You will want to use /scoreboard instead, which can apply a label based on a target's NBT data either in the form of a score or "tag". Tag labels are much more efficient to use for simple boolean situations like this one.

The SelectedItem compound holds a copy of the player's currently-held item on the hotbar, minus the Slot tag. You can apply a label based on that, though it must be removed first in the event the player is no longer holding the item:

All command blocks are set to "Always Active" and "Unconditional".

*

*Remove the label from players first, so that if they are no longer holding the item they will not receive the effect anymore.
/scoreboard players tag @a[tag=flashlight] remove flashlight

*Add a "flashlight" label to players that are holding a stick named "Flashlight".
/scoreboard players tag @a add flashlight {SelectedItem:{id:"minecraft:stick",tag:{display:{Name:"Flashlight"}}}}

*And you can then use the /effect command to correctly target the players who matched, as they will have a "flashlight" label now:
/effect @a[tag=flashlight] minecraft:night_vision


text:
Q: How to log info using NLog in Xamarin forms project I am using Nlog to log exceptions in my project(cross platform xamarin project).
My implementation:
public interface ILogger
{
    void Trace(string text, params object[] args);
    void Debug(string text, params object[] args);
    void Info(string text, params object[] args);
    void Warn(string text, params object[] args);
    void Error(string text, params object[] args);
    void Fatal(string text, params object[] args);
}

public interface ILogManager
{
    ILogger GetLog([System.Runtime.CompilerServices.CallerFilePath]string callerFilePath = "");
}

In Platform specific UWP project I have created 2 classes:
public class NLogLogger : ILogger
{
    private Logger log;

    public NLogLogger(Logger log)
    {
        this.log = log;
    }

    public void Debug(string text, params object[] args)
    {
        log.Debug(text, args);
    }

    public void Error(string text, params object[] args)
    {
        log.Error(text, args);
    }

    public void Fatal(string text, params object[] args)
    {
        log.Fatal(text, args);
    }

    public void Info(string text, params object[] args)
    {
        log.Info(text, args);
    }

    public void Trace(string text, params object[] args)
    {
        log.Trace(text, args);
    }

    public void Warn(string text, params object[] args)
    {
        log.Warn(text, args);
    }

}

NLogManager Class:
  public class NLogManager : ILogManager
  {
    public NLogManager()
    {
        var config = new LoggingConfiguration();

        var consoleTarget = new ConsoleTarget();
        config.AddTarget("console", consoleTarget);

        var consoleRule = new LoggingRule("*", LogLevel.Trace, consoleTarget);
        config.LoggingRules.Add(consoleRule);

        var fileTarget = new FileTarget();
        string folder = ApplicationData.Current.LocalFolder.Path;
        string fileNameWithDate = "Log_" + DateTime.Today.ToString("MMMddyyyy") + ".txt";
        fileTarget.FileName = Path.Combine(folder, fileNameWithDate);
        config.AddTarget("file", fileTarget);

        var fileRule = new LoggingRule("*", LogLevel.Warn, fileTarget);
        config.LoggingRules.Add(fileRule);

        LogManager.Configuration = config;
    }

    public EverwellUnpluggedLogger.ILogger GetLog([CallerFilePath] string callerFilePath = "")
    {
        string fileName = callerFilePath;

         if (fileName.Contains("/"))
           {
               fileName = fileName.Substring(fileName.LastIndexOf("/", StringComparison.CurrentCultureIgnoreCase) + 1);
           }

           var logger = LogManager.GetLogger(fileName);
           return new NLogLogger(logger);
    }
}

If exception is thrown in any method I am using below line to record it in text file. This works fine.
ILogger logger = DependencyService.Get<ILogManager>().GetLog();
        logger.Error(ex.Message, ex);

Similarly when when I am using logger.info(), this does not record anything in my text file.
 logger.Info(logs);

Is there a need to change any configuration in Nlog.config file?
Please help.

A: If you question is why this line doesn't log to fileTarget:
logger.Info(logs);

Then the issue is probably that you only include warnings (or worse):
var fileRule = new LoggingRule("*", LogLevel.Warn, fileTarget);

Try changing to this instead:
var fileRule = new LoggingRule("*", LogLevel.Info, fileTarget);


text:
Q: Load a pdf into S3 using User Defined Java Class in Pentaho import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;

import java.io.File;
import java.io.IOException;

public class UploadObject {

  public static void main(String[] args) throws IOException {

    Regions clientRegion = Regions.US_EAST_1;

    String fileObjKeyName = "N.pdf";

    String fileName = "C:\\home\\aws\\N.pdf";

    //To Test the File Upload

    String accessKeyId = "AKIAZGSMNGVXXXZ73VXE";

    String secretAccessKey = "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";

    String bucketName = "fioprod-s3-addon-us-east-12";

    try {

      final BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKeyId, secretAccessKey);

      //This code expects that you have AWS credentials set up per:

      // https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html

      AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
          .withRegion(clientRegion)
          .withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials))
          .build();

      // Upload a file as a new object with ContentType and title specified.

      PutObjectRequest request = new PutObjectRequest(bucketName, fileObjKeyName, new File(fileName));

      ObjectMetadata metadata = new ObjectMetadata();

      metadata.setContentType("plain/text");

      metadata.addUserMetadata("title", "someTitle");

      request.setMetadata(metadata);

      s3Client.putObject(request);

    } catch (AmazonServiceException e) {

      // The call was transmitted successfully, but Amazon S3 couldn't process

      // it, so it returned an error response.

      e.printStackTrace();

    } catch (SdkClientException e) {

      // Amazon S3 couldn't be contacted for a response, or the client

      // couldn't parse the response from Amazon S3.

      e.printStackTrace();

    }

  }

}

The above code works fine to load pdf file into S3 when I run it from IntelliJ IDE. I want this code to move to Pentaho "User Defined Class", when I do that it throws error - " Imported class "com.amazonaws.auth.AWSStaticCredentialsProvider" could not be loaded"
How do I resolve that? My ultimate goal is to load a .pdf or .zip file into S3 using pentaho.
Thank you for your time.

A: Your have written nice code which is working as well. You just need to keep aws-java-sdk jar to your data-integration/lib location.
You can download sdk jar file from Here
You can look my KTR also from Here   where I have included your code and make small changes to workable your code in User-defined-java-class in PDI
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;

import java.io.File;
import java.io.IOException;

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException{
    Object[] r = getRow();

 if (r == null) {
        setOutputDone();
        return false;
    }

    Regions clientRegion = Regions.US_EAST_1;

    String fileObjKeyName = "N.pdf";

    String fileName = "C:\\home\\aws\\N.pdf";

    //To Test the File Upload

    String accessKeyId = "AKIAZGSMNGVXXXZ73VXE";

    String secretAccessKey = "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";

    String bucketName = "fioprod-s3-addon-us-east-12";

      final BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKeyId, secretAccessKey);

      //This code expects that you have AWS credentials set up per:

      // https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html

      AmazonS3 s3Client = (AmazonS3)AmazonS3ClientBuilder.standard().withRegion(clientRegion).withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials)).build();

      // Upload a file as a new object with ContentType and title specified.

      PutObjectRequest request = new PutObjectRequest(bucketName, fileObjKeyName, new File(fileName));

      ObjectMetadata metadata = new ObjectMetadata();

      metadata.setContentType("plain/text");

      metadata.addUserMetadata("title", "someTitle");

      request.setMetadata(metadata);

      s3Client.putObject(request);

    putRow(data.outputRowMeta, r);
     return true;

}


text:
Q: I can't figure out how to extract specific key:value pairs from a nested dictionary I'm working with IBM Watson VisualRecognition service and when I submit a file to be analyzed, I received the following dict response:
<class 'dict'>
{'images': [{'source': {'type': 'file', 'filename': 'frame_00100.jpg'},
'dimensions': {'height': 1080, 'width': 1920}, 'objects': {'collections':
[{'collection_id': 'a9081264-3000-4cbb-8cb8-9b11ad019460', 'objects':
[{'object': 'Car', 'location': {'left': 1119, 'top': 532, 'width': 390,
'height': 264}, 'score': 0.98179674}]}]}}]}

When I try to print the list of keys and values, this is what I get:
keys = resp.keys()
values = resp.values()
print(str(keys))
print(str(values))

dict_keys(['images'])
dict_values([[{'source': {'type': 'file', 'filename': 'frame_00100.jpg'}, 'dimensions': {'height':
1080, 'width': 1920}, 'objects': {'collections': [{'collection_id': 'a9081264-3000-4cbb-8cb8-
9b11ad019460', 'objects': [{'object': 'Car', 'location': {'left': 1119, 'top': 532, 'width': 390,
'height': 264}, 'score': 0.98179674}]}]}}]])

My objective is to be able to reference a specific value on the response later on my code. For instance, I'd like to be able to find resp['left'], which should return 1119

A: +1 to @PhilippSelenium's suggestion:

You just have to navigate through the dicts and lists until you find your element. Using ipython is really helpful in this case: d.get("images")[0].get("objects").get("collections")[0].get("objects")[0].get("location").get("left")

There are other libraries like flatten_json which will allow you to access the nested object from a "flat" dict. e.g:
>>> from flatten_json import flatten
>>> resp = {'images': [{'source': {'type': 'file', 'filename': 'frame_00100.jpg'},
... 'dimensions': {'height': 1080, 'width': 1920}, 'objects': {'collections':
... [{'collection_id': 'a9081264-3000-4cbb-8cb8-9b11ad019460', 'objects':
... [{'object': 'Car', 'location': {'left': 1119, 'top': 532, 'width': 390,
... 'height': 264}, 'score': 0.98179674}]}]}}]}
>>> resp = flatten(resp)
>>> print(resp["images_0_objects_collections_0_objects_0_location_left"])
1119

But its likely best to learn to do tit the hard way before trying to use a library to make it easy for you (the hard way is also more performant)


text:
Q: Sphinx in Docker: Lost connection to MySQL server at 'reading initial communication packet', system error: 0 I have trouble with connection to Sphinx in Docker from outside.
In docker container connection works fine:
root@b8161ac2de3e:/app# mysql -h127.0.0.1 -P 9306
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 2.3.2-id64-beta (4409612)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input
statement.

mysql>

Docker forwarding port:
b8161ac2de3e        test_sphinx          "searchd.sh"   9 minutes ago       Up 9 minutes        9000/tcp, 0.0.0.0:9306->9306/tcp   test_sphinx_1

But when I'm trying to connect from outside container, I've got this:
vagrant@test:/srv/projects/test$ mysql -h0.0.0.0 -P 9306
ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0

Do you have any ideas?
UP!
Add docker-compose.yml
version: '3'

services:

  web:
     image: nginx
     depends_on:
       - php-fpm
     volumes:
       - .:/app
       - ./docker/nginx/nginx.conf:/etc/nginx/nginx.conf
       - ./docker/nginx/frontend.conf:/etc/nginx/conf.d/default.conf
     restart: ${RESTART}
     ports:
       - 80:80

    php-fpm:
      build:
        context: ./docker/php-fpm
        args:
          ENABLE_XDEBUG: ${PHP_ENABLE_XDEBUG}
          PHP_CLI_UID: ${PHP_CLI_UID}
          PHP_CLI_GID: ${PHP_CLI_GID}
          PHP_FPM_UID: ${PHP_FPM_UID}
          PHP_FPM_GID: ${PHP_FPM_GID}
      environment:
        XDEBUG_CONFIG: remote_host=${XDEBUG_REMOTE_HOST} remote_port=${XDEBUG_REMOTE_PORT} remote_enable=On
        PHP_IDE_CONFIG: serverName=app
      volumes:
        - .:/app
        - ./docker/php-fpm/config/php.ini:/usr/local/etc/php/php.ini
        - ./sysconfig/etc/freetds:/etc/freetds
        - ./sysconfig/etc/odbc.ini:/etc/odbc.ini
        - ./sysconfig/etc/odbcinst.ini:/etc/odbcinst.ini
        - ./sysconfig/usr/local/sphinxsearch/etc/sphinx.conf:/etc/sphinxsearch/sphinx.conf
        - ./sysconfig/usr/local/sphinxsearch:/usr/local/sphinxsearch
        - ./docker/sphinx/data:/usr/local/sphinxsearch/var/data
        - ./docker/sphinx/log:/usr/local/sphinxsearch/var/log
      restart: ${RESTART}

  mysql:
      image: mysql
      restart: always
      environment:
        - MYSQL_ROOT_PASSWORD=root
        - MYSQL_DATABASE=blog
      ports:
        - 3306:3306

  sphinx:
    build:
      context: ./docker/php-fpm
      args:
        ENABLE_XDEBUG: ${PHP_ENABLE_XDEBUG}
        PHP_CLI_UID: ${PHP_CLI_UID}
        PHP_CLI_GID: ${PHP_CLI_GID}
        PHP_FPM_UID: ${PHP_FPM_UID}
        PHP_FPM_GID: ${PHP_FPM_GID}
    environment:
      XDEBUG_CONFIG: remote_host=${XDEBUG_REMOTE_HOST} remote_port=${XDEBUG_REMOTE_PORT} remote_enable=On
      PHP_IDE_CONFIG: serverName=app
    command: /app/docker/php-fpm/searchd.sh
    volumes:
        - .:/app
        - ./docker/php-fpm/config/php.ini:/usr/local/etc/php/php.ini
        - ./sysconfig/etc/freetds:/etc/freetds
        - ./sysconfig/etc/odbc.ini:/etc/odbc.ini
        - ./sysconfig/etc/odbcinst.ini:/etc/odbcinst.ini
        - ./sysconfig/usr/local/sphinxsearch/etc/sphinx.conf:/etc/sphinxsearch/sphinx.conf
        - ./sysconfig/usr/local/sphinxsearch:/usr/local/sphinxsearch
        - ./docker/sphinx/data:/usr/local/sphinxsearch/var/data
    restart: ${RESTART}
    ports:
      - 9306:9306
    networks:
      - default
      - web

  redis:
    image: redis:latest

This starts services, other services except sphinx is available in host machine.


text:
Q: How to monitor space usage on ASM diskgroups Last night the recovery area on one of our Oracle Database Appliances went full. This was reported in one of the database alert logs, and we were able to clear out some space before the next log switch, at which point the production would have come to a halt.
It certainly would have been nice to have a little more warning, like when the disk group was 70% full.
What options do we have for monitoring disk usage inside ASM?

A: Try this...
col gname form a10
col dbname form a10
col file_type form a14

SELECT
    gname,
    dbname,
    file_type,
    round(SUM(space)/1024/1024) mb,
    round(SUM(space)/1024/1024/1024) gb,
    COUNT(*) "#FILES"
FROM
    (
        SELECT
            gname,
            regexp_substr(full_alias_path, '[[:alnum:]_]*',1,4) dbname,
            file_type,
            space,
            aname,
            system_created,
            alias_directory
        FROM
            (
                SELECT
                    concat('+'||gname, sys_connect_by_path(aname, '/')) full_alias_path,
                    system_created,
                    alias_directory,
                    file_type,
                    space,
                    level,
                    gname,
                    aname
                FROM
                    (
                        SELECT
                            b.name            gname,
                            a.parent_index    pindex,
                            a.name            aname,
                            a.reference_index rindex ,
                            a.system_created,
                            a.alias_directory,
                            c.type file_type,
                            c.space
                        FROM
                            v$asm_alias a,
                            v$asm_diskgroup b,
                            v$asm_file c
                        WHERE
                            a.group_number = b.group_number
                        AND a.group_number = c.group_number(+)
                        AND a.file_number = c.file_number(+)
                        AND a.file_incarnation = c.incarnation(+) ) START WITH (mod(pindex, power(2, 24))) = 0
                AND rindex IN
                    (
                        SELECT
                            a.reference_index
                        FROM
                            v$asm_alias a,
                            v$asm_diskgroup b
                        WHERE
                            a.group_number = b.group_number
                        AND (
                                mod(a.parent_index, power(2, 24))) = 0
                            and a.name like '&&db_name'
                    ) CONNECT BY prior rindex = pindex )
        WHERE
            NOT file_type IS NULL
            and system_created = 'Y' )
WHERE
    dbname like '&db_name'
GROUP BY
    gname,
    dbname,
    file_type
ORDER BY
    gname,
    dbname,
    file_type
/

A: Just use asmcmd. For example:
[oracle@oel61 ~]$ . oraenv
ORACLE_SID = [+ASM] ? +ASM
The Oracle base remains unchanged with value /u01/app/oracle
[oracle@oel61 ~]$ asmcmd lsdg
State    Type    Rebal  Sector  Block       AU  Total_MB  Free_MB  Req_mir_free_MB  Usable_file_MB  Offline_disks  Voting_files  Name
MOUNTED  EXTERN  N         512   4096  1048576     30708    28479                0           28479              0             N  DATA/
[oracle@oel61 ~]$

Or get the info directly from the ASM Oracle instance:
[oracle@oel61 ~]$ . oraenv
ORACLE_SID = [+ASM] ? +ASM
The Oracle base remains unchanged with value /u01/app/oracle
[oracle@oel61 ~]$ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.2.0 Production on Thu Mar 7 10:44:44 2013

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
With the Automatic Storage Management option

SQL> SELECT name, free_mb, total_mb, free_mb/total_mb*100 as percentage
     FROM v$asm_diskgroup;

NAME                  FREE_MB   TOTAL_MB PERCENTAGE
------------------------------ ---------- ---------- ----------
DATA                    28479      30708 92.7413052

SQL>


text:
Q: Subquery: Help correcting syntax errors I am recieving the following 2 errors when I try to run the below subquery:
Msg 156, Level 15, State 1, Line 11 - Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 13 - Incorrect syntax near ')'.
SELECT
RIGHT(A.Name,LEN(Name)-5) AS ASSOCIATE
,B.WeekEnding
,COUNT(B.ID)AS Policies
,SUM (B.Amount) AS Premium

FROM
dbo.Users A
INNER JOIN (SELECT*,
SELECT DATEADD(DAY,(12-DATEPART(WEEKDAY,CreateDate)%7)-6,CreateDate)
WeekEnding
FROM dbo.Policy) B
ON A.User = B.Agent

WHERE
B.CreateDate >= CONVERT (DATE,GETDATE()))

GROUP BY A.Name, B.WeekEnding
ORDER BY Policies DESC, Premium DESC

A: You have an extra SELECT in the subquery. It should be:
(SELECT *,
        DATEADD(DAY,(12-DATEPART(WEEKDAY,CreateDate)%7)-6,CreateDate) WeekEnding
 FROM dbo.Policy)

and you have an extra parenthesis here:
WHERE
B.CreateDate >= CONVERT (DATE,GETDATE()))
                                        ^


text:
Q: Pass an object property through an URL I have a list of objects defined like this.
var users = [{id:1,name:"Rudy",color:"Orange"},{id:2,name:"Sean",color:"Blue"},{id:2,name:"Rob",color:"Green"}]

I then make a table holding each object and their properties.
I want to be able to click on a row and open up a new page with all the properties in the corresponding object.
I have an html file called userinfo.html that looks like this:

    {{user}}
        {{user.id}}
        {{user.name}}
        {{user.color}}

I am trying to pass the user id through the URL. It will not let me do this no matter what I try. If I replace user.id with a string or integer it works fine.
Is there a reason it won't pass an object property. Is there a better way to accomplish this?
Thank You for any help!!

A: Use
{{user.id}}


text:
Q: How to fix appendix section headings while using titlesec package? I am writing a paper using article class. I use the titlesec package with [sc] option, e.g. \usepackage[sc]{titlesec} to write the document headings in small caps. When I use this package, it wrecks the headings in the appendix like this:
It does not mess with section headings of main body though. What is causing this and how to fix it? Here is MWE:
\documentclass{article}
\usepackage[sc]{titlesec}
\title{The Earth Shattering Paper}
\begin{document}
\maketitle
\newpage
\appendix
\begin{center}
\section*{\textsc{ONLINE APPENDIX}\\[0.8cm]
The Earth Shattering Paper\\[0.8cm]
Dr Smarty Pants}
\end{center}
\end{document}

A: The position of \begin{center} is wrong. It makes the lines filled. Put it in the section title:
\documentclass{article}
\usepackage[sc]{titlesec}
\title{The Earth Shattering Paper}
\begin{document}
\maketitle
\newpage
\appendix
%\centering%\begin{center}
\section*{\centering{\textsc
{ONLINE APPENDIX}}\\[0.8cm]
The Earth Shattering Paper\\[0.8cm]
Dr Smarty Pants}
%\end{center}
\end{document}


text:
Q: How two use two markdown themes with same blade names? I have created a second path in the mail config for markdown mailables:
'markdown' => [
    'theme' => 'default',

    'paths' => [
        resource_path('views/vendor/mail'),
        resource_path('views/vendor/newsletter'),
    ],
],

Every new component in views/vendor/newsletter can be accessed in a mail blade like this:
@component('mail::message-newsletter')

However, I can't access views/vendor/newsletter/message.php because its already in views/vendor/mail/message.php.
I would like to use same blade names button, footer, header, layout, message etc. for my newsletter template.
I tried to add a newsletter alias like this:
$this->loadViewsFrom(resource_path('views/vendor/newsletter'), 'newsletter');

so that I could access the message like this:
@component('newsletter::message')

Unfortunately, this returns the following error:

View [message] not found.

I could fix it by doing
$this->loadViewsFrom(resource_path('views/vendor/newsletter/html'), 'newsletter');

but then the markdown files in resource_path('views/vendor/newsletter/markdown' would not be rendered.
I thought it would work, because the newsletter path is set in the config. Isn't mail also just pointing to resource_path('views/vendor/mail')?

A: The mail namespace
@('mail::

is overwritten, depending on if render for HTML is called or renderText for text is called. This is hardcoded in Illuminate\Mail\Markdown so you can't use @('newsletter:: for HTML and raw.
What you could get the Markdown class from ServiceContainer and change the compontes path:
$markdown = \Illuminate\Container\Container::getInstance()->make(\Illuminate\Mail\Markdown::class);
$markdown->loadComponentsFrom([
    resource_path('views/vendor/newsletter'), ]);

this would use message, footer, header etc. only from newsletter folder.


text:
Q: Using pointer to member function of a base class on object of derived class Consider following code snippet:
struct Base {
    std::string foo () const { std::cout << "Base::foo()\n"; return "X"; }
};

struct Der : Base {};

struct Ptr : std::integral_constant<std::string (Base:: *) () const, &Base::foo> {};

and usage is like this:
Der der;
std::string s = (der.*Ptr::value) ();
std::cout << s << "\n";

Output is as desired:
Base::foo()
X

Everything seems to be fine.
My question is: Is this code correct? Or am I stepping on the land of undefined behavior? Can I use pointer to member function of a base class on object of derived class directly?

A: Roughly speaking, the member belongs to the suboject and thus you must use its type to identify it. Perfectly fine indeed.
The other way around doesn't even compile actually:
struct Ptr : std::integral_constant<std::string (Der:: *) () const, &Der::foo> {};

The error is pretty clear:

error: could not convert template argument '&Base::foo' from '[...] (Base::)() const}' to '[...] (Der::)() const'

Where I used [...] to reduce it a bit.


text:
Q: Delete Unregistered Users after a Week Currently I have ActionMailer send an email when a user registers. I then generate a random :sign_in_token with the user so that the user can activate his account. Once a user activates his account via email, the users :registration_complete boolean is set to true.
How can I delete users saved in the database a week after they have been created if they have not activated their account?
This is my current solution. But I am not sure if this is the best way to do it.
I get this ERROR message
NoMethodError (undefined method `-' for :created_at:Symbol):

USER MODEL
after_create :delete_unregistered_users

def delete_unregistered_users
  User.where("created_at <= ?", :created_at - 1.week && :registration_complete == false).each do |user|
    user.destroy
  end
end

A: def delete_unregistered_users
  User.where("created_at <= ? AND registration_complete = ?", Time.zone.now - 1.week,false).each do |user|
    user.destroy
  end
end

A: def delete_unregistered_users
  User.where("created_at <= ? && registration_complete=?", '#{Time.zone.now - 1.week}',false).each do |user|
     user.destroy
  end
end

A: try this
def delete_unregistered_users
  User.where("created_at <= ? AND registration_complete = ?", Time.zone.now - 1.week,false).destroy_all
end


text:
Q: Unable to use miniconda within docker container installing it with Dockerfile I want to use miniconda within a container coming from a Dockerfile based on Debian. I have seen several similar questions here

*

*Add Miniconda binaries to path in Docker container

*How to install packages with miniconda in Dockerfile?

*Problems running conda update in a dockerfile
But I have not been able to make it work with the answers there. My Dockerfile starts with:
RUN sudo apt-get update && sudo apt-get install -y build-essential gconf-service libasound2 libatk1.0-0 libcairo2 \
    libcups2 libfontconfig1 libgdk-pixbuf2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libxss1 fonts-liberation \
    libappindicator1 libnss3 lsb-release xdg-utils wget libappindicator3-1 libgbm1 python3-dev nano

There is a chunk of code related to miniconda that seems to work during the Dockerfile compilation, which is:
ENV PATH="/root/miniconda3/bin:$PATH"
ARG PATH="/root/miniconda3/bin:$PATH"
RUN wget \
    https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh \
    && mkdir /root/.conda \
    && bash Miniconda3-latest-Linux-x86_64.sh -b \
    && rm -f Miniconda3-latest-Linux-x86_64.sh
RUN conda --version

This doesn't throw any error, but if I enter to a bash console in the generated container, I get conda command not found error. Apart from these, I have tried all proposed solutions in the linked questions with no success. Also, I have tried this:
RUN mkdir -p ~/miniconda3 && \
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda3/miniconda.sh  && \
bash ~/miniconda3/miniconda.sh -b -u -p ~/miniconda3  && \
rm -rf ~/miniconda3/miniconda.sh  && \
~/miniconda3/bin/conda init bash  && \
~/miniconda3/bin/conda init zsh

Which does work if I execute the commands manually within the container in a bash console, but fails if I paste them into the Dockerfile


text:
Q: Starting a service and activity at same instance From a activity onClick event need to start an activity and a service also.
I have implemented that. But problem is that service is starting but activity is not loading properly. Only blank screen is coming. Sorry message is coming "Application is not responding" and asking me to either to wait or force close it.
@Override
        public void onClick(View arg0) {
            startService(new Intent(NewUIM.this, MyService.class));
            Intent i = new Intent(NewUIM.this, NewUI.class);
            startActivity(i);

            finish();
        }
    });

A: Implement AsynTask while the Service is running and implement the Activity . For more information, check the link : http://developer.android.com/reference/android/os/AsyncTask.html


text:
Q: Draw single(!) pixel with php Can someone help me to draw single pixel using php GD library?
I have such code:
$img    = imagecreatetruecolor(100, 100);
$c      = imagecolorallocate($img, 255, 0, 0);
$white  = imagecolorallocate($img, 255, 255, 255);
imagefill($img, 0, 0, $white);
imagesetpixel($img, 0, 0, $c);
imagejpeg($img, 'created.jpg');die();

But the output is really weird (it is approximate image in top-left corner):

Is it possible to draw just one red pixel at x-0 y-0 position?


text:
Q: What css property will cause the URL bar on Chrome android browser to auto hide? If you go to twitter.com on the Android Chrome browser and scroll up, then the address bar will auto hide itself to make more room for the webpage.
My app used to do this. But now I am not sure what I tweaked to make this no work.
The main div of the app is set to height: 100vh. And because the address bar does not auto hide, the bottom is clipped.


text:
Q: Comma before conjunction "As I saw it, the relationship between a typical African and his dog is one of tangible mutualism. I say tangible because the African sees himself as the dominant creature not to be bothered by the dog, but nevertheless responsible for providing for it."
Why is a comma necessary before but? If you have a comma before a coordinating conjunction, doesn't that mean both sides of the "but" have to be independent clauses? However, in this case, "nevertheless responsible for providing for it" doesn't make sense by itself so it is not an independent clause. If it is wrong to put a semi colon in the place of that comma, surely it should be wrong to put a comma there as well.

A: Commas, and all punctuation, should be used to help readability and, if desired, avoid ambiguity. Something you will find in most major style guides. Punctuation is not a matter of slavish adherence.

A: "But" itself is a coordinating conjunction. But "nevertheless" is a conjunctive adverb that has its own specific meaning. "So" is coordinating conjunction but "therefore" is a conjunctive adverb. Therefore, that clause can have a specific meaning because of the conjunctive adverb but the conjunction that leads that clause is coordinating conjunction, which means that clause can need a comma.


text:
Q: Difficulty generating unique arrays for each parent object I'm making a genetic simulator for a game and when I call my function to populate the array that determines the parents gene's it gives the same output for each parent.
Outputs would generally look like this.
ruby = [G, U, B, N, N, G]
jaune = [G, U, B, N, N, G]
The output I want would be something like this.
ruby = [R, A, N, R, N, B]
jaune = [W, N, W, N, N A]
import random
import time

class Parent():
    magic = [None, None, None, None, None, None]

    types = ['B', 'U', 'W', 'R', 'G', 'N', 'A']
    def gen(self):
        for i in range(0, 6):
            self.magic[i] = self.types[random.randint(0, 6)]

    def traits(self):
        print (self.magic)

jaune = Parent()
ruby = Parent()

jaune.gen()
ruby.gen()

jaune.traits()
ruby.traits()

A: Use a constructor, and self values. Your magic is a global variable.
import random
import time

types = ['B', 'U', 'W', 'R', 'G', 'N', 'A']

class Parent():
    def __init__(self):
        self.magic = []
        self.gen()

    def gen(self):
        for i in range(0, 6):
            self.magic.append(types[random.randint(0, 6)])

    def traits(self):
        print (self.magic)

jaune = Parent()
ruby = Parent()

jaune.traits()
ruby.traits()

Also, you can generate values inside the __init__.
Check

*

*Setters/Getters

*Local/Global variables

*Use self when a value is corresponding to a specific class, and not a static method


text:
Q: TCPSocket Service stops on device sleep mode I have a bounded service which performs TCP Socket connection and sends some data repeatedly. After the device goes into sleep mode thread stops and so the data send. What am I doing wrong?
As far as I know, service bounded to the Main Activity has to be START_STICKY but that doesn't fix my problem.
MainActivity class where the service is bounded and the connect button click starts socket sending thread in the AsyncTask:
public class MainActivity extends AppCompatActivity {

public MainActivity() {
    super();
}

private CTIController CTIControl;
protected boolean mBound = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onStart() {
    super.onStart();

    Intent intent = new Intent(this, CTIController.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    if (mBound) {
        //disconnect socket and stop sending thread
        CTIControl.GetControllersFactory().GetCTI2Controller().OnDisconnect();
        unbindService(mConnection);
        mBound = false;
    }
}

private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        LocalBinder binder = (LocalBinder) service;
        CTIControl = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
         mBound = false;
    }
};

/** Callled when the user clicks connect button */
public void ConnectClick(View view) {
    new ConnectOperation().execute("");
}

private class ConnectOperation extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        EditText ip = (EditText)findViewById(R.id.ip);
        EditText port = (EditText)findViewById(R.id.port);

        //start socket connection and run sending thread
        CTIControl.TryConnect(ip.getText().toString(), port);

        return "Executed";
    }
}

The CTIController Service which controls the Socket connection:
public class CTIController extends Service implements ICTIController {

private final IBinder mBinder = new LocalBinder();

public TryConnect(String ipAddress, int port) throws IOException{

    this.ClientSocket = new Socket();
    this.ClientSocket.connect(new InetSocketAddress(ipAddress, port), 10000);
    //... start sending data repeatedly

}

public class LocalBinder extends Binder {
    public CTIController getService() {
        return CTIController.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        return START_STICKY;
    }
}

And my manifest file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.PERSISTENT_ACTIVITY" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

<application
    android:allowBackup="true"
    android:persistent="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <service android:name=".controller.CTIController" android:exported="false"/>
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

A: Do change in onStartCommand of your service.
return START_REDELIVER_INTENT; instead of return START_STICKY;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

       return START_REDELIVER_INTENT;
    }
}


text: Q: Definite integral to Contour integral We know that integration from $0$ to $2 \pi$ of some trigonometric function can be converted to contour integration, can we do same for $0$ to $\pi$? Here contour won't be unit circle. If so then how?


text:
Q: How to add style to li before attribute Here is the timeline chart what I have to draw a circle before every li element.

ul.timeline>li:before {
  content: ' ';
  background: white;
  display: inline-block;
  position: absolute;
  border-radius: 50%;
  border: 3px solid #22c0e8;
  left: 20px;
  width: 20px;
  height: 20px;
  z-index: 400;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

Latest News

          New Web Design
          21 March, 2014

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque scelerisque diam non nisi semper, et elementum lorem ornare. Maecenas placerat facilisis mollis. Duis sagittis ligula in sodales vehicula....

          21 000 Job Seekers
          4 March, 2014

Curabitur purus sem, malesuada eu luctus eget, suscipit sed turpis. Nam pellentesque felis vitae justo accumsan, sed semper nisi sollicitudin...

          Awesome Employers
          1 April, 2014

Fusce ullamcorper ligula sit amet quam accumsan aliquet. Sed nulla odio, tincidunt vitae nunc vitae, mollis pharetra velit. Sed nec tempor nibh...

How can I change the color of the border, on the HTML element?
Here is the complete example: https://bootsnipp.com/snippets/featured/simple-vertical-timeline

A: I suppose you want to add the border between two blue circles, also want to remove the default ul style.
I have added a bit of css code to your code. Check it out below.

*

*To remove the default ul style, I have added list-style-type as
none.

*To add the vertical line connecting the list items, I
have added a pseudo class element :before to ul.timeline.

ul.timeline {
    list-style-type: none;
}
ul.timeline:before {
    content: ' ';
    background: #d4d9df;
    display: inline-block;
    position: absolute;
    left: 29px;
    width: 2px;
    height: 100%;
    z-index: 400;
}
ul.timeline>li:before {
  content: ' ';
  background: white;
  display: inline-block;
  position: absolute;
  border-radius: 50%;
  border: 3px solid #22c0e8;
  left: 20px;
  width: 20px;
  height: 20px;
  z-index: 400;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

Latest News

          New Web Design
          21 March, 2014

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque scelerisque diam non nisi semper, et elementum lorem ornare. Maecenas placerat facilisis mollis. Duis sagittis ligula in sodales vehicula....

          21 000 Job Seekers
          4 March, 2014

Curabitur purus sem, malesuada eu luctus eget, suscipit sed turpis. Nam pellentesque felis vitae justo accumsan, sed semper nisi sollicitudin...

          Awesome Employers
          1 April, 2014

Fusce ullamcorper ligula sit amet quam accumsan aliquet. Sed nulla odio, tincidunt vitae nunc vitae, mollis pharetra velit. Sed nec tempor nibh...

A: You can create a timeline using only Bootstrap classes (no extra CSS) like this. The border utility class is used to create the lines.

                    Timeline item content....

https://www.codeply.com/go/AX0ugyF5Vd

A: You can the border color to whatever you want
Please check this screen shot we change it on the live example
https://irfan-ranksol.tinytake.com/sf/MzAzMzMyN185MDkxMDMx


text:
Q: (Ogre3d/PhysX/C++) - how to do draw debug visualization Can you help me. I can not understand how to draw PhysX debug visualization in Ogre3D, together with normal objects.
I have the code for OpenGL, but i can not convert it to Ogre3d:
void RenderData(const PxRenderBuffer & data)
{
    glLineWidth(1.0f);
    glDisable(GL_LIGHTING);

    //----------Render Points------------------
    unsigned int NbPoints = data.getNbPoints();
    if(NbPoints)
    {
        float* pVertList = new float[NbPoints*3];
        float* pColorList = new float[NbPoints*4];
        int vertIndex = 0;
        int colorIndex = 0;
        const PxDebugPoint* Points = data.getPoints();
        while(NbPoints--)
        {
            pVertList[vertIndex++] = Points->pos.x;
            pVertList[vertIndex++] = Points->pos.y;
            pVertList[vertIndex++] = Points->pos.z;
            pColorList[colorIndex++] = (float)((Points->color>>16)&0xff)/255.0f;
            pColorList[colorIndex++] = (float)((Points->color>>8)&0xff)/255.0f;
            pColorList[colorIndex++] = (float)(Points->color&0xff)/255.0f;
            pColorList[colorIndex++] = 1.0f;
            Points++;
        }

        RenderBuffer(pVertList, pColorList, GL_POINTS, data.getNbPoints());

        delete[] pVertList;
        delete[] pColorList;
    }

    //----------Render Lines------------------
    unsigned int NbLines = data.getNbLines();
    if(NbLines)
    {
        float* pVertList = new float[NbLines*3*2];
        float* pColorList = new float[NbLines*4*2];
        int vertIndex = 0;
        int colorIndex = 0;
        const PxDebugLine* Lines = data.getLines();
        while(NbLines--)
        {
            pVertList[vertIndex++] = Lines->pos0.x;
            pVertList[vertIndex++] = Lines->pos0.y;
            pVertList[vertIndex++] = Lines->pos0.z;
            pColorList[colorIndex++] = (float)((Lines->color0>>16)&0xff)/255.0f;
            pColorList[colorIndex++] = (float)((Lines->color0>>8)&0xff)/255.0f;
            pColorList[colorIndex++] = (float)(Lines->color0&0xff)/255.0f;
            pColorList[colorIndex++] = 1.0f;

            pVertList[vertIndex++] = Lines->pos1.x;
            pVertList[vertIndex++] = Lines->pos1.y;
            pVertList[vertIndex++] = Lines->pos1.z;
            pColorList[colorIndex++] = (float)((Lines->color0>>16)&0xff)/255.0f;
            pColorList[colorIndex++] = (float)((Lines->color0>>8)&0xff)/255.0f;
            pColorList[colorIndex++] = (float)(Lines->color0&0xff)/255.0f;
            pColorList[colorIndex++] = 1.0f;

            Lines++;
        }

        RenderBuffer(pVertList, pColorList, GL_LINES, data.getNbLines()*2);

        delete[] pVertList;
        delete[] pColorList;
    }

    //----------Render Triangles------------------
    unsigned int NbTris = data.getNbTriangles();
    if(NbTris)
    {
        float* pVertList = new float[NbTris*3*3];
        float* pColorList = new float[NbTris*4*3];
        int vertIndex = 0;
        int colorIndex = 0;
        const PxDebugTriangle* Triangles = data.getTriangles();
        while(NbTris--)
        {
            pVertList[vertIndex++] = Triangles->pos0.x;
            pVertList[vertIndex++] = Triangles->pos0.y;
            pVertList[vertIndex++] = Triangles->pos0.z;

            pVertList[vertIndex++] = Triangles->pos1.x;
            pVertList[vertIndex++] = Triangles->pos1.y;
            pVertList[vertIndex++] = Triangles->pos1.z;

            pVertList[vertIndex++] = Triangles->pos2.x;
            pVertList[vertIndex++] = Triangles->pos2.y;
            pVertList[vertIndex++] = Triangles->pos2.z;

            for(int i=0;i<3;i++)
            {
                pColorList[colorIndex++] = (float)((Triangles->color0>>16)&0xff)/255.0f;
                pColorList[colorIndex++] = (float)((Triangles->color0>>8)&0xff)/255.0f;
                pColorList[colorIndex++] = (float)(Triangles->color0&0xff)/255.0f;
                pColorList[colorIndex++] = 1.0f;
            }

            Triangles++;
        }

        RenderBuffer(pVertList, pColorList, GL_TRIANGLES, data.getNbTriangles()*3);

        delete[] pVertList;
        delete[] pColorList;
    }
    glEnable(GL_LIGHTING);
    glColor4f(1.0f,1.0f,1.0f,1.0f);
}

void RenderBuffer(float* pVertList, float* pColorList, int type, int num)
{
    glEnableClientState(GL_VERTEX_ARRAY);
    glVertexPointer(3,GL_FLOAT, 0, pVertList);

    glEnableClientState(GL_COLOR_ARRAY);
    glColorPointer(4, GL_FLOAT, 0, pColorList);

    glDrawArrays(type, 0, num);

    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
}

Certainly, you may not use this code. I just want to draw PhysX debug visualization.

A: Have a look at how the Ogre3D PhysX wrapper called "NxOgre" (combined with Critter which is the actual bridge to Ogre3D) does things. A good starting point would be the wiki tutorial page.
A rough outline:
PhsyX provides for each scene in each world a debug render data structure. That can be taken and formed into a data structure that can be used within Ogre3D to be rendered.
for (World::SceneIterator iterator = mWorld->getScenes(); iterator != iterator.end(); iterator++)
{
    const NxDebugRenderable* renderable = iterator->getScene()->getDebugRenderable();
    if (renderable == 0)
       continue;

    unsigned int nbLines = renderable->getNbLines();
    const NxDebugLine* lines = renderable->getLines();

    while(nbLines--)
    {
       mMeshData->mLines.push_back(lines->p0.x);
       mMeshData->mLines.push_back(lines->p0.y);
       mMeshData->mLines.push_back(lines->p0.z);
       mMeshData->mLines.push_back(lines->p1.x);
       mMeshData->mLines.push_back(lines->p1.y);
       mMeshData->mLines.push_back(lines->p1.z);
       mMeshData->mColours.push_back(lines->color);
       mMeshData->mColours.push_back(lines->color);
       lines++;
    }

    mMeshData->mNbLines += renderable->getNbLines();
}

Most relevant parts:

*

*VisualDebugger::draw() = collect data from PhysX and store in structure to be alter passed on to the Ogre3D renderer

*Renderable::drawVisualDebugger() = previously stored data is passed to the Ogre3D vertex buffer


text:
Q: Speed Up TextEditing on Long Text With the following code performance degrades drastically as the text gets longer due to the view getting redrawn for every character typed (due to textViewDidChange). There are also a number of nasty side effects as well, such as insertion of sentence breaks likely due to autocorrect or some other mechanism. If I comment out or eliminate the textViewDidChange function, performance is much better and the side effects disappear, but then I no longer can capture the text to save it or interrogate it on the fly.
Does anyone know of a way around this? I thought that if I could just not refresh the text variable until the focus was moved to a different view, then I could capture the text before it needs to be saved. If that might work, I can't determine how to trap the focus change. I have tried implementing textViewDidEndEditing but that only gets triggered when the parent view ends editing. I'm using a save button and want to capture the text then.
I realize that there is a TextEditor view available, but it is just as slow on large text so I assume it is doing the same thing.
import SwiftUI

struct TextView: UIViewRepresentable {

    @Binding var text: String
    @Binding var textStyle: UIFont.TextStyle

    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()

        textView.delegate = context.coordinator
        textView.font = UIFont.preferredFont(forTextStyle: textStyle)
        textView.autocapitalizationType = .none
        textView.isSelectable = true
        textView.isUserInteractionEnabled = true

        return textView
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
        uiView.font = UIFont.preferredFont(forTextStyle: textStyle)
    }

    func makeCoordinator() -> Coordinator {
        Coordinator($text)
    }

    class Coordinator: NSObject, UITextViewDelegate {
        var text: Binding<String>

        init(_ text: Binding<String>) {
            self.text = text
        }

        func textViewDidChange(_ textView: UITextView) {
            self.text.wrappedValue = textView.text
        }
    }
}

Content View
import SwiftUI

struct ContentView: View {

    @State private var message = ""
    @State private var textStyle = UIFont.TextStyle.body

    var body: some View {
        ZStack(alignment: .topTrailing) {
            TextView(text: $message, textStyle: $textStyle)
                .padding(.horizontal)

            Button(action: {
                self.textStyle = (self.textStyle == .body) ? .title1 : .body
            }) {
                Image(systemName: "textformat")
                    .imageScale(.large)
                    .frame(width: 40, height: 40)
                    .foregroundColor(.white)
                    .background(Color.purple)
                    .clipShape(Circle())

            }
            .padding()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


text:
Q: Why owl-carousel change items width automatically when the window resized? I have a problem with owl-carousel 2. Following is my js code :
 $(".top_slider").owlCarousel({
    items:1,
    navigation: true,
    navigationText: ['

', '

'],
    loop: true,
    animateOut: 'fadeOut',
})

It works for my default window width. However , when I resize my page it automatically change owl-item width. (I found out that it comes from javascript).
For example it is default 1349px (my screen width).But when I change my width to 1024px owl-item width becomes 256px (1024 / 4) even if I only have 3 slider items. What is the problem and how can I fix this ? Thanks for any help.

A: window.addEventListener('resize', refreshOwl);

function refreshOwl() {
        let projectWidth = $(window).width();
        slidesPerPage = projectWidth/3;
        let options = $('.owl-carousel').data('owl.carousel').options;
        options.items = slidesPerPage;
        $('.owl-carousel').trigger('refresh.owl.carousel');
 }


text:
Q: Designated initializer in Objective-C Just to confirm is that the correct way to create designated initializer in Objective-C ?
Is this the correct way to init the ivars ?
Can you suggest me what to improve ?
Person.h
@interface Person : NSObject

@property (nonatomic, retain) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) NSString *sex;
@property (nonatomic, assign) int weight;

-(id)initWithName:(NSString *)name;
-(id)initWithName:(NSString *)name age:(int)age;
-(id)initWithName:(NSString *)name age:(int)age sex:(NSString *)s;
-(id)initWithName:(NSString *)name age:(int)age sex:(NSString *)s andWeight:(float)w;

@end

Person.m
@implementation Person

@synthesize name = _name;
@synthesize sex = _sex;
@synthesize age = _age;
@synthesize weight = _weight;

-(id)initWithName:(NSString *)name age:(int)age sex:(NSString *)s andWeight:(float)w
{
    if(self = [super init])
    {
        [self setName:name];
        [self setAge:age];
        [self setSex:s];
        [self setWeight:w];
    }
    return self;
}

-(id)initWithName:(NSString *)name age:(int)age sex:(NSString *)s
{
    return [self initWithName:name age:age sex:s andWeight:0];
}

-(id)initWithName:(NSString *)name age:(int)age
{
    return [self initWithName:name age:age sex:0];
}

-(id)initWithName:(NSString *)name
{
    return [self initWithName:name age:0];
}

-(id)init
{
    return [self initWithName:nil];
}

Thanks in advance !

A: It is correct in my opinion. You can improve efficiency by calling to the main init method from any other one, so you don't chain calls, but I think there are not a big difference.

A: Yeah, that's a typical pattern.  The designated  initializer has all of the parameters, and the simpler initializers fill in default values.

A: I would suggest to call -(id)initWithName:(NSString *)name age:(int)age sex:(NSString *)s andWeight:(float)w directly from each method. It can avoid multiple extra executions.
Apple recommends against using accessor methods in init or dealloc. You have variables like _name and you can use it.


text:
Q: What are the possible RNN modification to improve the model? I want to improve MNIST handwritten model with RNN model/LSTM .. have any one tried modification on RNN .. if so what are the different ways I can improve model ..please suggest

A: You can do something called scheduled sampling. A major problem with RNNs and with generative models in general is that during train time, they are not trained on their own predictions. Rather, they are trained on the gold labels. During inference time, there are no gold labels available and the model is fed it's own generations. This is something the model has not done before and if the model makes a mistake during the beginning of the generation phase, it will be more likely to make more mistakes.
The idea is to allow the model to be trained on it's own outputs gradually using a decay parameter which increases the probability of a predicted token being fed into the RNN rather than the gold label.
You can read about it in this paper : Scheduled Sampling for Sequence Prediction with Recurrent Neural Networks


text:
Q: Change Contract State From Active To Draft I was trying to set a contract state from Active to Draft using the code below:
SetStateRequest setState = new SetStateRequest();
setState.EntityMoniker = new EntityReference();
setState.EntityMoniker.Id = contractId;
setState.EntityMoniker.Name = "Contract";
setState.EntityMoniker.LogicalName = "contract";
setState.State = new OptionSetValue(0);
setState.Status = new OptionSetValue(1);
SetStateResponse setStateResponse = (SetStateResponse)service.Execute(setState);

My aim is to update an active contract, but to do that I need to have it in Draft state to update it and then put it back to Active, when updated. I would really much appreciate if somone could help me out here.
The plugin right now is firing the following error: "The target state is invalid.  The target state may not exist or the system does not allow changing to the target state from the current state.  Please check the documentation on this state change request"

A: EDIT:  It seems you must invoice a contract before you can cancel it - maybe it is not possible to set a contract status to draft from certain statuses?  See MSDN example here:
http://msdn.microsoft.com/en-us/library/gg328503.aspx
If you only care about the state (rather than the status), you can pass '-1' as an option set value, which will be ignored when the request is executed.  I have done something very similar in order to deactivate a product record.
/// <summary>
/// Deactivate the specified entity.
/// </summary>
/// <param name="entityRef">Entity to deactivate.</param>
/// <param name="service">Organisation service.</param>
/// <param name="status">Optional status code.</param>

private static void DeactivateEntity(EntityReference entityRef, IOrganizationService service, int status = -1)
{
    service.Execute(new SetStateRequest
        {
            EntityMoniker = entityRef,
            State = new OptionSetValue(1),
            Status = new OptionSetValue(status)
        });
}


text:
Q: Kendo-Grid Truncate string with no white-space I'm using a Kendo-Grid for filtering, everything is working fine except for a problem on my cell if there is no white space.
As displayed in the image:

the string is "https://www.linkedi/Testing" but it's displayed only until "Test".
This problem does not appear for string with white spaces like:

I'm newbie in client-side programming, thanks a lot to everyone.

A: The default behavior should be like this:

Im not sure why in your case its not like this, maybe older version of kendo.
To achieve the above behavior add css:
/*Overides kendo default*/
.k-grid td {
      text-overflow: ellipsis;
}

Example: ellipsis
To achieve text in new line add css:
/*Overides kendo default*/
.k-grid td {
      word-break: break-all;
}

Example: brake-all


text:
Q: Limit in Infinite Summation Over Function in Two Variables When can the following statement be made?
$$\lim_{N\to \infty} \frac{1}{N}\sum_{n\leq N}\lim_{k\to \infty} f(n,k)=\lim_{N\to \infty} \lim_{k\to \infty} \frac{1}{N}\sum_{n\leq N} f(n,k)= \lim_{k\to \infty}\lim_{N\to \infty} \frac{1}{N}\sum_{n\leq N} f(n,k)$$
Additionally, under what conditions can I let $N$ and $k$ tend to infinity at the same time at obtain
$$\lim_{N\to \infty} \frac{1}{N}\sum_{n\leq N} f(n,N)$$
assuming of course that the limit exists?

A: In general for double sequences, a sufficient condition for
$$\lim_{N \to \infty} (\lim_{k \to \infty} S_{Nk}) = \lim_{k \to \infty} (\lim_{N \to \infty} S_{Nk}) = \lim_{N \to \infty} S_{NN},$$
is the existence of the limit $\lim_{N \to \infty} S_{Nk} $ for all k and the uniform convergence of $S_{Nk} \to L_N$ as $k \to \infty$ for all $N$ or vice versa.
Sketch of proof:
(1) Using the uniform convergence, it can be shown that $L_N$ is a Cauchy sequence and, hence, converges to some limit $L$.
(2) It can then be shown that the double sequence converges in the sense that given any $\epsilon > 0$ there exists $M$ such that if $N,k > M$ we have $|S_{Nk} - L| < \epsilon.$
(3) From (2) it follows that both iterated limits are equal to $L$ and also equal to the limit of $S_{NN}$.
That $\lim_{N \to \infty} S_{NN} = L$ follows directly from (2) with $k = N$.
Again from (2), if $|S_{Nk} - L| < \epsilon$ for sufficiently large $N$ and $k$ , then  we have $\lim_{k \to \infty}|S_{Nk} - L| = | \lim_{k \to \infty}S_{N,k} - L| \leqslant \epsilon$, which implies $\lim_{N \to \infty} \lim_{k \to \infty} S_{Nk} = L$.
And so forth ...


text:
Q: What are the drawbacks of using the development version of Isabelle? This question is related to my last question.
In the answer to my question there is the statement that
"it is in general not a good idea to use the repository version for your work".
So then my question is: what are the most significant drawbacks of using the development version from the mecurial repository?
I also stated the resons why I decided to use the development version:

My experience is that Isabelle2013-2 is simply completely unusable. I
  get very frustrated, this is not fun. It is slow and crashed too
  often. With the dev version typing feels again normal, not slightly
  delayed. Sledgehammer is greatly improved again, it finds proofs
  faster and the metis proofs are faster too that it generates.
  I don't mind being part of the development process.
  Wither other theorem provers like Agda, users are advised to
  use the development version too.

NOTE: Researchers in Munich explicitly told me that using the
development version is a valuable alternative if the last stable version is older. Now it depends what older means, but three months old can be considered "old". For this reason, I would like to know the specific drawbacks (the most important aspects only) regarding Isabelle.
For instance, I think that a false lemma cannot be proven correct even in the development version, but would to like to know if it were the case. (In general, as a CS researcher I know the drawbacks are of using a development version of a software tool.)

A: In any way, you should have the same confidence in the development version than in the stable as long as the kernel and the logic's axioms have not been changed -- which is highly likely.
However, the tools -- including the definitional packages like function or datatypes, the proof methods like simp or auto and the framework components like locales and classes -- could have been modified such that they could fail more often, be slower or do things differently.
If such problems appear, there is a high probability that they would get corrected soon, but you would then have to update your repository, possibly update all your work, sometimes non trivially, while not being assured that other problems have not appeared and that the modications will remain until the next stable version.
Chances are that everything go well in the development version, but there can be sometimes problems or big reforms that could force you to change all your theories which is sometimes not an option. It can also be more difficult to get help, as you have seen in your last question.

A: There is a general misunderstanding here what a proper software release actually is, compared to ongoing changes in the development repository.
You will surely figure this out yourself, now that we are a few months past the latest release and many new things coming it at a high rate, until it will stabilize and converge again for the next release in summer 2014.


text:
Q: For which value of $k$ does the system of equations not have a unique solution? The following is the system of equations:
$$\begin{cases}
x-2y+2z=0\\
2x+ky-z=0\\
x-y+3z=-5
\end{cases}$$

A: Written in matrix form, this system is:
$$\begin{bmatrix}1 & -2 & 2\\ 2 &k& -1 \\ 1 & -1 & 3\end{bmatrix}\begin{bmatrix}x\\y\\z\end{bmatrix} = \begin{bmatrix}0\\0\\-5\end{bmatrix}.$$
In general, the matrix equation $\mathbf{A}\cdot \mathbf{x} = \mathbf{b}$ has a solution if and only if $\det{\mathbf{A}} \neq 0$.
To solve this problem, you can therefore compute the determinant of the 3×3 matrix and set it equal to zero. The system will have a solution for all values of $k$ except for those that make the determinant zero.

A: Putting the system of linear equations into a matrix, the next step is to try and use elementary row operations to get it to rref (reduced row echelon form).  Let's not worry about the constants in the right hand side of the system of linear equations for now.
$$
\begin{bmatrix}
1 & -2 & 2 \\
2 & k & -1\\
1 & -1 & 3
\end{bmatrix}
$$
Subtracting twice the first row from the second row and subtracting the first row from the third row, we get:
$$
\begin{bmatrix}
1 & -2 & 2 \\
0 & k+4 & -5\\
0 & 1 & 1
\end{bmatrix}
$$
If $k=-9$, the second row is a scalar multiple of the third row.  This means that if we had kept track of the augmented coefficient matrix, the second and third row would either equal the same thing, and thus cancel each other out, resulting in a free variable and infinite solutions, or equal different things, and thus be contradictory, meaning there would be no solutions to the system.
To confirm, we could check to make sure the second row, represented as a column vector, is not linearly independent of the other two equations:
$$
\begin{pmatrix}
2 \\
-9 \\
-1
\end{pmatrix}
=
\begin{pmatrix}
1 \\
-2 \\
2
\end{pmatrix}
p
+
\begin{pmatrix}
1 \\
-1 \\
-3
\end{pmatrix}
q
$$
$$
p+q=2 \\
-2p-q=-9 \\
-2p-2+p=-9 \\
p=7 \\
q=-5
$$
Now, we can see that the second equation is just 7 times the first equation minus 5 times the third equation.
As a third method, one could check the determinant and discover that it's $k+9$, so when $k=-9$, the determinant is zero, and the system will not have a unique solution.


text:
Q: SignalR - OnConnect() authorization - how to disconnect unauthorized user? In my hub, I have something like this (pseudocode):
public override Task OnConnected()
{
    var isLegal = Authorize();
    if (!isLegal) //not authorized
    {
        //how do I deny him this connection?
    }
    return base.OnConnected();
}

How to disconnect/deny connection to a user?

A: Add authorize attribute over the class,the user will be denied, if not authenticated.

A: The following link explains how to do Hub authentication and authorization.
http://www.asp.net/signalr/overview/security
If you choose not to use the existing auth mechanism, you'll need to check if the user is authorized in every hub method and return appropriate messages.


text:
Q: Using Output from one Function and calling it into another I'm trying to get my head around a fairly simple concept in PHP but I'm pretty green.
I have a function..
function pa_insertPage($atts, $content = null) {
    // Default output if no pageid given
    $output = NULL;
    // extract atts and assign to array
    extract(shortcode_atts(array("page" => '2404' // Value for Course Descriptions page
    ), $atts));
    // if a page id is specified, then run query
    if (!empty($page)) {
        $pageContent = new WP_query();
        $pageContent->query(array('page_id' => $page));
        while ($pageContent->have_posts()) : $pageContent->the_post();
            // assign the content to $output
            $output = apply_filters( 'the_content', get_the_content() );
        endwhile;
    }
    return $output;
}

And I'd like to use the returned $output from this function in another function called naada_assess()
In my naada_assess function I've called $recClasses =  pa_insertPage($output); but that doesn't seem to do the trick.

A: This isn't really a WordPress question... that said
$recClasses = pa_insertPage($output);

is incorrect. here you should be passing to insertPage whatever the arguments are. Then insertPage will return $output, making $recClasses the same value as $output.
    $recClasses = pa_insertPage('your attributes');
// $recClasses now equals $output;

A: If you have defined a shortcode like this:
 add_shortcode('myshortcode','pa_insertPage');

then you could try this inside your naada_assess() function:
$recClasses = do_shortcode('[myshortcode page="123"]');

as a way to retrieve the $output.


text:
Q: How to make a login system like that of facebook I have a enquiry, now this was a serious brainstorming problem for me. Do one thing at first, go to m.facebook.com from your phone, then login, then login from a computer and change the password from that computer, while changing the password, you are asked weather or not to deauthenticate the device that you are previously logged in with. if you choose keep them logged in, then again open fb from phone, then you don't need to login again, now the question is HOW? Because if fb don't store the hashed password in the cookie, then what does it store and yet it is secured? Anyone know about this login authentication system?

A: FB is probably using a cookie that has a very long lifetime.  This cookie's value is large random number that is used to pull information from a database.
Storing a password hash in the cookie is vulnerability that is so stupid it hurts my eyes just reading it.  Its also something I have exploited in the wild.


text:
Q: Eclipse plugin: how to show .* resources by default in perspective How to configure perspective in plugin/RCP to show .* resources.
Currently, it should be done manually by selecting Customize View... by every user.
In Eclipse plugin development how to show .* files in a new perspective by default?
Related
How to customize eclipse perspective programmatically?

A: I assume you want to show the *.resources in the package explorer. I do not think there is any plugin designed to do exactly that, but you still have some possibilities.
A simple way to do it, is to go to Customize View. You can just select Filters... from the view menu (the shortcut to .* resources will be shown after you modify it):

But of course you still need to do that for every user. If this is still too cumbersome you need to work with the extensions that defines them. You might have luck with creating you're own plugin that tries to overwrite the extension point that defines the filter. In short you have to add this to your plugin.xml
   <extension point="org.eclipse.jdt.ui.javaElementFilters">
    <filter
          targetId="org.eclipse.jdt.ui.PackageExplorer"
          name=".* resources (new)"
          enabled="false"
          description="Hides resources with names that start with a '.'"
          pattern=".*">
    </filter>
  </extension>

There is however a hack and there is no guarantee that this will work. If you look into org.eclipse.jdt.ui.actions.CustomFiltersActionGroup.CustomFiltersActionGroup(String, StructuredViewer) you will see that it depends on the order in which the filter-extensions are loaded. According to this question this is rather arbitrary.
Another way which requires more work, but is much less hacky and (to my best knowledge) is sure to work, is to modify the original extension point. This is defined in org.eclipse.jdt.ui so you have to replace this plugin. To do this you need to:

*

*Import the plugin: Open the Plug-ins view, right click on
org.eclipse.jdt.ui and select import as source

*Find the extension in plugin.xml (Search for name="%HideSystemFiles.label") and change enabled="true" to enabled="false"

*Create a "feature patch" with you plugin. Export it and install into your Eclipse. (see resources below)

One disadvantage with this approach, is that you have to maintain this every time org.eclipse.jdt.ui is updated, essentially going through all steps again.
For more info on feature patches see:

*

*http://eclipsesource.com/blogs/2012/07/30/patching-your-own-eclipse-ide/

*http://aniefer.blogspot.dk/2009/06/patching-features-with-p2.html

*http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.pde.doc.user%2Fguide%2Ftools%2Fproject_wizards%2Fnew_feature_patch.htm


text:
Q: Why is $store.user undefined? Learning Vue at the moment. I have a DefaultLayout page which, as far as I understand it, is the parent component of my Profile page defined in my router.
const routes = [
    {
        path: '/',
        component: DefaultLayout,
        meta: { requiresAuth: false },
        children: [
            { path: "/", name: "Home", component: Home },
            { path: "/perfil", name: "Profile", component: Profile },
            { path: "/blog", name: "Blog", component: Blog },
            { path: "/blog/:slug", name: "BlogPost", component: BlogPost },
            { path: "/equipa", name: "Team", component: Team },
            { path: "/links", name: "Links", component: Links },
          ],
    },

This is part of my script in the DefaultLayout page.

My child component, Profile.
<template>
<form class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" @submit="updateProfile">

            Email
          <input
            id="identity"
            class="shadow appearance-none borderrounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
            type="email"
            aria-describedby="emailHelp"
            v-model="user.email"
            :placeholder="user.email"
          />

          Password

          <input
            aria-describedby="passwordHelp"
            v-model="user.password"
            class="shadow appearance-none borderrounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
            id="password"
            type="password"
            :placeholder="user.password"
          />

          <button
            class="bg-blue-600 hover:bg-black text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
            type="submit"
          >
            Update
          </button>

</form>
</template>

When I press my update button it says:
Uncaught (in promise) TypeError: $setup.user is undefined in my DefaultLayout. It never throws an error if I don't press the button. I'm basically using the user to print the username on the navbar in DefaultLayout.
What could cause this?


text:
Q: Usage of "short" Let's say that I had a hundred dollars and I spent ten dollars in this case can I use "short" in sentence below?

My money get ten dollars short.

A: No.
The use of "short" in the context of money means "less than required"

I'm short on cash, so I can't buy a drink.
The dress costs $60, but you've only given my $50, so you're $10 short.

In the example you give, there is no shortage of money.
Simple ways to express your example:

I've spent ten dollars.
I'm down ten dollars (This sounds like what you might say if you had lost $10 while gambling)
I've got $90 left.

However, if you wanted to buy something that was worth $100, then you could say

I can't afford it! I'm short by $10. (or) I'm $10 short.


text:
Q: In QGraphicsView's wheelEvent, self.scale does not allow self.scrollContentsBy to work Both of the scale and scroll for the content of a QGraphicsView applied to the wheelEvent.
The problem is scroll only works if there is no scale on the wheelEvent.
No success with applying self.update() between scale and scroll call.
Extra points and guesses
If comment out the scroll part, scale works exact and on its place without displacement of view with scrolling up and down multiple times but with scroll part not commented out, with multiple scrolling (multiple zoom in and out) a little displacement of view has been obsereved.
It seems there is a conflict of fireing methods that call ui elements.
Appreciate your share of knowledge
# importing libraries
from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *
import sys

class Scene(QGraphicsScene):
    def __init__(self, _scene_width, _scene_height):
        super(Scene, self).__init__()
        self.setSceneRect(0, 0, _scene_width, _scene_height)
        map_center = _scene_width / 2
        te = QTextEdit()
        te.insertPlainText("Test Text")
        te.setGeometry(map_center, map_center, 100, 100)
        self.addWidget(te)

class View(QGraphicsView):
    def __init__(self, _scene_width, _scene_height):
        super(View, self).__init__()
        self.scale_factor = 1
        self.scene_width = _scene_width
        self.scene_height = _scene_height
        scene = Scene(_scene_width, _scene_height)
        self.setScene(scene)
        self.showMaximized()

    def wheelEvent(self, event):
        if self.underMouse():

            # scale part which doesn't let the scroll part to work
            if event.angleDelta().y() > 0:
                self.scale_factor = self.scale_factor * 1.2
                self.scale(1.2, 1.2)
            else:
                self.scale_factor = self.scale_factor / 1.2
                self.scale(1 / 1.2, 1 / 1.2)

            # scroll part which works fine if the scale part is commented out
            self.scrollContentsBy(10, 0) # values are just for testing

def main():
    app = QApplication(sys.argv)
    view = View(1000000, 1000000)
    view.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()