text:
Q: Web scraping with xpath jsonpath or anything else to pull filenames that end with .jpg This is another request for help as my 1st question was never really answered. I'm going to try a different approach here...
I need to be able to scrape all image filenames from a site.
 I'm using Ruby on Rails with Nokogiri (and Mechanize also). I can get the page.
However, once I get the page, I can't figure out how to use xpath to get the filenames I need (I'd love to be able to use begins-with "http://" and ends-with ".jpg" but haven't been able to figure out how).
An example url is the notorious Amazon product page:  http://www.amazon.com/Alternative-Womens-Jersey-Twist-Asymmetrical/dp/B00SM7E8EC/ref=sr_1_14?s=apparel&ie=UTF8&qid=1435518992&sr=1-14
The main product opens with a pink dress but I also want the gray and black dresses.  Using xpath's //img/@src I can get the pink dress but not the other two. (On a side note, when I try xpath's //img in my Chrome's XPather add-on, I get a lot of images returned but when I try to use just //img in Ruby I get an error; the exact code is:
tmp2 = Nokogiri::HTML(open(recommendation_url))
   tmp2.xpath('//img/@src').each do |i_img|
end

One more thing, when I create a bookmarklet that runs the following javascript code on amazon pages it works great!!:
    for (a=0;a<document.images.length;a++){
       x+='
'};
       if(x!='' {
          document.write(''+x+'');
          void(document.close())
       }else{
          alert('No images!')
       }
     }

My ideal solution would either be:
1. Figure out the xpath (or would jsonpath be better?) above
2. Be able to run this javascript code from Ruby on Rails
Can someone help?


text:
Q: WPF: capturing XAML into subclassed control i narrowed down what i want my wpf button to look like using XAML.
now i would like to create a sub classed button control that i can just re-use w/out having to write all that markup
<Button Click="TestGridColumnButton_Click" Background="Transparent" Width="16" Height="16" Margin="0,0,0,0" Padding="0,0,0,0" BorderBrush="{x:Null}">
    <Button.Template>
        <ControlTemplate>
            <Image HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource SourceStyle}" />
        </ControlTemplate>
    </Button.Template>
</Button>

how can i set all these properties using C# ?

A: Create a style for your button and add to a global resource dictionary.
<Application x:Class="TestApp.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Window1.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <Style x:Key="MyIconButtonStyle" TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Transparent" />
                <Setter Property="Width" Value="16" />
                <Setter Property="Height" Value="16" />
                <Setter Property="Margin" Value="0,0,0,0" />
                <Setter Property="Padding" Value="0,0,0,0" />
                <Setter Property="BorderBrush" Value="{x:Null}" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Image HorizontalAlignment="Center" VerticalAlignment="Center" Source="buttonImage.jpg"/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Use the style like this:
  <Button Style="{StaticResource MyIconButtonStyle}" Click="Button_Click"/>

A: There are multiple ways to do that :
[Note: For the sake of this answer, I assume you are creating a button in a simple window.]
1) A not-reusable and kind of dirty way would be to assign all the properties in the window's loaded event. By naming the button object, you can get reference to it and assign values to the properties, register to the event and assign a template. I assume you were having trouble with the template properties. To create a template in code, you can either use FrameworkElementFactory class (which is deprecated) or use XamlReader.Load method.(which is the preferred approach).
2) Create a custom control, for which a custom template is created in generic.xaml file. You can name elements in the custom template and retrieve references to them by overriding OnApplyTemplate method. Then you can create public properties which directly map to the Image element in the template or expose the Image element as a public property in the control. Using this approach, you can set properties in C# code using your exposed properties.
3) You can also define multiple styles and toggle between them in c# code. This method works just like in HTML when we toggle classes using JavaScript.
Hope this helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the count of GROUP BY query? How can I get the count of a GROUP BY SQL query?
SELECT     Voter.*, temp100.YadiNo, temp100.CountHouseNo
FROM       temp100
INNER JOIN Voter ON (temp100.HouseNo = Voter.HouseNo) AND (temp100.YadiNo = Voter.YadiNo)
WHERE      (((temp100.YadiNo) Between " & txtpartno.Text.Trim & " And " & txtpartno1.Text.Trim & ")
AND        ((temp100.CountHouseNo) Between " & txtfamilymeb.Text.Trim & " And " & txtfamilymeb1.Text.Trim & "))
ORDER BY   voter.houseno

This means I has displayed group by house number.
I want the count of this group of house numbers.

A: U can't use group by with order by,
so change order by to group by
like this

***SELECT     Voter.*, temp100.YadiNo, temp100.CountHouseNo
FROM       temp100
INNER JOIN Voter ON (temp100.HouseNo = Voter.HouseNo) AND (temp100.YadiNo = Voter.YadiNo)
WHERE      (((temp100.YadiNo) Between " & txtpartno.Text.Trim & " And " & txtpartno1.Text.Trim & ")
AND        ((temp100.CountHouseNo) Between " & txtfamilymeb.Text.Trim & " And " & txtfamilymeb1.Text.Trim & "))
GROUP BY   voter.houseno***

A: This is only a guess, this would count number of voters per House No., like:
 SELECT     Voter.houseno, COUNT(*) as CountHouseNo
 FROM       temp100
 INNER JOIN Voter ON (temp100.HouseNo = Voter.HouseNo) AND (temp100.YadiNo = Voter.YadiNo)
 WHERE      (((temp100.YadiNo) Between " & txtpartno.Text.Trim & " And " &   txtpartno1.Text.Trim & ")
 AND        ((temp100.CountHouseNo) Between " & txtfamilymeb.Text.Trim & " And " &  txtfamilymeb1.Text.Trim & "))
 GROUP BY   Voter.houseno
 ORDER BY   Voter.houseno

And if you want to include the YadiNo (whatever does this mean), you could do like this:
 SELECT     Voter.houseno, temp100.YadiNo, COUNT(*) as CountHouseNo
 FROM       temp100
 INNER JOIN Voter ON (temp100.HouseNo = Voter.HouseNo) AND (temp100.YadiNo = Voter.YadiNo)
 WHERE      (((temp100.YadiNo) Between " & txtpartno.Text.Trim & " And " &   txtpartno1.Text.Trim & ")
 AND        ((temp100.CountHouseNo) Between " & txtfamilymeb.Text.Trim & " And " &  txtfamilymeb1.Text.Trim & "))
 GROUP BY   Voter.houseno, temp100.YadiNo
 ORDER BY   Voter.houseno

COUNT() is an aggregate function that normally is paired with GROUP BY clause.
See example here.


text:
Q: Trying to complie sass with elixir and gulp but I when i try gup in terminal, get this error: I'm using laravel elixir and gulp to compile my sass files. but when i write gulp in termial I get this error.
fs.js:27
const { Math, Object } = primordials;
                         ^

ReferenceError: primordials is not defined
    at fs.js:27:26
    at req_ (/home/user/Videos/projetct-folder/project/node_modules/natives/index.js:143:24)
    at Object.req [as require] (/home/user/Videos/projetct-folder/projetct/node_modules/natives/index.js:55:10)
    at Object.<anonymous> (/home/user/Videos/projetct-folder/projetct/node_modules/laravel-elixir-livereload/node_modules/graceful-fs/fs.js:1:37)
    at Module._compile (internal/modules/cjs/loader.js:774:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
    at Module.load (internal/modules/cjs/loader.js:641:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Module.require (internal/modules/cjs/loader.js:681:19)
    at require (internal/modules/cjs/helpers.js:16:16)

Node version: 12.4.0
gulp CLI version: 2.2.0
gulp Local version: 4.0.2
gulpfile.js:
var elixir = require('laravel-elixir');
require('laravel-elixir-livereload');

elixir.config.assetsPath = 'themes/project/assets/';
elixir.config.publicPath = 'themes/project/assets/compiled/';

elixir(function(mix){

    mix.sass('agency.scss');

    mix.scripts([
        'jqBootstrapValidation.js',
        'agency.js',
        'contact_me.js',
        'recherche.js'
    ]);

    mix.livereload([
        'themes/project/assets/compiled/css/agency.css',
        'themes/project/**/*.htm',
        'themes/project/assets/compiled/js/*.js'
    ])
})

A: Judging by this bug report for Gulp, it's possible that one of the dependencies is using Gulp 3

one of the packages in your project is likely to be requiring gulp 3. If you inspect your package-lock.json which contains the list of installed packages, you should be able to sort it out.

It specifically mentions the graceful-fs module.


text:
Q: Utility that counts the number of files in a directory (recursively)? Is there any small Windows utility that counts the number of files in a directory recursively (including subdirectories) ?

A: The folder's properties will do it for you:

You can also use dir along with find from the command line:
dir /a-d /s /b folder_name | find /c ":"


text:
Q: Inheritance of C# attribute classes How does inheritance of attribute classes work in C#? To clarify, I am talking about the inheritance of the attribute classes themselves (i.e. base classes of System.Attributes), NOT any classes that happen to have them as attribute.
For some reason, I cannot seem to find anything on this (my searches always turn up with the other meaning).
For example, if a have a class AttributeA which extends System.Attribute:

*

*Do I have to separately mark subclasses of AttributeA with [AttributeUsage()]. (Since System.AttributeUsage's inheritance is true, I don't think I will.)

*Will AllowMultiple=false on the AttributeUsage of AttributeA prevent me from having multiple subclasses of AttributeA for attributes?
EDIT:
Programmers can only read code.
[AttributeUsage(AttributeTargets.Class, AllowMultiple=false)]
class AttributeA
{ }

class AttributeB : AttributeA
{ }

class AttributeC : AttributeA
{ }

[AttributeB]
[AttributeC]
class Foo
{ }

Does this work?

A: (I was finally able to try it.)
The example code does compile. I still like to have documentation, although I suppose C# is C# and it isn't going to change that. (Right?)
Evidently:

*

*The subclasses inherit AttributeUsage, as expected.

*AllowMultiple refers only to attributes of (strictly) the original class, not subclasses.

*Also, AttributeUsage can be effectively "re-defined".

With
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
class AttributeA : Attribute
{ }

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
class AttributeB : AttributeA
{ }

class AttributeC : AttributeA
{ }

the following is okay
[AttributeA]
[AttributeB]
[AttributeB]
[AttributeC]
class Foo
{ }

but this isn't
[AttributeA]
[AttributeB]
[AttributeC]
[AttributeC]
class Foo
{ }

A: You can control this behavior by using the named parameter Inherited for your AttributeUsageAttribute.
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
class AttributeA
{ }

class AttributeB : AttributeA
{ }

class AttributeC : AttributeA
{ }

A: The attribute usage is for the classes using the attributes.
For example, if you mark class A with AttributeA and class B is a subclass of A, you don't need to mark class B with AttributeB if AttributeA AttributeUsage's inheritance is true.


text:
Q: Maximum singular value of a matrix valued function Let $f$ be an analytic matrix-valued function, $\Lambda(A)$ be the spectrum of $A$ and $\sigma_1(A)$ the maximum singular value of $A$.
It is known that
$$\Lambda(f(A)) = f(\Lambda(A)) := \{f(\Lambda) : \lambda \in \Lambda(A) \}$$
Although a similar relation is not valid in general for singular values, numerical experiments suggest that the following inequality holds for the maximum singular value of $A$:
$$ \sigma_{1}( f(A) ) \le f(\sigma_{1}(A)). $$

*

*Is this inequality true?

*Other inequalities of these type also hold for the other singular values?

A: Let $\| \cdot \|$ denote any sub-multiplicative matrix-norm.  Let $f(x)$ be given by
$$
f(x) = \sum_{k=0}^\infty a_k x^k
$$
where $a_k \geq 0$.  We then have
$$
\|f(A)\| =
\left\|\sum_{k=0}^\infty a_k A^k\right\| \leq
\sum_{k=0}^\infty \|a_k A^k\| =
\sum_{k=0}^\infty a_k \|A^k\| \leq
\sum_{k=0}^\infty a_k \|A\|^k = f(\|A\|)
$$
Some examples of $\|\cdot\|$ that work here:

*

*spectral norm: $\|A\|=$ largest singular value of $A$

*Ky-Fan $k$-norm: $\|A\|=$ sum of $k$ largest singular values of $A$

*Schatten $p$-norm: see here.

So, the inequality may not hold for other singular values (I don't think it will), but it will work for other matrix norms, such as the examples that I've provided.


text:
Q: How to store superscript in XML attribute and read using XSL? I have a requirement where I need create an XML document dynamically. Some of the attributes of the nodes of this XML contain superscript Reg etc. My question is how should I store such superscript characters in XML and then read it using XSL to render as HTML. A sample XML is shown below:
<?xml version="1.0" encoding="utf-8"?>
<node name="Some text ®"/>

I know this cannot be stored under sup tag inside attribute as it breaks XML. I tried using <sup> also in place of opening and closing tag. But then they are rendered as  on HTML instead of actually making it superscript.
Please let me know the solution for this problem. I have control over generation of XML. I can write it the correct way, If I know what is the right way to store superscripts.

A: Since you're using XSL to transform the input into HTML, I would suggest using a different method to encode the fact that some things need to be superscripts.  Make up your own simple markup, for example
<node name="Some text [[®]]"/>

The markup can be anything that you can uniquely identify later and doesn't occur naturally in your data. Then in your XSL process the attribute values that can contain this markup with a custom template that converts the special markup to  and .  This allows you to keep the document structure (i.e. not move these string values to text nodes) and still achieve your goal.

A:
Please let me know the solution for this problem. I have control over
  generation of XML. I can write it the correct way, If I know what is
  the right way to store superscripts.

Because attributes can only contain values (no nodes), the solution is to store markup (nodes) inside elements:
<node>
 <name>Some text ®</name>
</node>

A: If it's only single characters like ® that need to be made superscript, then you can leave the XML without crooks like , i.e. like
<node name="Some text ®"/>

and look for the to-be-superscripted characters during processing. A template like this might help:
<xsl:template match="node/@name">
  <xsl:param name="nameString" select="string()"/>

  <xsl:variable name="firstChar" select="substring($nameString,1,1)"/>

  <xsl:choose>

    <xsl:when test="contains('®',$firstChar)">
      <xsl:value-of select="$firstChar"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$firstChar"/>
    </xsl:otherwise>
  </xsl:choose>

  <xsl:if test="$firstChar!=''">
    <xsl:apply-templates select=".">
      <xsl:with-param name="nameString" select="substring($nameString,2)"/>
    </xsl:apply-templates>
  </xsl:if>
</xsl:template>

This approach is however not very efficient, especially if you have lots of name attributes and/or very long name attributes. If your application is performance critical, then better do some testing whether the impact on processing times is justifiable.


text:
Q: NodeJS v8.getHeapSpaceStatistics() meaning I'm learning about memory management of chrome v8 engine,
const v8 = require('v8');

console.log(v8.getHeapSpaceStatistics())

what does read_only_space、map_space mean?

A: Those are different parts of V8's managed heap. As their names imply, read_only_space is for read-only data (and should have constant size throughout the lifecycle of your app), and map_space is for what V8 internally calls "maps" (a.k.a. "shape descriptors" or "hidden classes"; note this has nothing to do with a JavaScript new Map()). Most of your app's memory usage will be in old_space, and possibly large_object_space if you allocate very large objects.


text:
Q: ".exe parou de funcionar" Tenho o seguinte código:
typedef struct {
     unsigned int ordem;
     int *elementos;
}MAT_DIAG;

void criar_matriz (MAT_DIAG *m, int d);
void inicializar_matriz (MAT_DIAG *m);
void imprimir_matriz (MAT_DIAG *m);
int retornar_elemento_matriz (MAT_DIAG *m, int i, int j);

void main(){
    int ord, o=1;
    MAT_DIAG *d;

    printf ("Qual e a ordem da matriz? ");
    scanf ("%d", &ord);
    while ((o>=1)&&(o<=2)){
    printf ("\n");
    printf ("1. Criar e inicializar matriz\n");
    printf ("2. Imprimir matriz\n");
    printf ("Escolha a opcao: ");
    scanf ("%d", &o);
    printf ("\n");

    switch (o){
        case 1: criar_matriz(d, ord);
                inicializar_matriz(d);
        break;
        case 2: imprimir_matriz(d);
        break;
        default: printf ("Opcao invalida");
                exit(1);
    }
}
}

void criar_matriz(MAT_DIAG *m, int d){
    m->ordem=d;
    m->elementos = (int *)malloc(sizeof(int)*d);
    if (!m->elementos){
        printf ("Nao foi possivel reservar memoria para a matriz!\n");
        exit(2); }
}

void inicializar_matriz(MAT_DIAG *m){
    int i;
    printf ("\nEntre com os elementos da diagonal principal da matriz: \n");
    for (i=0;i<m->ordem;i++){
        printf ("matriz[%d][%d]",i+1,i+1);
        scanf ("%d",m->elementos+i);}
}

void imprimir_matriz(MAT_DIAG *m){
    int i, j;
    for (i=0;i<m->ordem;i++){
        printf ("\n");
        for (j=0;j<m->ordem;j++){
            printf ("%05d ", retornar_elemento_matriz(m,i,j));
        }
    }
}

Não sei porque, mas quando compilo diz que o programa parou de funcionar. D:

A:     MAT_DIAG *d;

    /* ... codigo que nao atribui valor a d ... */

        case 1: criar_matriz(d, ord);
                inicializar_matriz(d);
        break;
        case 2: imprimir_matriz(d);
        break;

    /* ... */

Nas linhas do case 1 e nas do case 2 usas a variável d sem esta ter sido atribuida um valor.

Sugestão de solução: altera criar_matriz() para devolver um ponteiro e atribui esse ponteiro à variável:
        case 1: d = criar_matriz(ord);

A: Aqui está uma  segunda solução. A primeira foi citada pelo @pmg.
//code...
//passa o endereço de d para a função cria_matriz saber onde está na memória o d,
//pois voce trabalha em escopos diferentes,
//se vc não passar o endereço de d, a função cria_matriz simplesmente faz uma cópia de d
case 1: criar_matriz(&d, ord);
//code....

//cria matriz recebe um endereço de ponteio, ou seja preciso de um ponteiro para ponteiro..
void criar_matriz(MAT_DIAG **m, int d){
    int i;
    //aloco a matriz na memória
    (*m) = (MAT_DIAG *)malloc(sizeof(MAT_DIAG) * d * d);
    if(!(*m)){
        printf ("Nao foi possivel reservar memoria para a matriz!\n");
        exit(2);
    }
    (*m)->ordem=d;
    for(i=0;i<d;i++){
        //aloco todos os elmentos da matriz na memória
        (*m+i)->elementos=(int *)malloc(sizeof(int));
        if (!(*m)->elementos){
            printf ("Nao foi possivel reservar memoria para a matriz!\n");
            exit(2);
        }
    }
}


text:
Q: "X is exclusive y" I've read a conference paper
by Sven Koehler et al., where it says,

[Figure 5.] Finetuning of the ACDC model with an increasing number of GCN patients. There is one plot for each label each with one line per dataset. The blue (upper) line describes the dice score on the ACDC split + n GCN patients, the orange (middle) line describes the dice score on the held out ACDC test split and the green line (lower) describes the dice score on the unseen GCN patients. The latter is exclusive the GCN patients which were added for the finetuning.

I first thought this was a typo, and it should read instead, The latter is exclusively the GCN patients which..., but this would not make sense (in the context of the study presented there, as we need an independent sample of GCN patients for the evaluation).
Thus, I am now thinking they rather want to say, The latter is without the GCN patients which..., which is exactly the opposite meaning. Is my interpretation correct? Can "exclusive" actually be used in this way?

A: There are two possibilities raised by adding a single word, which have opposite meanings. Exclusive of means excluding:

The latter is exclusive of the GCN patients

Exclusive to would mean including GCN and excluding all others:

The latter is exclusive to the GCN patients

This answer explains it well: https://ell.stackexchange.com/questions/200070/meaning-of-exclusive-to-of-in-in-the-given-scenarios


text:
Q: Downgrade to python 3.5 to use tensorflow I am following a tutorial about deep learning with keras. I have managed to install keras through anaconda. It also requires tensorflow which I have failed to install properly. From the related posts, python 3.5 and 64 bit are required to run tf. The version under anaconda is 3.6 and when I tried to downgrade it with conda install python=3.5, it started the procedure but after a while it threw the following:
The following packages will be DOWNGRADED:

    anaconda:            custom-py36_0      --> custom-py35_0
    python:              3.6.1-2            --> 3.5.3-3

And now when I activate tensorflow and run "python" on pycharm terminal, it gets:
Python 3.5.3 |Anaconda custom (64-bit)| (default, May 15 2017, 10:43:23) [MSC v.1900 64 bit (AMD64)] on win32

In addition, I have already installed tensorflow and I have a tensorflow folder under Anaconda/envs folder. And finally under that folder, I have all the files and documents related to tensorflow. However, when I try to import it as:
import tensorflow as tf

It throws No module named 'tensorflow'.
What am I missing?

A: Ok I had installed tf following the steps given here: https://www.tensorflow.org/install/install_windows
However, it was still version 3.6 and did not work out. After downgrading to 3.5, I had to remove all previously set environments and then need to re-install again. When doing that it worked. Here are the steps I followed:
conda remove --name tensorflow --all
conda create -n tensorflow
activate tensorflow
https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.1.0-cp35-cp35m-win_amd64.whl


text:
Q: How to access public download folder in every platform in Xamarin.Forms I need to create a backup service so I intend to save the SQLite database file on each platform. The saved file should be available after the uninstall of the app.
I intend to use the Downloads folder (which should be available on every platform).
I have created an interface and use the following code per platform:
Interface:
public interface IBackupService
{
  string GetDownloadPath();
}

Android:
public string GetDownloadPath()
{
  return Android.OS.Environment.DirectoryDownloads;
}

UWP:
public string GetDownloadPath()
{
  return Windows.Storage.KnownFolders.???????;
}

What should I do about that? Is there a public library that I could use?

A: There does not seem to be a general downloads folder as per this documentation on KnownFolders. So your assumption on the Downloads folder being on every platform doesn't seem to be correct.
If we dive in a bit further we get to the DocumentsLibrary which seems the obvious choice for this kind of purpose, but it is not. Microsoft says:

The Documents library is not intended for general use. For more info,
  see App capability declarations. Also, see the following blog post.
  Dealing with Documents: How (not) to use the documentsLibrary capability in Windows Store apps

The paragraph after that seems to describe what we have to do then;

If your app has to create and update files that only your app uses,
  consider using the app's local folder. Get the app's local folder from
  the Windows.Storage.ApplicationData.Current.LocalFolder property.

So, as I can extract from your question you only want to use storage for your app, so the Windows.Storage.ApplicationData.Current.LocalFolder seems to be the right choice according to Microsoft.


text:
Q: Action Bar Sherlock has deprecated methods I downloaded the ActionBarSherlock version 4.1.0.0, and added a the Android Project library into Eclipse 4.2 on my Win7 java 1.6 update 24 machine.  I used an Eclipse Project Build Target of Android 4.1 in Project | Properties | Project Build Target.  I want to incorporate the ActionBar functionality into an existing app that has minSdkVersion="7".  I noted the code from the ActionBarSherlock library appears to have some deprecated methods, and an error:
Example 1: ActionBarContainer.java, ActionBarContextView.java, ScrollingTabContainerView.java  - uses setBackgroundDrawable - The method setBackgroundDrawable(Drawable) from the type View is deprecated
public ActionBarContainer(Context context, AttributeSet attrs) {
    super(context, attrs);

    setBackgroundDrawable(null);

    TypedArray a = context.obtainStyledAttributes(attrs,
            R.styleable.SherlockActionBar);
    mBackground = a.getDrawable(R.styleable.SherlockActionBar_background);
    mStackedBackground = a.getDrawable(
            R.styleable.SherlockActionBar_backgroundStacked);

    if (getId() == R.id.abs__split_action_bar) {
        mIsSplit = true;
        mSplitBackground = a.getDrawable(
                R.styleable.SherlockActionBar_backgroundSplit);
    }
    a.recycle();

    setWillNotDraw(mIsSplit ? mSplitBackground == null :
            mBackground == null && mStackedBackground == null);
}

Quick fix shows as Add @SupressWarnings 'deprecation' for ActionBarContainer
Example 2:
IcsProgressBar.java uses animationResolution which shows as deprecated, same quick fix as above
private static final int[] ProgressBar = new int[] {
    ...
    android.R.attr.animationResolution

Also, I have an error in ActivityChooserView.java:
private static class SetActivated {
    public static void invoke(View view, boolean activated) {
        view.setActivated(activated);
    }
}

Error is on SetActivated - Call requires API 11 (current min is 7).  This makes sense based on the manifest:
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="15"/>

Shouldn't API 7 be fine, since Action Bar Sherlock should work at at Andriod 2.x?  Have others experienced this, and if so, what is the recommended action?  Supress/ignore the deprecation?  What about the error on SetActivated? I reviewed the readme and did some net searches but did not come up with anything on this.  Thanks for any suggestions.
Thanks!

A: It is just fine. The code is 2.x compatible and even some methods are deprecated as of 4.x, they are still there. It also do not mean on 4.x these deprecated methods will be used. The source is 2.x-4.x so there's no other way (not to mention reflection, but that'd hurt performance, and is for now not necessary). So it is safe to just ignore this. It would probably be better to turn depreciation off for certain files but it is not there. So do not worry.

A: This is doesn't really answer the question but I ran into the same issue when I had to have a minSdkVersion 9 and I wanted to have ActionBarSherlock but I was getting the same error of the actionBar requires minSdkVersion 11.
Apparently in ADT 21.1 you make a values-v11/styles.xml and put the actionBar in there.
https://code.google.com/p/android/issues/detail?id=48283


text:
Q: Cannot log in to Dockerized SSH daemon service using Ubuntu 16.04 When I execute the example below from the Docker website, it works fine. As soon as I change it to ubuntu:16.04, however, the screencast password never works. It just keeps prompting to enter the correct password. Is there something different in 16.04 regarding the chpasswd?
# sshd
#
# VERSION               0.0.2

FROM ubuntu:14.04
MAINTAINER Sven Dowideit <SvenDowideit@docker.com>

RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:screencast' | chpasswd
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config

# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile

EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]

Update: I also tried replacing the last line CMD ["/usr/sbin/sshd", "-D"] with RUN service ssh restart, but it still doesn't work. Makes me curious about when to use service ssh restart versus /usr/sbin/sshd -D

A: I also encountered this problem when pulling the latest version of Ubuntu (18.04). The original solution doesn't fix the problem as in this version, the keyword is prefixed with '#'. The following updated syntax will fix it whether you are using 14:04, 16:04 or 18:04:
sed -ir 's/^#*PermitRootLogin .*/PermitRootLogin yes/' /etc/ssh/sshd_config

A: Generally, if you are trying to ssh into a container, something might be wrong (The nsenter command is now docker exec but the basic gist of the post still holds).
Ubuntu ssh config
Ubuntu 14:04 /etc/ssh/sshd_config
root@1404:/# grep PermitRootLogin /etc/ssh/sshd_config
PermitRootLogin without-password
# the setting of "PermitRootLogin without-password".

The default Ubuntu 16:04 /etc/ssh/sshd_config contains an updated PermitRootLogin config.
root@1604:/# grep PermitRootLogin /etc/ssh/sshd_config
PermitRootLogin prohibit-password
# the setting of "PermitRootLogin without-password".

The sed command 's/PermitRootLogin without-password/PermitRootLogin yes/' will only change the comment in the 16.04 config rather than the required config line.
Fix
Use sed -ir 's/^\s*PermitRootLogin\s+.+/PermitRootLogin yes/' /etc/ssh/sshd_config
The regular expression breaks down to
^      # Start of line
\s*    # 0 or many white spaces
PermitRootLogin
\s+    # 1 or many white spaces
.+     # anything else on the line

So, replace any non commented lines starting with PermitRootLogin * with PermitRootLogin yes. You can also contribute your updates back to Docker.


text:
Q: Store data to $localStorage.$default in angularjs I am trying to store data in $localStorage Please help me
below is my code in angularjs
 $http.get(token_url+"jewellery/quick_keys/get_layout_data/"+edit_layout_id).success(function(result){ /* token url is to provide path to get layout list as per id*/
           console.log(result); /*result is in the form of jeson encode*/
    });

In console I get data as
new_layout [Object { _id=13952057,  name="Default 1",  page=[5],  more...}, Object { _id=55531173,  name="Default 2",  page=[3],  more...}, Object { _id=53907588,  name="Default 3",  page=[3],  more...}, Object { _id=6117442,  name="Default 4",  page=[3],  more...}]

i want to store this data to $localstorage.$default as in format as
new_layout: [{
              _id : 13952057,
              name:  'Default 1',
              page:  [{
                         pageID : 1,
                         product : [ name: 'Lee' }]
                      }],
              image: '',
              Width: 25
           }]
      [{
              _id : 55531173,
              name:  'Default 2',
              page:  [{
                         pageID : 2,
                         product : [ name: 'Jo' }]
                      }],
              image: '',
              Width: 25
           }]

A: For local storage there is a module for that look at below url:
https://github.com/grevory/angular-local-storage
and other link for HTML5 local storage and angularJs
http://amitavroy.com/justread/content/articles/html5-local-storage-angular-js
Also, You can use ngstorage:
ngStorage contains two services: $localStorage and $sessionStorage.
angular.module('app', [
   'ngStorage'
]).controller('Ctrl', function(
    $scope,
    $localStorage,
    $sessionStorage
){});

You can see the demo
. Hope this helps.


text:
Q: Polymer redux state undefined property Inside of my element I can access my state via statePath without a problem.
But when I try it inside a function I get undefined.
but I can dump state object with correct values to console.
const state = this.getState();
console.log(state.User); // undefiend
console.log(state); // I can see User with value as JSON

What am I missing?


text:
Q: Classloader castException with karaf CXF using blueprint I have a problem to launch my bundle in karaf.
I have installed the features cxf and http.
But when i try to install my bundle in Karaf, i have this Exception :
2016-09-18 17:07:49,157 | ERROR | nsole user karaf | BlueprintContainerImpl           | 12 - org.apache.aries.blueprint.core - 1.6.2 | Unable to start blueprint container for bundle karafcxf.rest/1.0.0.SNAPSHOT
org.osgi.service.blueprint.container.ComponentDefinitionException: Unable to initialize bean cxf
....
Caused by: org.apache.cxf.bus.extension.ExtensionException: Could not create object of extension class org.apache.cxf.ws.policy.PolicyEngineImpl.
        at org.apache.cxf.bus.extension.Extension.load(Extension.java:241)
        at org.apache.cxf.bus.osgi.CXFExtensionBundleListener$OSGiExtension.load(CXFExtensionBundleListener.java:145)
        at org.......
Caused by: java.lang.ClassCastException: Cannot cast org.apache.cxf.service.factory.FactoryBeanListenerManager to org.apache.cxf.service.factory.FactoryBeanListenerManager
        at java.lang.Class.cast(Class.java:3258)[:1.8.0]
        at org.apache.cxf.bus.extension.ExtensionManagerImpl.getBeanOfType(ExtensionManagerImpl.java:322)
        at org.apache.cxf.bus.blueprint.BlueprintBeanLocator.getBeanOfType(BlueprintBeanLocator.java:99)
           at .....
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)[:1.8.0]
            at java.lang.reflect.Constructor.newInstance(Constructor.java:408)[:1.8.0]
            at org.apache.cxf.bus.extension.Extension.load(Extension.java:217)

here is my blueprint context :
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0"
    xmlns:jaxws="http://cxf.apache.org/blueprint/jaxws" xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs"
    xmlns:cxf="http://cxf.apache.org/blueprint/core"
    xsi:schemaLocation="
  http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
  http://cxf.apache.org/blueprint/jaxws http://cxf.apache.org/schemas/blueprint/jaxws.xsd
  http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd
  http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd">

    <cxf:bus id="cxfBus1">
        <cxf:features>
            <cxf:logging />
        </cxf:features>
    </cxf:bus>

    <!-- <bean id="resourceWriter" -->
    <!-- class="com.wordnik.swagger.jaxrs.listing.ResourceListingProvider" /> -->
    <!-- <bean id="apiWriter" -->
    <!-- class="com.wordnik.swagger.jaxrs.listing.ApiDeclarationProvider" /> -->

  <!-- JAXRS providers -->
<!--     <bean id="jsonProvider" class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider" /> -->

<!--    <bean id="swaggerResourceJSON" -->
<!--        class="com.wordnik.swagger.jaxrs.listing.ApiListingResourceJSON" /> -->

    <!-- CXF Swagger2Feature -->
<!--    <bean id="swagger2Feature" class="org.apache.cxf.jaxrs.swagger.Swagger2Feature"> -->
<!--        <property name="resourcePackage" value="com.sau.swagger.intg" /> -->
<!--        <property name="version" value="2.0" /> -->
<!--        <property name="basePath" -->
<!--            value="http://localhost:8080/SwaggerUI-Integration/rest" /> -->
<!--        <property name="title" value="Swagger UI Integration Sample" /> -->
<!--        <property name="description" -->
<!--            value="Swagger UI Integration Sample for demonstrating its working." /> -->
<!--        <property name="contact" value="saurabh29july@gmail.com" /> -->
<!--        <property name="scan" value="true" /> -->
<!--    </bean> -->

    <jaxrs:server address="/karafsimple" id="someRestService">
        <jaxrs:serviceBeans>
            <ref component-id="restServiceImpl" />
        </jaxrs:serviceBeans>
<!--        <jaxrs:providers> -->
<!--            <ref component-id="jsonProvider" /> -->
<!--        </jaxrs:providers> -->
<!--        <jaxrs:features> -->
<!--            <ref component-id="swagger2Feature" /> -->
<!--        </jaxrs:features> -->
    </jaxrs:server>

    <!-- Implementation of the rest service -->
    <bean id="restServiceImpl" class="me.rerun.karafcxf.rest.HelloRestServiceImpl">
        <property name="helloService" ref="helloServiceBean" />  <!--Points to the reference below -->
    </bean>

    <!-- This has to point to the service registered through serviceimpl.xml
        in the service.impl project -->
    <reference id="helloServiceBean" interface="me.rerun.karafcxf.service.impl.HelloService">

    </reference>

</blueprint>

Here is my maven dependecy tree :
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building karafcxf.rest 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ karafcxf.rest ---
[INFO] karafcxf:karafcxf.rest:bundle:1.0-SNAPSHOT
[INFO] +- karafcxf:karafcxf.service.impl:jar:1.0-SNAPSHOT:compile
[INFO] +- log4j:log4j:jar:1.2.17:compile
[INFO] +- com.google.guava:guava:jar:14.0.1:compile
[INFO] +- org.apache.commons:commons-lang3:jar:3.1:compile
[INFO] +- org.codehaus.jackson:jackson-core-asl:jar:1.8.9:compile
[INFO] +- org.codehaus.jackson:jackson-mapper-asl:jar:1.8.9:compile
[INFO] +- org.slf4j:slf4j-api:jar:1.7.2:compile
[INFO] +- org.slf4j:slf4j-log4j12:jar:1.6.6:compile
[INFO] +- org.apache.solr:solr-solrj:jar:4.4.0:compile
[INFO] |  +- org.apache.zookeeper:zookeeper:jar:3.4.5:compile
[INFO] |  +- commons-io:commons-io:jar:2.1:compile
[INFO] |  +- org.noggit:noggit:jar:0.5:compile
[INFO] |  +- org.apache.httpcomponents:httpmime:jar:4.2.3:compile
[INFO] |  \- org.codehaus.woodstox:wstx-asl:jar:3.2.7:runtime
[INFO] +- org.osgi:org.osgi.core:jar:4.3.1:provided
[INFO] +- org.apache.cxf:cxf-rt-frontend-jaxrs:jar:2.7.11:compile
[INFO] |  +- org.apache.cxf:cxf-api:jar:2.7.11:compile
[INFO] |  |  +- org.codehaus.woodstox:woodstox-core-asl:jar:4.2.1:compile
[INFO] |  |  |  \- org.codehaus.woodstox:stax2-api:jar:3.1.4:compile
[INFO] |  |  +- org.apache.ws.xmlschema:xmlschema-core:jar:2.1.0:compile
[INFO] |  |  +- org.apache.geronimo.specs:geronimo-javamail_1.4_spec:jar:1.7.1:compile
[INFO] |  |  \- wsdl4j:wsdl4j:jar:1.6.3:compile
[INFO] |  +- org.apache.cxf:cxf-rt-core:jar:2.7.11:compile
[INFO] |  |  \- com.sun.xml.bind:jaxb-impl:jar:2.1.13:compile
[INFO] |  +- javax.ws.rs:javax.ws.rs-api:jar:2.0-m10:compile
[INFO] |  \- org.apache.cxf:cxf-rt-bindings-xml:jar:2.7.11:compile
[INFO] +- org.apache.cxf:cxf-rt-frontend-jaxws:jar:2.7.11:compile
[INFO] |  +- xml-resolver:xml-resolver:jar:1.2:compile
[INFO] |  +- asm:asm:jar:3.3.1:compile
[INFO] |  +- org.apache.cxf:cxf-rt-bindings-soap:jar:2.7.11:compile
[INFO] |  |  \- org.apache.cxf:cxf-rt-databinding-jaxb:jar:2.7.11:compile
[INFO] |  +- org.apache.cxf:cxf-rt-frontend-simple:jar:2.7.11:compile
[INFO] |  \- org.apache.cxf:cxf-rt-ws-addr:jar:2.7.11:compile
[INFO] |     \- org.apache.cxf:cxf-rt-ws-policy:jar:2.7.11:compile
[INFO] |        \- org.apache.neethi:neethi:jar:3.0.3:compile
[INFO] +- org.apache.cxf:cxf-rt-transports-http:jar:2.7.11:compile
[INFO] +- org.apache.cxf:cxf-rt-transports-http-jetty:jar:2.7.11:compile
[INFO] |  +- org.eclipse.jetty:jetty-server:jar:8.1.14.v20131031:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-continuation:jar:8.1.14.v20131031:compile
[INFO] |  |  \- org.eclipse.jetty:jetty-http:jar:8.1.14.v20131031:compile
[INFO] |  |     \- org.eclipse.jetty:jetty-io:jar:8.1.14.v20131031:compile
[INFO] |  |        \- org.eclipse.jetty:jetty-util:jar:8.1.14.v20131031:compile
[INFO] |  +- org.eclipse.jetty:jetty-security:jar:8.1.14.v20131031:compile
[INFO] |  \- org.apache.geronimo.specs:geronimo-servlet_3.0_spec:jar:1.0:compile
[INFO] \- org.apache.httpcomponents:httpclient:jar:4.2.3:compile
[INFO]    +- org.apache.httpcomponents:httpcore:jar:4.2.2:compile
[INFO]    +- commons-logging:commons-logging:jar:1.1.1:compile
[INFO]    \- commons-codec:commons-codec:jar:1.6:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.865 s
[INFO] Finished at: 2016-09-18T17:17:41+02:00
[INFO] Final Memory: 14M/246M
[INFO] ------------------------------------------------------------------------


text:
Q: Cleansng and replacing data with a complex hierarchy I have data with complex hierarchy - lists, dicts, strings.
I need to find all values contains '?', remove it and all that comes after it and insert the cleaned back.
I do not understand how to do it correctly - it's kinda complicated for my current level.
I tried for strings in list:
    parsed["data"] = [{'dimensions':[{'name': '608907?afwafaw'}], 'metrics': [1.0, 2.0]}, {'dimensions':[{'name': '189812?awfawg'}], 'metrics': [2.0, 3.0]}]

I expect:
parsed["data"] = [{'dimensions':[{'name': '608907'}], 'metrics': [1.0, 2.0]}, {'dimensions':[{'name': '189812'}], 'metrics': [2.0, 3.0]}]

without any '?blablabla', just int

A: Here is a recursive solution without any external dependencies, this should work for any deep objects:
...
parsed["data"] = [{'dimensions':[{'name': '608907?afwafaw'}], 'metrics': [1.0, 2.0]}, {'dimensions':[{'name': '189812?awfawg'}], 'metrics': [2.0, 3.0]}]

def cleanse(obj):
    if isinstance(obj, dict):
        for key in obj.keys():
            obj[key] = cleanse(obj[key])
    elif isinstance(obj, list):
        for i in range(len(obj)):
            obj[i] = cleanse(obj[i])
    elif isinstance(obj, str):
        return obj.split('?')[0] # split at question mark and take only the first part, which is a number
    return obj

cleanse(parsed['data'])

print(parsed['data']) # output: [{'dimensions': [{'name': '608907'}], 'metrics': [1.0, 2.0]}, {'dimensions': [{'name': '189812'}], 'metrics': [2.0, 3.0]}]

A: If all your data looks like your example, this should do it:
for record in parsed["data"]:
    for dim in record["dimensions"]:
        dim["name"] = dim["name"].split("?")[0]

It only checks "name" in "dimensions", since that's the values that need cleaning. It doesn't bother to check if the value already contains a question mark, since this will be a no-op if it does not.


text:
Q: Display second dropdown based on selection in first dropdown? I need that based on the choice made in "dropdown list type_w" show me the "dropdown list of lmg or marks".
I tried with addEventListener (""), but it doesn't work for me.
I also used CSS with "display: none" / "display: block" and JavaScript with switch/case, but it doesn't works.
</select>
 <select id="type_w">
   <option value="null" selected> --- </option>
   <option value="lmg"> LMG </option>
   <option value="marks"> Marksman Rifle </option>
 </select>

 <select id="w_lmg" hidden>
   <option value="null" selected> --- </option>
   <option value="mg5"> MG5 </option>
 </select>

 <select id="w_marks" hidden>
   <option value="null" selected> --- </option>
   <option value="mk17"> MK17 Military </option>
 </select>
</form>
</div>

A: I just write a small jQuery code, I hope it'll help you out. Thanks

$(document).ready(function() {
  $('#type_w').change(function() {
    $(".hide-submenu").hide();
    $("#w_" + this.value).show();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="type_w">
  <option value="null" selected> --- </option>
  <option value="lmg"> LMG </option>
  <option value="marks"> Marksman Rifle </option>
</select>

<select id="w_lmg" class="hide-submenu" hidden>
  <option value="null" selected> --- </option>
  <option value="mg5"> MG5 </option>
</select>

<select id="w_marks" class="hide-submenu" hidden>
  <option value="null" selected> --- </option>
  <option value="mk17"> MK17 Military </option>
</select>

A: Without jQuery:

document.addEventListener('DOMContentLoaded', function() {

 document.querySelector('#type_w').addEventListener("change", function (e) {

  document.querySelector('#w_lmg').classList.add('hidden');
  document.querySelector('#w_marks').classList.add('hidden');

  if(e.target.selectedIndex == 1) {
   document.querySelector('#w_lmg').classList.remove('hidden');
  }

  if(e.target.selectedIndex == 2) {
   document.querySelector('#w_marks').classList.remove('hidden');
  }

 });

});
.hidden {
 display:none;
}
<select id="type_w">
 <option value="null" selected> --- </option>
 <option value="lmg"> LMG </option>
 <option value="marks"> Marksman Rifle </option>
</select>

<select id="w_lmg" class="hidden">
 <option value="null" selected> --- </option>
 <option value="mg5"> MG5 </option>
</select>

<select id="w_marks" class="hidden">
 <option value="null" selected> --- </option>
 <option value="mk17"> MK17 Military </option>
</select>

A: Ok, I'm going to provide the code you need to get this working, but I should say there are quite a few ways to do this. Without the full scope of context and the desired end result, it's difficult to say this is definitely the way to do it.
I won't ask you to change your HTML except for one key element, remove the "hidden" attribute. If you wish to hide/show HTML elements use CSS as your first point of call.
<script>

// run script once once the page has loaded
document.addEventListener("DOMContentLoaded", function(event) {init()});

// this will apply the event handler to the primary select
function init() {
 // apply even handler to detect when primary select has changed
 document.querySelector("#type_w").addEventListener("change", function(ev){
  var selects = document.querySelectorAll("#w_lmg, #w_marks").forEach(
   function(item){
    item.style.display = ("w_"+ev.currentTarget.value==item.id ? "inline" : "none")
   }
  )
 });
}

</script>

As I say, you will need to remove the "hidden" attribute in your HTML to get the above to work. You could use .hidden but using CSS is (imo) the better solution here.
If you are wondering how to set the two secondary selects as hidden via CSS you could use this:
<style>
 #w_lmg, #w_marks { display: none }
</style>

or if you wish a JS solution, insert this code as the first line within the init() function:
// hide the two child <select>
 document.querySelectorAll("#w_lmg, #w_marks").forEach(
   function(item) {
    item.style.display = "none";
   }
 );


text:
Q: Sequential, Dependent Deferred calls I have two functions getStudentById(studentId) and getBookTitleById(bookId) where the data is retrieved via ajax calls (these functions are to be left alone)
My goal, using Deferreds:

*

*get the Student object,

*then get the Book Title based on the Student object's favoriteBookId property,

*then call the method showMessage(student, bookTitle) resulting in "John likes Book 222"
This example is simplified. In essence the goal is to make a certain number of ajax calls in succession, where the next call depends on the result of the previous, and at the end, offer access to ALL the resolves
code:
var getStudentById = function(studentId){
  return $.Deferred(function(def){
      def.resolve({name:"John",favoriteBookId:222});  //assume ajax gets Student obj
    }).promise();
}

var getBookTitleById = function(bookId){
  return $.Deferred(function(def){
      def.resolve("Book " + bookId);  //assume ajax call gets title
    }).promise();
}

var showMessage = function(student, bookTitle){
   alert(student.name + " likes " + bookTitle)
}

I've seen many solutions that follow the following pattern
deferred_a.then(b).then(c).then(y).then(z).done(r)

which would translate to:
getStudentById(5)    //resolves with student object
.then(function(student){
    return getBookTitleById(student.favoriteBookId)}
)
.done(function(bookTitle){
    alert(bookTitle);  //obviously  this works

    // how can I get reference to the student object here? so i can say:
    // showMessage (student, bookTitle)
});

but i need to call the method showMessage(student, bookTitle), where the parameters are the result of each ajax call in the chain
I cannot find an (elegant) example where ALL the results of sequential Deferred calls are accessible at the end of the chain, as it the done function gets the result of the LAST then
My best solution is to wrap the second Deferred in a factory-type method, but this cant be the best solution, right?  Am I missing something from the Deferred usage that should simplify this?
getStudentById(5)
.then(function(student){
        return $.Deferred(function(def){
            getBookTitleById(student.favoriteBookId)
            .done(function(bookTitle){def.resolve({student:student, bookTitle:bookTitle})})
        }).promise();
    })
.done(function(studentAndBookTitle){
    alert(studentAndBookTitle.student.name + " likes " + studentAndBookTitle.bookTitle);
});

A: Another way to chain together promises is to have one then handler return another promise.  The advantage of this is that you can make use of closures in order to reference variables from the resolution of the first promise within the resolution of the second promise.
So your example would look like:
getStudentById(5)
.then(function(student) {
    return getBookTitleById(student.favoriteBookId)
    .then(function (bookTitle) {
        doSomethingWithStudentAndBookTitle(student, bookTitle)
    });
});

function doSomethingWithStudentAndBookTitle(student, bookTitle) {
    alert(student.name + " likes " + bookTitle);
}

EDIT: This solution is somewhat similar to your last snippet; but

*

*getBookTitleById already returns a promise, you don't need to wrap it in a deferred and then get the promise from it.

*You're already making use of closure to wrap those two properties into a single object; there's no reason (at least none that I can see) that you need to wrap those properties up and then do something with them in a different spot, rather than just doing something with them right there.
EDIT 2: Created a function to separate data consumption from data providing.

A: Genob, your "best solution" is totally viable and acceptable. It just needs tidying :
getStudentById(5).then(function(student) {
    return getBookTitleById(student.favoriteBookId).then(function(bookTitle) {
        return {
            student: student,
            bookTitle: bookTitle
        });
}).done(function(superObj) {
    alert(superObj.student.name + " likes " + superObj.bookTitle);
});

You might also consider a mild variant of the same approach, which is possible because student is already an object, allowing it to be extended rather than creating a super-object.
getStudentById(5).then(function(student) {
    return getBookTitleById(student.favoriteBookId).then(function(bookTitle) {
        return $.extend(student, {
            favoriteBookTitle: bookTitle
        });
    });
}).done(function(extendedStudent) {
    alert(extendedStudent.name + " likes " + extendedStudent.favoriteBookTitle);
});

This approach (both variants) may be summarised as "passing data down the promise chain in an accumulator object" or more simply a "promised data accumulator" pattern (my term - you won't find it anywhere else).
However achieved, it is good to keep the "consumer" method (the terminal .done()) free from the confines of nesting/closures.


text:
Q: In Spring, is it possible to return an image to the browser and include metadata about the image in the same response? I'm reading TIFF and PDF files off a network drive and returning each page as an image to the browser which get displayed as JPG.  This part works fine.  However I'm finding it inefficient because I first have to make a request to the server to determine how many pages the file has, which results in reading in the image on the server, getting the number of pages and returning that value.  Once that value is returned to the browser, I then have to make a request for each page to be returned as an image, so the file on the network drive is read in again, and the requested page number is returned as a byte[] representing a BufferedImage of the page.
What I'd ultimately like to do is make a request for the first page in the file, and then in the response to the browser, indicate the number of pages in the file so that each additional page can be requested.  This would reduce the amount of requests as no initial request would be required just to determine the number of pages.
I'm not sure if this is possible.  I've spent some time researching to see if I could get response headers from images, but haven't found anything.

A: Why not adding the info to a cookie via reponse in your image-serving controller?
If you name the cookie in a way that would "link" it to a specific set of images you wouldn't need to hassle with "how can i read headers of an image?"


text:
Q: How to understand this Unity Coroutine? using UnityEngine;
using System.Collections;

public class CoroutineExample : MonoBehaviour
{
    IEnumerator Start ()
    {
        print ("Starting " + Time.time);
        yield return StartCoroutine (WaitAndPrint ());
        print ("Done " + Time.time);
    }

    IEnumerator WaitAndPrint ()
    {
        yield return new WaitForSeconds (5f);
        print ("WaitAndPrint " + Time.time);
    }
}

The result is
Starting 0
WaitAndPrint 5.010554
Done 5.010554

I have two questions?
First, How to understand the return value of function Start(). I used to see the return value of Start() is void. And in my view, Start() only executes once (one frame) by Unity, but yield return seems make Start() function execute in two frames;
Second, I am also confused by the result. I think the result should be
Starting 0
Done 5.010554
WaitAndPrint 5.010554

Because StartCoroutine() starts the function WaitAndPrint(). In function WaitAndPrint(), yield return makes this function pause in this frame and return to Start(). Then Start() continues going on and prints "Done xxxxx". After 5 seconds, WaitAndPrint() resume and
prints "WaitAndPrint xxxxx".
Where am I wrong?

A: When you call yield return the control is taken by Unity.
When you start a Coroutine Unity will take the IEnumerator returned by the method and will call MoveNext on the IEnumerator returned.
Based on the type of object and on the values in the object Unity will decide what to do.
In you case in the Start method the yield statement return another IEnumerator so Unity will not call MoveNext on the Start returned object until the second IEnumerator finishes.
In WaitAndPrint the first MoveNext returns a WaitForSeconds object, based on that Unity decides that it will not call MoveNext on in until 5 seconds have passed. After 5 seconds it calls MoveNext again and the rest of the method is executed, which is just this line
print ("WaitAndPrint" + Time.time);

As the IEnumerator returned by yield return StartCoroutine (WaitAndPrint ()); reached its end it will call MoveNext on the IEnumerator that was returned by Start, this in turn will execute what ever is left of Start:
print ("Done " + Time.time);

Hope this is clear enough :)

A: Here's how I understand this result :
The Start() function is called once by Unity and prints "Started".
Then the following line does two things :
yield return StartCoroutine (WaitAndPrint ());

*

*it starts the WaitAndPrint() coroutine

*it waits for it to be over before continuing in the Start() coroutine.

The WaitAndPrint() coroutine will do its stuff :

*

*Wait for 5 seconds

*Print "WaitAndPrint" + time

Then the Start() coroutine will resume and print "Done" + time.
This is why
print ("WaitAndPrint" + Time.time);

is printed before :
print ("Done " + Time.time);

Also, you should edit your post, it misses a space in the first result :
WaitAndPrint5.010554

Should be
WaitAndPrint 5.010554

Sorry if it's not clear, it's my first time answering on StackOverflow, hope it helped !

A: IEnumerators are iterator blocks, they dont necessarily execute for 1 frame, when you put a yield return, you essentially are telling it to iterate over multiple frames.

When a yield return statement is reached in the iterator method,
  expression is returned, and the current location in code is retained.

*

*https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx

A: Instead of IEnumerators you can "nearly" always use Invoke method. Try to work with that one and your life will be easier :)


text:
Q: Can a numpy.prod array reduction be replaced by numpy.einsum? I have an huge 8D array view that i want to reduce to 2D by multiplying the elements together over 4 axes and summing them over 2 axes. I didn´t find any example in the numpy.einsum documentation where the elements of the same array are multiplied with each other. The following works, but requires a lot of additional memory during computation:
import numpy as np
a = np.zeros((2048,2048,64,64,dtype=float32)
a[...] = data
b = np.lib.stride_tricks.sliding_window_view(a,(3,3)+a.shape[2:],axis=(0,1,2,3))
c = np.sum(np.prod(b,axis=(2,3,4,5)),axis=(2,3))

Can this operation be performed by numpy.einsum to save memory?


text:
Q: Cannot import module from Powershell started from Start-Process I have a powershell script: MyPSScript.ps1:
function DoFoo() {
  $Powershell = "C:\windows\System32\WindowsPowerShell\v1.0\Powershell.exe"
  $Command = "& C:\Temp\myscript.ps1"
  Start-Process $Powershell -ArgumentList ("-noexit", "-noprofile", "-Command", $Command)
}

In myscript.ps1 I have:
Import-Module "C:\Temp\myscript2.ps1"
DoSomething()

In myscript2.ps1 I have:
function DoSomething() {
  Write-Output "Hello World"
}

The problem is that myscript.ps1 is correctly executed, but the module is not imported as nothing is printed. Also, since I open the new powershell window using -noexit, I can type in it and if I try to call DoSomething, Powershell complains because it cannot find the command.
The funny thing is that, if I try to type manually the same import directive, then it imports the file corrently...
Are there any issues in importing a module from a Powershell which has been called from another process as I am doing?

A: Beside the typo I fixed (missing "=") in your question, there are several problems in the script you provided. The first one (MyPSScript.ps1) defines a function DoFoo but never calls it. The second one (myscript.ps1) wrongly calls DoSometing() with parentheses. If you fix those two problems, you'll see your "Hello World".
MyPSScript.ps1:
function DoFoo() {
  $Powershell = "C:\windows\System32\WindowsPowerShell\v1.0\Powershell.exe"
  $Command = "& C:\Temp\myscript.ps1"
  Start-Process $Powershell -ArgumentList ("-noexit", "-noprofile", "-Command", $Command)
}

DoFoo

myscript.ps1:
Import-Module "C:\Temp\myscript2.ps1"
DoSomething

A: Powershell modules have a .psm1 file extension.
Rename your file "myscript2.ps1" to "myscript2.psm1", then it should work.


text:
Q: Cannot create Android 4.0 AVD with system bar Is there a way to create an android AVD with a system bar like in honeycomb? When I create any AVD I get "hard" keys to appear as part of the emulator and no system bar like in honeycomb. Anyway to get a system bar to show up?

A: You can do this by creating a new AVD and setting its screen resolution to wxga720. This will make it a "tablet" device.
For those who are actually interested in what is going on here, by creating a device with wxga720 resolution a hardware property called Hardware Back/Home keys is created and set to no. Also, another property called Keyboard lid support is set to no. These two together are what actually get rid of the "hard keys".

A: There is a bug in Android that sets the keyboard lid to 'yes' regardless of whether you type 'yes' or 'no'.  You can look under your home directory's ".android" folder, look under "avds" then the AVD you craeted, and go edit the config.ini file to set it to 'no'

A: Here's what worked for me, on both the WXGA720 skin and custom 1280x800 resolution:
Option A: Edit config.ini
*
*Navigate to the AVD directory (.android/avd/<name-of-avd>.avd/)

*Open config.ini in your desired text editor

*Set hw.lcd.density=160

*Save
Option B: Edit in Android SDK Manager (GUI)
*
*Click Tools | Manage AVDs...

*Select Android Virtual Device to edit

*Click Edit...

*Click the Value for the Abstracted LCD density property

*Enter 160

*Click Edit AVD to save
After editing the density, start the AVD and enjoy the Ice Cream Sandwich tablety goodness. :)
It seems like the logic in the emulator that determines whether to present a phone or tablet interface is based on the calculated physical size of the virtual device's screen, which is dependent on two parameters:  screen size and pixel density.
Like others, I had used the built-in WXGA720 skin hoping to work with the tablet interface, and was disappointed to be presented with a phone interface in landscape orientation.  I even tried a new device with a custom resolution of 1280x800 and set hw.mainKeys and hw.keyboard.lid in the config.ini to no avail.
The WXGA720 skin's default density of 320 produces a calculated screen size of 4.6" diagonal (4" x 2.25"), which I'm surmising is within the emulator's esoteric threshold for a phone device.  Even the custom resolution of 1280x800, defaulting at a density of 240 and thereby sporting a whopping 6.3" diagonal (!), is rendered with a phone interface.
Some well-named default AVD skins in the SDK ("WXGA720-phone" & "WXGA720-tablet", e.g.) would help eliminate the confusion here.  Perhaps we should nag Google.

A: I spent some time looking for this and digged trough Android 4.0 source to figure how it works. This is what I found out:

*

*Android decides whether to go into tablet mode using isTabletUI
function. The function just checks if the screen is XLARGE. By
further digging into the code I found that screen is detected as
XLARGE if its larger then 800x600 at medium density. I've managed to
make it run with systembar at 120 dpi with 600x450 resolution.

*There apears to be no way of making Android Emulator behave like Galaxy Nexus, that is have Phone interface with status bar and systembar. It will either have status bar (phone ui) or system bar (tablet ui). In other words it appears Galaxy Nexus is not running vanilla version of ICS as I would have expected..

A: Actually it's pretty easy, just go to the AVD Manager (the program that manages the emulator virtual images), select the Android 4 image, then add the property "Hardware Back/Home keys" and set it to "no
(from http://www.dandandin.net/how-to-show-the-new-softkeys-in-the-ice-cream-sandwich-emulator)

A: You're sure you picked the right API level too?  That one got me the first time, I thought I clicked on the right one, but I hadn't.


text:
Q: Create a list / arraylist of objects and sort the list (Java)
Possible Duplicate:
Sorting an ArrayList of Contacts based on name?

I have a student object and then I create ArrayList and add student to the list.
ArrayList<Student_Object> studentsList = new ArrayList<>();

Now, I want to sort the list by studentId fleid. How can I do it?
Is there a better solution? Thanks

So I have this method in the Student _Object class
Class is:
class Student_Object implements Comparator<Student_Object>

The method is:
public int compare(Student_Object student1, Student_Object student2){
    String student1TUID = student1.getTUID();
    String student2TUID = student2.getTUID();

return student1TUID.compareTo(student2TUID);

}

From where do I run the statment?
Collections.sort(studentsList);

If I run it from my main class I get error in netbeans:
no suitable method found for sort(ArrayList<Student_Object>)
    method Collections.<T#1>sort(List<T#1>,Comparator<? super T#1>) is not applicable
      (cannot instantiate from arguments because actual and formal argument lists differ in length)
    method Collections.<T#2>sort(List<T#2>) is not applicable
      (inferred type does not conform to declared bound(s)
        inferred: Student_Object
        bound(s): Comparable<? super Student_Object>)
  where T#1,T#2 are type-variables:
    T#1 extends Object declared in method <T#1>sort(List<T#1>,Comparator<? super T#1>)
    T#2 extends Comparable<? super T#2> declared in method <T#2>sort(List<T#2>)
----
(Alt-Enter shows hints)

Got it to work. I used Collections.sort(studentsList, new Student_Object());
Thanks everyone

A: One way would be:
Write a comparator and override compare method. Then use Collections.sort() by passing comparator.
Example:
class StudentComparator implements Comparator<Student> {

    public int compare(Student stud1, Student stud2){

        int stu1ID = stud1.getId();
        int stu2ID = stud2.getId();

        if(stu1ID > stu2ID)
            return 1;
        else if(stu1ID < st21ID )
            return -1;
        else
            return 0;
    }

}

Another flavor may be:
 class StudentComparator implements Comparator<Student> {

        public int compare(Student stud1, Student stud2){

            int stu1ID = stud1.getId();
            int stu2ID = stud2.getId();

           return stud1ID-stu2ID;
        }

    }

This tutorial may help you.

A: To do sorting you need to implement the Comparable interface.  I would also highly recommend implementing equals and hashCode while you are in there.  Example:
public class Student implements Comparable
{
    private String name;
    private int id;
    ...

    public int compareTo(Student otherStudent)
    {
       if(this.id < otherStudent.id)
       {
          return -1;
       }
       else if(this.id > otherStudent.id)
       {
           return 1;
       }
        else{
           return 0;
        }

    }
}


text:
Q: Website Link Problem after uploading to hosting When I'm working offline all are fine but after moved my files to the server the linking to the pages not updated properly.
ex:  When I enter my site name and check contact's link it shows contact.html and after I entering mysite.com/index.html and checked the contact's link it shows contact.php
I want to know what mistake I'm doing?


text:
Q: jenkins kubernetes-plugin set idletimeout in pipeline How to set Time in minutes to retain slave when idle and Max number of instances in pipeline when config podTemplate ?
I see these two config options in System->Could->kubernetes. But I use pipeline and I didn't figure it out how to set them.
Now My pipeline looks like below.
podTemplate(label: 'docker-go',
  containers: [
        containerTemplate(
            name: 'jnlp',
            image: 'docker.mydomain.com/library/jnlp-slave:2.62',
            command: '',
            args: '${computer.jnlpmac} ${computer.name}',
        ),
        containerTemplate(name: 'docker', image: 'docker.mydomain.com/library/docker:1.12.6', ttyEnabled: true, command: 'cat'),
        containerTemplate(name: 'golang', image: 'docker.mydomain.com/library/golang:1.8.3', ttyEnabled: true, command: '')
  ],
  volumes: [hostPathVolume(hostPath: '/var/run/docker.sock', mountPath: '/var/run/docker.sock')]
  ) {

  def image_tag = "docker.mydomain.com/deploy-demo/demo-go:v0.1"
  def workdir = "/go/src/demo-go"
  node('docker-go') {
    stage('setup') {

    }

    stage('clone') {
    }
    stage('compile') {

    }
    stage('build and push image') {
    }
  }
}

A: Ok, I figuire it out
Add these two.

idleMinutes: 10
instanceCap: 10

podTemplate(label: 'docker-go',
  containers: [
        containerTemplate(
            name: 'jnlp',
            image: 'docker.mydomain.com/library/jnlp-slave:2.62',
            command: '',
            args: '${computer.jnlpmac} ${computer.name}',
        ),
        containerTemplate(name: 'docker', image: 'docker.mydomain.com/library/docker:1.12.6', ttyEnabled: true, command: 'cat'),
        containerTemplate(name: 'golang', image: 'docker.mydomain.com/library/golang:1.8.3', ttyEnabled: true, command: '')
  ],
  volumes: [hostPathVolume(hostPath: '/var/run/docker.sock', mountPath: '/var/run/docker.sock')],
  idleMinutes: 10
  instanceCap: 10
  ) {

  def image_tag = "docker.mydomain.com/deploy-demo/demo-go:v0.1"
  def workdir = "/go/src/demo-go"
  node('docker-go') {
    stage('setup') {

    }

    stage('clone') {
    }
    stage('compile') {

    }
    stage('build and push image') {
    }
  }
}


text:
Q: Split date range into one row per month in SQL Server pt2 This question relates to this post: Split date range into one row per month in sql server
But I'm new to Stackoverflow and new users are not allowed to place comments to provided solutions.That's why I am now adding this as a new question.
The question was this:

I have a table with two column called "from_date" and "to_date"
The table looks like this:
Table (I am not allowed to embed my picture here, so please click the link)
I want result like:-
from_date      ||      to_date
  -----------         ------------
2013-11-25     ||      2013-11-30
2013-12-01     ||      2013-12-05
That date is splits from 2013-11-25 to 2013-11-30 and another date split from 2013-12-01 to 2013-12-05... Is it possible to split like this ?

Aaron Bertrand's solution is this:
DECLARE @d TABLE(from_date DATE, to_date DATE);

INSERT @d VALUES ('2013-11-25','2013-12-05');

;WITH n(n) AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY [object_id])-1
    FROM sys.all_columns
),
d(n,f,t,md,bp,ep) AS
(
    SELECT n.n, d.from_date, d.to_date,
           DATEDIFF(MONTH, d.from_date, d.to_date),
           DATEADD(MONTH, n.n, DATEADD(DAY, 1-DAY(from_date), from_date)),
           DATEADD(MONTH, n.n+1, DATEADD(DAY, 0-DAY(from_date), from_date))
    FROM n
    INNER JOIN @d AS d ON d.to_date >= DATEADD(MONTH, n.n-1, d.from_date)
)
SELECT original_from_date = f, original_to_date = t,
       new_from_date = CASE n WHEN 0  THEN f ELSE bp END,
       new_to_date   = CASE n WHEN md THEN t ELSE ep END
FROM d
WHERE md >= n
ORDER BY original_from_date, new_from_date;

Results:
original_from_date   original_to_date   new_from_date   new_to_date
------------------   ----------------   -------------   -----------
2013-11-25           2013-12-05         2013-11-25      2013-11-30
2013-11-25           2013-12-05         2013-12-01      2013-12-05

Aaron Bertrand's answer is a super powerful query, but it seems it only works well if the startdate is in a month following a month with 31 days. If you change the startdate to, for example, 2013-5-25 (following April, with only 30 days), the new_to_date values are incorrect: all full months suddenly get a max of 30 days then:
original_from_date  original_to_date    new_from_date   new_to_date
2013-05-25          2013-12-05          2013-05-25      2013-05-30
2013-05-25          2013-12-05          2013-06-01      2013-06-30
2013-05-25          2013-12-05          2013-07-01      2013-07-30
2013-05-25          2013-12-05          2013-08-01      2013-08-30
2013-05-25          2013-12-05          2013-09-01      2013-09-30
2013-05-25          2013-12-05          2013-10-01      2013-10-30
2013-05-25          2013-12-05          2013-11-01      2013-11-30
2013-05-25          2013-12-05          2013-12-01      2013-12-05

Can anyone edit the query so that end dates are correct (28,30,31 days, and 29 feb leap) regardless of what month the start date is in? I can't figure out how to do it.
Many thanks, Martijn Vermunt

A: The answer has been provided, the query has been edited and made perfect. Thank you @Aaron Bertrand
for updating the query!
DECLARE @d TABLE(from_date DATE, to_date DATE);

INSERT @d VALUES ('2013-11-25','2013-12-05');

;WITH n(n) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY [object_id])-1 FROM sys.all_columns
),
d(n,f,t,md,bp,ep) AS
(
SELECT n.n, d.from_date, d.to_date,
DATEDIFF(MONTH, d.from_date, d.to_date),
DATEADD(MONTH, n.n, DATEADD(DAY, 1-DAY(from_date), from_date)),
DATEADD(DAY, -1, DATEADD(MONTH, 1, DATEADD(MONTH, n.n,
 DATEADD(DAY, 1-DAY(from_date), from_date))))
FROM n INNER JOIN @d AS d
ON d.to_date >= DATEADD(MONTH, n.n-1, d.from_date)
)
SELECT original_from_date = f, original_to_date = t,
new_from_date = CASE n WHEN 0  THEN f ELSE bp END,
new_to_date   = CASE n WHEN md THEN t ELSE ep END
FROM d WHERE md >= n
ORDER BY original_from_date, new_from_date;


text:
Q: Add an array as a subdocument to a Mongoose model instance I am building an array with data and want to push that array to sub-document.
var pubArray = [];
var count = 5
for (i = 0; i < count; i++) {
  pubArray.push({publicationName: req.body.publicationName[i], dateSent:req.body.dateSent[i]});
};

Students.findOne({studentNumber: filter}, function (err, student) {
  student.publications.push({pubArray});
  student.save();
});

If I use the {publicationName: req.body.publicationName[i], dateSent:req.body.dateSent[i]} inside the student.publications.push it works fine.  If I try to push the array, nothing happens.

A: Note that the .push() method in mogoose works just like it's JavaScript equivalent in that it is "pushing" a single element onto the array, rather than a whole array. So you can either assign the whole array or just construct in the loop:
 student.publications = pubArray;

or:
// Construct with .push in loop:
Students.findOne({ "studentNumber": filter },function(err,student) {
    for ( var i = 0; i < count: i++ ) {
        student.publications.push({
            "publicationName": req.body.publicationName[i],
            "dateSent": req.body.dateSent[i]
        });
    }
    student.save(function(err) {
        // Complete
    });
});

But really you would be better off using an "atomic" operator of $push with $each in a direct update. This is then just one trip to the server, rather than two:
Students.update(
    { "studentNumber": filter },
    { "$push": { "publications": { "$each": pubArray } } },
    function(err,numAffected) {

    }
);

That is generally worlds better than the "find/modify/save" pattern, and not only in being more efficient, but it also avoids potential conflicts or overwriting data since the object and array is modified "in-place" in the database, with the state current to the time of modification.
Atomic operators should always be favoured for the performance benefits as well as lack of conflicts in modification.

A: The publications property of the student object is an Array. You can simply assign this property to the pubArray created earlier:
Students.findOne({studentNumber: filter}, function (err, student) {
  student.publications = pubArray;
  student.save();
});


text:
Q: How do I calculate the rendered location of the corners of a textblock? I am trying to get the rendered location of the corners of a textblock. I can't seem to find out how to do it. The textblock is bound by a border, which in turn in bound by a grid. Therefore the textblock and the border have no dimensions that I can pull in relation to the rest of the Window. I tried the following code, but only part of it works. The margin is 0 and the ActualWidth is 13.2. By the time that this line has been reached, the window and textblocks have been rendered.
double rightBound = textBlock.Margin.Left + textBlock.ActualWidth;

Update:
I have the following code which mostly does what I want. However, the points DO NOT line up with the UI elements well; they appear to be arbitrarily placed near the elements. The points do not line up with the boundaries of the block.
Point blockPoint = textBlock.TranslatePoint(new Point(0, 0), myMainWindow);

A: So your text box isn't dimensioned and is encapsulated by a border... The code you gave above might be grabbing the position of the text within the border, thus appearing like the lines are drawn randomly inside the element. Try grabbing the encapsulating border's position.


text:
Q: Resolve Drag into Vector Components Assume you have a sphere travelling at a velocity of $30$m/s, at angle $30^\circ$ relative to the local horizontal plane. For the purposes of the below equations please ignore more complicated influences on drag like turbulence.
It has a drag coefficient of $0.9$, and a frontal surface area of $0.2$m$^2$. I'm using a sphere because I assume the drag coefficient and frontal area is constant no matter the direction it travels. Therefore, using a basic formula for drag, this can be expressed by
$$D=\frac{1}{2} \cdot \rho \cdot A \cdot C_d \cdot V^2$$
My question is can you resolve this Drag force into its components by
$$D_x = D \cdot \cos\left(\frac{\pi}{6}\right)$$
$$D_y = D \cdot \sin\left(\frac{\pi}{6}\right)$$
Would this adequately resolve the drag force into its two components or do you need to resolve the velocity into its two components? e.g.
$$v_x = V \cdot \sin\left(\frac{\pi}{6}\right)$$
$$v_y = V \cdot \cos\left(\frac{\pi}{6}\right)$$
Then use those velocity components to calculate the drag acting in those directions? i.e.
$$D_x = \frac{1}{2} \cdot \rho \cdot A \cdot C_d \cdot (v_x)^2$$
$$D_y = \frac{1}{2} \cdot \rho \cdot A \cdot C_d \cdot (v_y)^2$$
I also assume the drag would be acting opposite the direction of the sphere, therefore become negative.
Are all of these interpretations correct? If they are incorrect please indicate which ones.

A: Drag acts in the opposite direction of velocity. Therefore, if
$$v_x = V \cdot \cos\left(\frac{\pi}{6}\right)$$
$$v_y= V \cdot \sin\left(\frac{\pi}{6}\right)$$
Then
$$D_x = -D \cdot \cos\left(\frac{\pi}{6}\right)$$
$$D_y =-D \cdot \sin\left(\frac{\pi}{6}\right)$$
This is because, in general, if for vectors $\mathbf a$ and $\mathbf b$ the following is true
$$\mathbf b\propto-\mathbf a$$
then it's also true that
$$b_x\propto-a_x$$
$$b_y\propto-a_y$$
However, it is not true in your case that
$$D_x = \frac{1}{2} \cdot \rho \cdot A \cdot C_d \cdot (v_x)^2$$
$$D_y = \frac{1}{2} \cdot \rho \cdot A \cdot C_d \cdot (v_y)^2$$
You just need to take the drag force and break it into components using the correct trigonometric functions as done above. You don't replace all instances of $a$ with $a_i$ for each general vector $\mathbf a$.

A: In the general case, we can write the drag force in vector form
$$\vec F_D=\frac {1}{2}\rho A C_D(Re)|\vec v_0-\vec v|(\vec v_0-\vec v)$$
here $\vec v_0$ is wind speed, $\vec v$ is body speed, $Re$ is Reynolds number.
In the particular case of $\vec v_0=0$, we have
$$\vec F_D=-\frac {1}{2}\rho A C_D(Re)|\vec v|\vec v$$
The projections of the force on the coordinate axis have the form
$$(F_D)_{x}=-\frac {1}{2}\rho A C_D(Re)|\vec v|v_x, (F_D)_{y}=-\frac {1}{2}\rho A C_D(Re)|\vec v|v_y$$
In this case $|\vec v|=\sqrt {v_x^2+v_y^2}$. For a spherical particle, I can recommend the empirical formula for the drag coefficient
$$C_D=\frac {21.1}{Re}+\frac {6.3}{Re^{0.5}}+0.25$$
For $Re>>1$, we have $C_D=0.25$ (this is not 0.9).


text:
Q: SQLite foreign key? I have 2 tables: A and B. A has a foreign key to B and B has a foreign key to A. But I cannot make a foreign key from A to B, because A is created before B.
How can I solve it when SQLite doesn't support Alter Table?
This is my sample database:
Create Table A(
  A_ID    INTEGER PRIMARY KEY,
  B_ID    INTEGER,
  A_DESCRIPTION    TEXT,

  FOREIGN KEY (B_ID) REFERENCES B(B_ID)
)

Create Table B(
  B_ID    INTEGER PRIMARY KEY,
  A_ID    INTEGER,
  B_DESCRIPTION    TEXT,

  FOREIGN KEY (A_ID) REFERENCES A(A_ID)
)

A: I believe your issue is actually how you are defining your foreign keys. Defining circular foreign keys works just fine for me. Try this query instead:
pragma foreign_keys=on;

Create Table A(
  A_ID    INTEGER PRIMARY KEY,
  B_ID    INTEGER REFERENCES B(B_ID),
  A_DESCRIPTION    TEXT
);

Create Table B(
  B_ID    INTEGER PRIMARY KEY,
  A_ID    INTEGER REFERENCES A(A_ID),
  B_DESCRIPTION    TEXT
);

A: Sqlite does support ALTER TABLE, but in a limited capacity.
From the documentation (http://www.sqlite.org/lang_altertable.html) :

The ALTER TABLE command in SQLite allows the user to rename a table or
  to add a new column to an existing table. It is not possible to rename
  a column, remove a column, or add or remove constraints from a table.

Since you aren't using constraints to your foreign keys, you could create both tables first and then add the foreign keys later with an ALTER TABLE ADD query, which is one of the few alter table commands that comes with SQLite.
CREATE TABLE A(
  ID    INTEGER PRIMARY KEY,
  A_DESCRIPTION    TEXT
)

CREATE TABLE B(
  ID    INTEGER PRIMARY KEY,
  B_DESCRIPTION    TEXT
)

ALTER TABLE A ADD FOREIGN KEY B_ID B(ID)
ALTER TABLE B ADD FOREIGN KEY A_ID A(ID)

If you need to add constraints to your table, this question over here covers it

A: You have a syntax error: there is a comma missing before FOREIGN KEY in table B.
Otherwise, your schema is correct.
(SQLite will interpret the REFERENCES clauses only when needed, so there is no problem creating a reference to a table that does not yet exist.)
Please note that inserting records will be problematic, unless you insert records with NULL values first and update them later when the referenced record exists.
It might be a better idea to create deferred foreign key constraints.

A: I believe I done it before by creating tables in a transaction. If it doesn't work i'll delete this answer.


text:
Q: Results change depending on whether set.seed is specified before or after loading RData file containing .Random.seed I am running an R script that reads an external RData file.  I am attempting to modify that R script to run without using that RData file to improve generality.
I discovered that the results returned by the script differ depending on whether I use a set.seed statement immediately before or immediately after loading the RData file.  I also discovered that the RData file contains a vector called .Random.seed.  Otherwise the RData file only contains data as far as I can tell, not any functions or code.
The mere presence of the .Random.seed vector in the RData file appears to change the results of random number generators (runif, rnorm, etc.) or sample statements in the script that appear after I load the RData file even though I never refer to this .Random.seed vector in the script.
How can I reproduce the results of the script that contains the RData file without actually including the RData file in the script?
load("CPT CAL.RData")
.Random.seed[1:5]
#[1]         403         493 -1955963110 -1150619109   212268921
sample(1:100, 10, replace = TRUE)
#[1] 100  60  76  39   7  57  28  85  89  73

sample(1:100, 10, replace = TRUE)
#[1] 81 89 15  4 60 32 58 71 62 17

sample(1:100, 10, replace = TRUE)
#[1] 18 46 89 66 23 24 24 41 37 70

##################################

# Here I try to reproduce the above results using the first element
# of the .Random.seed vector as a seed but this does not work
set.seed(403)
sample(1:100, 10, replace = TRUE)
#[1] 44 31 23 83 16 27 71 64 13 18

sample(1:100, 10, replace = TRUE)
#[1] 86 54 46 25 65 42 76 49 46 50

sample(1:100, 10, replace = TRUE)
#[1] 44 44 90 39 46 14 41 52 36 63

A: @MrFlick posted a very clear and very helpful explanation for why my original attempt at a solution did not work.
Subsequently I arrived at a solution adequate for my purposes.  I placed a set.seed statement immediately after loading the RData file into the original R script.  I saved the results as my target values.
Then I added the same set.seed statement into my revised version of the R script that never loads the RData file.
Both approaches returned the same results.


text:
Q: Virtual parent for containers and 'iterable' class I was wondering if there was a reason why there's no virtual parent inheritance for all std containers.
Since C++ is oop, I get some reason for using external function as such from algorithm header.
But i wonder why string does not have size() function ( doing the same as length ) for genericity?
Also, why is there no "iterable" class from which would iterables containers inherit ( because of the different types of iterator? )
This one come from my short experience with python. In my opinion, python's biggest strengh is how easy if is to use iterable.
EDIT:
To clarify myself: i know C++ is mutli-paradigm, but i would like to focus on containers. We could have keep C-style using struct and functions, why defining some as methods and others not? For encapsulation only?
Having both sequential and oop means is confusing and illogical i think
Why having begin(vec) and vec.begin() ?
And i speak about iterable, not iterators, and yes, iterator was a class in the std defining an iterface for iterator which is now deprecated ( and i understand why ). So iterators are object, why not doing iterable object ( juste to pack iterator begin and iterator end together if it is not to define virtual parent for iterable containers) ?
I hope i was clearer this time. I already got answer i thought about by myself for the most, but i would prefer an explanation about the current logic in the std.
Thank you for the time taken to read and answer.

A:
I was wondering if there was a reason why there's no virtual parent inheritance for all std containers.

There is a cost attached to this (virtual dispatch is not free!), and most people (all people?) wouldn't need it.
In C++, you don't pay for what you don't use. (In theory.)

i wonder why string does not have size() function ( doing the same as length ) for genericity?

It does.

why is there no "iterable" class from which would iterables containers inherit ( because of the different types of iterator? )

Because we don't need one. You claim that C++ is "oop", but that is not true: it is multi-paradigm, and most of the standard library (particularly the parts inherited from the antique STL) are template based, not object-oriented.
This allows us to provide iterators that fit a set of "requirements", rather than those that fit some definition of "class". For example, pointers (which do not have class type!) are a valid kind of iterator.

This one come from my short experience with python. In my opinion, python's biggest strengh is how easy if is to use iterable.

That's reasonable. But C++ is not Python.

A:
I was wondering if there was a reason why there's no virtual parent inheritance for all std containers.

Design decision at early stages of C++ standard forming. There is no much reason to do that - sure, you would have a nice common interface, but this can be also achieved with consistent standard managing (all containers already do have common set of functions without an explicit interface).
A disadvantage of a common base is that all containers would suddenly need virtual functions, and virtual functions are not free (more expensive at runtime than normal functions).

Since C++ is oop

It's not. C++ is a multiparadigm language. For example, you can have functions outside of any class (unlike Java, which is following OOP paradigm more strictly).

i get some reason for using external function as such from algorithm header.

A follow-up decision after the above. Having global functions accepting generic pair(s) of iterators allows to use any container (even user-defined) with these functions.

But i wonder why string does not have size() function ( doing the same as length ) for genericity?

It does have such a function and it always had. length() is another option, provided for better readability - it's more "English" to ask about length of string than to ask about size of string

Also, why is there no "iterable" class from which would iterables containers inherit ( because of the different types of iterator? ) This one come from my short experience with python. In my opinion, python's biggest strengh is how easy if is to use iterable.

There is one very good reason for that - iterators don't have to be of class type. Pointer type satisfies all of the requirements for RandomAccessIterator, but it is not a class.

A: C++ prefers compile-time polymorphism, suggesting you to use templates instead of virtual calls. Back in the good old days, it was more efficient (virtual calls are still not free).
There is however a certain level of standardization for containers: all of them support iterators, and standardized C++20 ranges are coming as well.


text:
Q: ath10k driver not working, hence wifi adoptor QCA6164 not recognised no additional drivers found except processor microcode firmware for Intel CPU under additional drivers,software and updates,settings. Hence i am not able to update the ath10k driver through settings. is there any way to update ath10k through terminal? and if updating doesn't work what should i do to make Ubuntu 16.04 recognize the WIFI adopter?

A: Follow the procedure from there: https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1436940
and it will work
As a summary, and assuming you are on version 16.04, open a terminal:
 1. sudo rm -r /lib/firmware/ath10k/QCA6174/
 2. cd /tmp ; wget https://github.com/kvalo/ath10k-firmware/archive/master.zip
 3. unzip master.zip ; sudo cp -r ath10k-firmware-master/QCA6174/ /lib/firmware/ath10k/
 4. cd /lib/firmware/ath10k/QCA6174/hw2.1/ ; sudo mv firmware-5.bin_SW_RM.1.1.1-00157-QCARMSWPZ-1 firmware-5.bin
 5. cd /lib/firmware/ath10k/QCA6174/hw3.0/ ; sudo mv
    firmware-4.bin_WLAN.RM.2.0-00180-QCARMSWPZ-1 firmware-4.bin
 6. sudo reboot


text:
Q: What is D and P of a Matrix? Just read something where it says to decompose a vector, say A.
[U S V]=svds(A,2).

Now, the document says to use the D and P of the decomposed vector in some other function. I guess, D is the diagonal elements S. What is P indicate ?
I guess, its a stupid question but I just cant figure it out.

A: One notation that comes to mind is the diagonalization of a real symmetric matrix, usually denoted A = PDP^T. In this case D is a diagnoal matrix of eigenvalues and P can be build from the corresponding eigenvectors
See e.g. http://en.wikipedia.org/wiki/Diagonalizable_matrix


text:
Q: how to get file names exisiting in a folder and put it in Jtable When I run my programme, I get only the first file name repeated as many times as files exist in the chosen folder (as rows).
For example, if I have three files in a folder, file1, file2 and file 3, after running the programme the Jtable will return:
file1
file1
file1

Here is my code:
File files = new File(directory);
File[] listOfFiles = files.listFiles();

DefaultTableModel dtm = new DefaultTableModel();
dtm.getDataVector().removeAllElements();
dtm.fireTableDataChanged();
Vector dataRows = new Vector();
dtm.addColumn("Nom");
for (File  fichier : listOfFiles)
{
  if (fichier.isFile())
  {
    fileNames = fichier.getName();
    if (fileNames.endsWith(".txt") || fileNames.endsWith(".TXT"))
    {
      dataRows.add(fileNames);
      dtm.addRow(dataRows);
    }
  }
}
TblFile.setModel(dtm);

A: Create a new instance of the Vector dataRows for each file, otherwise you're just adding the names as columns

A: I am not that familiar with swing, but try reinitializing the vector for each row, otherwise you are just adding on to the same vector object, which will always have the first entry as your first file
   for (File  fichier : listOfFiles)
   {

     if (fichier.isFile())
     {

       fileNames = fichier.getName();
       if (fileNames.endsWith(".txt") || fileNames.endsWith(".TXT"))

       {
         Vector dataRows = new Vector();
         dataRows.add(fileNames);
         dtm.addRow(dataRows);

       }
    }

  }
 TblFile.setModel(dtm);


text:
Q: How to update MySQL text column with concat with a prepared statement? I am trying to concatenate a text column with UPDATE in my database but I am unable to find any resouces online that explain how to do with a prepared statement. I keep getting an error:

syntax to use near '(admin_notes=?) WHERE id=?' at line 1

UPDATE problem_report SET concat(admin_notes=?) WHERE id=?

A: You are trying to UPDATE the admin_notes column. You need to concat the value not the column itself.
UPDATE problem_report SET admin_notes = concat(admin_notes,?) WHERE id=?


text:
Q: How to trigger animation when routed to the same page with different URL parameter using Angular in Ionic 5 I was trying to to trigger the animation when the page is routed to itself with different url parameter.
For instance, for post/1 url, the animation works fine but if I route to post/2 or post/3, the animation does not work.
I wrote the animation using Ionic Animation and calling the method everytime the route parameter changes. Could anyone please help?
Here's an excerpt from my code
HTML
<ion-icon class="custom-icon" name="chevron-back-outline"></ion-icon>

TS
constructor(private animationController: AnimationController) {
  this.route.params.subscribe((val) => {
    this.animateIcon();
  });
}

animateIcon() {
  this.animationController
    .create()
    .addElement(document.querySelector('.custom-icon'))
    .duration(1500)
    .iterations(3)
    .fromTo('transform', 'translateX(0px)', 'translateX(-80px)')
    .fromTo('opacity', '1', '0')
    .play();
}

A: Try to Put calling function to ionViewWillEnter()
constructor(private animationController: AnimationController) {

}

ionViewWillEnter(){
 this.route.params.subscribe((val) => {
    this.animateIcon();
  });
}

animateIcon() {
this.animationController
    .create()
    .addElement(document.querySelector('.custom-icon'))
    .duration(1500)
    .iterations(3)
    .fromTo('transform', 'translateX(0px)', 'translateX(-80px)')
    .fromTo('opacity', '1', '0')
    .play();
}

A: I have figured it out myself. Instead of capturing the class name using querySelector, I used ElementRef notation to make it work. Now it does work all the time when I route to any of the /post pages.
HTML
<ion-icon #leftIcon class="custom-icon" name="chevron-back-outline"></ion-icon>

TS
@ViewChild('icon1', { read: ElementRef, static: false }) leftIcon: ElementRef;

constructor(private animationController: AnimationController) {
  this.route.params.subscribe((val) => {
    this.animateIcon();
  });
}

animateIcon() {
  this.animationController
    .create()
    .addElement(this.leftIcon.nativeElement)
    .duration(1500)
    .iterations(3)
    .fromTo('transform', 'translateX(0px)', 'translateX(-80px)')
    .fromTo('opacity', '1', '0')
    .play();
}


text:
Q: Addressing relative paths within Google Chrome extension in my Google Chrome extension I'm trying to do an AJAX request using jQuery. This is the code I use:
//send data to the server
$.ajax({
    type: "PUT",
    url: "/addTransaction",
    data: receivedData,
    success: function(data){
        console.log(data);
    }
});

The problem I have is that Chrome tries to access to something like this chrome-extension://jeelhjnbimpcilllldencicbafjdgdon/addTransaction which gives of course an error. I don't want to put absolute paths because it resets the sessions in the server (node.js).
Any clue on how I can solve this? Thanks.


text:
Q: Azure Logic App - Unable to create connection to table storage I created a logic app on a free Azure subscription and now want to publish the logic app in a production environment. Only now I get the following error message when creating a connection to a table storage by using a shared storage key.

I get the same error message when i try to create the connection.

I have the following assignments on my account:

A: Please check whether you configured right access key of storage account while creating Table storage connector in logic apps. Please refer below microsoft doc link
https://learn.microsoft.com/en-us/azure/connectors/connectors-create-api-azureblobstorage

A: It seem you have not given permision to the azure storage table, assign access policy as per the below and it will work.
Table Storage Access Policy

Logic App Connection Setup

Hope this solve your problem


text:
Q: PHP - Auto login to another page How to automatically log on to another site without leaving the current page? Predefined username and password. Hiding fields display only button to logging. After clicking on the button, but not to leave the current site. I am sorry for my English.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="test" content="test">
  <title>Test</title>

<form id="loginForm" name="loginForm" method="post" action="http://www.streamuj.tv/login">

Uživatel:

<input type="text" name="username" size="22" tabindex="3" id="name" class="logintext" />

Heslo:

<input name="password" type="password" class="logintext" id="password" tabindex="4" size="22" />

Zapomněli jste heslo?

<input type="hidden" name="action_login" value="Přihlásit se" />
<input type="image" src="http://www.streamuj.tv/images/login.gif" tabindex="5" class="loginbutton" />

</form>

A: You could add another hidden input that is the URL of the current page. Then your login script can redirect back to the current page
<input name="URL" type="hidden" value="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>">

Just put that in your form.
Finish your login script with a redirect to that post value

A: outcome:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="test" content="test">
  <title>Test</title>

<form id="loginForm" name="loginForm" method="post" action="http://www.streamuj.tv/login">

Uživatel:

<input type="text" name="username" size="22" tabindex="3" id="name" class="logintext" />

Heslo:

<input name="password" type="password" class="logintext" id="password" tabindex="4" size="22" />

Zapomněli jste heslo?

<input type="hidden" name="action_login" value="Přihlásit se" />
<input type="image" src="http://www.streamuj.tv/images/login.gif" tabindex="5" class="loginbutton" />
<input name="URL" type="hidden" value="<?php echo 'http://www.test.cz/test.html' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>">

</form>

Or...?