text:
Q: A Good Use Case for an Consolidated Class in c#? I have 3 classes of conjugation tables - one for nouns, adjectives and verbs. As suggested in the answer to a previous question of mine, it would be greatly beneficial to have a base class for the verbs, and use an Enum to have all the actual conjugation types, so that I could distinguish between instances of the class. The Enum would look like this:
enum VerbConjugationType
{
    IndicativePresent,
    Participle,
    // etc
}

and the VerbConjugation class:
class VerbConjugation
{
    public VerbConjugationType conjugationType { get; set; }
    public string firstPersonSingular { get; set; }
    public string secondPersonSingular { get; set; }
    public string thirdPersonSingular { get; set; }
    public string firstPersonPlural { get; set; }
    public string secondPersonPlural { get; set; }
    public string thirdPersonPlural { get; set; }
    public string present { get; set; }
    public string past { get; set; }
}

However, there is one slight problem - several of the types of verb conjugations don't have the same format, that is to say that IndicativePresent looks like this:
{
  public string firstPersonSingular { get; set; }
  public string secondPersonSingular { get; set; }
  public string thirdPersonSingular { get; set; }
  public string firstPersonPlural { get; set; }
  public string secondPersonPlural { get; set; }
  public string thirdPersonPlural { get; set; }
}

and Participle looks like this:
{
  public string present { get; set; }
  public string past { get; set; }
}

Is there any way to have a single class VerbConjugation that can be instantiated with different sets of data depending on the VerbConjugationType (which would be an Enum)? That is to say, if I instantiate VerbConjugation with VerbConjugationType of IndicativePresent, I want only the data (as shown above) to be members of that instance of the class. Same goes for Participle; only string present and string past should be members of that instance.
Edit: It would be preferable if I could access data members in the following fashion:
VerbConjugation.Indicative.Present.fps (first person singular of indicative present)
and
VerbConjugation.Participle.present (present participle)
Is there a class/organization method that allows me to do this, even with the differences in data members for each conjugation type?
Another edit: Here is the code that I currently have, which might give a hint as to my desired structure - what I have doesn't seem like the right approach though:
class VerbTable
    {
        public char group { get; set; }
        public char auxillary { get; set; }
        public string[] prepositions { get; set; }
        public bool transitive { get; set; }
        public bool pronominal { get; set; }

        /*
         * The subject of the verb determined by the markers:
         * 'fps' (first person singular)
         * 'sps' (second person singular)
         * 'tps' (third person singular)
         * 'fpp' (first person plural)
         * 'spp' (second person plural)
         * 'tpp' (third person plural)
         * 'present' (present tense)
         * 'past' (past tense)
         * and their accompanying conjugations.
         */

        struct IndicativePresent
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct IndicativeSimplePast
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct IndicativePresentPerfect
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct IndicativePastPerfect
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct IndicativeImperfect
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct IndicativePluperfect
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct IndicativeFuture
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct IndicativePastFuture
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }

        struct SubjunctivePresent
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct SubjunctivePast
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct SubjunctiveImperfect
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct SubjunctivePluperfect
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct ConditionalPresent
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct ConditionalFirstPast
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct ConditionalSecondPast
        {
            public string fps { get; set; }
            public string sps { get; set; }
            public string tps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
            public string tpp { get; set; }
        }
        struct ImperativePresent
        {
            public string sps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
        }
        struct ImperativePast
        {
            public string sps { get; set; }
            public string fpp { get; set; }
            public string spp { get; set; }
        }
        struct Infinitive
        {
            public string present { get; set; }
            public string past { get; set; }
        }
        struct Participle
        {
            public string present { get; set; }
            public string past { get; set; }
        }
    }

and this class instance will be a member of the Word class like so
class Word
{
    // ...
    // Can access a specific conjugation with:
    // Word.VerbTable.IndicatifPresent.fps;
    public VerbTable verbTable { get; set; }
}

A: Nope.  Don't do this.  Make an abstract base class for Verb:
abstract class Verb
{
   // You can add in any properties that all Verbs share
}

Then create a IndicativePresent class:
class IndicativePresent : Verb
{
  public string firstPersonSingular { get; set; }
  public string secondPersonSingular { get; set; }
  public string thirdPersonSingular { get; set; }
  public string firstPersonPlural { get; set; }
  public string secondPersonPlural { get; set; }
  public string thirdPersonPlural { get; set; }
}

And a Participle class:
class Participle : Verb
{
  public string present { get; set; }
  public string past { get; set; }
}

Both types will derive from Verb, so you'll be able to tell each is a verb, however they'll both have different sets of properties.  You'll no longer need the VerbConjugationType type, as you can simply look at the type of the object:
var ip = new IndicativePresent();
var par = new Participle();

(ip is Verb)              // True
(par is Verb)             // True
(ip is IndicativePresent) // True
(par is Participle)       // True

A: I think what you want, in the end, is a Dictionary<whicheverenum, string> rather than a class of data elements.
Lets say we have a verb conjugation which has an IndicativePresent tense:
var verb = new Dictionary<IndicativePresent, string>();
if(current == VerbConjugationType.IndicativePresent)
{
  verb[IndicativePresent.FirstPersonSingular] = "whatever";
  ...
}

This is all the code you'd need, other than the enum definitions. It's starting to sound like you may actually want a structure of nested dictionaries or even multidimensional arrays (or jagged, more likely). You may be able to get away with either, because enums are integral types. Ultimately, the structure is going to be very complicated, especially if you want the level of chaining you've recently indicated.
You may end up with something like verb[ConjugationType.Indicative][Tense.Present][Target.FirstPerson][Number.Singular] = "something"; at worst case, at which point designing classes may start to look like a good idea again. The more complicated your data, the harder it is to represent, and few types of data are more complex than grammar.

A: The most efficient way would be to move your VerbConjugation class members down to a derived VerbConjugationWithPersons class. Participle and Imperative should derive from the former and not the latter.
EDIT: I meant the "persons" class members, of course. :)

A: It's not possible, but you can use inheritance.
abstract class VerbConjugation {}
class StandardConjugation : VerbConjugation {
  public string firstPersonSingular { get; set; }
  public string secondPersonSingular { get; set; }
  public string thirdPersonSingular { get; set; }
  public string firstPersonPlural { get; set; }
  public string secondPersonPlural { get; set; }
  public string thirdPersonPlural { get; set; }
}
class IndicativePresent : StandardConjugation {}
class IndicativeSimplePast : StandardConjugation {}
class IndicativePresentPerfect : StandardConjugation {}
class Imperative : VerbConjugation
{
    public string secondPersonSingular { get; set; }
    public string firstPersonPlural { get; set; }
    public string secondPersonPlural { get; set; }
}
class ImperativePast: Imperative {}
class ImperativePresent: Imperative {}
class Participle : VerbConjugation
{
  public string present { get; set; }
  public string past { get; set; }
}


text:
Q: Only use button every few seconds in Unity I am trying to make it so that a button in Unity that can only be pressed and activated every few seconds. I have an array with famous quotes and when I press my button it does display these quotes, but if you press the button continuously then it will cycle through all of the quotes without the ability to be thoughtful and read through them. Now, I have tried something like below, but it did nothing (as in the button still was able to be pressed and no effect was apparent):
Bool pressed;

void Function () {

   if (pressed) {
    //code to call array
     }
  }

I thought that a simple combination of bool and an if loop would be sufficient, but this does not work. Am I close to this concept? What would need to be changed to get this operating?

A: There are a few things you can do to achieve this. Your current code is never toggling the bool pressed. You can just catch the unwanted button presses with a localized bool like you are doing now, but there might be a better approach.
I would consider changing the intractability of the button to also show the end-user that they can not press the button for a short amount of time.
using UnityEngine.UI;

// button that will be pressed
[SerializeField] private Button btn = null;

// time until the button is re-enabled after being pressed
private float timeToWait = 5f;

// reference to the coroutine that toggles our button
private Coroutine buttonDisabled = null;

private void Start()
{
    // you can either add the OnClick in the inspector, or you can programmatically add it here
    btn.onClick.AddListener(ClickButton);
}

public void ClickButton()
{
    // if we have an ongoing coroutine do not start another
    if(buttonDisabled != null)
        return;

    // start our coroutine to re-enable the button
    buttonDisabled = StartCoroutine(DisableButtonForSeconds(timeToWait));

    // put any other code needed here such as displaying a new quote
}

private IEnumerator DisableButtonForSeconds(float seconds)
{
    // disable the button
    btn.interactable = false;

    // wait for our amount of time to re-enable
    yield return new WaitForSeconds(seconds);

    // re-enable the button
    btn.interactable = true;

    // reset our reference to be called again
    buttonDisabled = null;
}

Assign the button in the editor to btn and set whatever time you want to wait between button presses for timeToWait. You will also need to assign the button's OnClick to ClickButton, either in code or in the inspector. With this solution the function will not be able to be called as the button itself will be grayed out and not be able to be clicked. After the timeToWait duration is over, the button will reactivate. Place whatever other code you need in the ClickButton method that drives your quote cycling.
Edit: Here is similar code but using an Invoke instead of Coroutine as requested
using UnityEngine.UI;

// button that will be pressed
[SerializeField] private Button btn = null;

// time until the button is re-enabled after being pressed
private float timeToWait = 5f;

private void Start()
{
    // you can either add the OnClick in the inspector, or you can programmatically add it here
    btn.onClick.AddListener(ClickButton);
}

public void ClickButton()
{
    // do not start the function if we are already in the process
    if (IsInvoking("ReEnableButton"))
        return;

    // disable our button interactability
    btn.interactable = false;

    // call our function ReenableButton in timeToWait seconds
    Invoke("ReEnableButton", timeToWait);
}

private void ReEnableButton()
{
    // re-enable the button
    btn.interactable = true;
}

Edit 2: There are a few ways you can go about having one button disable all four buttons. In general practice, you do not want these buttons knowing about each other, so it would be a good idea to make a button manager that handles the OnClick now and sends the event to all Buttons it knows about.
using UnityEngine.UI;

public class ButtonManager : MonoBehaviour
{
    // assign these button references in the inspector by dragging them into the list
    [SerializeField] private List<YourButtonScript> YourButtons = new List<YourButtonScript>();

    private void Start()
    {
        // assign the onClick of each button here INSTEAD of the Start() in the button class
        // you can still have an onClick in the Button itself, but do NOT have it do the disabling

        foreach(YourButtonScript btn in YourButtons)
        {
            // assign our onClick to callback to disable all buttons
            btn.SetDisableOnclick(DisableAllButtons);
        }
    }

    public void DisableAllButtons()
    {
        foreach(YourButtonScript btn in YourButtons)
            btn.DisableButton();
    }
}

public class YourButtonScript : MonoBehaviour
{
    using UnityEngine.UI;

    // button that will be pressed
    [SerializeField] private Button btn = null;

    // time until the button is re-enabled after being pressed
    private float timeToWait = 5f;

    // reference to the coroutine that toggles our button
    private Coroutine buttonDisabled = null;

    public delegate void DisableButtonCallback();

    public void SetDisableOnclick(DisableButtonCallback callback)
    {
        // add the callback to the manager
        btn.onClick.AddListener(delegate{callback();});
    }

    private void Start()
    {
        // do NOT call the ClickButton anymore from here as the manager handles it
        // if you have other button specific data put it in HandleSpecificButtonQuoteData() now
        btn.onClick.AddListener(HandleSpecificButtonQuoteData);
    }

    private void HandleSpecificButtonQuoteData()
    {
        // put whatever code here that is specific to JUST this button
        // if it handles the quotes or what not, display it here
    }

    public void DisableButton()
    {
        // if we have an ongoing coroutine do not start another
        if(buttonDisabled != null)
            return;

        // start our coroutine to re-enable the button
        buttonDisabled = StartCoroutine(DisableButtonForSeconds(timeToWait));
    }

    private IEnumerator DisableButtonForSeconds(float seconds)
    {
        // disable the button
        btn.interactable = false;

        // wait for our amount of time to re-enable
        yield return new WaitForSeconds(seconds);

        // re-enable the button
        btn.interactable = true;

        // reset our reference to be called again
        buttonDisabled = null;
    }
}

Let me know if you have issues with this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Execute Terminal commands from Firemonkey (Android) Just as the question says, can you run terminal commands from a Firemonkey application on Android? Also, if possible, can you retrieve the output?
Some code would be nice as I can't find anything on this...
PS: rooting is not a problem.
Thanks for your help!


text:
Q: Opening multiple file in GrADS Hopefully this question is simple and easy enough to be solved.
I am having a trouble in opening the second file in GrADS. Suppose I have two files. The first is "sst06.ctl" and the second is "sst07.ctl", and within each files, there is only one variable named "sst"
Below are what happened when I tried opening both of them together:
ga-> open sst06.ctl
Scanning description file:  sst06.ctl
Data file rcp4.5/y2006/sst is open as file 1
LON set to 0 360
LAT set to -89.5 89.5
LEV set to 1000 1000
Time values set: 2006:1:1:0 2006:1:1:0
E set to 1 1
ga-> q file
File 1 :
  Descriptor: sst06.ctl
  Binary: rcp4.5/y2006/sst
  Type = Gridded
  Xsize = 360  Ysize = 180  Zsize = 37  Tsize = 365  Esize = 1
  Number of Variables = 1
     sst  0  99  sea surface temperature [K]
ga-> d sst
Contouring: -0 to 30 interval 3
ga-> c
ga-> open sst07.ctl
Scanning description file:  sst07.ctl
Data file rcp4.5/y2007/sst is open as file 2
ga-> d sst.2
Data Request Warning:  Request is completely outside file limits
  Entire grid contents are set to missing data
  Grid limits of file:     X = 1 360  Y = 1 180  Z = 1 37  T = 1 365  E = 1 1
  Grid limits of request:  X = 0 361  Y = 1 180  Z = 1 1  T = -364 -364  E = 1 1
  Warning issued for variable = sst.2
Cannot contour grid - all undefined values

Basically, I cannot plot the second file (sst07.ctl) and it produced "entire grid undefined" plot. Of course one might suspect that there is something wrong with the file "sst07.ctl". However if I only open "sst07.ctl" file alone, there is no problem as it can be successfullty contoured as it was with the "sst06.ctl" file previously. Below is the message:
ga-> reinit
No hardcopy metafile open
All files closed; all defined objects released;
All GrADS attributes have been reinitialized
ga-> open sst07.ctl
Scanning description file:  sst07.ctl
Data file rcp4.5/y2007/sst is open as file 1
LON set to 0 360
LAT set to -89.5 89.5
LEV set to 1000 1000
Time values set: 2007:1:1:0 2007:1:1:0
E set to 1 1
ga-> q file
File 1 :
  Descriptor: sst07.ctl
  Binary: rcp4.5/y2007/sst
  Type = Gridded
  Xsize = 360  Ysize = 180  Zsize = 37  Tsize = 365  Esize = 1
  Number of Variables = 1
     sst  0  99  sea surface temperature [K]
ga-> d sst
Contouring: -0 to 30 interval 3

The same error happened if I change the order of file opening (sst07.ctl first). The "sst06.ctl" file that is opened as the second file would result in an entire grid undefined message for the latter opened file. Below is the message:
ga-> reinit
ga-> open sst07.ctl
Scanning description file:  sst07.ctl
Data file rcp4.5/y2007/sst is open as file 1
LON set to 0 360
LAT set to -89.5 89.5
LEV set to 1000 1000
Time values set: 2007:1:1:0 2007:1:1:0
E set to 1 1
ga-> q file
File 1 :
  Descriptor: sst07.ctl
  Binary: rcp4.5/y2007/sst
  Type = Gridded
  Xsize = 360  Ysize = 180  Zsize = 37  Tsize = 365  Esize = 1
  Number of Variables = 1
     sst  0  99  sea surface temperature [K]
ga-> d sst
Contouring: -0 to 30 interval 3
ga-> c
ga-> open sst06.ctl
Scanning description file:  sst06.ctl
Data file rcp4.5/y2006/sst is open as file 2
ga-> q file
File 1 :
  Descriptor: sst07.ctl
  Binary: rcp4.5/y2007/sst
  Type = Gridded
  Xsize = 360  Ysize = 180  Zsize = 37  Tsize = 365  Esize = 1
  Number of Variables = 1
     sst  0  99  sea surface temperature [K]
ga-> d sst.2
Data Request Warning:  Request is completely outside file limits
  Entire grid contents are set to missing data
  Grid limits of file:     X = 1 360  Y = 1 180  Z = 1 37  T = 1 365  E = 1 1
  Grid limits of request:  X = 0 361  Y = 1 180  Z = 1 1  T = 366 366  E = 1 1
  Warning issued for variable = sst.2
Cannot contour grid - all undefined values

Anybody willing to help me with this? Thanks before!
EDIT1: Response to Ngoan Tran's post
This is the result of your suggestion.
ga-> reinit
No hardcopy metafile open
All files closed; all defined objects released;
All GrADS attributes have been reinitialized
ga-> open sst07.ctl
Scanning description file:  sst07.ctl
Data file rcp4.5/y2007/sst is open as file 1
LON set to 0 360
LAT set to -89.5 89.5
LEV set to 1000 1000
Time values set: 2007:1:1:0 2007:1:1:0
E set to 1 1
ga-> d sst
Contouring: -0 to 30 interval 3
ga-> open sst06.ctl
Scanning description file:  sst06.ctl
Data file rcp4.5/y2006/sst is open as file 2
ga-> set dfile 2
Default file set to: rcp4.5/y2006/sst
ga-> d sst
Data Request Warning:  Request is completely outside file limits
  Entire grid contents are set to missing data
  Grid limits of file:     X = 1 360  Y = 1 180  Z = 1 37  T = 1 365  E = 1 1
  Grid limits of request:  X = 0 361  Y = 1 180  Z = 1 1  T = 366 366  E = 1 1
  Warning issued for variable = sst
Cannot contour grid - all undefined values
ga->

Any ideas?

A: In order to handle multiple files at the same time, you have to change the descriptor file by using set dfile <file-number>. file-number is the order of files you opened.
In your case:

*

*After reinit (it reset all your configuration) you open sst07.ctl ,so sst07.ctl is file 1 and will be used as default. And when you run command d sst, GrADS will draw data of sst from sst07.ctl file.

*Then you open sst06.ctl, sst06.ctl will be file 2 and to use it you have to change the descriptor file by set dfile 2. And when you run command d sst, GrADS will draw data of sst from sst06.ctl file.
Try it.

A: Looking at the output from the plot call from your second opened file you are requesting data beyond the available time and partially outside the horizontal domain:
 Grid limits of file:     X = 1 360  Y = 1 180  Z = 1 37  T = 1 365  E = 1 1
 Grid limits of request:  X = **0 361**  Y = 1 180  Z = 1 1  T = **366 366**  E = 1 1

In GrADS the environment axes (X, Y, Z, T, E) are set relative to the first file you open. In your case the time and part of the horizontal domain are not the same (the x axis in the 2nd file has 2 more points) in both of your files, so you need to set the environment relative to the first file's constraints to plot from the second. Before you issue your second plot call you need to set the environment to (or a subset of) the second file but relative to the first file:
set lon 0 361
set lat 1 180
set t 366

or (better)
set time 00z01Jan2006;* <--- I've guessed at data dates here

It is usually better to close each file after use unless you are trying to plot a continuous output from both files as it can get confusing.


text:
Q: ld: can't link with a main executable file for architecture i386 error I want to add unit test target to my Xcode project which consist of lots of sub-projects. I'm adding test target to my main project. After I add it, I can't build it from test target (I can successfully build app target, just can't build test target).
Some settings are not default;
Build Active Architecture Only -> Yes (On my main target)
Test Target iOS Deployment Target -> 10.3

I'm getting below error

ld: can't link with a main executable file '/Users/emreonder/Library/Developer/Xcode/DerivedData/MyAppWorkspace-gdwblguzoliffpbypfnfrxayzvpe/Build/Products/Debug-iphonesimulator/MyApp.app/MyApp' for architecture i386
  clang: error: linker command failed with exit code 1 (use -v to see invocation
  Linker command failed with exit code 1 (use -v to see invocation)

I'm using Xcode 11.


text:
Q: EditText appears in Design but not in the real apk This is the activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
>

<TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Text:"
   />

<EditText
    android:layout_toRightOf="@id/label"
    android:layout_toEndOf="@id/label"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:hint="type ur text here"
    android:layout_alignBaseline="@id/label"

    />
</RelativeLayout>

In the Design, on Android Studio, both the TextView and the EditText can be seen, but after compiling only the TextView is visible.
Why?
Screenshots
Design:

Apk:

Thanks
Styles.xml:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

</resources>

A: Try this code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text:"
        />

    <EditText
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="type ur text here"
        />
</LinearLayout


text: Q: saw extension=php_curl.dll already enabled in php.ini I just installed PHP 5.5.12 which comes with WAMP server. I am trying to enable curl but after reading various posts like this one, I already see that extension=php_curl.dll is already uncommented. I am attaching the screenshot below showing the same. I am wondering, is it something which is coming uncommented from the recent version of WAMP server these days?


text:
Q: Cakephp 2.8.4 ignoring hasMany This is a very odd issue that I have not been able to figure out for a very long time.
I have a model Upload, with several hasMany all being ignored by UploadModel.
For example. Upload hasMany Face.
On comments table I have a field called foreign_key that hosts the Upload.id.
So the relationship in UploadModel looks like this:
$hasMany = ['Face' => ['foreignKey' => 'Face.upload_id']];

When performing a find in Upload with contain Face + conditions [Face.celebrity_id = 4018] I get the following error because the query is missing the Left Join to Face:
$media = $this->Upload->find('all',array(
        'conditions' => array(
            'Face.celebrity_id' => 4018
        ),
        'contain' => array(
            'Face'
        )
    ));

SQL Query:
SELECT `Upload`.`id`, `Upload`.`user_id`, `Upload`.`filename`, `Upload`.`created`
FROM `uploads` AS `Upload`
WHERE `Face`.`celebrity_id` = 4018;

SQL Error:
Unknown column 'Face.celebrity_id' in 'where clause'

As you can see the query is missing the left joing to Face, that's all the problem
If instead of in the $hasMany, I add the Face relationship in $belongsTo, it adds the relationship to the query and it works!
But an Upload can have many Faces, and Face.upload_id  has the foreignKey to Upload, so IT NEEDS TO BE A motherf***** HASMANY... lol

As you can see, this is terrible, I am already desperate, I have bypassed the issue by adding a bindModel() before each query, but it is totally unnecessary, the hasMany should work!!!!   f****!!!!!
The query that I want Cake to perform for me is this:
SELECT `Upload`.`id`, `Upload`.`filename` FROM `uploads` AS `Upload`
LEFT JOIN `upload_faces` AS `Face` ON (`Upload`.id = `Face`.`upload_id`)
WHERE `Face`.`celebrity_id` = 4018

I appreciate any help, thanks.

A: ok, so basically, it is not ignoring the hasMany, but I can not use conditions on a hasMany relationship, can only be done if it is a hasOne

A: In your test() function, you run query on upload table. So it can not match Face.celebrity_id field from your query. Two things you have know first:

*

*Condition you are writing in conditions clause is applied on the table matching with your model. In your case, upload is the table on which query is executed and your table contains no field Face.celebrity_id.

*$hasMany creates application level relations(associations). So by doing query like you have written in test() function, it doesn't join the query results.

What you can do is,
$this->find('all', array(
    'contain' => array(
    'Face' => array('conditions' => 'Face.celebrity_id = 4018'))))

This will return all rows of upload table with associated row of face table if celebrity_id is 4018, otherwise null array.
Hope this will help you and if you want that only those many rows will be returned which are associated with Face.celebrity_id = 4018, first you have to run query on face table and then another on first query result.
For more detail of second case you can refer this.


text:
Q: Transform python `cycle` to `list` Is there a way to transform cycle from itertools into list? Applying list(my_cycle) freezes my computer.
I would like to periodically switch between a collection of objects infinitely. They are stored in a cycle. If one of my objects become 'inactive' I would like to delete it from cycle. I solved it with another list with inactive objects but it looks like bad workaround.

A: No, you can not, because a cycle is an infinite sequence.  Your computer "freezes" because Python is trying to iterate a never-ending collection of items (if you left it long enough, the process would run out of memory and crash).
What you can do, is collect a predetermined finite amount of the items into a list:
n = 10  # some fixed size
results = []
for i in range(n):
    results.append(next(my_cycle))

There is no general way to know how many items to consume to get one pass through a cycle, because the cycle object does not expose any state about the period of the underlying iteration, i.e. how many items were iterated before repeating.
There is no public way to modify the items returned from a cycle once the first StopIteration from the original iterator has been encountered, they are all buffered to private memory somewhere:
>>> L = [0,1,2]
>>> g = itertools.cycle(L)
>>> next(g)
0
>>> L.remove(1)
>>> next(g)
2
>>> next(g)
0
>>> L.remove(2)
>>> next(g)
2

For cycling a mutable sequence, as an alternative design choice you could consider using a collections.deque instance as your data structure (the rotate method is efficient).

A: If your set of all object (active and inactive) never changes, and especially if transitions between active and inactive state are common, the total number of objects isn't outrageous or the set of inactive objects doesn't usually cover most of the total set, cycle would still work fairly well here, by keeping a set of inactive objects around and filtering out currently inactive objects "live":
from itertools import cycle, filterfalse

allobjects = [...]
numuniqueobjects = len(set(allobjects))
inactiveobjects = set()

# Each time we request an item, filterfalse pulls items from the cycle
# until we find one that isn't in our inactive set
for object in filterfalse(inactiveobjects.__contains__, cycle(allobjects)):

    # ... do actual stuff with object ...

    # Any objects that should go active again get removed from the set and will be
    # seen again the next time their turn comes up in the original order
    inactiveobjects -= objects_that_should_become_active()

    # Won't see this object again until it's removed from inactiveobjects
    if object.should_go_inactive():
        inactiveobjects.add(object)
        if len(inactiveobjects) == numuniqueobjects:
            # Nothing is active, continuing loop would cause infinite loop
            break

Advantages to this design are that:

*

*It makes it cheap to activate and deactivate objects

*It preserves original iteration order indefinitely (if an object was originally in position 4, when it goes inactive it is skipped, and when it goes active again, it reappears after position 3 and before position 5 the next time you cycle through)

The main downside is that it adds a tiny bit more overhead to the "nothing is changing" case, especially if the set of inactiveobjects grows to an appreciable fraction of the total number of objects; you still have to cycle all objects even if filter out many of them.
If that doesn't suit your use case, a custom version of cycle built on a deque as suggested by wim is probably the best general purpose solution:
from collections import deque
from collections.abc import Iterator

class mutablecycle(Iterator):
    def __init__(self, it):
        self.objects = deque(it)
        self.objects.reverse() # rotate defaults to equivalent of appendleft(pop())
                               # reverse so next item always at index -1

    def __next__(self):
        self.objects.rotate() # Moves rightmost element to index 0 efficiently
        try:
            return self.objects[0]
        except IndexError:
            raise StopIteration

    def removecurrent(self):
        # Remove last yielded element
        del self.objects[0]

    def remove(self, obj):
         self.objects.remove(obj)

    def add(self, obj, *, tofront=True):
        if tofront:
            # Putting it on right makes it be yielded on next request
            self.objects.append(obj)
        else:
            # Putting it on left makes it appear after all other elements
            self.objects.appendleft(obj)

Use would be:
mycycle = mutablecycle(allobjects):
for object in mycycle:
    # ... do stuff with object ...

    if object.should_go_inactive():
        mycycle.removecurrent()  # Implicitly removes object currently being iterated


text:
Q: Can't add image. when I run this process, it's not show. just show a image icon Can't add image. When I run this process, it's not showing. Just shows an image icon.

A: Add the image to your project folder and use relative paths. For example, create an images folder in the root folder and add your image inside of it an try to access it like this : src="./images/you-image.jpg"

A: Put the image in the same folder as the HTML file, and use the path like this instead of how you have it:

A: You must write like this: src="../images/example.jpg"
.. mean 'one folder back'. How many folder back u need, put some ../../../ like this.


text:
Q: Accept URL as parameter in path (special characters) I have a view and a path where I'd like to accept a str parameter and pass it to my make_request view.
The problem I'm having is the strings I'd like to accept are URLs. When I pass a string like 'https://example.com/' I get an error saying Page not found (404) as there are special characters.
urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('<str:url>', views.make_request, name='make_request'),
]

views.py
def make_request(url):
    print(url)

A: I ended up figuring this out.
The solution was to use the path converter.
urlpatterns = [
    path('<path:url>', views.make_request, name='make_request'),
]


text:
Q: DX11 sprite troubles I'm having trouble rendering a sprite in dx11, I've just started with the basics. Here is my simple shader code:
//Shader Model 4.0
//Default shaders for rendering a point sprite

Texture2D DiffuseTexture : register( t0 );

SamplerState DiffuseTextureSampler : register( s0 );

cbuffer cbViewProj : register( b0 )
{
    float3x3 ViewProjection;
}

struct VS_INPUT
{
    float2 Pos : POSITION;
    float2 Tex : TEXCOORD0;
};

struct PS_INPUT
{
    float4 Pos : SV_POSITION;
    float2 Tex : TEXCOORD0;
};

PS_INPUT VS( VS_INPUT input )
{
    PS_INPUT output;
    float3 oVec = float3(input.Pos.x, input.Pos.y, 1.0f);
    oVec = mul(oVec, ViewProjection);

    output.Pos = float4(oVec.x, oVec.y, 0.0f, 1.0f);
    output.Tex = input.Text;

    return output;
}

float4 PS( PS_INPUT input) : SV_Target
{
    return DiffuseTexture.Sample( DiffuseTextureSampler, input.Tex );
}

As you can see it has the bare minimum, not even a world matrix to move the sprite yet. My "ViewProjection" matrix is a 2D orthographic matrix. I used this setup with directx9 and everything worked fine.
Moving into dx11 I'm having trouble. I believe there is something wrong with the way I'm setting my ViewProjection matrix or how it is being read in the shader.
First I used PIX to check my vertex buffer / the order the vertices were entering the vertex shader:

So that seemed fine. Next I added the viewprojection matrix to project the verticies into screen space, as shown in the shader code I posted. The result...

So as you can see, the vertices are not projecting correct. For starters:

*

*prim0vert0 = prim0vert1

*prim1vert4 = prim1vert5

This doesn't make sense to me since there are different vertex values being processed. You can tell the vertices are entering in the same order as my initial testing by looking at the UV coords.
This is how my 3x3 viewprojection matrix buffer looks:

I manually wrote over the top what matrix row/column the buffer values correspond with. The three values at the bottom are just padding to ensure my buffer size is in multiples of 16. So... like in directx:

*

*m00 = matrix row1, column1

*m01 = matrix row1, column2

*etc

The red values on the right represent how my ViewProjection matrix accesses the buffer in the hlsl code.
For some reason it is treating it as a float4x4? Could that be me problem... or am I wayyyy of track in solving my problem
-UPDATE-
I've done a bit of research and am now working under the assumption the float3x3 becomes fragmented when being stored in the registers (as it is packed in groups of 4 floats).
Now it seems even if my application is completely 2D I should still use a 4x4 matrix due to this annoying behavior. Is this correct, or is there some workaround I am unaware of?

A: Modern graphics hardware is designed/optimized to work with 4x4 byte vectors, that's 4 floating point values. Even when you use float3 vector, internally it's still taking up a single register that holds float4.
For vector math to work properly, each point has to start at address that is 16 byte aligned, which is a problem when you have float3xN, cause 2nd point in would start at byte 12
So you have to pad your data to 16 byte alignment. Try using float4x3. Internally, your float3x3 operations will still take up space of float4x3


text:
Q: Global error page in JBoss7 I just want to override the HTTP 404 error page in Jboss7.
I have tried ,
<error-page>
       <error-code>404</error-code>
       <location>/NotFound.jsp</location>
</error-page>

But, until unless my application got up, I cannot see the page for 404 status code.
I need to have to have an error page while jboss got up and deploying my application, mean time if anybody tries to access my application , need to show them customize error page.
Could anybody help me out ?
Thanks in advance.


text:
Q: Where live struct with reference type as a property I've created struct with static array of reference type and property which take object from that array by unique id stored in struct - but i don't know it make any sense, i want to store struct on the stack.
struct TestStruct
{
 static TestClass[] Instances = new TestClass[16];
 int uid; //max value = 15
 TestClass Instance
 {
  get { return Instances[uid]; }
 }
}

A: The struct itself will be stored on the stack.
TestClass is your Reference Type. No matter what you do, those are going to be stored on the heap. In this case Instances is a static array on the heap.

A: Okay, so Instances is a static variable - so that will be on the heap. Likewise the array itself is a reference type, so that's going to be on the heap.
Only the uid variable is actually part of the value for a particular TestStruct, and that will be on the heap or on the stack depending on the context.
It's all an implementation detail though... what are you really trying to achieve?


text:
Q: How to access to entity field by attribute name in core data I have entity with attribute id.
I seen example:
var appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        var context:NSManagedObjectContext = appDel.managedObjectContext!
      var request = NSFetchRequest(entityName: "myentity")
      request.returnsObjectsAsFaults = false
      if let results = context.executeFetchRequest(request, error: nil) {
      if results.count > 0 {
                for result: AnyObject in results {
                    println(result.id)
                }
      }

But for me it return error:'AnyObject' does not have a member named 'id'
How can I do it in last version Xcode in swift?

A: Make an NSManagedObject Subclass. Once you have done this you can access the attributes using dot syntax rather than using object for key. Apple's documentation on NSManagedObject can be found here and information about creating the subclass here. Then in your for loop you cast the object as your managed object subclass type.
var error: NSErrorPointer = nil
if !fetchedResultController.performFetch(error)
{
    println("Unresolved error: \(error), \(error.debugDescription)")
}

let results = fetchedResultController.fetchedObjects as [YourSubclass]

for result in results {
    println(result.id)
}


text:
Q: PHP Field Entry On Change With Apostrophe I have the following form where when the user selects an option from the <select> the javascript enters it into the "name" field.  It's working perfectly except when the option contains an apostrophe it truncates it to only before the apostrophe.  I've tried adding the selectedValue = selectedValue.replace(/'/g, \"\\'\"); to the javascript but it is not helping.  Any advice would be appreciated.
#related form objects
echo "

Name: <input type=\"text\" name=\"name\" id=\"name\" value=\"$name\" size=\"50\">";

  echo "
Nearby Suggestions: <select name='nearby' id='nearby'>"; $places=file_get_contents('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='.$lat.','.$long.'&key=xxx&radius=80');
  $output= json_decode($places,true);
  foreach($output['results'] as $place){
    echo "<option value='$place[name]'>$place[name]</option>";
  }
  echo "</select>";

  #script to enter nearby field into name field upon selection
  echo "
";

A: You aren't escaping the values that come from your googleapis call.  So when you blindly load a value like Jim's Place into your <option> tag, the resulting code is:
<option value='Jim's Place'>Jim's Place</option>

which contains 3 apostrophes and is broken.  Convert the values first.
foreach($output['results'] as $place){
  $place_converted = htmlspecialchars($place['name'], ENT_QUOTES);
  echo "<option value='$place_converted'>$place_converted</option>
}

which correctly generates:
<option value='Jim's Place'>Jim's Place</option>

A: echo "<option value='$place[name]'>$place[name]</option>";

results in mismatched quotes.  Try replacing it with
echo "<option value=\"$place[name]\">$place[name]</option>";

You can escape your double quotes that wrap the value.


text:
Q: Export data from Access 2010 to Excel 2013 i am exporting data from Access to Excel using recordset to transfer data from access query to excel(as I have to manual formatting which cannot be done with transferSpreadsheet) and while i am using the code
with sheet1
.range("A2").CopyRecordset rs1
End With

This works fine till 3 sheets but when I initiate 4th sheet (as Excel has 3 sheets by default)
Set sheet4 = wb.Worksheets.Add

I am getting an error saying

Subscript out of range error.

Can someone help me out with the same?

A: Which line errors - adding the worksheet?
Code works for me:
Set Sheet4 = Sheets.Add
Maybe post your full procedure for analysis.

A: Without seeing the code it's impossible to say for sure.  Maybe a worksheet name is misspelled.  Just a guess.  Try the code samples below for some different ways of how to do this kind of task.
'************* Code Start *****************
'This code was originally written by Dev Ashish
'It is not to be altered or distributed,
'except as part of an application.
'You are free to use it in any application,
'provided the copyright notice is left unchanged.
'
'Code Courtesy of
'Dev Ashish
'
Sub sCopyFromRS()
'Send records to the first
'sheet in a new workbook
'
Dim rs As Recordset
Dim intMaxCol As Integer
Dim intMaxRow As Integer
Dim objXL As Excel.Application
Dim objWkb As Workbook
Dim objSht As Worksheet
  Set rs = CurrentDb.OpenRecordset("Customers", _
                    dbOpenSnapshot)
  intMaxCol = rs.Fields.Count
  If rs.RecordCount > 0 Then
    rs.MoveLast:    rs.MoveFirst
    intMaxRow = rs.RecordCount
    Set objXL = New Excel.Application
    With objXL
      .Visible = True
      Set objWkb = .Workbooks.Add
      Set objSht = objWkb.Worksheets(1)
      With objSht
        .Range(.Cells(1, 1), .Cells(intMaxRow, _
            intMaxCol)).CopyFromRecordset rs
      End With
    End With
  End If
End Sub

Sub sCopyRSExample()
'Copy records to first 20000 rows
'in an existing Excel Workbook and worksheet
'
Dim objXL As Excel.Application
Dim objWkb As Excel.Workbook
Dim objSht As Excel.Worksheet
Dim db As Database
Dim rs As Recordset
Dim intLastCol As Integer
Const conMAX_ROWS = 20000
Const conSHT_NAME = "SomeSheet"
Const conWKB_NAME = "J:\temp\book1.xls"
  Set db = CurrentDb
  Set objXL = New Excel.Application
  Set rs = db.OpenRecordset("Customers", dbOpenSnapshot)
  With objXL
    .Visible = True
    Set objWkb = .Workbooks.Open(conWKB_NAME)
    On Error Resume Next
    Set objSht = objWkb.Worksheets(conSHT_NAME)
    If Not Err.Number = 0 Then
      Set objSht = objWkb.Worksheets.Add
      objSht.Name = conSHT_NAME
    End If
    Err.Clear
    On Error GoTo 0
    intLastCol = objSht.UsedRange.Columns.Count
    With objSht
      .Range(.Cells(1, 1), .Cells(conMAX_ROWS, _
          intLastCol)).ClearContents
      .Range(.Cells(1, 1), _
        .Cells(1, rs.Fields.Count)).Font.Bold = True
      .Range("A2").CopyFromRecordset rs
    End With
  End With
  Set objSht = Nothing
  Set objWkb = Nothing
  Set objXL = Nothing
  Set rs = Nothing
  Set db = Nothing
End Sub

Sub sCopyRSToNamedRange()
'Copy records to a named range
'on an existing worksheet on a
'workbook
'
Dim objXL As Excel.Application
Dim objWkb As Excel.Workbook
Dim objSht As Excel.Worksheet
Dim db As Database
Dim rs As Recordset
Const conMAX_ROWS = 20000
Const conSHT_NAME = "SomeSheet"
Const conWKB_NAME = "c:\temp\book1.xls"
Const conRANGE = "RangeForRS"

  Set db = CurrentDb
  Set objXL = New Excel.Application
  Set rs = db.OpenRecordset("Customers", dbOpenSnapshot)
  With objXL
    .Visible = True
    Set objWkb = .Workbooks.Open(conWKB_NAME)
    On Error Resume Next
    Set objSht = objWkb.Worksheets(conSHT_NAME)
    If Not Err.Number = 0 Then
      Set objSht = objWkb.Worksheets.Add
      objSht.Name = conSHT_NAME
    End If
    Err.Clear
    On Error GoTo 0
    objSht.Range(conRANGE).CopyFromRecordset rs
  End With
  Set objSht = Nothing
  Set objWkb = Nothing
  Set objXL = Nothing
  Set rs = Nothing
  Set db = Nothing
End Sub
'************* Code End *****************


text:
Q: What is the correct cache size to prevent tomcat log from getting flooded with cache warning messages I am running Apache Tomcat/9.0.19 and recently I have noticed a lot of warning messages on the catalina.out log.
WARNING [main] org.apache.catalina.webresources.Cache.getResource Unable to add the resource at [/WEB-INF/classes/static/maps/scripts/app-72be477367.js.map] to the cache for web application [##01] because there was insufficient free space available after evicting expired cache entries - consider increasing the maximum size of the cache

WARNING [main] org.apache.catalina.webresources.Cache.getResource Unable to add the resource at [/WEB-INF/classes/static/maps/scripts/app-f223be6846.js.map] to the cache for web application [##01] because there was insufficient free space available after evicting expired cache entries - consider increasing the maximum size of the cache

Adding the following line to the conf/context.xml solves this problem and my log is no longer flooded.
 <Resources cachingAllowed="true" cacheMaxSize="100000" />

How do I know what is the correct entry for my cacheMaxSize. Am I over-allocating space to cache.

A: I had the same problem and was able to fix it, but there was an extra step for me, because I am running a server inside the Eclipse IDE, not stand alone on my PC.
Besides allocating a decent about of space for the cache, you must make sure you fix the right server. I made the mistake of fixing the tomcat server on my PC. Wrong! I eventually realized the Eclipse makes it's own copy of the tomcat server. I had to go into the eclipse- workspace-Servers directory and fix THAT copy of tomcat v 9.0.
I'll take a shot at your question about what size. It seems to make sense that you need to look at the size of the web site being presented and use that as the minimum size for the cache. Keeping in mind that a website could pull in a good amount of extra software from the server disk(s) or else where, you may want to add extra space. The best size to use is trail and error, although you could go through all the website code and expected usage and make calculations at how much memory will be used. Anyway, I just guessed. The total disk space for the website I'm using is only 22 M-bytes, so the cache size of 100000, i.e. 100 M-bytes seemed ok and I used that and it worked. I have plenty of memory space on my PC so that was not an issue for me.


text:
Q: OAuth v2 Authorization Code returned in Location HTTP header I am using the OAuth to obtain an access token from Microsoft Graph. I am specifically using the Authorization Code grant type. The first step is to request a Code via an HTTP GET. The code is then used in a second HTTP POST API call along with the client_id and client_secret.
What is confusing me is how the Authorization Code is being delivered. It is returned as part of the HTTP Headers named Location.

Is this expected? I was looking for it in a response body similar to how an access_token is returned. Is returning the Code via the Location header expected?

A: AUTHORIZATION CODE FLOW
This flow is very standard for browser clients, so behaviour looks correct:

*

*The browser receives the authorization code as part of a redirect, where there are security risks, such as the code being included in logs or visible to the user, or possibly being intercepted by a malicious party.

*The UI's logic then makes a direct HTTPS call to swap the code for tokens. Using two stages to get OAuth tokens reduces the threat surface for browser clients.

TESTING THE CODE FLOW
The Code Flow is tricky to test in tools like Postman. Have a look at OAuth Tools as a better alternative - see also this video.
Here are some values of mine you can use as a first step:

*

*Select Add Environment and enter the base Azure AD URL, which for my developer account has this value as issuer, then click discover to populate other endpoints:
https://login.microsoftonline.com/7f071fbc-8bf2-4e61-bb48-dabd8e2f5b5a/v2.0

*Then start a Code Flow with a client id such as this one of mine: c5ea6d78-c637-4f7f-b238-2264f5d4b479

*Then, once the settings look like the below screenshot, start a login redirect:

You can then update to your own settings and do the same thing with a test user. Then scroll down and select the 'Redeem Code' option, and use the client_secret_post option to swap the code for tokens. Then view the JWT details etc.
One problem is that my Azure AD client is a Single Page App and Azure AD requires this header to be added to the curl request during the redeem step. Not sure if you will face that problem and I will see if I can get the tool updated to allow extra headers etc to be typed in.

*

*-H 'Origin: https://web.mycompany.com'


text:
Q: GCE startup script: can't find $HOME after exporting in startup script I am trying to run a GCE startup script that downloads all dependencies, clones a repository and runs a python program. Here is the code

#! /usr/bin/bash
apt-get update
apt-get -y install python3.7
apt-get -y install git
export HOME=/home/codingassignment
echo $HOME
cd $HOME
rm -rf sshlogin-counter/
git clone https://rutu2605:************@github.com/rutu2605/sshlogin-counter.git
nohup python3 -u ./sshlogin-counter/alphaclient.py > output.log 2>&1 &

When I run echo$HOME, it displays the path in the log file. However when I cd into it, it says directory not found
May 08 23:15:18 alphaclient google_metadata_script_runner[488]: startup-script: /home/codingassignment
May 08 23:15:18 alphaclient google_metadata_script_runner[488]: startup-script: /tmp/metadata-scripts701519516/startup-script: line 7: cd: /home/codingassignment: No such file or directory

A: That's because at the time when the script is executed, the /home/codingassignment directory doesn't exist yet. To quote the answer you referred to in the comment:

The startup script is executed as root when the user have been not created yet and no user is logged in

The user home directory for the codingassignment user is created later, when you try to login through SSH for example, if you're using the SSH button in Cloud Console or use the gcloud compute ssh command.
My suggestion:
a) Download the code to some "neutral" directory, like /assignment and set proper permissions for this folder so that the codingassignment user can access it later.
b) Try first creating the user with adduser - this might solve your problem. First create the user, then use su codingassignment to drop root permissions, if you don't need them when executing the script.


text:
Q: Yii dataProvider theme main.php In my SiteController.php
public function actionIndex()
{
    // renders the view file 'protected/views/site/index.php'
    // using the default layout 'protected/views/layouts/main.php'
    //$this->render('index');

    $dataProviderUser=new CActiveDataProvider('User',array(
                'pagination'=>array(
                    'pageSize'=>20,
                ),
            ));
    $dataProviderDomain = new CActiveDataProvider('Domain');

    $this->render('index',array(
    'dataProvider1'=>$dataProviderUser,
    'dataProvider2'=>$dataProviderDomain
    ));
}

In my themes/k/views/layout/main.php
        <?php
        if(!Yii::app()->user->isGuest)
        {
        $this->widget('zii.widgets.CListView', array(
            'dataProvider'=>$dataProvider2,
            'itemView'=>'_view',));
        ?>

This error appears: Undefined variable: dataProvider2
If i do this in my main.php:
<?php
        $dataProvider2 = new CActiveDataProvider('Domain');
        if(!Yii::app()->user->isGuest)
        {
        $this->widget('zii.widgets.CListView', array(
            'dataProvider'=>$dataProvider2,
            'itemView'=>'_view',));
        ?>

That works fine so far. But if I go to the User Profil:
/user/view/id/5

Property "Domain.username" is not defined.
So in my User _view.php Yii seems to take the Domain Dataprovider.
How do I past those dataProviders to my layout main.php file?
The SiteController.php doesn't seem to do that right.
Would be very nice, if someone has an idea here.
Thanks in advanced.

A: Variables that you have defined in your controller action are only available to immediate view files that are being used to render a view. They are not available to layouts. However, layouts will be able to use public methods and properties of the controller. So, if you want to pass a variable to your layout you need to declare it as a property of the controller. There are two ways of doing this.
Firstly, you can just create a public variable.
Class YourController extends CController{

public $dataProvider2;

public function actionIndex(){
// renders the view file 'protected/views/site/index.php'
    // using the default layout 'protected/views/layouts/main.php'
    //$this->render('index');

    $dataProviderUser=new CActiveDataProvider('User',array(
                'pagination'=>array(
                    'pageSize'=>20,
                ),
            ));
    $dataProviderDomain = new CActiveDataProvider('Domain');

//Added new line here
$this->dataProvider2 = $dataProviderDomain;
    $this->render('index',array(
    'dataProvider1'=>$dataProviderUser,
    'dataProvider2'=>$dataProviderDomain
    ));
}

}

$this->dataProvider is now available in your view file, but don't foorget to check that it exists before using it.
The other method is to use the magic getter method from Yii.
In your model, describe a method like this;
public function getdataProvider2(){
return $this->_dataProvider2;
}

and you'll need a property;
private $_dataProvider2;


text:
Q: How do i get text from a dynamic element with selenium? So this is my xpath :
.//*[@id='highcharts-m6xwk29-6']/svg/rect[1]

Every time you refresh or access the page , this part "m6xwk29-6" changes with random characters and numbers . I have tried with contains but it does not work at all . This is the CssSelector :
#highcharts-efwz4kr-2 > svg > text:nth-child(23)

I just wanna get the text from this element . The html for this element is the following :
<text x="635" text-anchor="end" class="highcharts-plot-line-label " transform="translate(0,0)" style="font-size:14px;font-weight:bold;color:#dedede;fill:#dedede;" y="86" visibility="visible">1.07162</text>

The text that i wanna get is a value (in this case 1.07162) from a graph that updates every second (or less) .

A: Try to use below XPath:
'//*[starts-with(@id, "highcharts-")]/*[name()="svg"]/*[name()="text"]'


text:
Q: Motion of a rigid body on application of constant force perpendicular to a point which is not the center of mass? Consider a rod which has a uniform mass distribution which is free to move in space. Now, it is known that if an impulse (perpendicular to rod) is applied which does not pass through the center of mass, it will undergo pure rotational motion (with translation).
Now consider a situation where the force is applied constantly, and it remains perpendicular to the point of application throughout the situation even as the body undergoes motion.

What would be the motion of the body in such a case? How could this motion be described mathematically?

A: If the force is of constant magnitude, so is the torque applied about the center of mass. So the rotational motion is easy to calculate, as fixed rotational acceleration of $$ \alpha = \frac{F d}{I}$$ is applied.
The orientation is thus
$$ \theta(t) = \tfrac{1}{2} \alpha t^2 $$
But the direction of the force changes with time and so the acceleration of the center of mass
$$ \vec{a} = \frac{\vec{F}}{m} $$
As there is planar motion here, the force vector is
$$ \vec{F}(t) = \pmatrix{ F \cos \theta(t) \\ -F \sin \theta(t) } $$
Unfortunately the integral $$ \vec{v} = \tfrac{1}{m} \int \vec{F}(t)\,{\rm d}t $$ does not an analytical solution. But it is easily evaluated numerically, or experimentally.


text:
Q: Converting string of numbers seperated by spaces into int array I'm trying to build a recursive function that gets a string (char array) which should contain numbers seperated by spaces or tabs, and the amount of numbers which should be inserted, and insert each number to an int array.
I can't use any loop for this function, only recursion.
The number of spaces and tabs between two numbers are unknown. (although the char array is a 1000 chars buffer)
I'm using gets_s for the input string.
If there is wrong char in the string or incorrect amount of inserted numbers the function will print an error and restart itself (again whitout any loops).
+/- signs and leading zeros (001) are allowed.
So far I have a function which gets a char array which contains a valid number and returns its value as int (for example {'-','1','5','\0'} will return -15).
What is the best way to convert the string into the int array in order to use this array next in my program?
Thanks

A: In the comments I wrote:

This kind of "don't use the most appropriate tool to solve" problem should be a red flag to you; your resource, whatever it is, is teaching you to solve problems in an inappropriate way. Why, in the real world, would anyone not use loops in C here? Alternatively, if the author wants to teach functional programming, why would they use a non-functional language likc C? Get a better book!

Nonetheless, here I find myself offering an answer...
First off, they're technically both loops! I gather when you state that you can't use any loop, you're actually referring to procedural loops (i.e. loops built from goto, while, do...while or for), and not functional loops (which are built by recursive function application). They're both technically loops, and since C is a procedural language you should use procedural loops. Nonetheless...
There's a pattern! Procedural loops can be converted to functional loops simply by observing and reproducing a pattern. That is, every procedural loop has an equivalent functional loop, and they all end up looking very similar. Look for the pattern below.
Here's a function containing a basic procedural loop:
void procedural_loop_on_str(char const *source, size_t source_position, int *dest, size_t dest_position) {
    while (source[source_position] != '\0') {
        source_position++;
    }
}

... and here it is as a functional loop:
void functional_loop_on_str(char const *source, size_t source_position, int *dest, size_t dest_position) {
    if (source[source_position] != '\0') {
        source_position++;
        functional_loop_on_str(source, source_position, dest, dest_position);
    }
}

The two pieces of code seem very similar, don't they? Any procedural loop can be trivially translated to a functional equivalent based on this observation; all you'll be doing is adding the extra code that fills in your loop. As an exercise, consider isolating the parts of this code that are identical. They generally sit in the same place in both pieces of code; they're not hard to find! In fact, here are those differences, side-by-side:
    while ...                                  if ...
                                                   functional_loop_on_str...

The only difficulties come in place when backtracking is necessary, which is irrelevant for this question. Hence, you should be able to write the procedural version and translate it to a functional version easily. Allow me to start you off:
void procedural_loop_on_str(char const *source, size_t source_position, int *dest, size_t dest_position) {
    while (source[source_position] != '\0') {
        int value, nbytes, success = sscanf(source + source_position, "%d%n", &value, &nbytes);
        if (!success) { nbytes = 1; }
        else { /* XXX: You do this part!
                *      You need to do something with value, dest and dest_position */
        }
        source_position += nbytes;
    }
}

... and here it is translated to our functional version by reproducing the pattern:
void functional_loop_on_str(char const *source, size_t source_position, int *dest, size_t dest_position) {
    if (source[source_position] != '\0') {
        int value, nbytes, success = sscanf(source + source_position, "%d%n", &value, &nbytes);
        if (!success) { nbytes = 1; }
        else { /* XXX: You do this part!
                *      You need to do something with value, dest and dest_position */
        }
        source_position += nbytes;
        functional_loop_on_str(source, source_position, dest, dest_position)
    }
}

Notice how little has actually changed between the two examples; most of the pattern is still there! Recall the exercise above? Well, you can do the same here to find that the same changes are made in the same place when converting from procedural to functional.
I think this pattern would've been obvious to you had you read a (better) book about functional programming and a (better) book about C programming, or even created these basic examples yourself to observe the pattern. Nonetheless, I stand by my beliefs that:

*

*You shouldn't be using functional loops in C or any procedural language for that matter, but specifically not C; if C were designed for every-day functional looping, there'd be optimisation guarantees in the standard. If your guide is guiding otherwise, consider choosing a new guide such as the book with the giant blue "C", written by founding forefathers of C Kernighan & Richie (choose the second edition). I'll leave you to find that one.

*You shouldn't be using procedural languages to study functional elements. This is a no-brainer. Consider Scheme; there's a REALLY NICE "wizard book" about Scheme!

Either way, it appears you need a better book!

A: pass a pointer to the end of you integer array as an argument to the function s well as a pointer to the current character in the string. if not white space, add the number to the int array and increment the int pointer. increment the char pointer appropriatley regaurdless and recurse. I assume you can handle converting strings to ints, there are many posts to help with this if not.

A: sscanf sounds like the tool you need. It's the one I would use. You can recursively read your string into your int array. I would also create an int array with 501 positions, since that is the highest amount of ints you can get(if each int is just a single digit number and there is just one space between them).
Alternatively you could use atoi


text:
Q: Paginate long text using php I've a long text (More than 10,000 words) contains html tags stored in a string.
And want to wrap every 1000 words with

 with considering auto close opened html tags and auto open closed html tags in the different chunks.
I found many solutions but they depend on the number of characters and don't consider auto open/close html tags.
Also the php function wordwrap neglects fixing html tags problem.
Simulation

   Dynamic long text more than 10,000 words (Text contains HTML (img, p, span, i, ...etc) tags)

Wrong result

Chunk 1 : first approximately 1000 words with their html tags
          ## Unclosed
 tag ##

      ## The closed
 tag of the previous chunk ##

Chunk 2 : second approximately 1000 words with their html tags

 ## unclosed
 tag ##

      ## Missing open
 tag because it was cut in the previous chunk ##
      Chunk 3 : third approximately 1000 words with their html tags

Expected result

Chunk 1 : first approximately 1000 words with their html tags

Chunk 2 : second approximately 1000 words with their html tags

Chunk 3 : third approximately 1000 words with their html tags

And then i can paginate the result with javascript.
After searching i found the accepted answer here: Shortening text tweet-like without cutting links inside

cutting the text (from the start only) and auto close opened html tags.
I tried to modify the code to auto open closed tags if i cut from the middle of the text but unfortunately i failed to do the job.
I don't mind if there are another better solutions to paginate the long text according to the number of words using (php or javascript or both of them).

A: So the idea is to use JQuery to chunk the immediate children via cloning and splitting the internal text. It may need some more work for further nested HTML but it's a start:
function chunkText(length) {
    var words = $(this).text().split(" ");
  var res = [$(this)];
  if (words.length > br) {
    var overflow = $(this).clone();
    var keepText = words.slice(0,length);
    $(this).text(keepText.join(" "));
    overflow.text(words.slice(length).join(" "));
    res = res.concat(chunkText.call(overflow, length));

    }
  return res;
}

var br = 10; //Words to split on

$("#long-text > *").each( function () {
        var chunks = chunkText.call(this,br);
    $.each(chunks, function (i,v) {
      $("#long-text")
          .append($("
").addClass("chunk").append(v))
          .append($("").attr("src","image.jpg")));
    });

});

Basic demo:
https://jsfiddle.net/o2d8zf4v/


text:
Q: Google Translate default language i am trying to change the default languge of Google Translate from "Select a Language" to "EN". Unfortunately my jquery is not working. Here is my code. Hope you could help me.

j(' #google_translate_element .goog-te-menu-value span').ready(function (){

     j(this).replaceWith("EN");

    });

j(' #google_translate_element .goog-te-menu-value span').each(function (){

     j(this).text("EN")

           });

A: Google translate uses some cookie called "googtrans" to track and follow the language that is selected. You can set that aforementioned cookie yourself before the pages load and then Google translate will use it.
// PHP code sample, could be accomplished with any language that can set cookies
// set the default language translation to English.
setcookie('googtrans', '/en/en');

example:
setcookie("googtrans", "/en/en", time()+3600, "/", "www.example.com");

Also, adding #googtrans(xx) and append it to the end of the query string will also translate the page for you in the language you prefer automatically, as if you are setting the cookie yourself (where xx is the language code, i.e. en for english - fr for french), etc.
Hopefully it works fine with you :)


text:
Q: Installing Build Tools from Android Studio I have a problem with Android Studio on OSX. The following error message is shown

Failed to find Build Tools revision 23.0.2
Install Build Tools 23.0.2 and sync project

The link, unfortunately, isn't clickable. It should be, I know it works on Windows, but OSX, it's not responding.
SDK Manager on OSX is a little different. It doesn't allow you to install older versions of Build Tools (only the latest).

So the question is "How can I install 23.0.2 Build Tools on OSX?"
or maybe "Why is my Android Studio install buggy and I can't click any links! :)"

A: I think I have a solution. I know it's a bit noobish but I went into build.gradle and changed the buildToolsVersion from 23.0.2 to 23.0.3 (which I know is installed)
ext {
    minSdkVersion = 19
    compileSdkVersion = 23
    buildToolsVersion = '23.0.3'
    sourceCompatibility = JavaVersion.VERSION_1_7
    minifyEnabled = false
    versionCode = 1
    versionName = "1.0"
    documentationFolder = "${rootDir}/outputDoc/"
}


text:
Q: How can I make incremental backups of a running linux system using freeware? I'm looking for an incremental backup tool to use on a plain old running disk based linux system, such as ubuntu or the like, and a tool which is freeware.

This is for a plain old desktop linux, and not for a virtual setup.
I'm already aware of tools that can be used to do backups when the system is idle like clonezilla.
I'm also already aware of many tools that are suggested for this purpose but which can not be trusted to accurately capture a running OS, like for example rsync, which is fine for a static file-system, but not for a running file-system.
An example of what I'm looking for is Acronis for linux and windows, but it's not freeware.
I also read somewhere that Btrfs (Butter-file-system) has some of this capability.
This is a similar question, but does not ask about an incremental backup.

A: If you are using LVS (and many OS's do), and have free space (or you can shrink a filesystem to free space or add more disk to it), you can take a snapshot, mount the snapshot and do an RSYNC of that.   This will work provided you are using a journalling filesystem - and most modern filesystems do journalling.

A: Btrfs is the way to go. It can take snapshots of live systems, and then can do incremental backups. There are many FOSS solutions, you can find a list of them on the Incremental Backup page of the Btrfs wiki, with ot without ssh/rsync. It also has a section on how to it by hand, it is useful in case you want to understand the basic idea.


text:
Q: What happens(with respect to memory) when two int variables are given same value in java? I know that local variables are stored on stack in java. But what happens with respect to memory allocation on stack when two int variables are given same value in java(How are they related)? Is there any kind of copy on write semantic? How does it works then?

A: The obvious answer is that int x=5; int y=5; does the same as int x=5; int y=6; with the only exception being that, in your case, the memory that's been associated with y will look the same as as it does for x.
It's difficult to envisage a JVM where some kind of copy on write semantic is used - i.e. x and y are allocated the same piece of memory until one of them changes the value. As far as I know, that is theroetically permissible by the Java Language Specification, but it's unlikely to be used by anything so trivial as an int: the overhead in setting up the copy on write would far outweigh them having different memory from the outset.
(Out of interest, it was possible to write copy-on-write semantics for the C++ std::string class, but since C++11 it's been disallowed).

A: It will definitely create to variable in stack. which hold value 5.
There's no other way.
Any variable local/global,primitive/non-primitive stores some value
For primitive value is some whatever you assign according to type.
For non primitive value is memory address of the object in heap but in the end both holds value and does not lookup if some other var has the same either way.


text:
Q: Make payable App free for only one country (Google Console) Not sure I am allowed to ask this here, but I guess this has also to do with developing apps.
Is there a way to give a payable app for free for only one country?
Meaning that I have a payed app and I would like to give the app for free in a specific country.

A: No, an app is either paid or free regardless of country.
For paid apps, prices can be set per country but this is always higher than 0.00
Minimum prices
https://support.google.com/googleplay/android-developer/answer/10532353?visit_id=637826106815754209-1478538205&rd=1
Set up your app's prices:
https://support.google.com/googleplay/android-developer/answer/6334373?hl=en


text:
Q: In a VMware environment, is it possible to move a Windows Disk from one VM guest to another? I have VMware server with Windows SBS server VM guest.  It has a C: drive and a D: drive. The D: drive is a separate disk in the VM guest settings.
We would like to migrate this to a new Windows 2012 File Server.  I wonder if it is possible to create a new Windows server with a 60GB system disk (C: drive), and then do the following:
1) Shut down the SBS server VM guest.
2) Move the file or files associated with the second disk from the SBS VM folder on the esx host to the folder for the new Windows File server on the ESXi host, and then add that drive to the settings/configuration of the new file server guest?

A: Yes. You can attach the VMDK to another virtual machine.


text:
Q: Is a pseudonatural transformation of strict 2-functors to Cat isomorphic to a 2-natural transformation? Let $\mathcal{C}$ be a strict 2-category. A corollary of the bicategorical Yoneda lemma says that any pseudofunctor $\mathcal{C} \to \operatorname{Cat}$ is pseudonaturally equivalent to a strict 2-functor. I would like to know if the "next level" of strictification is true; namely, is it true that any pseudonatural transformation of strict 2-functors $\mathcal{C} \to \operatorname{Cat}$ is isomorphic (via an invertible modification) to a 2-natural transformation?
The specific case of this that I am interested is when $\mathcal{C}$ is the delooping of a monoidal category: the first statement says that any left $\mathcal{C}$-module can be made into a "strict" left $\mathcal{C}$-module, while the second would imply that any morphism of left $\mathcal{C}$-modules can be strictified.

A: No, it is not true.  For a counterexample, let C be the delooping of the group Z/2 (regarded as a discrete monoidal category).  A strict C-module is then a category equipped with an involution, a strict C-module morphism is a functor preserving the involution strictly, and a pseudo C-module morphism preserves the involution up to coherent isomorphism.  In particular, a strict C-module morphism must map an object fixed by the involution to another fixed object, but a pseudo C-module morphism can map a fixed object to one which is only fixed up to isomorphism.  Thus, if A is a C-module with fixed objects and B is a C-module with no fixed objects, there can be pseudo C-module morphisms from A to B, but there cannot be any strict C-module morphisms from A to B.
It is, however, true that any strict (or even pseudo) 2-functor $F:C\to Cat$ is pseudonaturally equivalent to a strict 2-functor $F':C\to Cat$ which has the property that any pseudonatural transformation $F'\to G$ is isomorphic to a strict 2-natural transformation.  An $F'$ with this property is called flexible (if you're a 2-category theorist) or cofibrant (if you're a homotopy theorist).  The possibility of flexible replacement follows from generalities about 2-monads: there is a strict 2-monad T on the 2-category $Cat^{ob(C)}$ for which strict T-algebras are strict 2-functors $C\to Cat$, strict T-morphisms are strict 2-natural transformations, and pseudo T-morphisms are pseudonatural transformations.  The general coherence theorems of Power and Lack (see the papers "A general coherence result" and "Codescent objects and coherence") apply to this 2-monad and specialize to the statement I quoted above.  The homotopy theorist can instead construct a model structure on the 2-category of strict 2-functors and strict 2-natural transformations in which the cofibrant objects are cofibrant/flexible; see Lack's paper "Homotopy-theoretic aspects of 2-monads."


text:
Q: How to read huffman tree frequency from a file I have to create a huffman tree whose alphabtes(symbols, i mean "aaabbacaccba" etc.) must be given as Input.txt file at sole argument.
I then have to create the frequency corresponding to each  alphabtes.
I have problem in createing frequencies.
I want something like this: suppose if i have to read this in input.txt: "aabcccadde". Then my code must print like this:
sym:a, freq:3
sym:b, freq:1
sym:c, freq:3
sym:d, freq:2
sym:e, freq:1

My code for this is working correctly: see below:
   while (c != EOF && c != '\n' && c != '\r')
   {
    Object1.data[count].symbol = c;
    if(Object1.data[count].symbol =='a')
    {
      save_a++;
    }
    if(Object1.data[count].symbol =='b')
    {
      save_b++;
    }
    if(Object1.data[count].symbol =='c')
    {
      save_c++;
    }
    if(Object1.data[count].symbol =='d')
    {
      save_d++;
    }
    if(Object1.data[count].symbol =='e')
    {
      save_e++;
    }
    count++;
    c = fgetc(input_file);
   }
    cout<< "save_a : "<<save_a <<endl<< "save_b : "<<save_b <<endl<< "save_c: "<<save_c<<endl<< "save_d : "<<save_d <<endl<< "save_e: "<<save_e<<endl;

so the output is:
save_a : 5
save_b : 3
save_c: 2
save_d : 2
save_e: 3

But the problem is when user again changes the frequency to "pqabbaddqpc". The user here added two more alphabets, where i have only counter to read the count of a,b,c,d and e only. I mean i want to create some dynamic kind of system where the user can enter any alphabets to calculate the frequencies.
Is it possible to do achieve this ?
Any help please ?

A: Its simple if you map each alphabet according to its integer value to table which maintains its count .
int freq[256];
char c;
while((c=fgetc(fp))!=EOF) {

  freq[(unsigned int)c]++;;

}

Here as there are only 256 possible characters so there is no memory overhead as such and then you can easily extract the character present in input as they will have freq > 0


text:
Q: excluding foreign key fields from django forms Assume following models.
class Address(models.Model):
    house_number = models.CharField(max_length=50)
    street_1 = models.CharField(max_length=500)
    street_2 = models.CharField(max_length=500)
    town = models.CharField(max_length=500)
    postal_area = models.CharField(max_length=500)
    country = models.CharField(max_length=500)

class RegisteredUser(User):
    address = models.ForeignKey(Address)
    registered_date = models.DateTimeField('registered_date')

My question is how do I exclude address field from a Django form. Currently it gives a list box to select an address.
My Form code is:
class CreateRegUserForm(forms.ModelForm):
    confirm_email = forms.EmailField(
        label="Confirm email",
        required=True,
    )

    class Meta:
        model = RegisteredUser
        exclude = ('password','last_login','is_superuser','is_staff','is_active','date_joined','registered_date','address_id',)

A: Just add address in exclude list
class CreateRegUserForm(forms.ModelForm):
    confirm_email = forms.EmailField(
        label="Confirm email",
        required=True,
    )

    class Meta:
        model = RegisteredUser
        exclude = ('address','password','last_login','is_superuser','is_staff','is_active','date_joined','registered_date','address_id',)


text:
Q: default user.properties file to generate Jmeter HTML report from csv file? I'm able to generate the csv but when I click on Tools|Generate HTML report,
user.properties file :The specified file  doesnt exist
Isn't there some default one?

A: Default user.properties file comes with your JMeter installation and lives in its "bin" folder.
If you lost your own one by accident - you can always get it back from i.e. JMeter Github or download a new JMeter build and extract it from there
The funny thing is that the "default" user.properties file doesn't add any value because all settings are commented out therefore you can feed an arbitrary empty file to JMeter
I think the reason for having this file is that JMeter's Results File Configuration can be customized and for example if you ran a JMeter test with one .jtl file configuration you won't be able to generate the dashboard on the "default" one, the result file configurations must match.
More information:

*

*Configuring JMeter

*Apache JMeter Properties Customization Guide

A: user.properties is required currently, you can open an enhancement for adding a default one.

user.properties file The user.properties file used to run the load test


text:
Q: Can't mass-assign protected attributes: title, description, cloth_type, pic Rails 3 When doing a POST to /cloth/create I get a WARNING: Can't mass-assign protected attributes: title, description, cloth_type, pic
cloth.rb
class Cloth
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::MultiParameterAttributes   attr_accessible :pics

  field :title
  field :description
  field :cloth_type
  belongs_to :seller
  has_many :pics

  attr_accessible :pic_attributes
  accepts_nested_attributes_for:pics
end

pic.rb
class Pic
  include Mongoid::Document
  include Mongoid::Paperclip

  has_mongoid_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" },
  :storage => :cloud_files,
  :cloudfiles_credentials =>  "#{Rails.root}/config/rackspace.yml",
  :path => ":attachment/:id/:timestamp_:style.:extension"

  belongs_to :cloth
  attr_accessible :cloth_attributes

  def create
    @cloth = Cloth.create!(params[:cloth])
  end
end

A: The answer can be found here: http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-attr_accessible
However, I will elucidate.
By setting attr_accessible :pic_attributes, you are setting a white list for what attributes can be set via mass assignment. In other words, you are saying that ONLY the attributes you've listed can be set by doing things like cloth = Cloth.new(params[:cloth]). Any other attribute you are saying should be set by using their accessors, such as cloth.title = params[:title].
If you need the attr_accessible, then add the other attributes to your list.
attr_accessible :pic_attributes, :title, :description, etc ...


text:
Q: AutoCompleteTextView in android with shared preferences In my application I need to show list of user who are logging in. In my username text field.
I tried to store in sharedpreferences and retrieve but I couldn't. How can I get it done?
I parsed the array to json and stored it in an array then used in a arrayadapter.
Here is my code:
public class MainActivity extends Activity {

SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;

public static String user_id;
EditText etxt_user;
String PLAYLISTS;
String[] listt;

ArrayList<String> array;
JSONArray jArray;

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

    etxt_user = (EditText) findViewById(R.id.textView1);
    user_id = etxt_user.getText().toString();

      sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        final Editor editor = sharedpreferences.edit();

        array = new ArrayList<String>();
        jArray = new JSONArray(array);

//          final JSONArray jArray = new JSONArray(array);
//            editor.putString("buttonArray", jArray.toString());
//          editor.commit();

        final ArrayList<String> array1 = new ArrayList<String>();

//  final String name = sharedpreferences.getString("buttonArray", null);

        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, array);
        final AutoCompleteTextView textView = (AutoCompleteTextView)findViewById(R.id.textView1);
        textView.setAdapter(adapter);

        Button b1= (Button)findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                array.add(etxt_user.getText().toString());

                editor.putString("buttonArray", jArray.toString());
                editor.commit();

                String name = sharedpreferences.getString("buttonArray", null);

                System.out.println("222222222222"+jArray.toString());
                System.out.println("333333333333"+name);
                System.out.println("444444444444"+array);

                editor.putString(PLAYLISTS,etxt_user.getText().toString());

            }
        });
    }

A: If data is static save it in Strings.xml, else you can save it in DB and access it.
Here is the link that will help you http://www.giantflyingsaucer.com/blog/?p=1342


text:
Q: Is it is possible to replace one array to other new 8 HDD array in HP RAID 1+0 without losing data on old array? Currently, I have 4 hard disks which have been configured as RAID 1+0 in HP Proliant 380 G7, SmartArray p410i. I am planning to buy other new 8 hard disks to replace old array by swapping the disks out and keep the old array as backup. I also make full backup and I will use this backup to restore to new 8 hard disk array. Can I still use the old 4 disks if I already configured RAID 1+0 with new 8 disks?
So if I decide I want to go back to the old array (for example restore to the new array failed), I can just take the new array 8 disks out, put the old array 4 disks in and the data will be readable?
I did the research on HP Business Communities forum and they said it is possible to do that without data lost. they instructed to start the server without any disk and try clear any configuration exists then put previous disks back which was installed on the server in the correct slots if possible.
May someone confirm this that it really works?

A: HP Smart Array solutions keep the RAID configuration on disk. If you remove the old disk set and keep the drives in order (labeled 1 through 4), you can use them with any similar-generation controller. They would still constitute a bootable array/logical drive.
When you talk about keeping the old disks as a backup, are you just thinking about using it as a fall-back solution? But you still have a backup process in place... What would happen to the 4 disks after you migrate?
Why are you moving to 8 disks? Space? Speed?
You could safely replace the 4 disks with 4 of the larger disks (assuming that they're larger) and add the additional 4 disks. From there, you could perform an online RAID resize/transformation that will redistribute data across the new drives.
This can be done entirely online without any downtime.
Please take a look at the HP Smart Array Reference Manual and its section on Array Expansion and Migration.


text:
Q: symfony 2 doctrine 2 I create method for select current premises foto, all works good
public function findByDistrictIds($criteria)
{
    $q = $this->getEntityManager()->
            createQuery('SELECT f.id, f.path FROM RealestateCoreBundle:Foto f WHERE f.premises in (:criteria)');
    $q->setParameter('criteria', $criteria);
    return $q->getResult();
}

but when I add to select command "f.premises", get error

[Semantical Error] line 0, col 23 near 'premises FROM': Error: Invalid PathExpression. Must be a StateFieldPathExpression.

How i can get foto with premises_id? And how use "WHERE IN" clause in queryBuilder?

A: Ah. This came up recently. Premises is a relation field so you need to do a fetch join. Note the Premises alias p in the field list:
SELECT f.id, f.path, p
  FROM RealestateCoreBundle:Foto f
  JOIN f.premises p
 WHERE ...

Hope this helps :)

A: public function findByDistrictIds($criteria)
{
    $q = $this->getEntityManager()->
    createQuery('SELECT f.id, f.path FROM RealestateCoreBundle:Foto f WHERE f.premises =     :criteria');
    $q->setParameter('criteria', $criteria);
    return $q->getResult();
}

You can try to use f.premises = :criteria
instead of f.premises in (:criteria)

A: Regarding the WHERE IN in query builder, you can pass $criteria as an array to setParameter() method. Also make sure that array is in this format.
$criteria = array('1','2','3'); /* correct */

$criteria = array('1,2,3'); /* incorrect. Some people misunderstand this and set the array like this which is incorrect */

So your query would be something like this,
$q = $this->getEntityManager()->
        createQuery('
                    SELECT f.id, f.path FROM RealestateCoreBundle:Foto f
                    WHERE f.premises in (:criteria)');
$q->setParameter('criteria', array('1','2','3'));

Hope this helps.


text:
Q: Full outer join missing values with null I'm trying to use full outer join on postgresql database to get a union of tables that has null values for the missing rows. However, it is not working for me.
Here is the example:
create temp table nutrient_names (
    name text
);

insert into nutrient_names values
('fat'),
('sugar'),
('sodium'),
('total fat');

create temp table nutrients (
    food_id int,
    name text,
    quantity float8
);

insert into nutrients values
(1, 'fat', 0.3),
(1, 'sugar', 15),
(1, 'sodium', 10),
(1, 'total fat', 25),
(2, 'sugar', 10),
(2, 'sodium', 4);

Here is the output:
select n.name, n.food_id, n.quantity from nutrient_names nn
full outer join nutrients n
on nn.name = n.name
order by n.food_id, n.name;

+---------------------------------+
|name           |food_id |quantity|
+---------------------------------+
|    'fat'      |1       |'0.3'   |
|    'sodium'   |1       |'10'    |
|    'sugar'    |1       |'15'    |
|    'total fat'|1       |'25'    |
|    'sodium'   |2       |'4'     |
|    'sugar'    |2       |'10'    |
+---------------------------------+

What I want:
+---------------------------------+
|name           |food_id |quantity|
+---------------------------------+
|    'fat'      |1       |'0.3'   |
|    'sodium'   |1       |'10'    |
|    'sugar'    |1       |'15'    |
|    'total fat'|1       |'25'    |
|    'fat'      |2       |null    | <----
|    'sodium'   |2       |'4'     |
|    'sugar'    |2       |'10'    |
|    'total fat'|2       |null    | <----
+---------------------------------+

A: I suggest having two tables representing nutrition types and types of food. Then have an extra table specifying the nutrition values.
You can do a cross join on food and nutritions and then do a left join on the nutrition values to get your results.
I made a fiddle for you to look at here http://sqlfiddle.com/#!17/d974b/3
The reason that you cannot do a full outer join is that if you have the quantity on a row you have the id aswell. They are in the same dataset.

A: It doesn't look like FULL JOIN suits here. Based on your example you want to list all rows from nutrient_names as many times as you have food IDs. This is usually done with CROSS JOIN.
If you don't have a separate table with the list of food IDs, you can build it on the fly and then join to it:
WITH
CTE_IDs
AS
(
    SELECT DISTINCT
        food_id
    FROM nutrients
)
SELECT
    nutrient_names.name
    ,CTE_IDs.food_id
    ,nutrients.quantity
FROM
    CTE_IDs
    CROSS JOIN nutrient_names
    LEFT JOIN nutrients
        ON  nutrients.name = nutrient_names.name
        AND nutrients.food_id = CTE_IDs.food_id
;

A: if you have 2 tables (t1 and t2) with cols: dimension_1, dimension_2, measure_1, measure_2
you can write
select dimension_1, dimension_2, sum(measure_1) as measure_1, sum(measure_2) as measure_2
from t1
full join t2 using(dimension_1, dimension_2)
group by dimension_1, dimension_2