text:
Q: Magento get a product collection in an arbitrary order I have developed a custom search engine for our Magento store and I am trying to load the product collection in a very specific order (I have ranked the results according to an algorithm I designed).
I can load the product collection correctly, however it is not in the order that I would like it to be in. Here is basically how it is working now:
My database query basically comes back with a PHP array of product IDs. For this example lets say it looks like this:
$entity_ids = array(140452, 38601 );

Now I can transpose the 140452 and the 38601 and the product collection comes back in the same order each time. I would like the product collection to be in the same order as the ID of the entity ids.
The code I am using to create my collection is as follows:
$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('entity_id', array('in' => $entity_ids))
    ->setPageSize($results_per_page)
    ->setCurPage($current_page)
    ->load();

Is there a way to set the sort order to be the order of the $entity_ids array?

A: Collections inherit from the class
Varien_Data_Collection_Db

There's a method named addOrder on that class.
public function addOrder($field, $direction = self::SORT_ORDER_DESC)
{
    return $this->_setOrder($field, $direction);
}

So, you'd think something like this should work for basic ordering
Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addOrder('entity_id');

However, it doesn't.  Because of the complex joining involved in EAV Collections, there's a special method used to add an attribute to the order clause
Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection::addAttributeToSort

However again, this can only be used to add simple attributes.  To create an arbitrary sort, you'll need to manipulate the Zend_Select object directly.  I'm not a big fan of this, and I'm not a big fan of using custom mysql functions to achieve things, but it appears it's the only way to do this
I tested the following code on a stock install and got the desired results.  You should be able to use it to get what you want.
        $ids = array(16,18,17,19);
        $products = Mage::getModel('catalog/product')->getCollection()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('entity_id',$ids);

                    //shakes fist at PDO's array parameter
                    $ids = array_map('intval', $ids);
        $products->getSelect()->order("find_in_set(e.entity_id,'".implode(',',$ids)."')");
        foreach($products as $product)
        {
            var_dump($product->getEntityId());
            var_dump($product->getSku());
        }

A: There is no way to sort arbitrarily in SQL so you would have to sort the results in PHP afterwards. Then the bigger problem is you are using page sizing to limit the number of results being returned, some of the records you want might not be returned because of this.
The better solution is to add an attribute to products which you can then use to sort by. Products in categories already have a 'position' value which is used in this way. Then you only need to use the addOrder()addAttributeToSort() method that Alan suggested but with your custom attribute.
(Explanation is hurried, let me know if not clear enough)


text:
Q: Why is there a pause before the light comes on/mac starts charging when plugging in? My mental model of a charger is that you plug it in and electricity fires out of it like a hose whether you like it or not. When I plug in my macbook charger, it often takes a few seconds before the light comes on and the menu bar icon says charging.

A: This is only educated speculation, but I imagine it's related to the amount of switching that has to take place when changing from battery power to being on the mains. The electrical input needs to be registered, the hardware switched from running off battery to a charging state if needed, and time for the kernel to be informed of the state change based on the polling frequency. Then the other power management daemons have to pick up the state change and the OS get the message that the power state has changed. If that polling was taking place at intervals of less than a few seconds, I'd be surprised.

A: The typical process of charging a battery:
First the system detects the power plug.
Now the Battery status is evaluated and and the battery circuit determines the amount of current to draw.
It is not like a hose, it is a calculated current amount. In other words the battery is the boss and only takes what it needs without overheating or damage.
If you look at you battery Icon in the menu bar you will see it takes a moment or two to determine how long it will take to charge to 100%.
Once that process is completed and the charging is on the way, you are given a visual indication (LED) of activity.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the difference between object.method(a,b) and method(a,b) in Ruby I am very new to programming and am trying to learn Ruby. I can't quite get my head around methods at the moment. I uderstand that:
Methods allow me to execute a chunk of code without having to rewrite it, such a method looks like:
example_method

Arguments allow me to pass values into the code within the method that go in the place of the placeholders defined in the method. This way I can execute a set of code with different inputs. Methods with arguments look like:
example_method( x , y )

But I am confused about what an instantiation of a method on an object is actually doing. For example:
object.example_method( x, y )

What does this mean? Why is the method attached to an object with the period notation? Do we do this so we can reference Instance / Class variables of the object within our method? Is there any other reason to do this?
For the example if:
def example_method(x , y)
  x * y
end

Will object.exaple_method(a , b) be the same as example_method(a , b) ?
Thanks for any help, sorry if I am not being clear.

A: Ruby is an Object Oriented language. This means that objects not only have members (=state) but also methods (=behavior). When you are calling a method on an object (is which case the object is called the caller) the method that runs is the method which corresponds to this object's type behavior.
When you are calling a method with no caller, self is implicitly the caller. From irb, self is considered main, or global scope.
Example:
def my_method(a)
  "#{a} from main"
end

class A
  def my_method(a)
    "#{a} from A"
  end
end

class B
  def my_method(a)
    "#{a} from B"
  end
end

a = A.new
b = B.new

my_method(1)
# => "1 from main"
a.my_method(1)
# => "1 from A"
b.my_method(1)
# => "1 from B"

A: If I assume correctly what you're asking it's a class method vs an instance method
def Object
  def self.example_method(x, y)
    #this is a class method
    x * y
  end

  def example_method(x,y)
    #this is an instance method
    x * y
  end
end

So now we've defined them here's how we call them
#This called the class method
Object.example_method(3,3) => 9

#To call the instance method we have to have an instance
object = Object.new
object.example_method(3,3) => 9


text:
Q: How to cache images from PictureBox in C# winform Im trying to load images from a website. It loads very slowly. Everytime its selected. Any way to cache the image.
picturebox1.ImageLocation = "http://example.com/Image.jpg";

That form will be opened many times frequently, right now each time form is opened, images are being downloaded every time. It is unnecessary increasing traffic.
Is it possible to tell PictureBox to cache image (as Browser do), so next time same images is requested, it should load quickly. Is this possible?
   if (listBox1.SelectedIndex == 0)
        {
            richTextBox1.Text = "Explore any game with Dex";
            Image img = Image.FromFile("https://i.imgur.com/Jb6lTp1.png");
            pictureBox1.Image = img;
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

It says given path format is not supported

A: Try this way:
First Create a function to check whether file exist or not. If exist then simply load the file from local path else download the file from URL and store it in local.
//Function to validate the local cache file

    private Image load_image()
    {
       Image img=null;
        if(!(File.Exists(@"d:\samp.png")))
        {
            using (HttpClient httpclient= new HttpClient())
            {
                var response = httpclient.GetAsync(@"https://i.imgur.com/Jb6lTp1.png");
                if (!response.Result.IsSuccessStatusCode)
                {
                    return img;
                }
                using (var fs= new FileStream(@"d:\samp.png",FileMode.CreateNew))  // Path can be added as parameter of function
                {
                    response.Result.Content.CopyToAsync(fs);
                }

            }
        }
        img = Image.FromFile(@"d:\samp.png");
       return img;
    }

 //calling the function of click event

    private void button1_Click(object sender, EventArgs e)
    {

      if (listBox1.SelectedIndex == 0)
        {
        richTextBox1.Text = "Explore any game with Dex";
        pictureBox1.Image = load_image();
        pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
        }
    }

NOTE: Handle the exceptions where ever required. Use parameters in function as per requirement

A: Use PictureBox's Load method in the Form1_Load event. Also make sure the URL is valid.
private void Form1_Load(object sender, EventArgs e)
{
    pictureBox1.Load("https://www.nippon.com/en/ncommon/contents/japan-data/169591/169591.jpg");
}


text:
Q: How to determine if the sd card is available or not so that the user can store information either in the external or internal storage I am trying to save the following bitmap either in the external storage, if available and if not available, to save it in the internal storage. I thought that the following code should work but when I removed my sd card, I am still getting the toast message from the sd card section. I can get it to work if I just use either the external or internal section of the code but can't seem to figure out how to get both of them working together...
save.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        LinearLayout ll = findViewById(R.id.form_linear_layout);
        Bitmap bitmap = getBitmapFromView(ll);

        String state = Environment.getExternalStorageState();
        if (!Environment.MEDIA_MOUNTED.equals(state)) {

            pathInternal = saveInternalImage(bitmap);
            //If it isn't mounted - we can't write into it.
            // return "";
        } else {
            path = saveImage(bitmap);
        }
    }

    public String saveInternalImage(Bitmap myBitmap) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File wallpaperDirectory = new File(
                Environment.getDataDirectory() + IMAGE_DIRECTORY /*iDyme folder*/);

        // have the object build the directory structure, if needed.
        if (!wallpaperDirectory.exists()) {
            wallpaperDirectory.mkdirs();
            Log.d("hhhhh", wallpaperDirectory.toString());
        }

        try {
            File f = new File(wallpaperDirectory, Calendar.getInstance()
                    .getTimeInMillis() + ".jpg");
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            MediaScannerConnection.scanFile(MainActivity.this,
                    new String[]{f.getPath()},
                    new String[]{"image/jpeg"}, null);
            fo.close();
            Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
            //  Toast.makeText(MainActivity.this, "You have successfully saved into the phone internal memory!", Toast.LENGTH_SHORT).show();
            return f.getAbsolutePath();

        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Toast.makeText(MainActivity.this, "You have successfully saved into the phone internal memory!", Toast.LENGTH_SHORT).show();
        return "";
    }

    public String saveImage(Bitmap myBitmap) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File wallpaperDirectory = new File(
                Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY /*iDyme folder*/);

        String state = Environment.getExternalStorageState();
        if (!Environment.MEDIA_MOUNTED.equals(state)) {

            Toast.makeText(MainActivity.this, "You do not have an SD Card!", Toast.LENGTH_SHORT).show();

            //If it isn't mounted - we can't write into it.
            //    return "";
        }

        // have the object build the directory structure, if needed.
        if (!wallpaperDirectory.exists()) {
            wallpaperDirectory.mkdirs();
            Log.d("hhhhh", wallpaperDirectory.toString());
        }

        try {
            File f = new File(wallpaperDirectory, Calendar.getInstance()
                    .getTimeInMillis() + ".jpg");
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            MediaScannerConnection.scanFile(MainActivity.this,
                    new String[]{f.getPath()},
                    new String[]{"image/jpeg"}, null);
            fo.close();
            Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
            //     Toast.makeText(MainActivity.this, "You have successfully saved into the phone External memory!", Toast.LENGTH_SHORT).show();
            //        return f.getAbsolutePath();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        Toast.makeText(MainActivity.this, "You have successfully saved into the phone External memory!", Toast.LENGTH_SHORT).show();
        return "";
    }
}

A: For example check bool condition:
Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

and more info you can find here.


text:
Q: Wpf textbox converter to double in combination with updatesourcetrigger=propertychanged In our project we have a WPF textbox that is bound to a double. There is a converter that allows in the convertback to for example use both "." and "," to as decimal points and in the convert method it formats the double to the n2 numeric format.
  Here you can see a simplefied version of  our converter:
public class DoubleConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null || value.GetType() != typeof(double))
            return null;
        else
            return ((double)value).ToString("n2");
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
           return null
        else
             return Double.Parse(((string)value).Replace('.',','));
    }
}

The textbox looks like this:
        <TextBox  Text="{Binding Path=Factor, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Width="500" Height="50" />

And the double property raises a propertychanged event:
public double Factor
    {
        get { return _factor; }
        set
        {
            _factor = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Factor"));
        }
    }

This used to work fine in previous versions of WPF because the convert was'nt called when you were entering text. This behavior apparently has changed and now the convert method is called on every text entry, causing the double to be formatted when you type something.Even if you don't use formatting you have the problem of not being able to enter a decimal point.
This can be solve by not using UpdateSourceTrigger=Propertychanged, but we need this for validation. We implement validation by using the IDataErrorInterface. I know there is a ValidateWithoutUpdate method, but this doesn't work for validation using the IDataErrorInterface.
So what I basicly need is ConvertBack (and thus the validation) to happen OnPropertyChanged and the Convert to only happen OnLostFocus.
  Is this possible? Or is there another solution for our problem?

A: Yes, the behavior change from .Net 3.5 to .Net 4.0, where it now sends source updates back to targets even if the update originated from the target.  This SO post explains it a bit and provides a solution:
Why does binding setup behave differently in .NET 4 vs .NET 3.5
These are the options I've found so far for dealing with this:

*

*Have the converter maintain the state of the input on ConvertBack and restoring it in Convert (suggested in link above)

*Change backing data to strings, handle conversion in model

*Create a custom control that handles this kind of numeric input similar to how a DateTimePicker works (it maintains a string and double representation of the data; displays the string, but is bound by the double)


text: Q: web.config with multiple impersonation My applications use data from one SQL server on our network.  The SQL server is on separate machine from the IIS server that hosts my applications.  I am using integrated security, Windows authentication, and impersonation in the web.config. Now I need to connect to another SQL box that does work with the impersonated account.  So how do I pass proper identity to each of the SQL servers to get data from each?  The web.config only allows one impersonation.


text:
Q: How can I get the center of a scaled image wherever I want it---(x,y)---in the document? According to some coordinate system, whatever that may be, how can I position a scaled image where I want it in the document using the center of the image as the point of reference? For example, something like this:
\being{whatever}(4cm,6cm)
     \includegraphics[scale=0.5]{img.jpg}
\end{whatever}

Here is my minimal working whatever:
\documentclass{article}
\usepackage{something}
\title{Cartesian closed categories and the price of eggs}
\author{Jane Doe}
\date{September 1994}
\begin{document}
   \maketitle
   Hello world!
\end{document}

A: Simply replace the text that was being placed with the appropriate \includegraphics:

Below is an adaption of What are the ways to position things absolutely on the page to use \includegraphics[<<options>>]{<<file>>} instead of given text.
Code:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}

%% ------ https://tex.stackexchange.com/a/169836/4301
%% Following obtained from \layout. May need adjustment based on class and
%% page settings.  Alternatively, can set these to 0pt and then position will
%% be relative to bottom left of page.
\newcommand*{\BottomLeftX}{1.0in+\hoffset+\oddsidemargin}%
\newcommand*{\BottomLeftY}{\paperheight-1.0in-\voffset-\topmargin-\headheight-\headsep-\textheight}%

\newcommand*{\AbsolutePosition}[4][]{%
    % #1 = tikz options
    % #2 = x (from south west corner of page
    % #3 = y
    % #4 = text
    \begin{tikzpicture}[remember picture,overlay, ultra thick]
        %\draw [shift={(#2,#3)},#1]  (current page.south west) circle (2pt)
        \draw [#1]  ($(current page.south west) + (\BottomLeftX,\BottomLeftY) + (#2,#3)$)
            %circle (2pt) %  adding `[opacity=0.2]` to the node below will let you see this reference point
                node[] {#4};
    \end{tikzpicture}%
}

\title{Cartesian closed categories and the price of eggs}
\author{Jane Doe}
\date{September 1994}
\begin{document}
   \maketitle
   Hello world!

\AbsolutePosition[fill=red,draw=red]{7.0cm}{12.0cm}{\includegraphics[scale=0.1]{../images/EiffelWide}}
\end{document}


text:
Q: Don't fire mouseenter event on parent For tags (td, p, li) that contain text, I added a data-id attribute. When hovering over a tag that has a data-id attribute, the button needs to be displayed. Everything works fine, except when the tags are nested, for example:

text

This example displays two buttons, one for the parent and one for the child. I added e.stopImmediatePropagation(); but that doesn't work for td. Here is the code itself:
$('[data-id]').mouseenter(function (e) {
  GodObj.btnadd = $('<button class="btn btn-outline-dark btn-note-tag">' +
    '' + '</button>');

  $(this).append(GodObj.btnadd);
  e.stopImmediatePropagation();
}).mouseleave(function () {
  $(GodObj.btnadd).remove();
});

Example when two buttons are drawn:

...

Content is added by users through the editor on the site, so there is no strict rule for the level of nesting of tags into each other.
How to make the button render only once or for parent or child elements?

A: You need to start with e.stopImmediatePropagation();:
            $('[data-id]').mouseenter(function (e) {
                e.stopImmediatePropagation();
                GodObj.btnadd = $('<button class="btn btn-outline-dark btn-note-tag">' +
                    '' +
                    '</button>');
                $(this).append(GodObj.btnadd);
            }).mouseleave(function () {
                $(GodObj.btnadd).remove();
            });


text:
Q: Remove high-speed noise from power supply Could anyone help me a bit sort this out?
I have implemented the following schematic on a PCB for the decoupling of a supply rail of an Ethernet Switch.

More specifically it is the IO supply of the SSMII interface. This implementation is also what the manufacturer proposes. The 3.3V comes from a step-down DC-DC converter.
I have noticed that the power supply after the L (so IC side) is not very clean. When measured with the oscilloscope on pin 1 of L462, I had the following waveform

The frequency measured by the oscilloscope is not always the same. It varies a bit between 25MHz and 60MHz. Although this was true before making the following changes (the measurement was taken with These)

*

*Substitute one 10nF and one 100nF with two 330pF capacitors

*Add an additional 4.7uF capacitor (all ceramic) at the L462.1 pin.

On the other side, the L462.2 side, all Looks quieter.
What can I additionally do in order to have a cleaner power supply? Use an additional capacitor? Replace with another value? Normally at these frequencies the 100nF and 10nF are indeed effective, no?
Here also the layout. The supply rail after the bead (the relative big component upper left) is coloured with yellow. They are all connected through a small plane on an inner layer. It is probably not ideal that many capacitors share the same via, but at this area there are not any more GND balls. Also probably the light green capacitors should be turned horizontally and be connected to the two GND vias on the right side of the image.

So, I took some new measurements by using the technique of soldering a Coax cable directly on a capacitor and the results can be seen in the waveforms below.
First at L462.1:

and second at the L462.2 pin:

I mean, apart from the frequency (here I detected more clearly the 31.25MHz, which is the half of the 62.5MHz with which the data signals of this Interface work), it is still clear that the disturbances are there and that they are filtered away from the main board's supply with the ferrite bead.
Then, lastly, I substituted the ferrite bead with a 0-Ohm resistor:

I think it is clear that the disturbances come from the IC and that without the filtering the situation would be worse.
So the question remains, how to make the power supply quieter?

A: When decoupling the use of parallel capacitors with values that are decade apart is like playing russian roulette. That is because you will get a resonant spike when the network with the bigger capacitor has become inductive and the network with smaller capacitor is still capacitive. I don't know if this is the problem here but maybe you should try replacing all the capacitors with one value either 10 or 100n. I did fast ltspice simulation to illustrate my point.

This is impedance with two different value capacitors connected by traces with identical inductances.

And this is impedance with identical capacitor values.
Edit: Here is the simulation file as requested in comments:
Version 4
SHEET 1 880 680
WIRE 208 208 -16 208
WIRE 304 208 208 208
WIRE 208 240 208 208
WIRE 304 240 304 208
WIRE -16 336 -16 208
WIRE 208 336 208 304
WIRE 304 336 304 304
WIRE -16 480 -16 416
WIRE 16 480 -16 480
WIRE 208 480 208 416
WIRE 208 480 16 480
WIRE 304 480 304 416
WIRE 304 480 208 480
WIRE 16 544 16 480
FLAG 16 544 0
SYMBOL voltage -16 320 R0
SYMATTR InstName V1
SYMATTR Value ""
SYMATTR Value2 AC 1 0
SYMBOL cap 192 240 R0
SYMATTR InstName C1
SYMATTR Value 100n
SYMBOL ind 192 320 R0
SYMATTR InstName L1
SYMATTR Value 3.5n
SYMBOL cap 288 240 R0
SYMATTR InstName C2
SYMATTR Value 10n
SYMBOL ind 288 320 R0
SYMATTR InstName L2
SYMATTR Value 3.5n
TEXT 432 256 Left 2 !.ac dec 1000 1 1000000000

The expression to plot is:V(n001)/I(V1).
Also I might not have understood correctly how you connected the capacitors but since inductance has a big influence here you should make sure that all the parallel caps are not connected through common but separate inductances. The motivation is that when connected in parallel the combined impedance of capacitance increases while the combined impedance of inductance reduces. So multiple capacitors having current flow through the same via is bad idea for decoupling purposes. Do whatever you can to avoid that.

A: Probing and grounding setup for measurements like this make all the difference. What you are seeing on the scope may in fact be quite different from reality.
So when making the measurements make sure that the probe tip is right at the capacitor / ferrite bead node and that the probe ground is right at the IC / capacitor GND. Long test leads can pickup noise from other parts of your system. As a minimum try winding the scope GND lead around the probe body so it does not expose itself as an open antenna loop.
Also evaluate your layout so to make sure that the capacitor grounds shown return / connect directly back to the GND pins of the IC directly associated with the AA13 -> AA18 power rail pins.
Using the above careful measurement technique check if the noise that you see is indeed worse on the IC chip side of the ferrite bead. If it is then it is highly likely that layout of your PC board has less than optimum power and ground connections to the IC chip and the associated bypass capacitors. Hopefully you have a full GND plane on the board.
If the noise turns out to actually be worse on the 3.3V side of the ferrite bead then the source of the noise is most likely from the DC-DC converter that produces the 3.3V. In this case it may be helpful to add a second ferrite bead in series with the one you have now and then add an additional capacitor from between then to the GND. (This will not be of much help of course if the overall GND system on the board is compromised).


text:
Q: MySQL Connector : could not process parameters can't delete rows I can't use execute method
conn = connect(**cinfo)
cursor = conn.cursor()
# Drop the tables.
drop_query = 'DELETE FROM %s;'
tables = ['History', 'Product', 'Category']
for table in tables:
    cursor.execute(drop_query, (table,))
conn.commit()

I have this error:

Failed executing the operation; Could not process parameters

EDIT:
I want to delete all the rows of these tables

A: Try it with TRUNCATE. It will remove all the rows in your given table. This is what MySQL Documentation mention about it.

TRUNCATE TABLE empties a table completely. It requires the DROP privilege. Logically, TRUNCATE TABLE is similar to a DELETE statement that deletes all rows, or a sequence of DROP TABLE and CREATE TABLE statements.

conn = connect(**cinfo)
cursor = conn.cursor()
# Drop the tables.
drop_query = "TRUNCATE TABLE {};"
tables = ['History', 'Product', 'Category']
for table in tables:
    cursor.execute(drop_query.format(table))
conn.commit()
conn.close()

For more information you can read this How to Delete All Rows of a MySQL Table in Python article too. Use string concatenate with format.
conn = connect(**cinfo)
cursor = conn.cursor()
# Drop the tables.
drop_query = "DELETE FROM {};"
tables = ['History', 'Product', 'Category']
for table in tables:
    cursor.execute(drop_query.format(table))
conn.commit()
conn.close()


text:
Q: 3D randomized generation of planets For a project, I'm doing creation of planets in 3D space, based around a center "homeworld", that are randomly generated in all directions from the origin.
I've looked at procedural generation and Perlin noise, but I couldn't find a decent way to make them applicable, but I'm new to randomized generation of any kind.
Any good starting points for an algorithm for 3D-point generation, centered around the origin, preferably based on a seed (so the same seed makes the same universe).
Thanks!

A: Try using a set of different random numbers rather than trying for a specific algorithm to do this with a single seed.
first one is 1-360 is the rotation around the y axis
second one is 1-180 is the deviation from the y axis (wobble)
third one is 1-<really big  number> is the distance from your centre point (homeworld)
fourth (optional) one is to randomize the radius of the planet
fifth (optional) is to randomize the colour of the object

To plot your planet then it's just some simple trigonometry to work out the location in 3d space (x,y,z) from your origin (homeworld).
And so long as your seed values for each are the same you will be able to generate a very large planet space.
If you want to do this with a single seed, then use that seed to generate 'random' seed numbers for all the subsequent random number generators.

A: I had an idea in the long time it took to load this page which I don't see represented yet.
You could start with a tetrahedron and then, for a specified number of iterations,

*

*select a triangular face at random

*

*replace the face with a new tetrahedron erected on that base.

With a completely uniform random number distribution, this should approximate a sphere. With a deterministic PRNG, the result should be reproducible by using the same initial seed.


text:
Q: Disable category filter from head I want to delete this dropdown list All category:

I saw a lot of answers how to disable category dropdown via xml, but not of them helped me. I will be grateful if someone will explain me how to use unsetChild-method or something like this. This is original code:
<reference name="header">
    <block type="core/template" name="top.search" as="topSearch" template="catalogsearch/form.mini.phtml"/>
</reference>

I tried this one, but still no changes:
<reference name="header">
    <block type="core/template" name="top.search" as="topSearch" template="catalogsearch/form.mini.phtml">
        <action method="unsetChild"><alias>category_filter</alias></action>
    </block>
</reference>

A: Using Template path hints from backend find the path to your file form.mini.phtmlusually it will be placed under app\design\frontend\yourpackage\yourtheme\template\catalogsearch\form.mini.phtmlthen delete the drop down list coding carefully.(If you not sure about coding create a backup copy of form.mini.phtml then try your tests)
If you simply want to hide dropdown listshowing on frontend only,use css display:none under specific .class on your respective stylesheet.

A: I think you have an extension, and you need to disable the extension. Try path hints and see the name, and then search in admin panel for that name and disable it.


text:
Q: If $x,y,z$ are positive numbers, then prove that $\frac {x}{x+y} + \frac{y}{y+z} +\frac {z}{z+x} \le 2$
If $x$, $y$ and $z$ are positive numbers, then prove that $$\frac {x}{x+y} + \frac{y}{y+z} +\frac {z}{z+x} \le 2.$$

Though I have solved a lot of problems on AM-GM inequality, I am unable to solve this one. I am also not showing my working because I do not think that they will be of any help.

A: $$\sum_{cyc}\frac{x}{x+y}\leq\sum_{cyc}\frac{x+z}{x+y+z}=2$$

A: Solution by C-S.
We need to prove that:
$$\sum_{cyc}\left(\frac{x}{x+y}-1\right)\leq-1$$ or
$$\sum_{cyc}\frac{y}{x+y}\geq1,$$
which is true because by C-S
$$\sum_{cyc}\frac{y}{x+y}=\sum_{cyc}\frac{y^2}{xy+y^2}\geq\frac{(x+y+z)^2}{\sum\limits_{cyc}(xy+y^2)}\geq1.$$
But the previous idea is still better:
$$\sum_{cyc}\frac{y}{x+y}\geq\sum_{cyc}\frac{y}{x+y+z}=1.$$

A: Alternatively: let $a = x+y, b = y+z, c = z+x$, then $a,b,c$ are the lengths of the sides of a... triangle From this: $x = (x+y+z) - (y+z) = \dfrac{a+b+c}{2} - b = \dfrac{a+c-b}{2}, y = \dfrac{a+b+c}{2} - c = \dfrac{a+b-c}{2}, z = \dfrac{a+b+c}{2}-a = \dfrac{b+c-a}{2}\implies LHS = \dfrac{a+c-b}{2a}+\dfrac{a+b-c}{2b}+\dfrac{b+c-a}{2c}\le 2=RHS\iff \dfrac{c-b}{a}+\dfrac{a-c}{b}+\dfrac{b-a}{c}\le 1$. Assume $0 < a \le b\le c$, then observe: $\dfrac{b-a}{c} < \dfrac{c}{c} = 1$, and $\dfrac{c-b}{a}+\dfrac{a-c}{b} = \dfrac{bc-b^2+a^2-ac}{ab}= \dfrac{(b-a)(c-a-b)}{ab}\le 0$ since $a \le b, c < a+b$. Thus $\dfrac{c-b}{a}+\dfrac{a-c}{b}+\dfrac{b-a}{c} < 1$, and the inequality is proven...

A: If you want to do this more by hand write $$2=\frac {x+y}{x+y}+\frac {y+z}{y+z}$$ and the inequality becomes $$\frac z{x+z}\le\frac y{x+y}+\frac z{y+z}$$
If you now clear denominators (everything is positive) and expand the expression is homogeneous and not too difficult to work with. On the left you get $z(x+y)(y+z)=xyz+xz^2+y^2z+yz^2$ and it is easy to spot that these will appear on the right with other positive terms.


text:
Q: How to import NgbCalendar in Storybook? I built Angular component that uses ngbDatepicker. The component (named DatepickerComponent) imports following classes:
import { NgbDateStruct, NgbCalendar, NgbDatepickerI18n, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap';

I want to display the component in Storybook by creating story datepicker.stories.ts:
import { withPreview, previewTemplate, DEFAULT_ANGULAR_CODESANDBOX } from 'storybook-addon-preview';
import { moduleMetadata } from '@storybook/angular';
import { DatepickerComponent } from 'src/app/datepicker/datepicker.component';
import { NgbModule, NgbCalendar } from '@ng-bootstrap/ng-bootstrap';

export default {
  title: 'Datepicker',
  decorators: [
    moduleMetadata({
      declarations: [DatepickerComponent],
      imports: [NgbModule, NgbCalendar]
    }),
    withPreview
  ]
};

export const Datepicker = () => ({
  component: DatepickerComponent
});
Datepicker.story = { name: 'Datepicker' };

When I run storybook, I get this error message:

Unexpected value 'NgbCalendar' imported by the module 'DynamicModule'. Please add a @NgModule annotation.

How should I correctly import NgbCalendar?

A: The same providers, that are defined in @Component, have to be in moduleMetadata in story as well:
export default {
  title: 'Datepicker',
  decorators: [
    moduleMetadata({
      declarations: [
        DatepickerComponent
      ],
      imports: [NgbModule],
      providers: [
        I18n,
        { provide: NgbDatepickerI18n, useClass: CustomDatepickerI18n },
        { provide: NgbDateParserFormatter, useClass: CustomNgbDateParserFormatter }
      ]
    })
  ]
};


text:
Q: iAd in Xcode, connecting AdBannerView to delegate? So, after watching Geeky Lemon's tutorial on youtube (https://www.youtube.com/watch?v=0NkgmhpJovM&list=UU6-UA1FoMnbO2LCLWPCM9aA&index=27) on how to implement iAds into your app. My problem is, when I have all the code finished and try to connect my AdBannerView to the delegate, for some reason in the storyboard when I select the AdBannerView I can see the delegate connection in inspector on the right hand side, however there is no way to connect it.
Here is my code.
My .h file:
#import <iAd/iAd.h>
#import <UIKit/UIKit.h>

@interface FirstViewController : UIViewController <MFMessageComposeViewControllerDelegate,    ADBannerViewDelegate>         {
}

My .m file:
#import "FirstViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController

- (void) bannerViewDidLoadAd:(ADBannerView *)banner{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[banner setAlpha:1];
[UIView commitAnimations];

}

- (void) bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[banner setAlpha:0];
[UIView commitAnimations];
}

So in recap I need to know how to connect my banner to files owner, while using a storyboard?
Please can you help, any help given is greatly appreciated.
Thanks in advanced.

A: One way to connect your delegate is to select your Ad Banner View and then bring up the Outlet Collection inspector (on the right side).  Then control click on the "delegate" and drag the connection line over to your view controller, like this:

Make sure you've set your view controller to be the right custom type, too!


text:
Q: Installing phpmyadmin in another port I have a VPS where i host different websites, not only in apache but other platforms like Ruby on Rails. To set this up, I use nginx as front-end webserver, as proxy. I have apache running in port 8080.
Now I wanted to install phpmyadmin, so I did sudo apt-get install phpmyadmin but i get nothing when I access either http://<myserverip>/phpmyadmin or http://<myserverip>:80/phpmyadmin
How could I solve this problem?

A: Try to change the phpmyadmin port to 8080
(default) nano /etc/apache2/conf.d/phpmyadmin.conf
Since your Apache is running on that port.


text:
Q: Error 1004 - Open a workbook I try to open a workbook in a folder which a user decide by entering Dateconso. Open the workbook copy/paste in another workbook.
The problem is that the code breaks at opening the file.

Execution error 1004:'11400. 16.01.xlsm' not found.

Here the thing the name of the workbook is 11400.16.01.xlsm without any space between 11400. and 16 (which is Dateconso).
I understand that it cannot open this workbook because it doesn't exist...but this is not the workbook I want to open !!!
Sub consolidation()
        '
        ' Macro

        ' Déclaration des variables
          Dim wb As Workbook
          Dim myPath As String
          Dim myFile As String
          Dim Dateconso As String

         'Optimisation de la Macro Speed
         Application.ScreenUpdating = True
         Application.EnableEvents = True

        'Sélection de la date
          Dateconso = InputBox("Quelle date souhaitez-vous consolider?","Question")
         If Dateconso = "" Then Exit Sub 'Si rien exit le  programme

         'Trouve les fichiers qui on la date associée
         myFile = Dir("Z:\7. Personnel\Florian\Projet_BDC\Test\*.xlsm")

    While myFile <> ""
        If InStr(myFile, Dateconso) > 0 Then 'si tu trouve la date recherchée, alors ouvre le fichier puis copie toute puis colle
           Set wb = Workbooks.Open(Filename:=myFile)
           wb.Worksheets(1).Range("A1").Select
           Range(Selection, Selection.End(xlToRight)).Select
           Range(Selection, Selection.End(xlDown)).Select
           Selection.Copy
           Workbooks("Consolidation.xlsm").Worksheets(2).Activate
           ActiveSheet.Paste
           wb.Close
           Else: MsgBox "Fichiers introuvables, vérifiez le format de date entré" 'Si il ne trouve rien, préviens l'utilisateur
           Exit Sub
        End If
        myFile = Dir()
    Wend

End Sub

A: This actually has nothing to do with the way that VBA is misreading the filename. In fact, the repair (e.g. extra space character) is necessary in a filenname containing periods for some reason. Leave the filename alone.
The problem is that you are not supplying the path along with the filename. The Dir function only returns the filename, not the full path. You need to add the path back in before using it.
Dim fp As String, fn As String

fp = "Z:\7. Personnel\Florian\Projet_BDC\Test\"
fn = Dir(fp & "*.xlsm")

While fn <> ""
    If InStr(fn, Dateconso) > 0 Then 'si tu trouve la date recherchée, alors ouvre le fichier puis copie toute puis colle
       Set wb = Workbooks.Open(Filename:=fp & fn)
            'do stuff
       wb.Close
       Else: MsgBox "Fichiers introuvables, vérifiez le format de date entré" 'Si il ne trouve rien, préviens l'utilisateur
       Exit Sub
    End If
    fn = Dir()
Wend


text:
Q: "Pulling down" the elements of the 2D array to the blank spaces within the array I am a beginner in C and I just wanted to create a simple program on CM-DOS that is like Bejewelled.
I am almost done with the coding but there is just ONE problem:
In Bejewelled, when the matches are found, the elements above those matches will replace the the empty spaces created by the matches (the so-called "Pull Down").
I am having trouble with it because the program just ignores my code for Pulling down and
just prints the empty space as is.
Please help?
My Program is 2D array of a[6][6].
Initialize(b); is a function that checks if the generated alphabet has any matches with the existing alphabets. If yes, then it will re-genrate the generated alphabet into another until
there is no match.
It basically fills the random alphabets from 'A' to 'D' into b[8][8] then converts b[8][8] into
a[6][6] then prints grid.
Here is my problematic pulling down code:
void pull(char a[6][6], char b[8][8])
{
int j=0,i=0,loop=0;

while(loop){
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= 5; j++)
{
if(a[i][j]==' ')
{
a[i][j]=a[i-1][j];
loop=1;
}
else if (a[i][j] == a[0][j])
{
a[i][j] = rand()%4 + 'A';
initialize(b);
}
}
}
}
}

This is what I want (For Example)
C   A   B   C   D   C

A   B   C   D   B   D

D   C   D   !A   A   A!  // Match Found

A   B   D   C   B   C

B   D   C   A   C   D

C   D   C   B   C   C

Then
C   A   B   C   D   C

A   B   C   D   B   D

D   C   D   ?   ?   ?  // ? = space

A   B   D   C   B   C

B   D   C   A   C   D

C   D   C   B   C   C

Then
C   A   B   C   D   C

A   B   C   ?   ?   ?  // ? = space gets swapped upward

D   C   D   D   B   D

A   B   D   C   B   C

B   D   C   A   C   D

C   D   C   B   C   C

And then
C   A   B   ?   ?   ?

A   B   C   C   D   C

D   C   D   D   B   D

A   B   D   C   B   C

B   D   C   A   C   D

C   D   C   B   C   C

If the ? reaches the maximum height, it generates new random alphabets into ?
C   A   B   A*  C*  B* // *New Alphabets

A   B   C   C   D   C

D   C   D   D   B   D

A   B   D   C   B   C

B   D   C   A   C   D

C   D   C   B   C   C

A: void nomatch(char a[6][6])
{
int i, j,k;
int ini;

ini=0;
do {
for (k = 0; k < 7; k++)
{
for (i = 0; i < 7; i++)
{
for (j = 0; j < 7; j++)
{
if (a[i][j] == a[i+1][j] && a[i+1][j] == a[i+2][j])
{
a[i + 1][j] = get_randltr(a[i][j]);
a[i + 2][j] = get_randltr(a[i][j]);
ini=1;
}
if (a[i][j] == a[i][j+1] && a[i][j+1] == a[i][j+2])
{
a[i][j + 1] = get_randltr(a[i][j]);
a[i][j + 2] = get_randltr(a[i][j]);
ini=1;
}
else
ini=0;
}
}
}
}while(ini);
}

void initialize(char a[8][8])
{
int i, j;
int ini;

ini=0;
do {
for (i = 1; i < 7; i++)
{
for (j = 1; j < 7; j++)
{
if (a[i][j] == a[i-1][j] && a[i-1][j] == a[i-2][j])
{
a[i - 1][j] = get_randltr(a[i][j]);
a[i - 2][j] = get_randltr(a[i][j]);
ini=1;
}
if (a[i][j] == a[i+1][j] && a[i+1][j] == a[i+2][j])
{
a[i + 1][j] = get_randltr(a[i][j]);
a[i + 2][j] = get_randltr(a[i][j]);
ini=1;
}
if (a[i][j] == a[i][j-1] && a[i][j-1] == a[i][j-2])
{
a[i][j - 1] = get_randltr(a[i][j]);
a[i][j - 2] = get_randltr(a[i][j]);
ini=1;
}
if (a[i][j] == a[i][j+1] && a[i][j+1] == a[i][j+2])
{
a[i][j + 1] = get_randltr(a[i][j]);
a[i][j + 2] = get_randltr(a[i][j]);
ini=1;
}
else
ini=0;
}
}
}while(ini);
}

void pulling(char b[6][6])
{
int rowc, i, colc,empty,temp;

for(colc = 0; colc < 5; colc++)
{
for (i = 0; i < 5; i++)
{
for (rowc = 0; rowc < 5; rowc++)
{
empty = b[rowc][colc];

if (empty != '*')
{
if(b[rowc+1][colc] == '*')
{
temp = b[rowc][colc];
b[rowc][colc] = b[rowc+1][colc];
b[rowc+1][colc] = temp;

}
}
}

}

}
for (rowc=0; rowc<6; rowc++)
{
for (colc=0; colc<6; colc++)
{
if(b[rowc][colc] == '*')
{
b[rowc][colc] = rand()%4 + 'A';
nomatch(b);
}
}
}
}


text:
Q: Calling a function from a user entered variable [no eval()] I am trying to make a button 'thing' that handles buttons.
I need to have a way to call a user defined function when the button is clicked.
Here is an examples of an element that would be selected as a button:

So, when the button is clicked I want it to get the aFunction() value and use it to call that function.
Example:
elem.onclick = function(){
    action = this.getAttribute('buttonaction');
    action();
}

I know this example is wrong, but I think it conveys what I want to do.
Thanks,
- Michael Mitchell

A: You could setup your functions something like this:
var my_allowed_functions = {
    func1: function(arg1, arg) {
        alert(arg1 + arg2);
    },
    func2: function(arg1, arg) {
        alert(arg1 + arg2);
    }
};

And just call one of them by name:
my_allowed_functions['func1'].apply(this, argument_array);

A: html:

script :
var aFunction = function(){};

var buttons = document.querySelectorAll(".button");

[].forEach.call(buttons,function(button){
 button.onclick = function(event){
  var ct = event.currentTarget;
  var func = ct.getAttribute("buttonaction");
  window[func]()

 }
}

however , when you do  window[func]() you are still doing a scoped eval.
so why not just do :

A: There is no way to run arbitrary code without running arbitrary code. Your concern with eval is the security risk, however, if you used a different function named ponies to somehow run user entered code instead it would still be as dangerous.
Your requirements demand eval, so that is what you should use, or rethink your requirements.

A: Here's another method, with window:


text:
Q: Is element displayed in div I am trying to check if the element is displayed in the div(divContent) or not.
The starting point is: elements: 1,2,3,4 are displayed.
So why the function: checkIfInView, returns true for element number 6?
This is my jsfiddle:
http://jsfiddle.net/Ht6Ym/2971/
function checkIfInView(element){
    var offset = element.offset().top - $('#divContent').scrollTop();

    if(offset > $('#divContent').innerHeight){
        // Not in view
        return false;
    }
   return true;
}

thanks!

A: You're not calling innerHeight.  You need the parenthesis for it to execute the function.  Otherwise you are evaluating against the function declaration (not sure if that's the right term for it.  Correct me if I'm wrong please).
Change
if(offset > $('#divContent').innerHeight){

to
if(offset > $('#divContent').innerHeight()){


text:
Q: Trying to integrate Launch4j in a Maven project using Alakai plugin I am trying to integrate the generation of an installer as part of a maven compilation process.
I have found Alakai's plugin for Launch4j. I have create a simple Hello World application using Maven. I have tried to use configuration examples provided by Alakai, but when I compile my project, I get:

Failed to execute goal
  org.bluestemsoftware.open.maven.plugin:launch4j-plugin:1.5.0.0:launch4j
  (launch4j) on project Launch4j: Failed
  to build the executable; please verify
  your configuration. Application jar
  doesnt exist. -> [Help 1]

Unfortunately, Alakai's documentation is limited and I could not find much with Googling.

*

*Does anyone know where the Launch4j config.xml should be set? Is it within the project? Is it in a separate directory?

*Do I need to use the assembly plugin?

*I have installed Launch4j on my PC. Do I need to specify the installation directory in my pom.xml? If yes how?

*Does anyone have an operational pom.xml sample/example to share?

Thanks.

A: *

*There's no config.xml, you need to configure launch4j inside your pom.xml file.

*You could use maven-assembly-plugin, but I recommend you to use maven-shade-plugin.

*Don't need to specify launch4j installation, this plugin works 100% maven.

*Sure. Follows the shade and launch4j configs I use, that generates two exes, one console and one gui, using different main classes:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>1.4</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <shadedArtifactAttached>true</shadedArtifactAttached> <!-- Make the shaded artifact not the main one -->
        <shadedClassifierName>shaded</shadedClassifierName> <!-- set the suffix to the shaded jar -->
    </configuration>
</plugin>

<plugin>
    <groupId>org.bluestemsoftware.open.maven.plugin</groupId>
    <artifactId>launch4j-plugin</artifactId>
    <version>1.5.0.0</version>
    <executions>

        <!-- GUI exe -->
        <execution>
            <id>l4j-gui</id>
            <phase>package</phase>
            <goals>
                <goal>launch4j</goal>
            </goals>
            <configuration>
                <headerType>gui</headerType>
                <outfile>target/app-gui.exe</outfile>
                <jar>target/${artifactId}-${version}-shaded.jar</jar> <!-- 'shaded' is the value set on shadedClassifierName above -->
                <errTitle>App Err</errTitle>
                <classPath>
                    <mainClass>package.AppGUI</mainClass>
                </classPath>
                <icon>src/main/resources/icons/exeIcon.ico</icon>
                <jre>
                    <minVersion>1.5.0</minVersion>
                    <maxVersion>1.6.0</maxVersion>
                    <initialHeapSize>128</initialHeapSize>
                    <maxHeapSize>1024</maxHeapSize>
                </jre>
                <versionInfo>
                    <fileVersion>1.0.0.0</fileVersion>
                    <txtFileVersion>1.0.0.0</txtFileVersion>
                    <fileDescription>Desc</fileDescription>
                    <copyright>C</copyright>
                    <productVersion>1.0.0.0</productVersion>
                    <txtProductVersion>1.0.0.0</txtProductVersion>
                    <productName>Product</productName>
                    <internalName>Product</internalName>
                    <originalFilename>App.exe</originalFilename>
                </versionInfo>
            </configuration>
        </execution>

        <!-- Command-line exe -->
        <execution>
            <id>l4j-cli</id>
            <phase>package</phase>
            <goals>
                <goal>launch4j</goal>
            </goals>
            <configuration>
                <headerType>console</headerType>
                <outfile>target/app-cli.exe</outfile>
                <jar>target/${artifactId}-${version}-shaded.jar</jar> <!-- 'shaded' is the value set on shadedClassifierName above -->
                <errTitle>App Err</errTitle>
                <classPath>
                    <mainClass>package.AppCLI</mainClass>
                </classPath>
                <icon>src/main/resources/icons/exeIcon.ico</icon>
                <jre>
                    <minVersion>1.5.0</minVersion>
                    <maxVersion>1.6.0</maxVersion>
                    <initialHeapSize>128</initialHeapSize>
                    <maxHeapSize>1024</maxHeapSize>
                </jre>
            </configuration>
        </execution>
    </executions>
</plugin>

Alternatively, You can omit the 'jar' tag on launch4j-plugin and remove the extra configs of the shade-plugin, but be aware that this will replace the main jar of the flow (without embedded dependencies) by the shaded jar (with embedded dependencies), and this one will be installed on your local repo, or used in the reactor if needed.

A: For how to define the main class for the shade plugin, see http://maven.apache.org/plugins/maven-shade-plugin/examples/executable-jar.html.


text:
Q: How would I make this "team only item" script work? This is one of my first times writing in Lua so I'm not very good at it. Your suggestions and corrections would mean a great deal!
This is the code that isn't working:
game.Players.PlayerAdded:connect(function(plr)

    workspace.StarterPack:WaitForChild("Script")

    game:GetService(("Teams"):GetChildren()) do

        if plr.TeamColor == ("Really blue")then
            workspace.StarterPack.Script.Cuffs.State=Enabled:("True")
end)

Code is in:

*

*Starter Pack

*(inside) script

*(inside) tool

A: You shouldn't compress the code in that way because it make's it pretty 'unreadable'. Do you have got any kind of debug information which could guide us towards the main problem? Because as far as I can notice there are several non-ended blocks like the function, if statement and the do.
You could try to use this between. So in case you could post any source data, which you've got the inspiration from, would allow us to adapt the answer for what you are looking for:
local function handleConnection( thePlayer )
    workspace.StarterPack:WaitForChild( "Script" )

    if ( thePlayer.TeamColor == "Really blue" ) then
        workspace.StarterPack.Script.Cuffs.State = true
    end
end

game.Players.PlayerAdded:connect( handleConnection )


text:
Q: Generating a deep copy of NSDictionary in order to modify nested values Imagine the scenario where you have an NSDictionary (not a Dictionary) that contains keys and values of different types, for example an NSNumber and another NSDictionary. And there may be several nested NSDictionarys. You now need to peek into every dictionary in this structure (no matter how far nested it is) looking for a specific key, and everywhere it is found, replace its value with a different value.
How can this be achieved in Swift - specifically Swift 2?
I'm thinking a deep mutable copy of this structure could be created (NSMutableDictionary), then possibly use recursion in order to process and modify each dictionary if necessary. Once completed, replace the original structure with the modified mutable structure. If that's a good approach, how can one perform a deep mutable copy of this structure in order to work with it? Or how else could this be accomplished?
For example, this could be the dictionary:
{
    NUMFRIENDS = 3;
    GREETING =
    {
        HELLO = WORLD;
        WHATSUP = DUDE;
        ...
    }
    HELLO = WORLD;
    ...
}

And you wish to find all HELLO keys and replace their value with UNIVERSE.

A: In Objective-C I've been using this trick:
[NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:self]]

That makes automatically a deep copy of all objects using NSCoding protocol.
So in Swift the same trick should work:
NSKeyedUnarchiver.unarchiveObjectWithData(NSKeyedArchiver.archivedDataWithRootObject(self))


text:
Q: Can we say "x is almost double y" if x is more than y doubled? I just read a sentence in an English lesson:

Male winnings were almost triple those of female earnings.
(Talking about male vs female earnings in a golf competition).

However, the graph shows that female earnings were about 500k and male earnings were about 1700-1900k. So, they were more than triple female earnings. Is the word "almost" used correctly here?

A: I believe your question arises from the concept that you are considering a scale of earnings that has a direction, starting from zero and proceeding upwards. From that viewpoint, earnings of almost three times are less than three times. In the same way, on a journey, as we approach our destination, we may say that we are almost there. This interpretation is consistent with dictionary definitions such as the two below.
However, the meaning of almost does not always have such a direction. Consider "The cable car is almost at the half-way station". This tells us the cable car is near, but whether it is moving towards, away or has stopped is not defined.
Another example might be that scientists have almost reached absolute zero in their quest for lower temperatures: almost applies here to descent of the temperature scale rather than to its ascent.
Similarly, earnings almost three times are near three times, and by implication are distinguishable from two times or four times.

Almost = : very nearly but not exactly or entirely
Merriam Webster

= You use almost to indicate that something is not completely the case but is nearly the case.
Collins dictionary


text:
Q: How to delete duplicate lines while ignoring particular characters? I need to remove all of the duplicate lines from a file, but ignoring all appearances of these characters:
(),、""。!?#

As an example, these two lines would be considered duplicates, so one of them would be deleted:
"This is a line。"
This is a line

Similarly, these three lines would be considered duplicates, and only one would remain:
This is another line、 with more words。
"This is another line with more words。"
This is another line! with more words!

*

*It does not matter which of the duplicate lines is kept remaining in the document.

*After removing duplicates, the orders of the lines should not be changed.

*Nearly all lines have important punctuation, but the punctuation might vary somewhat. Whichever line is kept might still have punctuation, so the punctuation should not be deleted in the final output.

How can I delete all of the duplicate lines in a file, while ignoring some characters?

A: From your example, you could just delete your symbols, and then remove your duplicates.
For instance :
$ cat foo
«This is a line¡»
This is another line! with more words¡

Similarly, these three lines would be considered duplicates, and only one would remain:
This is a line

This is another line, with more words!
This is another line with more words

$ tr --delete '¡!«»,' < foo | awk '!a[$0]++'
This is a line
This is another line with more words

Similarly these three lines would be considered duplicates and only one would remain:

$

Seems to do the job.
Edit :
From your question, it seems like those symbol/punctuation mars do not matter. You should precise that.
I don't have time to write that but I think the easy way should be to parse your file and maintain an array of already printed line :
for each line:
  cleanedLine = stripFromSymbol(line)
  if cleanedLine not in AlreadyPrinted:
    AlreadyPrinted.push(cleanedLine)
    print line

A: This is an approach. You collect them into arrays keyed on a normalized version. Normalized here means remove all the chars you don't want and squash spaces too. Then it picks the shortest version to print/keep. That heuristic—which to keep—wasn't really specified so season to taste. Code is a bit terse for production so you might flesh it out for clarity.
use utf8;
use strictures;
use open qw/ :std :utf8 /;

my %tree;
while (my $original = <DATA>) {
    chomp $original;
    ( my $normalized = $original ) =~ tr/ (),、""。!?#/ /sd;
    push @{$tree{$normalized}}, $original;
    #print "O:",$original, $/;
    #print "N:",$normalized, $/;
}

@{$_} = sort { length $a <=> length $b } @{$_} for values %tree;

print $_->[0], $/ for values %tree;

__DATA__
"This is a line。"
This is a line
This  is   a line
This is another line、 with more words。
This is another line with more words
This is another line! with more words!

Yields–
This is another line with more words
This is a line


text:
Q: How do I dynamically make this child Fragment's TextView visible/invisible? I have a main Activity containing a parent Fragment, which in turn contains a child Fragment. I am trying to make a TextView in the child Fragment visible/invisible dynamically.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This text belongs to the Activity"
        android:id="@+id/textView"/>

    <FrameLayout
        android:id="@+id/parent_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

fragment_parent.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This text belongs to the parent fragment"
        android:id="@+id/textView"/>

    <FrameLayout
        android:id="@+id/child_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

fragment_child.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This text belongs to the child fragment"
        android:id="@+id/textView"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="But make this text visible dynamically!"
        android:id="@+id/make_this_text_visible"
        android:visibility="invisible"/>
</LinearLayout>

MainActivity.java
public class MainActivity extends AppCompatActivity {
    public static final String PARENT_TAG = "parent_tag";
    private ParentFragment mParentFragment;

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

        if (savedInstanceState == null) {
            mParentFragment = ParentFragment.newInstance();
            getSupportFragmentManager().beginTransaction().replace(R.id.parent_container, mParentFragment, PARENT_TAG).commit();
        }
        else {
            mParentFragment = (ParentFragment) getSupportFragmentManager().findFragmentByTag(PARENT_TAG);
        }
    }
}

ParentFragment.java
public class ParentFragment extends Fragment {
    public static final String CHILD_TAG = "child_tag";
    private ChildFragment mChildFragment;
    private List<Integer> mList;

    public static ParentFragment newInstance() {

        Bundle args = new Bundle();

        ParentFragment fragment = new ParentFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_parent, container, false);
        mList = new ArrayList<Integer>();

        if (savedInstanceState == null) {
            mChildFragment = ChildFragment.newInstance();
            getChildFragmentManager().beginTransaction().replace(R.id.child_container, mChildFragment, CHILD_TAG).commit();
        }
        else {
            mChildFragment = (ChildFragment) getChildFragmentManager().findFragmentByTag(CHILD_TAG);
        }
        getChildFragmentManager().executePendingTransactions(); //doesn't seem to do anything!
        doStuff();

        return view;
    }

    void doStuff() {
        mList.add(4); //pretend this is actually querying a database.
        //for simplicity it just receives a single 4.

        if (mList.size() > 0) { //the list is not empty, display the text!
            mChildFragment.setTextVisible(); //error! the textivew of the child fragment is null right now
        }
        else {
            mChildFragment.setTextInvisible(); //error! the textivew of the child fragment is null right now
        }
    }
}

ChildFragment.java
public class ChildFragment extends Fragment {
    private TextView mTextView;

    public static ChildFragment newInstance() {

        Bundle args = new Bundle();

        ChildFragment fragment = new ChildFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_child, container, false);
        mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
        return view;
    }

    public void setTextVisible() {
        mTextView.setVisibility(View.VISIBLE);
    }
    public void setTextInvisible() {
        mTextView.setVisibility(View.INVISIBLE);
    }
}

How can I ensure that the child fragment is formed by the time I call doStuff() in the ParentFragment?

A: What I would do is keep the state of the text view visibility so it can be updated properly once the view has been created if it hasn't been already. Instead of separate methods for setTextVisible() and setTextInvisible have a single method setTextVisibile(boolean isVisible) and implement it as follows:
public class ChildFragment extends Fragment {
    private TextView mTextView;
    private boolean mIsTextVisible;

    public static ChildFragment newInstance() {
        Bundle args = new Bundle();
        ChildFragment fragment = new ChildFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_child, container, false);
        mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
        setTextVisible(mIsTextVisible);

        return view;
    }

    public void setTextVisible(boolean isVisible) {
        mIsTextVisible = isVisible;
        if(mTextView != null) {
            mTextView.setVisibility(isVisible ? View.VISIBLE : View.GONE);
        }
    }
}

and then in the parent fragment you can call doStuff() without worrying about the current state of the views in the ChildFragment since mIsTextVisible is properly set. If the mTextView is null at the time setTextVisible() is called the visibility will still be properly set in onCreateView().
Just take care to save and restore the mIsTextVisible flag when the fragment is recreated such as when the device is rotated.

Alternative Answer Using A Callback
Using callbacks update the ParentFragment to implement
ChildFragment.OnViewCreatedListener and its method.
public class ParentFragment extends Fragment
    implements ChildFragment.OnViewCreatedListener {

    @Override
    public void onViewCreated() {
        doStuff();
    }
}

And then in ChildFragment
public class ChildFragment extends Fragment {
    public interface OnViewCreatedListener {
        void onViewCreated();
    }

    public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_child, container, false);
        mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);

        if(getParentFragment() instanceof OnViewCreatedListener) {
            ((OnViewCreatedListener) getParentFragment()).onViewCreated();
        } else if (getActivity() instanceof OnViewCreatedListener) {
            ((OnViewCreatedListener) getActivity()).onViewCreated();
        }

        return view;
    }
}


text:
Q: Xamarin Selecting An Image From Gallery And Displaying It In The Listview Adapter I have few questions. I have a listview,listview adapter and an activity that the listview is in. And there is a button for each listview column and it lets you choose an image from the gallery.
So all listview's objects are defined in the Adapter and you cant create the gallery selection from the Adapter. So im creating it with accessing to the activity.
1-) Can i pass my holder objects to OnActivityResult method? That would solve all the problems
2-) So how do i choose the image and then pass it to my adapter? I tried using a static variable for image uri but its not synchronizated. In my adapter class
public class Duzenle_Adapter
{
private LayoutInflater inflater;
public static Android.Net.Uri static_uri;
 public Duzenle_Adapter(Context context, int resource, List<Yemek_Liste> objects,Duzenle_Activity d) : base(context, resource, objects)
    {
        this.c = context;
        this.resource = resource;
        this.yemekler = objects;
        this.d = d;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        if (inflater == null)
        {
            inflater = (LayoutInflater)c.GetSystemService(Context.LayoutInflaterService);
        }
        if (convertView == null)
        {
            convertView = inflater.Inflate(resource, parent, false);
        }
        //List<Yemek_Liste> yemekler = new List<Yemek_Liste>();
        //yemekler = db.selectItem();
        Tutan_Duzenle tut = new Tutan_Duzenle(convertView);
        tut.img.SetImageResource(yemekler[position].Get_ImageID());//default image

        if (!tut.res_degis.HasOnClickListeners)
        {
            tut.res_degis.Click += delegate
            {

                d.tikla();
                tut.img.SetImageURI(static_uri);
            };
        }
   }

And in activity class ;
public class Duzenle_Activity:Activity
{
  ......

  protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);

        if (resultCode == Result.Ok)
        {

            Settings_Adapter.static_uri = data.Data;

        }
    }
    public void tikla()
    {
        var imageIntent = new Intent();
        imageIntent.SetType("image/*");
        imageIntent.SetAction(Intent.ActionGetContent);
        StartActivityForResult(
            Intent.CreateChooser(imageIntent, "Select photo"), 0);

    }
}

So it calls the function when the gallery opens up the adapter tries to set image uri to none.
Thanks in the advance. Sorry for the complicated post
Edit: Or is there anyway to wait for the "tikla" method to complete? That could solve the problem too.
Edit 2: Or can we customize the onActivityResult ? we can send the holder object as paramaters maybe?

A: [Activity(Label = "Duzenle_Activity", MainLauncher = true, Icon = "@drawable/icon")]
public class Duzenle_Activity : Activity
{
    ListView listView1;
    List<Yemek> objects = new List<Yemek>();

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        SetContentView(Resource.Layout.ChooseImageLayout);

        listView1 = FindViewById<ListView>(Resource.Id.listView1);
        for (int i = 0; i < 20; i++)
        {
            objects.Add(new Yemek { ButtonText = $"Select {i}" });
        }

        listView1.Adapter = new Duzenle_Adapter(this, objects);

    }

    public void tikla()
    {
        var imageIntent = new Intent();
        imageIntent.SetType("image/*");
        imageIntent.SetAction(Intent.ActionGetContent);
        StartActivityForResult(
            Intent.CreateChooser(imageIntent, "Select photo"), 0);

    }

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);

        if (resultCode == Result.Ok)
        {
            Duzenle_Adapter adapter = ((Duzenle_Adapter)listView1.Adapter);
            adapter.SelectedYemek.ImageUri = data.Data;
            adapter.NotifyDataSetChanged();
            //or listView1.Invalidate();
        }
    }
}

public class Yemek
{
    public string ButtonText { get; set; }
    public Android.Net.Uri ImageUri { get; set; }
}

public class Duzenle_Adapter : BaseAdapter<Yemek>
{
    List<Yemek> yemeklerList;
    Duzenle_Activity activity;
    int selectedPosition=-1;

    public override int Count
    {
        get
        {
            return yemeklerList.Count;
        }
    }

    public override Yemek this[int position]
    {
        get
        {
            return yemeklerList[position];
        }
    }

    public Duzenle_Adapter(Context context, List<Yemek> objects)
    {
        this.activity = (Duzenle_Activity)context;
        this.yemeklerList = objects;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        if (convertView == null) // no view to re-use, create new
            convertView = activity.LayoutInflater.Inflate(Resource.Layout.yemekler_cell, parent, false);

        var yemekler = yemeklerList[position];

        var btn = convertView.FindViewById<Button>(Resource.Id.button1);
        btn.Text = yemekler.ButtonText;
        btn.Tag = position; //store item position in Tag

        if (!btn.HasOnClickListeners)
            btn.Click += Btn_Click;
        var imgView = convertView.FindViewById<ImageView>(Resource.Id.imageView1);
        if (yemeklerList[position].ImageUri == null)
            imgView.SetImageResource(Resource.Drawable.Icon);
        else
            imgView.SetImageURI(yemeklerList[position].ImageUri);

        return convertView;
    }

    private void Btn_Click(object sender, EventArgs e)
    {
        selectedPosition = (int)((Button)sender).Tag; //store selected item position
        activity.tikla();
    }

    public override long GetItemId(int position)
    {

        return yemeklerList[position].GetHashCode(); //not used
    }

    public Yemek SelectedYemek
    {
        get
        {
            return yemeklerList[selectedPosition];
        }
    }
}

yemekler_cell.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Button
        android:text="Select Image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button1" />
    <ImageView
        android:src="@android:drawable/ic_menu_gallery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView1"
        android:layout_gravity="center" />
</LinearLayout>

ChooseImageLayout.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <ListView
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView1" />
</LinearLayout>


text:
Q: How to check if a variable exists in flex In flex, how to check if a variable exists? I have tried using
if (this['some_variable'] != undefined) {
    //do something
}

There is a run time error saying the property some_variable does not exists. I have checked with null instead of undefined, still the same error.
please help.
[EDIT]
Based on the replies I have used this.hasOwnProperty('variable_name'). I found that its returning true if variable_name is a public but false if its private/protected. How to check for a private variable?

A: There are two ways for that:
if ("some_variable" in this) {
    //do something
}

It uses in operator.
And:
if (this.hasOwnProperty("some_variable")) {
    //do something
}

See documentation about hasOwnProperty().
What about getting information about private/protected properties the situation is that you can't get this info with the current state of Flash Player. The only possible way, I suppose, is some kind of runtime bytecode manipulation. But as far as I know nobody implemented it yet.
But I have a question about getting info about private/protected properties: for what purpose you need it? The nature of these properties/methods is you can't call them. Even if you know about their existence.

A: You can use
if (this. hasOwnProperty("some_variable")) {
    //access the variable inside
}

A: if (this.hasOwnProperty('some_variable')) DO_IT_!()
Explanation:
this['some_variable'] tries to evaluate the value of the instance property some_variable. If there is no such a property, you will get this error.
To test if a property exists for a particular object use hasOwnProperty or wrap your condition in a try/catch block or use if ('some_variable' in this).
Usually you create an object property in a class file:
public class MyClass {
   public var myProperty : String = "ich bin hier";
}

Then you refer to that property within the class:
trace (myProperty);
trace (this.myProperty);

Using the array syntax [] is also possible but will throw the error if the property is not defined.
trace (this['myProperty']);

And finally! If you declare your class to be dynamic you might use the array syntax even if the property does not exist.
public dynamic class MyClass {
   public function MyClass() {
       trace (this["never_declared_property"]);
   }
}


text:
Q: Use glob ** to match file extensions based on recursive parameter I'm trying to match files with a given extension using a glob pattern.  The glob function (from glob module) has a parameter 'recursive', which seems like it should turn on or off searching subdirectories.  However, I've been unable to construct a glob pattern which will match files of a type in the current directory only if recursive=False and in subdirectories too if recursive=True.
folder='C:\\test'
glob(folder+'**.ext',recursive=True) #fails to find any files
glob(folder+'\\**.ext',recursive=True) #fails to search subfolders
glob(folder+'\\**',recursive=True) #fails to filter by type
glob(folder+'\\**\\*.ext',recursive=False) #searches subfolders when it shouldn't
glob(folder+'**\\*.ext',recursive=True) #fails to search subfolders

Based on the documentation

"**" will match any files and zero or more directories

So, I would expect ** to act like * except that it also matches slashes.  However, it isn't working as expected (see the first two examples above).
Why isn't ** working as expected and is there a pattern that will match certain file types and recursion can be switched on or off using only the recursive argument?

A: I think you have misunderstood the meaning of recursive=True. It is used to allow ** to mean searching subdirectories to a variable depth -- glob(folder+'\\**\\*.ext',recursive=True) will find any *.ext files in the starting folder or anywhere below it.  Without recursive=True, ** would be interpreted in the normal way, with each * meaning to match any number of characters excluding \, and ** would therefore just be equivalent to * -- in other words glob(folder+'\\**\\*.ext',recursive=False) would search for any *.ext files that are exactly one level of subdirectory down from the starting folder, but not in the starting folder itself or in deeper subdirectories.
Exactly which you should use will depend on what you are trying to look for -- and it may indeed be that you need to select between different cases with an if statement -- but there is no use case for using ** with recursive=False, because it is just equivalent to * in that case.
The most likely useful options are:
glob(folder+'\\*.ext',recursive=False)  # search in top folder only
glob(folder+'\\*\\*.ext',recursive=False)  # search exactly one level down
glob(folder+'\\**\\*.ext',recursive=True)  # search to arbitrary depth

The ,recursive=False can be omitted because it is the default.
If there were exactly two options that you wanted to select between using a boolean option, you could always write your own wrapper function, for example:
def myglob(folder, pattern, subdirs=False):
    if subdirs:
        return glob(f'{folder}\\**\\{pattern}', recursive=True)
    else
        return glob(f'{folder}\\{pattern}')

print(myglob(folder, '*.ext', subdirs=False))
print(myglob(folder, '*.ext', subdirs=True))
print(myglob(folder, '*.ext'))  # same as subdirs=False in this example

(In Unix-like operating systems, read / for \ above.)

A: Operation of glob '**'
The glob source code can be found here.  Other than comments, '**' only appears in the _isrecursive function:
def _isrecursive(pattern):
    if isinstance(pattern, bytes):
        return pattern == b'**'
    else:
        return pattern == '**'

Because the _isrecursive function checks for '' using the equality operator, '' will only operate as intended if it is the entire 'pattern'.  The _isrecursive function is called 4 times in the source code, once for the entire glob and 3 times for 'basename', which is defined as:
dirname, basename = os.path.split(pathname)

This is called recursively, splitting tails from the path one at a time, and each time, basename is everything following the slash (technically os.sep,which is \ for Windows or / for POSIX).  That means that in order for '**' to operate as described, it may not be adjacent to anything other than slashes.
If recursive is not explicitly set to True, '**' = '*'+'*' = '*' since '*' matches 0 or more non-slash characters.
Matching Extensions
Because of how '**' operates, it must be used to represent an entire level of the glob.  Since it represents 0 or more levels, r'folder\**\*.ext' will match files in 'folder', as well as subfolders.  However, without recursive set to true, this pattern will match only files in the first level of subfolders.
'**.ext' will not work because '**' isn't alone.  This leaves the following options:

*

*Use a different library (eg. os.walk, pathlib.glob, etc.)

*[f for f in glob(folder+'\\**',recursive=subdirs) if f.endswith('.ext')]

*glob(folder+('\\**' if subdirs else '')+'\\*.ext, recursive=True)
Or equivalently,
if recursive:
    glob(folder+'\\**\\*.ext', recursive=True)
else:
    glob(folder+'\\*.ext')

*glob(folder+'\\..\\**\\*.ext', recursive=subdirs) #not recommended since it will also match files in sibling folders


text:
Q: Splitting an update operation into chunks, with commits I am running a process acting on a returned list like this
MATCH p=(Item{name:'x'})-[r:RELATED_TO]->(w:item)
where r.relatedness > 0.25
[PERFORM CALCS AND UPDATE w]

The initial MATCH only brings back about 100 nodes, but the perform calcs step is an n^2 operation, with a reasonably large n. Each [PERFORM...]  step can be performed independently. The whole thing might take a day to run.
I would like to break this up so that it commits after each [PERFORM... ] step. This way in the event of a failure I can start up from where I left off.
In SQL server I might store the results of the initial MATCH to a table, and work through it using a CURSOR, marking off completed rows as I went
How can I do something analogous in Neo4J?

A: As a concept:
1) Save the result of the first query:
WITH 'x' as itemName
MERGE (T:SavedQueryResult {name: itemName})
WITH itemName, T
MATCH (:item {name: itemName})-[r:RELATED_TO]->(w:item) WHERE r.relatedness > 0.25
MERGE (I:SavedID {id: ID(w), processed: false})
MERGE (T)-[:hasResult]->(I)

2) And execute a sequence of queries:
WITH 'x' as itemName
MATCH (T:SavedQueryResult {name: itemName})-[:hasResult]->(I:SavedID {processed: false})
MATCH (w:item) WHERE ID(w) = I.id
[PERFORM CALCS AND UPDATE w]
SET I.processed = true

3) To process the saved results, you can use the apoc.periodic.commit from the APOC library.


text:
Q: Double press SHIFT to "Open Quickly" in Xcode In Xcode > Preferences > Key Bindings I would like to register the key "SHIFT SHIFT" for the command "Open Quickly..". It makes my transition from Intellij Idea much faster and comfortable.
But the KeyBindings doesn't accept "SHIFT SHIFT" as a key... anyone know any other way?


text:
Q: How do I check if the user has entered a null value in Go? reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Println("Hello",text)

How do I check if the user has entered a null value and where do I put the code? Note - I've already tried checking the length = 0 and = " " but, they don't seem to be working.
Please suggest an alternative way for doing this. Thanks!

A: bufio.Reader.ReadString() returns a string that also contains the delimeter, in this case the newline character \n.
If the user does not enter anything just presses the Enter key, the return value of ReadString() will be "\n", so you have to compare the result to "\n" to check for empty input:
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, err := reader.ReadString('\n')
if err != nil {
    panic(err) // Don't forget to check and handle returned errors!
}

if text == "\n" {
    fmt.Println("No input!")
} else {
    fmt.Println("Hello", text)
}

An even better alternative would be to use strings.TrimSpace() which removes leading and trailing white space characters (newline included; it isn't a meaningful name if someone inputs 2 spaces and presses Enter, this solution also filters that out). You can compare to the empty string "" if you called strings.TrimSpace() prior:
text = strings.TrimSpace(text)
if text == "" {
    fmt.Println("No input!")
} else {
    fmt.Println("Hello", text)
}

A: // The best algorithm I have written so far
package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    Wellcome()
    sina := get_Informations()
    fmt.Printf("%v", sina)
    Goodbye()
}

func Wellcome() {
    fmt.Println("Welcome to this Program ...[*]")
}

func get_Informations() (string){
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter First-Name: ")
    firstName, _ := reader.ReadString('\n')
    if len(firstName) >= 5 {
        return firstName
    }
    for {
        fmt.Print("First-Name must be more than 3 characters: ")
        firstName, _ := reader.ReadString('\n')
        if len(firstName) < 5 {
            continue
        }else if len(firstName) >=5{
            return firstName
        }

    }
}

func Goodbye() {
    fmt.Println("   ")
    fmt.Println("   ")
    fmt.Println(" [*]----------------------[*]  ")
    fmt.Println(" [*]----THANKS.GOODBYE----[*]  ")
    fmt.Println(" [*]----------------------[*]  ")
    fmt.Println("   ")
    fmt.Println("   ")
}


text:
Q: Use of z index and position:fixed to make layered scrolling https://jsfiddle.net/t1r088ve/9/
I can't figure out how to make the content section scale so that the user can scroll through all the content without making the website have 2 vertical scrollbars.
I also can't figure out how to make the content scroll up to reveal the footer in the same way that the cover page does.
Please help.
I'm fine with using Javascript or JQuery if that's the way to get it working.
This is the relevant code, I think:
.container,
.container-fluid {
    margin-bottom: 100vh;
    position: relative;
    top: 0;
    left: 0;
    overflow: auto;
    height: 100%;
}

.body {
    height: 100%;
    background-color: #eee;
    z-index: -1;
    position: fixed;
    top: 0;
    left: 0;
    margin-bottom: 100vh;
}

#parallax {
    overflow: hidden;
    height: 100vh;
    z-index: 10;
}

#footer {
    position: fixed;
    bottom: 0px;
    left: 0px;
    width: 100%;
    z-index: -10;
    background-color: #666;
    background-attachment: fixed;
    height: 100vh;
}

A: Here's a codepen that I think achieves what you're looking for via jquery.
It uses this script, which basically checks the height of the initial div and when the bottom of the div reaches the top of the screen the .body class is position is changed from fixed to relative There were also some minior changes to the css
Jquery
var height = $(window).height();

$(window).resize(function(){
   height = $(window).height();
});

$(document).on('scroll', function(){
  var windowpos = $(this).scrollTop()
  if(height- windowpos < 0){
    $('.body').css('position', 'relative');
  } else {
    $('.body').css('position', 'fixed')
  }
})

CSS
html, body{
  margin: 0;
  padding: 0;
  width: 100%;
}

.container,
.container-fluid {
  position: relative;
  top: 0;
  left: 0;
  overflow: auto;
  height: 100%;
  padding: 0;
  margin: 0 0 100vh 0;
}

.body {
  width: 100%;
  background-color: #eee;
  z-index: -1;
  position: fixed;
  top: 0;
  left: 0;
  padding: 20vh 0;
  margin: auto;
}

.contentpage {
  min-height: 60vh;
  width: 80%;
  margin: 0 auto 20vh auto;
  background-color: #f9f9f9;
  border-left: 20px solid #FF4B3B;
  border-right: 20px solid #FF4B3B;
  border-bottom: 20px solid #FF4B3B;
}


text:
Q: Scrape text under  using Requests-HTML (Requests-HTML, Python) I am attempting to extract the socket type of the cpu as you can see in the following image. I have identified that the socket type is under the <h4> Socket heading as seen in the following image.
So far I have been able to scrape .spec.block and find all <h4>'s nested inside. However I can't get the text under each heading
Here is my code
from requests_html import HTMLSession
session = HTMLSession()

r = session.get('https://au.pcpartpicker.com/product/' + jLF48d)
about = r.html.find('.specs.block')[0]
about = about.find('h4')

print(about.text)

This prints
 [ <Element 'h4' >, <Element 'h4' >, <Element 'h4' >, <Element 'h4' >,
 <Element 'h4' >, <Element 'h4' >, <Element 'h4' >, <Element 'h4' >,
 <Element 'h4' >, <Element 'h4' >, <Element 'h4' >]

However when I change the print statement to:
print(about.text)

I get the following error:

AttributeError: 'list' object has no attribute 'text'

Update:
print(about[0].text)

This code prints:

Manufacturer
  AMD
  Which is the first heading and text however I need the 4th

Any idea what code I can use to reach the desired result?
If you require any more information please let me know.

A: Replacing:
    print(about[0].text)
With
print(about[3].text)

As seen on the code in my question above solved the problem for me!


text:
Q: Event handler for location.hash changing? I have a Flash document viewer embedded in my page, where the user can view the preview version of the document, and then purchase the full version if they like.  Is it possible to have a hyperlink in the document itself "BUY NOW" which would command the browser to do something on the current page without having to refresh?
I'm imagining something like:
www.example.com/currentpage.php#buy

...as a link in the embedded document, which would in theory scroll to a position in the parent web page.  Are there any mechanisms, maybe event handlers where I can run some js upon being directed to the "#buy" anchor?

EDIT: I just discovered Javascript has a
window.location.hash

object that I can check, but I don't want to poll for it, the question remains if there are any mechanisms or events to detect it changing?


text:
Q: Cube 3D points rotations X & Z Include details about your goal:

*

*So first of all, my goal is to make the points rotations of a cube aroud X, Y, and Z axis to rotate the cube itself.

Describe expected:

*

*I expect to have that after an 17.18° rotation around X axis:

*

*I expect to have that after an 17.18° rotation around Z axis:

Actual results:

*

*Black shape is the default cube with no rotations

*White shape is the rotated cube.

*My actual result after an 17.18° rotation around X axis with my formula:

*

*My actual result after an 17.18° rotation around Z axis with my formula:

Show what you've tried and tell us what you found (on this site or elsewhere) and why it didn't meet your needs. You can get better answers when you provide research.
I have saw a few site that describe exactly what I want:

*

*https://www.desmos.com/calculator/imazvy40oz?lang=fr

*https://fr.khanacademy.org/computer-programming/cube-rotating-with-user-interaction/5953495622746112
Show some code

*

*First of all i am using Java because my problem is my Minecraft virtually shape don't meet with the real one;

Rotation methods

public void rotateX() {
        for(int i = 0; i < points.size(); i++) {

            Vector vector = points.get(i);

          double sinTheta = Math.sin(eulerAngle.getX());
          double cosTheta = Math.cos(eulerAngle.getX());

          double y = vector.getY();
          double z = vector.getZ();

            vector.setY(y * cosTheta - z * sinTheta);
        vector.setZ(z * cosTheta + y * sinTheta);
    }
}

public void rotateY() {
    for(int i = 0; i < points.size(); i++) {

        Vector vector = points.get(i);

        double sinTheta = Math.sin(eulerAngle.getY());
        double cosTheta = Math.cos(eulerAngle.getY());

        double x = vector.getX();
        double z = vector.getZ();

        vector.setX(x * cosTheta - z * sinTheta);
      vector.setZ(z * cosTheta + x * sinTheta);
    }
}

public void rotateZ() {
        for(int i = 0; i < points.size(); i++) {

            Vector vector = points.get(i);

            double sinTheta = Math.sin(eulerAngle.getZ());
          double cosTheta = Math.cos(eulerAngle.getZ());

          double x = vector.getX();
          double y = vector.getY();

            vector.setX(x * cosTheta - y * sinTheta);
        vector.setY(y * cosTheta + x * sinTheta);
    }
}

My setup method
    public void setupPoints() {

    ArrayList<Vector> points = new ArrayList<Vector>();

    points.add(getA());
    points.add(getB());
    points.add(getC());
    points.add(getD());
    points.add(getE());
    points.add(getF());
    points.add(getG());
    points.add(getH());

    this.points = points;

    rotateZ();
    rotateY();
    rotateX();
}

My points locations are (i know its not an exact cube):

My enviroment:

note: Only Y rotation works perfectly, i noticed that the rotation on the Y axis corresponds to that of the Z axis in a coordinate system where Y would be the "height", its the first time that i work on 3d space plan so i am learning. Thanks if you read until here.

A: Your rotation methods are correct, but they rotate around axes that pass through the origin.
You are expecting them to rotate around an axis that passes through the center of the object. You don't see the problem with the rotation around Y axis because it happens to pass through the center of the cube.
You can fix this by "moving" the object to the origin before rotating, and moving it back after rotating. For example, for the X rotation:
      double y = vector.getY() - objectCenterY;
      double z = vector.getZ() - objectCenterZ;

      vector.setY(y * cosTheta - z * sinTheta + objectCenterY);
      vector.setZ(z * cosTheta + y * sinTheta + objectCenterZ);


text:
Q: Access REST API in Java with json parameters I do not know what I am doing wrong, but I cannot access a REST API using the POST method in Java with Json parameters.
Each time I run the program, I receive Java.net.SocketException - Connection Reset.
I tried to access the API from PHP, and it worked.
Code: https://github.com/BobTheProgrammer/Question/blob/master/POST

A: try this one
    public static void HttpPost() {
    try {

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "https://api.website.net/auth/token");
        StringEntity input = new StringEntity("{\"auth\":{\"user\":{\"id\":\"bla\",\"password\":\"bla\"}\"method\":\"user\",\"website\":\"http://website.net/\"}}");
        post.setEntity(input);
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

A: There is a problem with the JSON syntax in your source code in line number 55, you have missed a comma after the user object.
Replace this line
String urlParameters = "{\"auth\":{\"user\":{\"id\":\"bla\",\"password\":\"bla\"}\"method\":\"user\",\"website\":\"http://website.net/\"}}";

with this one(added a comma after the user object before method)
String urlParameters = "{\"auth\":{\"user\":{\"id\":\"bla\",\"password\":\"bla\"},\"method\":\"user\",\"website\":\"http://website.net/\"}}";


text:
Q: awk to pass a bash variable to script to insert value on each line Trying to pass a bash variable to an awk script to insert a value in front of each line, currently the script runs but prints 0 in each line. Thank you :).
file
2022/.../.../...
2022/.../.../...

awk
id=1234

awk -v r="$id" '{print /"id"/"/"$0}'

current
0/2022/.../.../...
0/2022/.../.../...

desired
1234/2022/.../.../...
1234/2022/.../.../...

A: You are passing variable correctly but not using correctly inside the awk.
/"id"/" is a regex expression that will attempt to match "id" string in each line and since it doesn't exist it returns 0 and that's what you get in output.
You may just use:
awk -v r="$id" '{print r "/" $0}' file

1234/2022/.../.../...
1234/2022/.../.../...

btw this sed solution would also work:
sed "s~^~$id/~" file

1234/2022/.../.../...
1234/2022/.../.../...

A: this should make it clear why it appended "0/" :
0/
    # gawk profile, created Tue Aug 30 14:49:38 2022

    # Rule(s)

     1  {
     1      print (/"id"/) "/" $0
    }

It's a regex non-match, concat with a string containing ASCII "/" (\057 | 0x2F)`, then concat with input row