text:
Q: Write a scroll callback that gets called at regular intervals I want to write a scroll callback function that gets called after every one second when user scrolls. I tried
window.on('scroll', function(e) {
//scroll function body
});

But the problem is it gets called everytime user scrolls even one pixel. Can someone please suggest a solution.

A: You can write a function like this
scrollCb = function(func, later) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

and call it like
scrollCb(function() {
   //Your scroll callback handler
}, 1000);


text:
Q: Is there any reason why the `explicit` keyword is used in the constructor of std::auto_ptr? This is the ctor used to construct a std::auto_ptr object from a standard pointer, in VS2008 compiler.
template<class _Ty>
class auto_ptr
{
   public:
   explicit auto_ptr(_Ty *_Ptr = 0) _THROW0() : _Myptr(_Ptr) {}

   private:
   _Ty *_Myptr;
};

Is there any particular reason why the explicit keyword is used above ?
In other words, why can't I initialize an auto_ptr with
std::auto_ptr<Class A> ptr = new Class A; ?

A: Becasue you could otherwise unintentionally do something like:
void foo(std::auto_ptr<int> p)
{
}

void boo()
{
    int* p = new int();
    foo(p);
    delete p; // oops a bug, p was implicitly converted into auto_ptr and deleted in foo.... confusing
}

In contrast with where you are actually explicitly aware of what is happening:
void boo()
{
    int* p = new int();
    foo(std::auto_ptr<int>(p)); // aha, p will be destroyed once foo is done.
}

A: Constructing a std::auto_ptr is a transfer in ownership. It is best for everyone involved that transfers of ownership be kept explicit. For instance:
void frobnicate(const std::auto_ptr<Class> & ptr);

Class *instance = new Class();
frobnicate(instance);
delete instance;

If the constructor was implicit, then this code would compile, and it would be nearly impossible to notice that it was wrong without checking the definition of frobnicate. Besides, while using = for initialization is now harder, you can still use the other initialization syntax:
std::auto_ptr<Class> instance(new Class);
frobnicate(instance);

A: First, solving the immediate issue, you can initialize it like this:
std::auto_ptr<Class A> ptr(new A);

Second, implicit conversions can cause more harm than good, so it's a good reflex to make constructors callable with a single parameter explicit to start with and then ponder if implicitness could be valuable.

A: What's wrong with just using:
std::auto_ptr<T> ptr(new T());

If you allow implicit conversion then you can run into all sorts of issues with implicit casts being inserted where they are least expected.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to send a pdf file to multiple emails using Python? My aim for this program is to send multiple e-mail addresses a message along with a PDF file attached to the e-mail. How would I do that? I have two Traceback calls(Shown after the code). So far the code works when there is no attachments being sent but as I try to send an attachment everything seems to fall apart. Thanks
EDIT: I believe I have to use these two lines of code somewhere.
message.attach(part)
text = message.as_string()
Although when I write them down it says Unresolved attribute reference 'attach' for class 'str'
from email.mime.base import MIMEBase
import pandas as pd
import smtplib, ssl

subject = "An email with attachment from Python"
sender_email = input("Enter your E-mail Address: ")
password = input("Enter your password: ")

email_list = pd.read_excel("D:\Learning Python\Mini_Projects\emailaddresses.xlsx", engine="openpyxl")
# Read Excel Spreadsheet
names = email_list['Name']
receiver_email = email_list['Email']

message = """Subject: Training Program!
Hi {names}, I hope you received this e-mail with the attachment"""
filename = "TrainingProgram.pdf"

with open(filename, "rb") as attachment:
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

encoders.encode_base64(part)

part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)
context = ssl.create_default_context()
with  smtplib.SMTP("smtp.gmail.com", 587) as server:
    server.starttls(context=context)
    server.login(sender_email, password)
    for i in range(len(receiver_email)):
        name = names[i]
        email = receiver_email[i]
        server.sendmail(sender_email, receiver_email, message)
    print("E-mails Sent!")

File "D:/Learning Python/Mini_Projects/main.py", line 117, in <module>
    server.sendmail(sender_email, [email], message)
  File "C:\Users\janss\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 859, in sendmail
    msg = _fix_eols(msg).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\U0001f4aa' in position 27: ordinal not in range(128)

A: ASCII encoding does not support emojis. Remove the  in the email body, and it should work. If you absolutely want to keep the emoji, you would have to use a MIMEText object, see this question for an example.
EDIT:
Why aren't you using the name and email variables in the for loop ?
The current code sends an email to an adress being a list, I wonder why it's not erroring there ...
    for i in range(len(receiver_email)):
        name = names[i]
        email = receiver_email[i]
        server.sendmail(sender_email, receiver_email, message)

Maybe you meant your for loop like the following ?
    for email in receiver_email:
        server.sendmail(sender_email, email, message)

Additionally, your message will be sent as you coded it, instead of with the names filled in. For this, you need to put an f in front of the string. I think the message should be like this:
message = f"""Subject: Training Program!
Hi {", ".join(names)}, I hope you received this e-mail with the attachment"""

EDIT2:

Unresolved attribute reference 'attach' for class 'str'

This is because str has no method attach, only email.mime.multipart.MIMEMultipart has. See this answer on how to correctly send attachments.


text:
Q: Mathematica: How is OptionValue implemented? The implementation of the built-in OptionValue contains some piece of magic so that

OptionValue[name] is equivalent to
  OptionValue[f, name], where f is the
  head of the left-hand side of the
  transformation rule in which
  OptionValue[name] appears.

Does anybody have an idea for how to achieve something similar for Options, i.e. implement an autoOptions[] that would resolve to the options defined for the symbol on the left hand side of the transformation rule in which autoOptions[] appears?
For clarity, what I am looking for is a way to make
Options[foo]={bar->1};
foo[OptionsPattern[]]:=autoOptions[]
foo[]

output {bar->1}
The eventual goal is to do something like requested in this question without having to change anything but the RHS of a definition.

A: Here is a simple, very schematic version:
Module[{tried},
  Unprotect[SetDelayed];
  SetDelayed[f_[args___, optpt : OptionsPattern[]], rhs_] /;
    !FreeQ[Unevaluated[rhs], autoOptions[]] :=
     Block[{tried = True},
       f[args, optpt] :=
         Block[{autoOptions}, autoOptions[] = Options[f]; rhs]] /; ! TrueQ[tried];
  Protect[SetDelayed];]

Your usage:
In[8]:= Options[foo] = {bar -> 1};
foo[OptionsPattern[]] := autoOptions[]
foo[]

Out[10]= {bar -> 1}

Note that this won't work when explicit options are also passed - accounting for them is some more work, and this is not generally a good practice since I overloaded SetDelayed - but you asked for it and you get it.


text:
Q: How do access custom layout from PreferenceFragmentCompat? I want to access views from a custom layout that was set to a preference
settings_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android">

    <Preference
            android:key="storage"
            android:layout="@layout/layout_storage" />

    ...
</PreferenceScreen>

SettingsFragment.kt
class SettingsFragment: PreferenceFragmentCompat() {
    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        addPreferencesFromResource(R.xml.settings_screen)
    }
}

There was a question on stackoverflow similar to this, but in that answer, he is accessing the view from the main layout file not from preference
PreferenceFragmentCompat custom layout
and also I found this article, he uses onBindView method to access the custom view.
https://code.luasoftware.com/tutorials/android/override-layout-of-android-preference/
but there is no method call onBindView in PreferenceFragmentCompat
UPDATED
layout_storage.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        android:padding="20dp"
        android:orientation="vertical"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <LinearLayout
            android:paddingBottom="5dp"
            android:orientation="horizontal"
            android:layout_width="match_parent" android:layout_height="wrap_content">

        <TextView
                android:textColor="@color/colorGray"
                android:paddingTop="5dp"
                android:layout_weight="1"
                android:text="USED"
                android:layout_width="0dp"
                android:layout_height="wrap_content"/>

        <TextView
                android:textColor="@color/colorGray"
                android:text="FREE"
                android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    </LinearLayout>

    <ProgressBar
            android:progress="30"
            android:scaleY="5"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:id="@+id/progressBar"/>

</LinearLayout>

Now I want to get the progressBar

A: Override the following method in PreferenceFragmentCompat :
@Override
protected RecyclerView.Adapter onCreateAdapter(PreferenceScreen preferenceScreen) {
    return new PreferenceGroupAdapter(preferenceScreen) {
        public PreferenceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            PreferenceViewHolder holder = super.onCreateViewHolder(parent, viewType);
            View customLayout = holder.itemView;
            if (customLayout.getId() == R.id.myCustomId) {
                // get ref on your layout or modify it
            }
            return holder;
        }
    };
}

You might want to add an id in your LinearLayout to check for correct Layout...
Hope it helps !

A: You can add your preference layout in onCreatePreferences using setPreferencesFromResource for more detail visit PreferenceFragmentCompat and Android App Settings with Preference Fragment Compat
public static class SettingsFragment extends PreferenceFragmentCompat {

@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
    // Load the preferences from an XML resource
    setPreferencesFromResource(R.xml.settings_screen, rootKey);

    SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences();

    PreferenceScreen preferenceScreen = getPreferenceScreen();

    int count = preferenceScreen.getPreferenceCount();

    for (int i = 0; i < count ; i++) {
    Preference p = preferenceScreen.getPreference(i);
    if (!(p instanceof CheckBoxPreference)) {
    String value = sharedPreferences.getString(p.getKey(), "");
    setPreferenceSummery(p, value);
      }
     }
}
}

Interface definition for a callback to be invoked when a shared preference is changed- onSharedPreferenceChanged
    @Override
  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

  Preference preference = findPreference(key);

  if (preference != null) {

  if (!(preference instanceof CheckBoxPreference)) {
  String value = sharedPreferences.getString(preference.getKey(), "");
  setPreferenceSummery(preference, value);
        }
     }
  }


text:
Q: Routing In Angular6 I have application that have a navigation bar and in the navigation bar i have contactUs component.
i can open the navigation bar from any of my componenets, and to go to contactUs component.
in the contactUs  component i have a back button and i want to be able to take the user back from any component he opend the contactUs .
how can i achieve this?
i tried using routerLink on the button, and a navigatebyUrl with the router module but i only can take the user back from a specific url, like "/home"
and i want it to be changes depends on the user location,
e.g
if user is open the
About > contactUs (so contactUs back button take back to About Component)
Home > contactUs (so contactUs back button take back to Home Component)
How can i achieve this approch?

A: You need to give specific code or name to each component. When clicking on it you can store it so ewhere like in globat variable or local storage. For example if you click on contact button from about us page then store about us page from route so ewhere. Now once you are on contact page, and when you click back button then you can find out last saved value in the local storage and redirect to that page.


text:
Q: Working with streams in PDFrw for Python? I'm trying to read in an example PDF with PDFrw. The PDF contains the phrase Hello Matthew in the bottom left corner at coordinates (100, 100). When I attempt to output the text (if I even can?) I get a stream of data. I can't seem to figure out how to get that as text.
>>> import pdfrw

>>> file_object = pdfrw.PdfReader("Hello.pdf")
>>> file_object
{'/ID': ['<f643bc0910dfb67725d53e11054f4609>', '<f643bc0910dfb67725d53e11054f4609>'], '/Info': (5, 0), '/Root': {'/Outl
ines': (8, 0), '/PageMode': '/UseNone', '/Pages': {'/Count': '1', '/Kids': [{'/Contents': (7, 0), '/MediaBox': ['0', '0
', '595.2756', '841.8898'], '/Parent': {...}, '/Resources': {'/Font': (1, 0), '/ProcSet': ['/PDF', '/Text', '/ImageB',
'/ImageC', '/ImageI']}, '/Rotate': '0', '/Trans': {}, '/Type': '/Page'}], '/Type': '/Pages'}, '/Type': '/Catalog'}, '/S
ize': '9'}

>>> file_object.pages[0]
{'/Contents': (7, 0), '/MediaBox': ['0', '0', '595.2756', '841.8898'], '/Parent': {'/Count': '1', '/Kids': [{...}], '/T
ype': '/Pages'}, '/Resources': {'/Font': (1, 0), '/ProcSet': ['/PDF', '/Text', '/ImageB', '/ImageC', '/ImageI']}, '/Rot
ate': '0', '/Trans': {}, '/Type': '/Page'}

>>> file_object.pages[0].keys()
['/Contents', '/MediaBox', '/Parent', '/Resources', '/Rotate', '/Trans', '/Type']

>>> file_object.pages[0].Contents
{'/Filter': ['/ASCII85Decode', '/FlateDecode'], '/Length': '102'}

>>> file_object.pages[0].Contents.stream
'GapQh0E=F,0U\\H3T\\pNYT^QKk?tc>IP,;W#U1^23ihPEM_?CW4KISi90EC-p>QkRte=<%V"lI7]P)Rn29neZ[Kb,htEWn&q7Q2"V~>'

A: That stream is compressed.  You can tell that by the dictionary /Filter parameter.
Unfortunately, pdfrw does not (yet?) know how to decompress with that type of filter.  If you run your pdf through something like pdftk first to decompress it, you might see something more reasonable.
Disclaimer:  I am the primary pdfrw author.
But...
Even then, especially for non-ASCII fonts, character to glyph mapping in PDFs is complicated, so you won't always see something that looks reasonable.
If you really want to deeply examine text PDF files, pdfminer might be more useful -- pdfrw has not yet really grown the tools to do that too well.

A: If your filter is only /Flatedecode or you can find an ASCII85Decode filter to run first (they must be run in order). I have been using pdfrw.uncompress.uncompress(page.Contents) to decode /Flatedecode streams (not the sames as PdfReader.uncompress(), the method does not pass a stream to the processing function, it gives it all of the indirect_objects).
>>> pdf = pdfrw.PdfReader('foo.pdf')
>>> pages = pdf.Root.Pages.Kids
>>> p1 = pages[0]
>>> p1.Contents
{'/Filter': '/FlateDecode', '/Length': '13679'}
>>> p1.Contents.stream[:30]
'x\x9cÕ}Ý\x92æ¶\x91å½"ô\x0eu5Q߬ëk\x02üßP8BRwË'
>>> pdfrw.uncompress.uncompress([p1.Contents]) # Contents object/s in a list.
True # it returns True even if the stream is not decoded.
>>> p1.Contents.stream[:30]
'/Artifact <</Attached [/Top]/T' # ready for parsing

Then search for lines ending in either 'TJ' or 'Tj' and take any values inside round brackets from those lines... and you have your text.
If you need location information for the text then find blocks of lines between BT and ET. Then check the line endings, if you have Tm it should be an array of 6 values [1,0,0,1,x,y] the last two numbers give you the bottom left corner of the text starting position.


text:
Q: create new record using many to many relation in php for yiiframework Hi I am quite new to php
Here i have two models as users and roles, they have many to relation through third model as
users_roles.
following are my models as
Users.php
public function relations()
    {
        return array(
            'userRoles' => array(self::HAS_MANY, 'UserRoles', 'id_users'),
        );
    }

Roles.php
public function relations()
    {
        return array(
            'userRoles' => array(self::HAS_MANY, 'UserRoles', 'id_roles'),
        );
    }

UsersRoles.php
public function relations()
    {
        return array(
            'idUsers' => array(self::BELONGS_TO, 'Users', 'id_users'),
            'idRoles' => array(self::BELONGS_TO, 'Roles', 'id_roles'),
        );
    }

Now when i creating users I added roles using checkboxes as
<?php echo $form->labelEx($model,'roles'); ?>
        <?php

        //print_r($userRoles);
        //die;

        echo CHtml::activeCheckboxList(
                $userRoles, 'id_roles',
                CHtml::listData(Roles::model()->findAll(), 'id', 'name'),
                array('template'=>'{input} {label}',)
        );
        ?>
        <?php echo $form->error($model,'roles'); ?>

now how can i save those checkbox values in my users_roles tables?

A: First your relations for Users and Roles have a typo, they both refer to model UserRoles when it should be UsersRoles.
Now to your question.  I would create a function in the UsersRoles model named something like refreshRoles($user, $roles).  Where $user is the user id you are selecting roles for, and $roles is an array of roles that should be set.  The function would retrieve the list of Roles by id_users, and compare it to $roles, deleting roles that are missing from $roles, and adding roles that are missing from the UsersRoles table.
That would look something like this:
function refreshRoles($user, $roles) {
   $userRoles = $this->findAllByAttribute(array('id_users' => $user));
   foreach ($userRoles as $userRole) {
      if (!in_array($userRole->id_roles, $roles)) {
         $userRole->delete();
      }
      else {
         $key = array_search($userRole->id_roles, $roles));
         unset($roles[$key]);
   }
   foreach ($roles as $role) {
      $model = new UsersRoles();
      $model->id_users = $user;
      $model->id_roles = $role;
      $model->save(false);
   }
}

Call this function from your controller just after you save your user model (if you are indeed saving the user).  Note, this is untested, but will give you a direction to head.


text:
Q: document.referrer blank when using back button I am using document.referrer in javascript to check where the user has come from. At the moment I am looking into what happens if the user is on my page, navigates to a different page then uses their back button to return to the original page. When I alert the referrer sometimes its blank and sometimes it has the address. I can't seem to find any pattern with when it is blank and when it is not. Does anyone know why it might be blank sometimes and others not? This is happening in IE7 and firefox over HTTP

A: This is most probably a bug in IE:
http://webbugtrack.blogspot.com/2008/11/bug-421-ie-fails-to-pass-http-referer.html


text:
Q: Definition of complex-valued forms using exterior algebra and tensor products Let $M$ be a complex manifold. I have seen the bundle of complex valued $k$-forms defined as $\Lambda^k(M) \otimes \mathbb{C}$. What this means is that if $V := T_xM$ for some $x \in M$, then the fiber at $x$ is $\Lambda^k( \hom_\mathbb R (V, \mathbb R) ) \otimes_\mathbb R \mathbb C$.
What I know is that:
$$
\Lambda^k( \hom_\mathbb R (V, \mathbb R) ) \otimes_\mathbb R \mathbb C \simeq_\mathbb R \hom_\mathbb R (\Lambda^k (V), \mathbb C)
$$
and the $\mathbb R$ vector space on the right hand side is isomorphic to the $\mathbb R$-vector space of $\mathbb R$-multilinear alternate maps from $V^k$ to $\mathbb C$.
However, I have also seen that for example $(1,0)$-forms are characterized by being $0$ on $(1,0)$-vectors, and $(1,0)$ vectors live inside $V^\mathbb C:= V \otimes_\mathbb R \mathbb C$. So it must be the case that these complex valued forms take as arguments elements from $V^\mathbb C$.
So the question is, how do I see elements in $\hom_\mathbb R (\Lambda^k(V), \mathbb C)$ as maps taking as arguments elements from $(V^\mathbb C)^k$?
The only two options that I can logically think of to make my forms take arguments from $V^\mathbb C$ are either
$$
\Lambda^k( \hom_\mathbb R (V^\mathbb C, \mathbb R))\otimes_\mathbb R \mathbb C
\simeq_\mathbb R
\hom_\mathbb R(\Lambda^k(V^\mathbb C), \mathbb C),
$$
i.e. $\mathbb R$-multilinear maps from $(V^\mathbb C)^k$ to $\mathbb C$ (seen as an $\mathbb R$-vector space),
or
$$
\Lambda^k( \hom_\mathbb C(V^\mathbb C, \mathbb C))
\simeq_\mathbb C
\hom_\mathbb C(\Lambda^k(V^\mathbb C), \mathbb C)
$$
i.e. $\mathbb C$-multilinear maps from $(V^\mathbb C)^k$ to $\mathbb C$ (seen as a $\mathbb C$-vector space).
It is not clear to me whether one of these two latter vector spaces is isomorphic with $\hom_\mathbb R(\Lambda^k(V), \mathbb C)$ and if so, over which field - over $\mathbb R$ or over $\mathbb C$. This is why I don't know whether my question is one of convention or of linear algebra.
In short, when we say complex-valued forms, do we mean $\hom_\mathbb C(\Lambda^k(V^\mathbb C), \mathbb C)$ as a $\mathbb C$ vector space? Do we mean $\hom_\mathbb R(\Lambda^k(V), \mathbb C)$ as an $\mathbb R$-vector space or, if not, as a $\mathbb C$-vector space etc.? And are some of these in fact equivalent?


text:
Q: Android Studio Flutter UI Guides don't work This may be a silly question but i do not see the flutter UI Guides. I checked the "Emphasize widgets with multiple children" and all plugins are installed and activated. I am using version 3.4.2 .
Is this an error in Android Studio or just a silly mistake?
Thanks for helping.

A: This is what is is happening on my Android Studio (3.4)
Before

After

A: This bug was fixed with the flutter plugin-update 38.2


text:
Q: What is the meaning of "his path beaten out in the turf" Suddenly the darkness about him glowed; a furnace fire had shot up on the mountain, and for a moment the little world of the woodside and the steep hill shone in a pale light, and he thought he saw his path beaten out in the turf before him.
It's from Arthur Machen's Hill of Dreams. I didn't quite understand what it means to "his path beaten out in the turf"

A: He looked at the turf (grass) in front of him, and thought he could see it flattened, as if by feet which had passed before, in a way which suggested a trail or path that he should follow.


text:
Q: GCM Push Notification without using JSON I am trying to migrate my application from C2DM service to new GCM push notification. I have successfully integrated the GCMIntentService class which extends GCMBaseIntentService.  When I send the push notification from server using PHP, the GCM sends the message data as a JSON object.  I am using the following code in my Android GCM service, and its returning a null value with the new code.
public void onMessage(Context context, Intent intent)
    {
        String action = intent.getAction();
        if ("com.google.android.c2dm.intent.RECEIVE".equals(action))   {
             message=intent.getStringExtra("message");
            createNotification(context);
        }
   }

The PHP Script contains :
$headers = array(
                    'Authorization: key=' . $apiKey,
                    'Content-Type: application/json'
                );
// Open connection
$ch = curl_init();

// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );

curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );

Please suggest me what all the changes I require in my PHP script to send the push notification using GCM libraries and without JSON.
Thanks in advance
Tim

A: you have to send the payload via JSON - whats the reason you do not want to use JSON?

A: You can indeed send payload without JSON (if you preferred), just like C2DM.
First, the content type is changed to this:
Content-Type: application/x-www-form-urlencoded;charset=UTF-8

Then your HTTP body will contain this:
registration_id=xxxxxx&collapse_key=yyyyy&data.data1=value1&data.data2=value2

HOWEVER, by sending payload as plain text you can only send it to one device at a time. This reason alone should make you avoid using this option, unless you already have bulk-sending logic in your C2DM code that you don't wish to change.
See here for more details: http://developer.android.com/guide/google/gcm/gcm.html#request


text:
Q: Cannot perform buffering loop with arcpy I have 5 buffers to perform using 5 fields of a shapefile. I try to run it with the following code:
Buffers = ['JF1','JF2','JF3','FF','FB']
env.workspace = "C:\Mydirectory\Myfile.shp"
network = "C:\Mydirectory\Myfile.shp"
out = "C:\Myoutputdirectory\Myfinaldirectory"
for buff in Buffers:
    arcpy.Buffer_analysis(network, out, buff,)

But when I do it I receive the following error:
ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000725: Output Feature Class: Dataset Myfinaldirectory.shp already exists.
Failed to execute (Buffer).

What is the problem?

A: You aren't specifying a name for your output shapefile. arcpy is treating out as a file and appending ".shp" for you. You want a unique name for each output so that it isn't overwritten each loop.
import os
Buffers = ['JF1','JF2','JF3','FF','FB']

# This is a workspace
env.workspace = r"C:\Mydirectory"
# This is present in the workspace
network = "Myfile.shp"

# This is a directory, not a file
out = r"C:\Myoutputdirectory\Myfinaldirectory"

for buff in Buffers:
    # results in .\JF1.shp, .\JF2.shp, etc.
    arcpy.Buffer_analysis(network, os.path.join(out, buff), buff)

Edit:
Fixed pathing per @artwork21 comments. Thanks!


text:
Q: Ruby: Using the "index" method with "OR" Using the index method, I'm trying to find if a value exists using a certain variable, and if that variable doesn't exist, then try another variable; a little something like this (3rd line below):
a = [ "a", "b", "c" ]
a.index("b")   #=> 1
a.index("z" or "y" or "x" or "b")   #=> 1

..meaning that if "z" is not found in the array, then try "y"; if y is not found, then try x; if x is not found then try b
How would I do that correctly?

A: Depends on your end goal. If you just want to see if a contains a z, y, x or b, you can do this:
(a & %w{z y x b}).length > 0   # gives true if a contains z, y, x and/or b.

what we're doing is seeing if there is a set intersection where a contains some shared elements with the set of desired quantities, then testing to see if there were any of those elements.

A: TIMTOWTDI. But I prefer using Array#inject.
%w(x y z b).inject(nil) { |i, e| i or a.index(e) } #=> 1

And there is an another way to do this with more similar to your pseudo-code.
class String
  def | other
    ->(e) { self==e || other==e }
  end
end

class Proc
  def | other
    ->(e) { self.call(e) || other==e }
  end
end

a.index(&('x' | 'y' | 'z' | 'b')) #=> 1


text:
Q: what is the proper way to use the adjective "calm" Do we say "in calm", "on calm", or just "calm"? For example:

I am writing in calm
   or
I am writing on calm

A: There's no obvious grammatical or syntactic reason why we don't say "I'm writing this in calm".
As @CarSmack points out, "She lived in calm all the days of her life" is perhaps more acceptable. But idiomatically, "She lived in tranquility all the days of her life", for example, is far more likely.
To describe your overall state, use adjectival "I am calm as/while I write". To associate the state more closely with the action of the verb, use adverbial "I am calmly writing" (or "I am writing calmly").


text:
Q: Rails app not loading new environment variable added to /etc/environment I'm trying to add an environment variable to use in my Rails App. Currently, our app uses several environment variables defined in /etc/environment. They work fine. So I've added a new variable to /etc/environment (and rebooted for the hell of it). But when I try to access the new variable, its undefined. Printing out ENV.inspect shows all the original variables, but not my newly added one.  Why oh why?
Running Apache 2 / Passenger 4 / Rails 4. Recently upgraded from Passenger 2 / Rails 3 if its significant.
Edit
Turns out the ones I thought 'work fine' don't work either (they're redefined in my Rails app). So none of the variables in /etc/environment are loaded into the app. Not sure why I thought that system worked, but it doesn't.

A: Might not be good news to you, but you have to reboot the instance to see it happen (or check the other tricks at that question).
You can also use SetEnv at your Apache config and just restarting apache itself will make your app see the new values.

A: ENV
Upgrading from Rails 3 - Rails 4 should not be a major concern for the ENV variables, unless the way Rails processes them will have changed.
We use the following:

This works for us with Rails 4, Ubuntu 12.04, Passenger, Apache 2
--
The problem you may have is that your Rails application has not updated since you added the new variables.
When you run a Rails app, it essentially loads an "instance" of the application, and then keeps loading it somehow. I'm not totally sure how it works, but I do know the likes of Passenger essentially "cache" a rails app whilst in production
This means if you're adding new Environment variables, perhaps the likes of Passenger has made it so the Rails application has not been updated? If this is the case you may wish to use the touch tmp/restart.txt command:


text:
Q: Set variable once for all examples in RSpec suite (without using a global variable) What is the conventional way to set a variable once to be used by all examples in an RSpec suite?
I currently set a global variable in spec_helper that checks whether the specs are being run in a "debug mode"
$debug = ENV.key?('DEBUG') && (ENV['DEBUG'].casecmp('false') != 0) && (ENV['DEBUG'].casecmp('no') != 0)

How do I make this information available to all the examples in the suite without using a global variable and without re-computing the value for each context and/or example? (My understanding is that using a before(:all) block would re-compute it  once per context; but, that before(:suite) can't be used to set instance variables.)
(Note: I'm asking more to learn about good design that to address this specific problem.  I know one global isn't a big deal.)

A: for this purpose I usually write custom modules that I can include in the spec_helper.rb file.
Let's say that I am testing a back-end API and I don't want to parse every time the JSON response body.
spec/
spec/spec_helper.rb
spec/support/request_helper.rb
spec/controllers/api/v1/users_controller_spec.rb

I first define a function in a module placed under the support subfolder.
# request_helper.rb
module Request
  module JsonHelpers
    def json_response
      @json_response ||= JSON.parse(response.body, symbolize_names: true)
    end
  end
end

Then I include this module by default for some test types
#spec_helper.rb
#...
RSpec.configure do |config|
  config.include Request::JsonHelpers, type: :controller
end

Then I use methods defined in the test.
# users_controller_spec.rb
require 'rails_helper'

RSpec.describe Api::V1::UsersController, type: :controller do
  # ...

 describe "POST #create" do

    context "when is successfully created" do
      before(:each) do
        @user_attributes = FactoryGirl.attributes_for :user
        post :create, params: { user: @user_attributes }
      end

      it "renders the json representation for the user record just created" do
        user_response = json_response[:user]
        expect(user_response[:email]).to eq(@user_attributes[:email])
      end

      it { should respond_with 201 }
    end
end

In your case, you could create a module such as
module EnvHelper
  def is_debug_mode?
    @debug_mode ||= ENV['DEBUG']
  end
end

Then you can include it and simply use the method is_debug_mode? in your tests.

A: There is an easy way to keep all the setup stuff in spec_helper.rb, including custom variables, and access those variables in tests. The following is modified from the RSpec-core 3.10 docs, and is not Rails-specific.
Create a new setting for RSpec.configure called my_variable, and give it a value, like this:
# spec/spec_helper.rb

RSpec.configure do |config|
  config.add_setting :my_variable
  config.my_variable = "Value of my_variable"
end

Access settings as a new read-only property in RSpec.configuration from your test:
# spec/my_spec.rb

RSpec.describe(MyModule) do
  it "creates an instance of something" do
    my_instance = MyModule::MyClass.new(RSpec.configuration.my_variable)
  end
end


text:
Q: HTML/TS - Obtaining value totals from column values I have an ngFor populating table values. One column provides quantities and I'm looking to total the values of this column only. I can only find ways that give the 'rows' total but I need the value to have the quantity total. I've tried using the code below, the result is NaN, I'm wondering is there a more simplistic way to calculate from an ngFor column?
-- HTML --

   {{row.quantity}}

   {{row.custName}}

{{row.startDate}}

      Total: {{totalQty}}

-- TS --
totalMeds: number;

  ngOnInit() {
    this.quantityTotal();
  }

  quantityTotal() {
    this.total1 = this.column1.filter(item =>
    item.administration.quantity.valueOf());
    this.total2 = this.column2.filter(item =>
    item.administration.quantity.valueOf());
    this.total3 = this.column3.filter(item => item.administration.quantity.valueOf());

    this.totalQty = this.total1 * this.total2 * this.total3;
  }

A: you should use reduce -or iterate over the array-
quantityTotal(){
   return this.rows.reduce((a:number,b:any)=>b.administration.quantity?
                    a+b.administration.quantity:
                    a
   ,0)
}

See that reduce is only a compact way to say
a=0
this.rows.forEach(x=>{
   a=b.administration.quantity?
        a+b.administration.quantity:a
})
return a


text:
Q: How and when did the ('chiefly British') sense of 'wheeze', meaning 'good plan, scheme' arise? The American Heritage Dictionary entry for this sense of wheeze adds only a [chiefly British] caveat:

wheeze  ... [noun]
...

*

*

*[chiefly British] A clever scheme.

Collins adds a [slang] caveat:

wheeze [noun]: ...

*

*

*[slang] [Brit] a trick, idea, or plan (esp in the phrase good wheeze)

But neither these dictionaries nor RHK Webster's, Wiktionary, CED, Lexico nor the Online Etymological Dictionary suggests how the 'scheme' sense evolved from the original 'breathe raspingly' sense.
Those non-paywalled online dictionaries listing the 'scheme' sense always include it as a polyseme, not a homonym. It is possible that the '[informal] a hackneyed joke or anecdote' sense (Collins) is an intermediate, though Lexico says that this is mainly an American usage.  But I have found not even a suggestion of how or when the 'scheme' sense, I'd say mainly a dated [CED] UK usage and very informal, with a strong connotation of roguishness, arose.

A: Apart from a few early Australian usages, the term is mainly used in BrE according to GDoS. The term appears to be from late 19th century and appears to have developed out of its original sense of "theatrical gag" as suggested by  A Dictionary of Slang and Unconventional English
by Eric  Partridge
Wheeze:

*a trick or dodge frequently used.

1885  [Aus]   Bulletin (Sydney) 14 Feb. 7/4: And we remember on one occasion, when some miscreant cracked this sorry wheeze, a gentleman, whom Melancholy had Marked for Her Own, said it was 'almost good enough for Punch.'

1890  [UK]    Sporting Times 1 Feb. 1/3: [He] retired to the Woods, to see if the Forty Bank Notes were Still Between the Leaves, and Cogitate upon the Success with which his B.C. 55 Wheeze had Worked.

1904  [Aus]   Sun. Times (Perth) 13 Mar. 11/3: A schemester who works every wheeze.

1908  [UK]    A.N. Lyons Arthur's 22: That 'ere was a champion wheeze while it lasted.

................

2000 [UK]

Guardian G2 18 Jan. 14: It is a good wheeze.

A: The OED gives an earlier date and a more precise origin:

Wheeze (n.) 2. Originally Theatre slang, A joke or comic gag introduced into the performance of a piece by a clown or comedian, esp. a comic phrase or saying introduced repeatedly; hence, (gen. slang or colloquial) a catchphrase constantly repeated; more widely, a trick or dodge frequently used; also, a piece of special information, a 'tip'.
1864   J. G. Bertram Glimpses Real Life 131   The art of getting up 'wheezes', as the clown's jokes are called.

A: OED's first attestation of 'wheeze' in the sense of "a trick or dodge frequently used" (op. cit., partial quote) from Bertram's 1864 Glimpses of real life as seen in the theatrical world and in Bohemia was printed earlier, in the 16 Nov 1861 issue of All the Year Round.
The 'wheeze' had, by 1874, made an appearance in that year's edition of Hotten's The Slang Dictionary, with this definition:

Wheeze, a joke, an anecdote, or dialogue, not strictly connected with a piece that is being played, but introduced by an actor, sometimes with the assistance and for the benefit of others. The dialogues which take place between the songs at ... entertainments are also known as wheezes. The word actually means a new notion as applied to dialogue.

A 'wheeze' entry does not appear in the 1869 edition of Hotten's classic.


text:
Q: linkedin Ios bundle identifier already taken We are trying to configure the application DriveMeTo to use the linkedin login.
When we try to configure "iOS bundle identifiers:" with "it.drivemeto" value in the linkedin site app configuration page, on clicking Update button we receive the error "Your changes could not be saved right now, please try again." .
Probably the issue depend on the fact that this bundle id is already taken from a previus accout where we have no more access to. Please may you suggest a way to fix this issue? The bundle is legally registered form our company.
Waiting for your answer we wish you a good day.


text:
Q: Angular Momentum and Force
I'm stuck on number 5. The answers to the first 4 are correct, but I dont know how to set up number 5. Any idea that I would have would require me having some kind of time information, but thats not given. Any suggestions?

A: I'm not sure I totally understand the question, but I can make an educated guess. Firstly, I envisage a person sitting on the merry-go round with their body pointed tangentially to the circle, in which cases no force in that direction is required.
However, if the person is free to move radially (can slip inwards/outwards), then a force is required to counteract the centripetal force. In other words,
$$F_{holding} = F_{centripetal}$$
Consider the appropriate equation for centripetal force in terms of your known variables, and you can then plug in the values to get the answer.
(P.S. Don't look at my edit unless you want the answer, best you try yourself first!)

A: Think about these:

*

*What is the shape of the path the person takes?

*What force is needed to keep the person traveling along that path?


text:
Q: How to find the index of the max value in a list for Python? I have a list, and I need to find the maximum element in the list and also record the index at which that max element is at.
This is my code.
list_c = [-14, 7, -9, 2]

max_val = 0
idx_max = 0

for i in range(len(list_c)):
    if list_c[i] > max_val:
        max_val = list_c[i]
        idx_max = list_c.index(i)

return list_c, max_val, idx_max

Please help. I am just beginning to code and got stuck here.

A: It is easiest to just apply logic to the entire list. You can get the max value of a list using max(list), and you can use the same index function you use above to get the index of this number in the list.
max_val = max(list_c)
idx_max = list_c.index(max_val)

If you want to loop over the values to find the max, then take note of the following:

*

*list.index(value) will find the index of that value in the list. In your case you are writing list.index(index_number) which doesnt make sense. 'i' already represents the list index, so just set idx_max = 'i'.

*Further, you should note that if you set max_val to zero, if all the list items are less than zero, it will stay at zero during the loop and never find the max value. It is better to start by setting max_val to the first item of the list ie list_c[0].
 list_c = [-14, 7, -9, 2]

 max_val = list_c[0]
 idx_max = 0

 for i in range(len(list_c)):
     if list_c[i] > max_val:
         max_val = list_c[i]
         idx_max = i

NB 'return' is used to return values from a function. If you want to print the values, use print(list_c, max_val, idx_max).

A: You can use NumPy argmax() by converting your list to a NumPy array.
import numpy as np
list_c = [-14, 7, -9, 2]
print("Index max:",np.argmax(np.asarray(list_c)))
print("Value max:",list_c[np.argmax(np.asarray(list_c))])

Index max: 1
Value max: 7

A: .index can only be done on elements in the list. So, do idx_max = list_c.index(list_c[i])
max_val = list_c[i]
idx_max = list_c.index(list_c[i])

However, here is a shortened version
list_c = [-14, 7, -9, 2]
print(max(list_c),list_c.index(max(list_c)))

A: *

*You are trying to find the index of i. It should be list_c[i].

Easy way/Better way is: idx_max = i. (Based on @Matthias comment above.)

*

*Use print to print the results and not return. You use return inside functions.

*Also your code doesn't work if list_c has all negative values because you are setting max_val to 0. You get a 0 always.

list_c = [-14, 7, -9, 2]

max_val = 0
idx_max = 0

for i in range(len(list_c)):
    if list_c[i] > max_val:
        max_val = list_c[i]
        idx_max = i

print(list_c, max_val, idx_max)

[-14, 7, -9, 2] 7 1

A: Looping twice through an array is inefficient. Use built-in enumerate() and max() with the comparison lambda expression returning the second element  of the enumeration:
>>> list_c = [-14, 7, -9, 2]
>>> print(max(enumerate(list_c), key=lambda x: x[1]))
(1, 7)

A: All you need is .max() and .index() function. First, you find max element of the list, then just simply get it index using index() function.
You can see a complete tutorial here: https://www.kite.com/python/answers/how-to-find-the-index-of-the-max-value-in-a-list-in-python


text:
Q: Error resolving template [twitterConnect], template might not exist or might not be accessible by any of the configured Template Resolvers Ι'm trying to implement ConnectController from Spring Social Twitter. Spring Social Facebook is working fine but when it comes to twitter I get this error error.org.thymeleaf.exceptions.TemplateInputException: Error resolving template [twitterConnect], template might not exist or might not be accessible by any of the configured Template Resolvers
This is my social Configuration class
@Configuration
public class socialConfig {

        @Autowired
        DataSource dataSource;

        @Bean
        public ConnectionFactoryLocator addConnectionFactories() {
            ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
            registry.addConnectionFactory(new FacebookConnectionFactory("appid","appsecret"));
            registry.addConnectionFactory(new TwitterConnectionFactory("consumerKey","consumerSecret"));
            return registry;

        }

        @Bean
        public UsersConnectionRepository getUsersConnectionRepository() {
            return new JdbcUsersConnectionRepository(dataSource, addConnectionFactories(), Encryptors.noOpText());

        }

        @Bean
        @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
        public ConnectionRepository connectionRepository(){
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null) {
            throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
        }
            return getUsersConnectionRepository().createConnectionRepository(authentication.getName());
        }

        @Bean
        public ConnectController connectController() {
            ConnectController controller = new ConnectController(addConnectionFactories(),
            connectionRepository());

            controller.setViewPath("");

            return controller ;
        }


text:
Q: Simple email duplicate submission Node.js I have been working on a simple duplicate email submission, here it is:
   var filter = function (o) { // o.email query - already submitted query a@a.com

    return o.email === email; // passing a@a.com or awe@awe.com

   };

  db.one(filter, function(email) { // function not picking up callback

    if (email == null) {  //same - callback returns null

        error.add('duplicate');
        self.json(error);
        return;

    }

    /....other code .../
});

How could I get the result of the callback?

A: In the node.js world, callbacks have the convention of placing the first parameter as the error (err), and the second parameter as the data result (email).
db.one(filter, function(err, email) {
  console.log(email);
});


text:
Q: Predict bounding box only I am having two folders training and testing. Each folder has 14k images of a random single object like chair , box ,fan , can ,etc..
Addition to this i have 4 columns [x1,x2,y1,y2] for each image of training set in which that random object is enclosed(bounding box).
With this information i want to predict the bounding boxes for the test set.
I am very new in Computer Vision,It would be very helpful if any one can help me how to start with training such kind of models.
I found yolov3 but it includes classification as well.

A: I recommend you see the github code here.
In detect.py, there is do_detect() function.
this function returns both class and bbox that you want to get from image.
boxes = do_detect(model, image, confidence_threshold, nms_threshold)


text:
Q: Select data from mysql with php, display in html dropdown list and insert selected value as URL parameter via javascript First, please understand I have just begun to learn php, javascript and ajax in the past 10 days so I will need some hand-holding and step-by-step examples and guidance. I've carefully read the courses for those topics at w3schools and found them very helpful; as a result, I was able to write some basic code for my project by using their examples and other snippets I've found here and other sites.
This post is a little lengthy so I can explain my ultimate goal for this code and what I've already tried.
I have started writing a piece of very complex code that has multiple parts, but the final result will be a dropdown selection list with an image thumbnail button of the main_image of that page linked to an external URL which is dynamically created based on the user's dropdown list selection.
This is my project:
I am building a website with Joomla 3.x.x, Bootstrap 3 and j2store (with other components and modules) that features photos for sale as digital images and that can be applied to physical products (canvas prints, t-shirts, coffee mugs, etc). Those physical products exist on a 3rd party website (Zazzle) which are embedded into my private website with Zazzle's RSS feed and another 3rd party javascript code (to embed Zazzle RSS feed grid displays into my website).
The Zazzle API allows my users to choose any image from my private website and apply that image to any product available in Zazzle's marketplace.
My users would ultimately select a category of products from a dropdown list on my website and then click a button that would open a new window to connect to the Zazzle marketplace which would display a grid of relevant physical products featuring the image shown on the active page of my website where the user clicked the button.
For example, the user starts by looking at the page on my website with the main_image "Light Purple African Daisy", chooses a category of electronic products from a dropdown list and then clicks the "Design Your Own Gifts" button which opens a new window, connects to the Zazzle marketplace and displays a grid of electronic products showing the "Light Purple African Daisy" image on the user's chosen products.
The URL behind the "Design Your Own Gifts" button needs to be created dynamically with the selected value after the user chooses a category of products from a dropdown list on my website.
This is the Zazzle API I need to use:
https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg= <DYNAMIC CATEGORY ID FROM DROPDOWN SELECTION LIST> &t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid= <URLENCODED DYNAMIC PATH OF ACTIVE PAGE MAIN_IMAGE>"

I have created 2 tables in mysql database that hold the Names, Category IDs and Department IDs for the products in my Zazzle marketplace. I am also getting the main_image path from my j2store productimages table.
The code I have been able to write so far accomplishes the following tasks:

*

*Connect to the database

*Choose Columns/Tables

*GET Data from Columns/Tables

*Create HTML Form to Display Result of MYSQL Query

*Create Dropdown Selection List of Query Results

*Echo encoded URL with Zazzle API concatenated with Parameters/Dynamic Values

This is my code so far:

Create Zazzle Products

Select a Template Category

<form name="create-zproducts" id="create-zproducts" action="create-zproduct.php" method="POST">
    <?php
                //connection
                $con = mysqli_connect('localhost', 'user', 'password', 'database');
                if (!$con) {
                    die('Could not connect: ' . mysqli_error($con));
}
                $sql="SELECT * FROM david_cim_template_categories, david_j2store_productimages";
                $cg = $_GET['cim_template_cg'];
                $coverimage_iid = $_GET['main_image'];
                $result = mysqli_query($con,$sql);
    ?>
    <select name="selectZcategories" id="selectZcategories">
    <?php
    while($row = mysqli_fetch_array($result)) {
        echo '<option value="'.$row['cim_template_cg'].':'.$row['cim_template_cgname']'">'.$row['cim_template_cgname'].'</option>';
    }
    ?>
    </select>
    <button onclick="ajaxFunction();">Submit</button>

<?php

?>

<?php
    echo $ZAPI = "https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg=";
    echo $cg = ['cim_template_cg'];
    echo $ZPARAM = "&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid=https%3A%2F%2Fwww.capturedimagesofmaine.com%2Fimages%2Fproducts%2Foriginal%2F";
    echo $coverimage_iid = ['main_image'];
    echo $product_text = "&t_text1_txt=Welcome";
?>
</form>

// new file (select_zproduct.php) added to same path as create_zproduct.php
// contents of select_zproduct.php below:
<?php
if( isset($_POST['selection']) )
{
   $selecterData=$_POST['selection'];
   $selecterArrayData=explode(':', $selecterData);

   $cg=$selecterArrayData[0];
   $coverimage_iid=$selecterArrayData[1];

   $url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$cg.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$coverimage_iid.'';
   ?>

   <?php
}
?>

The code above is just the beginning of what I've been able to write by myself so far.
My obstacle at the moment is not being able to make the " cg= " parameter display the numeric value of $cg= which was selected by the user from the dropdown list. The current code returns the word "Array" in the URL instead of the selected value. (eg. cg=Array instead of cg=196215449301144739)
I believe I need to use AJAX and Javascript to accomplish this action but I don't know enough to write it by myself yet.
The Code I Need to Write will accomplish the following tasks:

*Assign proper $variables to URL fragments ($ZAPI, $cg, etc) to be used for concatenation

*Assign proper $variables to database dropdown SELECTION Result to be used in the URL above

*Concatenate all $variables

*Parse all $variables

*Embed final encoded URL into button

*Use thumbnail of active page main_image as button image src

What I need to know right now is how do I insert the numeric value of 'cim_template_cg' into the " cg= " parameter in the final URL so the final URL will output " &cg=196215449301144739 " when the user selects the 'cim_template_cgname' associated with that cg=.
Once I see the solution I can apply it to the other dynamic values I need to create. I've only written one javascript code with help from a snippet so any AJAX or Javascript code that needs to be written will need to be shown to me in an example and describing related files, please.
Thanks for your help in advance!

A: So if I understood your question properly, you have the necessary data to achieve this, i.e. you have the URL path and ID from the database, as well as the URL string, which needs these database values dynamically added upon selection?
And to answer one of your questions, yes this can be done via AJAX if you wish for the PHP logic to be handled in a seperate file.
What you could do, is concatenate your URL path and ID from the database with a seperator value that you could perform an explode(); on to get the values.
so, your <select> would look something like this instead:
<select name="selectZcategories" id="zCategories">
  <?php
  while($row = mysqli_fetch_array($result)) {
    echo '<option value="'.$row['cim_template_cg'].':'.$row['cim_template_cgname'].'">'.$row['cim_template_cgname'].'</option>';
  }
  ?>
</select>

Now to the AJAX function. Personally, I use the jQuery library, simply because it makes things easy and simple. It simplifies a lot of the code, so I am going to go by the jQuery standards in my AJAX example. If you wish to use jQuery AJAX to achieve the same results, you will need to install jQuery into a library that you include like any other normal JS/CSS file etc.
function ajaxFunction() {
   var selectedData=$("#zCategories option:selected").val();

   $.ajax({
      type : "POST",
      url: "/path/to/file.php",
      data: { selection : selectedData },
      success: function (html) {
          //Success handling
      }
   })
}

What this achieves, is that the function will take the selected value of the <select> and parse the data to another file using the POST method. You are able to do a lot of things in the success function if you so desire, but for our purpose, I'll simply perform the redirect in the PHP file.
When the data has been parsed to the other file, you then perform an explode(); on the value to split it up into our two variables that we will parse along in our URL.
The PHP file could look something like this:
<?php
if( isset($_POST['selection']) )
{
   $selecterData=$_POST['selection'];
   $selecterArrayData=explode(':', $selecterData);

   $categoryID=$selecterArrayData[0];
   $imagePath=$selecterArrayData[1];

   $url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$categoryID.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$imagePath.'';
   ?>

   <?php
}
?>

How you call the AJAX function initially is up to you. It could be via a button for instance.
<button onclick="ajaxFunction();">Submit</button>

Hope this helped, or pointed you towards the right direction.
For tests as per request by your comment,
Ajax for test:
function ajaxFunction() {
   var selectedData=$("#zCategories option:selected").val();

   $.ajax({
      type : "POST",
      url: "/path/to/file.php",
      data: { selection : selectedData },
      success: function (html) {
          //Success handling
          alert(html);
      }
   })
}

PHP:
<?php
    if( isset($_POST['selection']) )
    {
       $selecterData=$_POST['selection'];
       $selecterArrayData=explode(':', $selecterData);

       $categoryID=$selecterArrayData[0];
       $imagePath=$selecterArrayData[1];

       $url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$categoryID.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$imagePath.'';

       echo 'cg: '.$categoryID.' img path: '.$imagePath;
       ?>

       <?php
    }
 ?>

A: I contacted the developer of J2Store for help with getting the main_image value from the active J2Store product page and embedding my final API URL into my J2Store product pages so he rewrote my code to integrate error-free with both Joomla and J2Store, as follows:
<?php
/**
* @package J2Store
* @copyright Copyright (c)2014-17 Ramesh Elamathi / J2Store.org
* @license GNU GPL v3 or later
*
* Bootstrap 2 layout of product detail
*/
// No direct access
defined('_JEXEC') or die;
$db = JFactory::getDbo();
$query = $db->getQuery(true)->select('*')->from('#__cim_template_categories');
$db->setQuery($query);
$cg_values = $db->loadObjectList();
$image_path = JUri::root();
$main_image = $image_path.$this->product->main_image;

//$zazzle_api = 'https://www.zazzle.com/api/create/at-238500395169782226';
$zazzle_api = 'https://www.zazzle.com/api/create/at-238500395169782226';
?>
<?php if(count($cg_values)): ?>

  <form method="get" class="zazzle_api_form" action="<?php echo $zazzle_api; ?>">
    <select name="cg" class="cg">
      <?php foreach($cg_values as $cg_value): ?>
          <option value="<?php echo $cg_value->cim_template_cg; ?>">
            <?php echo $cg_value->cim_template_cgname; ?>
          </option>
      <?php endforeach; ?>
    </select>
    <input type="hidden" name="rf" value="238500395169782226" />
    <input type="hidden" name="ax" value="DesignBlast"  />
    <input type="hidden" name="sr" value="250508120301240636"  />
    <input type="hidden" name="t__useQpc" value="false"  />
    <input type="hidden" name="ed" value="true"  />
    <input type="hidden" name="t__smart" value="false"  />
    <input type="hidden" name="continueUrl" value="<?php echo urlencode('https://www.zazzle.com?www.capturedimagesmaine.com'); ?>"  />
    <input type="hidden" name="tc" value=""  />
    <input type="hidden" name="ic" value=""  />
    <input type="hidden" name="t_text1_txt" value=""  />
    <input type="hidden" name="t_coverimage_iid" value="<?php echo $main_image; ?>"
/>
    <input class="btn btn-primary" type="submit" value="Create Your Own Custom Gifts"
/>
  </form>

<?php endif; ?>


text:
Q: How to use jquery toggle for multiple childs in different parents? Basically i have a few parents that have the same class:

And when i click on a parent class i want to toggle its child. For that i'm using:
$(document).ready(function(){
    $('.parent').click(function(e){
        $(this).children('.child').toggle();
    });
});

This does toggle my child but if i leave it visible and i click on the next parent i want to make all other children disappear.
Is this possible using only jquery/javascript?
Thank you!

A: You could use a class to manage display and just toggle that class on current parent and remove it from others

$('.parent').click(function(){
  $('.active').not(this).removeClass('active');
  $(this).toggleClass('active');
})
.parent{ margin-bottom:2em}
.child{display:none}
.active .child{ display:block}

Parent 1

Child

Parent 2

Child

Parent 3

Child

A: I think you need to show only one of childs. To do this work first hide all childs then show clicked child.
$('.parent').click(function(e){
  $(this).siblings().children('.child:visible').toggle();
  $(this).children('.child').toggle();
}).children(".child").toggle();

$('.parent').click(function(e){
  $(this).siblings().children('.child:visible').slideUp();
  $(this).children('.child').slideDown();
}).children(".child").slideUp();

parent1

child1

parent2

child2

parent3

child3

A: Please Try This:-
$('.parent').click(function(e){
            if($(this).children('.child').is(':visible')){
                $(this).children('.child').slideUp();
            }else{
                $('.parent .child').slideUp();
                $(this).children('.child').slideDown();
            }
        });


text:
Q: Javascript array of arrays query I am using highcharts.js to plot a simple column graph using my json data, I have done this before but now I'm plotting with a slightly different dataset (filtered and different format)
For "processed_json", idea used : http://codeinjs.blogspot.com/2013/07/preprocess-json-data-to-use-in.html
Currently, my processed_json is :
function plotgraph1(filter1)
        {
            var processed_json = new Array();

            $j.map(filter1, function(obj, i) {
             processed_json.push(obj[0], obj[1]);
             console.log(processed_json)

            });
...................
         }

Console prints :
["2014-06-14T18:30:00Z", 4044,
 "2014-06-15T18:30:00Z", 5030,
 "2014-06-16T18:30:00Z", 4913,
 "2014-06-17T18:30:00Z", 4985,
 "2014-06-18T18:30:00Z", 4778,
 "2014-06-19T18:30:00Z", 4733,
 "2014-06-20T18:30:00Z", 3960,
 "2014-06-21T18:30:00Z", 4221,  .......]

Opening up gives :
0: "2014-06-14T18:30:00Z"
1: 4044
2: "2014-06-15T18:30:00Z"
3: 5030
4: "2014-06-16T18:30:00Z"
5: 4913

.......... and so on
It is storing the date1, metric1 and so on, but I want it to store it in different arrays.
Basically, it should be an array of arrays, for each day, a separate array.
So that highcharts.js can read it properly.
Now it's reading the data but, since all dates are in one array it's skipping a date and showing 28 dates instead of 14 days (which is the selected range); (double basically)
Earlier and correct "processed_json" is :
[Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2]]
0: Array[2]
0: "2014-04-30T18:30:00Z"
1: 200303

I was trying something like this :
var processed_json1 = [];
            for ( var i = 0; i < processed_json.length; i++)
            {
            processed_json1.push(processed_json[i]);
            }

But, clearly this is wrong and I am wasting too much time. Any good direction/suggestion will be highly appreciated to convert my data format to the correct one for highcharts to read it properly.

A: Giving multiple arguments to push is just short for calling push separately with each argument, it doesn't collect them together in an array. You need to make them an object first:
function plotgraph1(filter1)
{
    var processed_json = $j.each(filter1, function(i, obj) {
        processed_json.push([obj[0], obj[1]]);

    });
    console.log(processed_json)
    ...................
}

DEMO

A: I think you are looking for something like the following:
            var array = [];
        for(var i=0;i<5;i++){
            array.push({"date":"metric"});
        }
        console.log(array);

Outputs:
[Object, Object, Object, Object, Object]
0: Object
date: "metric"
1: Object
date: "metric"
2: Object

A: processed_json.reduce(function(soFar, val, idx) {
    if (idx % 2 == 0) {soFar.push([]);}
    soFar[soFar.length - 1].push(val);
    return soFar;
}, []);
//=> [["2014-06-14T18:30:00Z", 4044], ["2014-06-15T18:30:00Z", 5030], ...]

Is that what you're looking for?


text:
Q: Windows Server 2016 Installation doesn't found Network adpter (Hard Drive Found!) I have a just bought PowerEdge T640 server and i am trying to install Windows Server 2016 Standard.
I have downloaded the Windows Server 2016 ISO and mount a bootable pendrive using Rufus.
I boot the T640 Server and insert the pendrive and it recognizes it, so i start the installation.
The problem comes when i have to choose where to install Windows as no Disk appers.
I have an 240GB SSD Disk.
I need some help on how to make this SDD visible for the installation program.
Thx for help.
Edit:
I have installed Windows Server 2016 after investigating through Lifecycle Controller.
Then i have set the IP address in the Network configuration and i have checked with ping that while in the LifeCycle ping works, another laptop in the LAN sees the T640.
Then i save settings in T640 and reestart server
The Server works fine but ping doesn't works now, i check the server and no Ethernet adapter appears.
It's supposed to have two Bradcom Adv. Dual 10GBASE - T Ethernet adapters.
Thx in advance

A: Use the Lifecycle Controller to install the operating system. It will inject the drivers that Windows needs to find the hard drive.

A: The above answer usually works, I'm leaving this here in case you can't access the Lifecycle Controller for whatever reason.
You can download the driver from Dell's website, in your case:
PowerEdge T640
In the case of Windows Server 2016 the package would be:

Windows Server 2016 64bit driver for PERC S140 Controller

Also, make sure the drive has been enabled, either through the iDRAC or the server's boot settings by creating a virtual drive with the 240GB SSD you mentioned.


text:
Q: HP smart array p400 RAID 1+0; two disks crashed I am running a RAID 1+0 on a HP ProLiant DL360 G5 with 6 disks (each 146 GB).
The mirror groups looks as follows:
Group 1

*

*146 GB 1-Port SAS Drive at Port 1l: Box1:Bay1

*146 GB 1-Port SAS Drive at Port 1l: Box1:Bay2

*0 GB 1-Port SAS Drive at Port 1l: Box1:Bay3

Group 2

*

*146 GB 1-Port SAS Drive at Port 1l: Box1:Bay4

*146 GB 1-Port SAS Drive at Port 2l: Box1:Bay5

*0 GB 1-Port SAS Drive at Port 2l: Box1:Bay6

Unfortunately the disks in bay 3 and bay 6 are not working anymore (almost since the same time). Is there a chance to get the system back online again by replacing disk 3 + 6 by new ones?
* UPDATE *
It's a MS Server 2003 R2. I've got the information that the disks are broken from the HP smart start CD diagnostics tool. The following versions are in place:
* ACU Version 8.60.7.0
* Diagnostic Module Version 5.2.52.0
* INFOMGR Version 5.9-29.0
Server was already off (pressing power button) when people involved me. ROM/RAM firmware revision is 2.10

A: If you can shut the system down gracefully, you can be able to jog the disks through a simple power-down operation.
You're correct in that the mirror groups mate RAID1 pairs from each group, as in this example.
If you can get the system off and the drives spun down (also remove power), there's some hope that they'll spin up and give the controller a chance to perform an array recovery.
Of course, at the same time, you'll want to get spares or replacements ready or on the way.
Can you share the specific server model, firmware, OS and other details? There are cases of early firmware revisions of that Smart Array P400 giving false-positive failure indications on drives, so a comprehensive evaluation of your firmware and system health is in order.

Edit:
You say the Smart Array P400 RAID controller's firmware version is 2.10 from May 2007. The current version of firmware for that system is 7.18!!
You are severely behind. Also, I suggested pulling the power cables to the system for a few minutes and trying a cold start. Take close note of the RAID controller messages as the system boots. Or does the system even boot properly? Do the physical disks have error lights illuminated?
Can you try a firmware update of all of the components using the bootable HP Firmware DVD just to rule-out bad firmware interactions or a false-positive disk failure?

A: If disk 3 and 6 have failed and they won't come back online, then no, you can not get your data back.


text:
Q: Наилучший способ сортировки массива. Какой способ является самым лучшим и по вашему мнению и почему? Есть ли способы быстрее способа, основанного на алгоритме "быстрой сортировки"? Если да, то будьте добры рассказать, где можно о нем почитать.
A: Коротко.
@Котик_хочет_кушать правильно сказал, что лучшего способа нет.
Из почти всегда применимых алгоритмов quicksort IMHO самый быстрый (время O(N*log N)), хотя (даже правильно реализованый) изредка (на практике очень редко) может привести к времени порядка O(N^2).
Он требует log N дополнительной памяти, т.е. на практике можете считать, что не требует.
Основной недостаток quicksort - это неустойчивый (unstable) алгоритм.
Сортировка называется устойчивой, если порядок записей с одинаковыми ключами после сортировки сохраняется. Очевидно, что если Вы сортируете массив чисел, то устойчивость алгоритма неважна (одно число 10 от другого 10 неотличимо). Для сортровки записей (структур) это не так (хотя зависит от прикладной задачи).
Из устойчивых сортировок (я рассматриваю алгоритмы со временем O(N*log N)) IMHO самым быстрым является сортировка слиянием (mergesort) в ее почти простейшей реализации, требующий N/2 дополнительной памяти.
Похожие результаты (иногда м.б. даже быстрее, но обычно медленнее) показывает timsort (это тоже разновидность сортировки слиянием). Обычно она требует 30-40% N дополнительной памяти.
Также (пользуясь случаем) хочу обратить внимание на yamsort. Еще один алгоритм и программа устойчивой (stable) сортировки слиянием c небольшой (около 6 % от размера сортируемого массива) дополнительной памятью. Он несколько медленнее timsort, но при сортировке очень больших массивов (особенно в многопользовательских системах), когда дополниетельная память вызывает paging, это алгоритм оказывается значительно быстрее других устойчивых сортировок.
По этой ссылке (в Sourse/Readme.txt) описан данный алгоритм и есть некоторые результаты измерения разных сортировок, а также исходники нескольких сортировок и пример программы для их измерения.
A: *

*Лучшего способа нет, если говорить о "разумных" алгоритмах и не учитывать эзотерику типа Bogosort или Intelligent Design Sort.

*

*Стандартные операции sort в современных языках обычно используют разные алгоритмы в зависимости от размера входных данных. То есть, на маленьких размерах массивов O(N^2) сортировка вставками часто оказывается более эффективной, чем, например, O(N log N) быстрая сортировка.

*Естественно, что для больших размеров выбирается сортировка с O(N log N) временем работы.

*

*Можно строго доказать, что, если S - алгоритм сортировки, основанный на построении дерева решений, то O(N log N) - это минимальное возможное время работы алгоритма S в худшем его случае. А это означает, что все алгоритмы типа quicksort, mergesort, сортировки вставками и т.п. не могут работать за время, меньшее, чем O(N log N).

Тем не менее, есть сортировки, которые не используют деревья решений и работают за линейное время при некоторых ограничениях. Например, поразрядная сортировка.

*

*Из литературы - Cormen, Introduction To Algorithms.

A: я просто оставлю это здесь

источник: Алгоритм сортировки Timsort


text:
Q: A query which pulls below result with key-value pairs Context:
I am working in one cluster datastax dse 5.1.8 with spark  version 2.0.2.17 and Scala version 2.11.11.
Problem:
I am a table with this structure definition
CREATE TABLE test (
location text,
cell text,
testdate timestamp,
model text,
testnumber bigint,
reading bigint,
scan bigint,
testtype text,
readingtype text,
payloadtype text,
datatype text,
measurementid timeuuid,
aircraftengineposition text,
aircrafttailnumber text,
aircrafttypename text,
analysisnumber bigint,
archiveddate timestamp,
archivemethod text,
createddate timestamp,
edwid bigint,
engineserialnumber text,
etdscampus text,
etdsrecordid bigint,
etdssetid bigint,
fleet text,
flightnumber text,
jnumber bigint,
method text,
modifieddate timestamp,
parameters map<text, frozen<tuple<text, text, bigint, double, text>>>,
payloadchecksum blob,
payloadlocation text,
payloaduri text,
payloaduserreference text,
powerset text,
rating text,
status text,
vehicle text,
PRIMARY KEY ((location, cell, testdate, model, testnumber, reading, scan, testtype, readingtype, payloadtype, datatype), measurementid)
) WITH CLUSTERING ORDER BY (measurementid DESC)

My primary keys is:
    location, cell, testdate, model, testnumber, reading,
    scan,testtype,readingtype, payloadtype, datatype
When i query this table by using the column parameters from cassandra i get tuple below for one row for example:
{'PF121A': ('R', None, None, 1131.65942, None), 'PT25AA': ('R', None, None, 29.40011, None), 'PT25AB': ('R', None, None, 29.83459, None), 'PT25AC': ('R', None, None, 29.93993, None), 'PT25AD': ('R', None, None, 14.02732, None), 'PT25AE': ('R', None, None, 31.12416, None), 'PT25AF': ('R', None, None, 31.06807, None), 'PT25SA': ('R', None, None, 14.02681, None), 'PT25SB': ('R', None, None, 29.39588, None), 'PT25SC': ('R', None, None, 29.6147, None), 'PT25SD': ('R', None, None, 29.97557, None), 'PT25SE': ('R', None, None, 30.94819, None), 'PT25SF': ('R', None, None, 30.66682, None), 'PT31FA': ('R', None, None, 814.65393, None), 'PT31FB': ('R', None, None, 818.90576, None), 'PT31FC': ('R', None, None, 819.23676, None), 'PT31FD': ('R', None, None, 814.65485, None), 'PT31FE': ('R', None, None, 814.4751, None), 'PT31FF': ('R', None, None, 813.31396, None), 'PT31RA': ('R', None, None, 812.73108, None), 'PT31RB': ('R', None, None, 814.26917, None), 'PT31RC': ('R', None, None, 814.9386, None), 'PT31RD': ('R', None, None, 814.97534, None), 'PT31RE': ('R', None, None, 814.57043, None), 'PT31RF': ('R', None, None, 813.4953, None), 'PT49JA': ('R', None, None, 137.66408, None), 'PT49JB': ('R', None, None, 136.09262, None), 'PT49JC': ('R', None, None, 134.53801, None), 'PT49JD': ('R', None, None, 135.47989, None), 'PT49JE': ('R', None, None, 134.17297, None), 'PT49WA': ('R', None, None, 138.44234, None), 'PT49WB': ('R', None, None, 136.7596, None), 'PT49WC': ('R', None, None, 135.41495, None), 'PT49WD': ('R', None, None, 135.69455, None), 'PT49WE': ('R', None, None, 133.96593, None), 'PT50EA': ('R', None, None, 20.66105, None), 'PT50EB': ('R', None, None, 20.15389, None), 'PT50EC': ('R', None, None, 20.01845, None), 'PT50ED': ('R', None, None, 19.94046, None), 'PT50EE': ('R', None, None, 14.02631, None), 'PT50EF': ('R', None, None, 20.40714, None), 'PT50SA': ('R', None, None, 20.47363, None), 'PT50SB': ('R', None, None, 19.98885, None), 'PT50SC': ('R', None, None, 19.87228, None), 'PT50SD': ('R', None, None, 19.74927, None), 'PT50SE': ('R', None, None, 19.84222, None), 'PT50SF': ('R', None, None, 14.0299, None), 'PUBDAT': ('R', None, None, 14717, None), 'PUBTIM': ('R', None, None, 6.1759e+07, None), 'TACALL': ('R', None, None, 217.15161, None), 'TACALR': ('R', None, None, 215.13361, None), 'TACAUL': ('R', None, None, 192.04047, None), 'TACAUR': ('R', None, None, 207.94643, None), 'TACFLL': ('R', None, None, 166.98624, None), 'TACFLR': ('R', None, None, 153.83304, None), 'TACFUL': ('R', None, None, 180.14462, None), 'TACFUR': ('R', None, None, 168.80762, None), 'TACMUL': ('R', None, None, 183.63214, None), 'TACMUR': ('R', None, None, 111.59378, None), 'TM25AA': ('R', None, None, 209.83342, None), 'TM25AB': ('R', None, None, 209.16489, None), 'TM25AC': ('R', None, None, 209.9166, None), 'TM25AD': ('R', None, None, 216.28339, None), 'TM25AE': ('R', None, None, 221.4989, None), 'TM25AF': ('R', None, None, 227.64745, None), 'TM25SA': ('R', None, None, 209.70547, None), 'TM25SB': ('R', None, None, 208.61472, None), 'TM25SC': ('R', None, None, 208.71387, None), 'TM25SD': ('R', None, None, 212.55757, None), 'TM25SE': ('R', None, None, 222.05238, None), 'TM25SF': ('R', None, None, 227.34381, None), 'TM31FA': ('R', None, None, 1303.27625, None), 'TM31FB': ('R', None, None, 1302.17749, None), 'TM31FC': ('R', None, None, 1301.16431, None), 'TM31FD': ('R', None, None, 1300.43945, None), 'TM31FE': ('R', None, None, 1306.04688, None), 'TM31FF': ('R', None, None, 1308.64978, None), 'TM31RA': ('R', None, None, 1308.25098, None), 'TM31RB': ('R', None, None, 1307.29443, None), 'TM31RC': ('R', None, None, 1307.47229, None), 'TM31RD': ('R', None, None, 1308.46118, None), 'TM31RE': ('R', None, None, 1311.94226, None), 'TM31RF': ('R', None, None, 1317.01111, None), 'TM50EA': ('R', None, None, 1066.51196, None), 'TM50EB': ('R', None, None, 1037.17004, None), 'TM50EC': ('R', None, None, 1035.68445, None), 'TM50ED': ('R', None, None, 1030.4646, None), 'TM50EE': ('R', None, None, 1022.53888, None), 'TM50EF': ('R', None, None, 1016.54425, None), 'TM50SA': ('R', None, None, 1064.77722, None), 'TM50SB': ('R', None, None, 1044.97632, None), 'TM50SC': ('R', None, None, 1044.73755, None), 'TM50SD': ('R', None, None, 1046.18323, None), 'TM50SE': ('R', None, None, 1047.10889, None), 'TM50SF': ('R', None, None, 1042.55457, None), 'XNHCT1': ('R', None, None, 10639.88574, None), 'XNLCT1': ('R', None, None, 2448.99121, None)}
My problem is to use scala query which allow me to pull result above with key value pair, example to have from the result above these example:
KEY: VALUE PAIR

PF121A: 1131.65942
PT25AA: 29.40011
PT25AB: 29.83459
PT25AC: 29.93993
PT25AD: 14.02732
PT25AE: 31.12416
PT25AF: 31.06807

Below the first query i used from spark but i don't know how to continue:
scala> val parameters = sc.cassandraTable(String).select("parameters")
parameters: com.datastax.spark.connector.rdd.CassandraTableScanRDD[String] = CassandraTableScanRDD[1] at RDD at CassandraRDD.scala:19

result for 5 lines:
scala> parameters.take(10)
res1: Array[String] = Array({PT25AF: (R, null, null, 14.898366928100586, null),PT31RD: (R, null, null, 73.38668060302734, null),PT49WD: (R, null, null, 20.127065658569336, null),TM50SC: (R, null, null, 803.0751342773438, null),PT50SE: (R, null, null, 14.305357933044434, null),TACAUL: (R, null, null, 211.5594940185547, null),PT31RE: (R, null, null, 73.51492309570312, null),PT31FE: (R, null, null, 73.38947296142578, null),TM50SF: (R, null, null, 810.0723876953125, null),PT50ED: (R, null, null, 14.262494087219238, null),PT49JC: (R, null, null, 20.577911376953125, null),TACMUR: (R, null, null, 113.4200668334961, null),TM50EF: (R, null, null, 802.0999145507812, null),PT50EE: (R, null, null, 14.02810001373291, null),PT25SC: (R, null, null, 14.932862281799316, null),PT25AA: (R, null, null, 14..

Thank you for your help.


text:
Q: Display base64 encoded image on a browser when hitting a specific url I want to display a image that is encoded with base64_encode. The image is fetching from mysql db based on the id parameter passed through the URL. The Content-type has been set. Say i have a code in index.php file and i am hitting that file in browser with url localhost:8080/products_images/index.php?id=1000
header('Content-Type:image/png');
if (isset($_GET['id'])) {
$id = $_GET['id'];
}

$sql = "SELECT image FROM table WHERE id = ".(int)$id;

$image = $dbInstance->getArray($sql);
unset($sql);
echo '';

Instead of displaying the image on a browser, it says The image "localhost:8080/products_images/index.php?id=1000" cannot be displayed because it contains errors.
I know its happening because on a browser DOM, i can clearly see the image tag appearing like following
Instead of showing the encoded string to img src tag, its showing the whole URL.
Any help would be appreciated!

A: To send the image to the client, you might try to load the image from the string with imagecreatefromstring function then send it to the client with imagepng function, it should give you something like that:
<?php
    $data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
    . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
    . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
    . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';

    $data = base64_decode($data);
    $im = imagecreatefromstring($data);

    if ($im !== false) {

        header('Content-Type: image/png');

        // Send the image
        imagepng($im);

        imagedestroy($im);

    } else {

        echo 'An error occurred.';

    }
?>

I got it from the php doc


text:
Q: Is it possible to compile a flex project that uses Cairngorm with command line? Has anyone tried to compile a flex project that uses Cairngorm with command line?

A: Ensure that the Cairngorm SWC is in your library path. For instance, if you have the SWC in a folder called "libs" that is relative to the current directory, you should include the following command line argument for mxmlc:
--library-path+="libs"

Notice the += in there. This means that "libs" is added to the current library path, which may already include other folders. The quotes are optional if you don't have spaces in your path.


text:
Q: Prime factorisation of ideals I am concerned with the following proposition:
Let $R$ be a commutative ring with unity, and $I\subsetneqq R$ be a proper ideal. Then there exist prime ideals $P_1,\dots,P_d$ containing $I$ so that $I=P_1 P_2 \cdots P_d$.
The notes that I took down argues as follows. Let $\mathcal S$ be the collection of all proper ideals $I$ for which the above is FALSE. Then there is a maximal element $I\in \mathcal S$. We claim that $I$ is prime. Suppose not. Then there are $a,b\notin I$ with $ab\in I$. Let $J_1:=\langle a \rangle+I$, $J_2:=\langle b \rangle+I$. Then $J_1,J_2$ both strictly contain $I$, and are not in $\mathcal S$ by maximality. Thus $J_1,J_2$ satisfies the factorisation property. Take $P_1,\dots,P_d$ all containing $J_1$ so that $J_1= P_1\cdots P_d$, and take $Q_1,\dots,Q_s$ all containing $J_2$ so that $J_2= Q_1\cdots Q_s$. Then note that
  \begin{align*}
  P_1\cdots P_d\cdot Q_1\cdots Q_s
  &= J_1 J_2=(\langle a \rangle+I)(\langle b \rangle+I)\\
  &=\left\{\sum_{i,j}c_i a d_j b+c_i a s_j+d_j b r_i+ r_i s_j\right\}\\
  &\subseteq I,\text{ since }ab\in I \text{ and $I$ is an ideal}.
  \end{align*}
  Since $I\subsetneqq J_1$, $I$ is a proper ideal of $R$. Since $I$ admits such factorisation as shown, we see that $I\notin \mathcal S$, which is a contradiction. Thus $I$ is prime.
Lastly, since $I$ is prime, take $P_1=I$ so that $I=P_1$ is a trivial factorisation. Hence $I\notin \mathcal S$, which is a contradiction. Thus $\mathcal S=\varnothing$.
The only place where I got stuck is the last line in the computation of $P_1\cdots P_d\cdot Q_1\cdots Q_s$, since it only proves one direction. What about the other direction? Or is such proposition actually false?


text:
Q: Difference b/w two methods in vectors. Prove that in a right angled triangle the mid point of the hyphotenuse is equidistant from its vertices.
My Solution -
In triangle ABC right angled at A. Let D be the mid point of the hyphotenuse BC. We have to show that AD=CD=BD.
CD=BD=1/2BC.
$\vec{AD} = \vec{AB} + \vec{BD}$
$\vec{AD} = \vec{AB} + 1/2\vec{BC}$
$= \vec{AB} + 1/2(\vec{BA} + \vec{AC}$
$= \vec{AB} - 1/2\vec{AB} + 1/2\vec{AC}$
$= 1/2\vec{AB} + 1/2\vec{AC}$
Then on squaring,
$AB^2= 1/4(AB^2 - 2AB.AC + AC^2)$
AB perpendicular to AC so AB.AC = 0.
$AB^2 = 1/4 BC^2$
AB = 1/2 BC
So AD = BD = CD
Hence proved. But i have few questions.

Question 1 -

Can we solve above question using one vertice as origin? If yes please provide solution.

Qusetion 2 -

I have seen many questions some of them solved using one vertice as origin. And some of them not taking one vertice as origin. How to know where to use one vertice as origin vector or not?

A: Here, you are using pure vector calculus, but in a certain way, you are trying to decompose all your vectors in the "basis" $(\vec{AB},\vec{AC})$.
You could translate your demonstration by choosing $A$ as the origin, and vectors $\vec i$ and $\vec j$ of length $1$ and directions those of $\vec{AB}$ and $\vec{AC}$, and use cartesian coordinates to do the math.
Those methods are completely equivalent.

A: "Can we solve above question using one vertex as origin? If yes please provide solution."
Yes, of course.  Let the distance from A to B be "b" and the distance from A to C be "c".  Set up a coordinate system so that A is at the origin, B on the x-axis, and C on the y-axis.  (We can do that because A is a right angle.)
Then B is the point (b, 0) and C is the point (0, c).  The midpoint of the hypotenuse is (b/2, c/2).  The distance from that point to A, (0, 0), is $\sqrt{(b/2- 0)^2+ (c/2- 0)^2}= \sqrt{b^2/4+ c^2/4}= \frac{1}{2}\sqrt{b^2+ c^2}$.  Similarly, the distance from that point to B is $\sqrt{(b/2- b)^2+ (c/2- 0)^2}= \sqrt{b^2/4+ c^2/4}= \frac{1}{2}\sqrt{b^2+ c^2}$ and the distance from that point to C is $\sqrt{(b/2- 0)^2+ (c/2- c)^2}= \sqrt{b^2/4+ c^2/4}= \frac{1}{2}\sqrt{b^2+ c^2}$.
"I have seen many questions some of them solved using one vertice as origin. And some of them not taking one vertice as origin. How to know where to use one vertice as origin vector or not?"
You don't "know"- you try it and see if it works.
  If it doesn't, try something else!

A: Let $(A;\vec i,\vec j)$ be an orthonormal frame where $\vec{AB}=b\vec i$ and $\vec{AC}=c\vec i$.
Coordinates are : $A(0,0)$, $B(b,0)$, $C(0,c)$ and $D(b/2,c/2)$, and
$$AD=\sqrt{(b/2)^2+(c/2)^2}=\frac12\sqrt{b^2+c^2}=BD=CD$$
The demonstration without choosing an origin is exactly the one you gave...


text:
Q: Python Discord Bot reproduce audio from youtube link I'm trying to make my discord bot reporoduce audio from a link
@client.command()
async def play(ctx, url):
   #...code

but it seems that I need to have installed a program called FFmpeg, and the problem is that i'm running my bot on replit.com,(which aparently you can't install nothing but packages) is there a way that I can play youtube audio links wihout installing any app, or there is any solution that someone can tell me?

A: It seems that in replit.com they solved the problem with not being able to install any program to solve this, they have created a template called Discordpy-Music-Boy
Here is the link: https://replit.com/@replit/Discordpy-Music-Bot#main.py
They removed the capacity to install FFmpeg because it was initially used for botting and spamming, so they removed the functionality, as this post explains:
https://replit.com/talk/ask/Installing-FFmpeg/28721
And theres is no need to install nothing since it solves the problem with the FFmpeg using another package called youtube_dl that resolve most of the problem, but it's not perfect as some commands don't work, but it works fine for a small project.


text:
Q: ghc-modi and cabal version (Haskell newbie here)
I'm trying to configure HaskForce plugin into IntelliJ IDEA, configured "ghc-mod" with "legacy-interactive" in "GHC Modi" Flags. The root problem seems to be related to cabal version, although when I try autocompleting on any Haskell symbol, I get this:
ghc-modi error
           Unable to parse problems from ghc-modi: cabal-helper-wrapper.exe: ghc: readCreateProcess: does not exist (No such file or directory)

           ghc-mod: readCreateProcess: C:\ACME\projects\htest\.cabal-sandbox\cabal-helper-0.5.3.0-553kah86RQN6BuDX6XLBiX\cabal-helper-wrapper.exe "C:\\ACME\\projects\\htest" "C:\\ACME\\projects\\htest\\dist" (exit 1): failed

When I run this last command (C:\ACME\projects\htest\.cabal-sandbox\cabal-helper-0.5.3.0-553kah86RQN6BuDX6XLBiX\cabal-helper-wrapper.exe "C:\\ACME\\projects\\htest" "C:\\ACME\\projects\\htest\\dist"), it tries to install cabal 1.18:
cabal-helper-wrapper.exe: Installing Cabal version 1.18.1.3 failed.

I already have cabal, of version 1.22 (installed via Haskell Platform v7.10.2-a, released recently in August).
Is there any way to work around this issue (i.e. still use ghc-mod / ghc-modi)?

A: Updated Haskforce plugin (0.3-beta24) seems to work correctly with following ghc-mod:
ghc-mod version 5.4.0.0 compiled by GHC 7.10.2


text:
Q: How to copy contents of one file into a after a specific line in another file How to copy contents of one file into a after a specific line in another file?
I would like to copy the contents of file1 after the following string:
<!-- INSERT SMART FIELDS HERE -->

My code so far.
file1 = open('newfile.xml')
file2 = open('../file.xml', "rb+")
regex = re.compile(r"<[^*]-- INSERT SMART FIELDS HERE -->")
 for line in file1.readlines():
   for comment in file2.readlines():
       our_match = regex.findall(comment)
             if match in our_match:

A: The basic idea is to read the first file until you find the line you are looking for and aftewards just read each line of the first file and write to the second file.
regex = re.compile(r"<[^*]-- INSERT SMART FIELDS HERE -->")
line_found = False

with open('newfile.xml') as file1:
    for line in file1:
        if re.match(line):
            line_found = True
            break
    with open('../file.xml', "w+") as file2:
        if line_found:
            for line in file1:
                file2.write(line)


text:
Q: Reading serial number of external monitor connected to M2 MacBook How can I read serial number of a connected external monitor to a M2 Mac book pro programatically or using any terminal commands.
"system_profiler SPUSBDataType | grep "Serial Number" -B5" fails to get serial.
ioreg -lw0 | grep -i "DisplayAttributes"
display attributes seems empty.
and "AppleCLCD2" is also missing in ioreg -lw0.
is there any other terminal command to read serial number of the connected external displays (with M2 Macbook).


text:
Q: C# No file access in Windows 8.1 App In my Windows 8.1 app I want to write to Json file in my datamodel. (See image 1).
I have a button click event with the following code:
Uri dataUri = new Uri("ms-appx:///DataModel/SampleData.json");
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);
await Windows.Storage.FileIO.WriteTextAsync(file, "sampletext");

But I receive an UnauthorizedAccessException after pressing the button. (See image 2).
Is there a way to access to Json file for writing purposes?


text:
Q: image difference algorithm based on visual perception I have tried searching google for this for quite some time and have had no luck find what I need. What I am trying to do is I have a few different versions of the same image these versions being derived from the original by dithering them to a palette. The image is split into 8x8 tiles that use one of n palettes. I want to pick which palette looks best. There are a few questions on stackoverflow relating to image difference however they suggest a simple algorithm
Σ(R1n-R2n)^2+(G1n-G2n)^2+(B1n-B2n)^2 and picking the lowest sum. Some suggest that to improve this a better delta algorithm can be used, I have tried CIEDE2000 still found the results unsatisfactory and in many instances I can manually pick a better tile. Note that I did do a bit of verification of my implementation of CIEDE2000 using precomputed data and used this library for http://www.getreuer.info/home/colorspace rgb to CIELab so I doubt that the reason I am a bit disappointed with the results is due to a bug and most of the time it does an okay job. What I want to do is implement a better algorithm than just the delta to pick the best tile. Does anyone know of a good algorithm for this (inclusive) or better terminology so that when I search for this I find more relevant information?


text:
Q: Dynamically change image using Name Manager in Excel I have a table that has a dynamic number of rows. There is a specific column that changes the image based on the value of the cell next to it.
I have tried using this guide:
https://www.youtube.com/watch?v=yHBQ9Qxli3M
But it can only be used with a specific row and not dynamically.
I have tried using:
=INDIRECT("RC[-1]",0)

in my image's name but doesn't seem to change based on the targeted cell.
A link to my excel file:
https://drive.google.com/open?id=1v1RXhdPYU4j2CqxgNEWUtJ8gHbZV33xN

A: There is another way to do this via VBA. You can place this code in the under 'Sheet1'. It detects when a change is made to column M, and then copies and pastes the image from your lookup table.
Note:

*

*it only works when the value 1 is inserted into the cell

*remove the '1' value deletes the image

*dragging down 1 values will not work (though the macro could be adjusted). Best to enter the '1' values one at a time ;)

    Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells, SelectedCells As Range, s As Shape
    Set KeyCells = Range("M13:M1000")
    Set SelectedCells = Range(Target.Address)

    If Not Application.Intersect(KeyCells, SelectedCells) Is Nothing Then
    'Place a 1 in the cell to insert an image
    If Application.Sum(Range(Target.Address)) = 1 Then
      Sheets("Shapes").Shapes("Shape" & Range(Target.Address).Offset(0, -2).Value).Copy
      ActiveSheet.Paste
      Selection.Left = SelectedCells.Left
      Selection.Top = SelectedCells.Top
      SelectedCells.Select
    Else 'Deletes the pictures if a 1 is not present
      For Each s In ActiveSheet.Shapes
        If Not Intersect(SelectedCells, s.TopLeftCell) Is Nothing Then
            s.Delete
        End If
      Next s
    End If
    End If
    End Sub


text:
Q: How to get resolved object in the child component from the ui-router state? Here is my code:
export function resolveUser(userService: UserService) {
  return userService.get();
}
 let homeState = {
  parent: 'app',
  name: 'home',
  url: '/home'
  component: HomeComponent,
  resolve: [
    { token: 'currentUser', deps: [UserService], resolveFn: resolveUser },
  ]
};

@Component({
   selector: 'app-home',
   template: '<app-menu></app-menu>'
})
export class HomeComponent {
    @Input('currentUser') user: User; //user exists
}

@Component({
   selector: 'app-menu',
   template: '<div>{{user.name}}</div>'
})
export class MenuComponent {
    @Input('currentUser') user: User; //user undefined
}

currentUser field in the HomeComponent is defined, but in the MenuComponent is not defined, although MenuComponent is a child of HomeComponent.
How cat I get currentUser in the MenuComponent?


text:
Q: How to save an excel file in a particular folder using openpyxl in python code
This is the code I am entering
from openpyxl import Workbook
from datetime import datetime

timestr=datetime.now().strftime("%d%m%Y-%H%M%S")

workbook = Workbook()
sheet = workbook.active
sheet["A1"]="Email"
sheet["B1"]="Password"
sheet["C1"]="Phoneno"
workbook.save("C:\Users\HARSHIL\Desktop\Proxlight-Designer-main\Backend Logs\"backend_"+timestr+"data.xlsx"")

I am able to save the file randomly in the folder where I saved my python file but i am unable to do so when i want to save it to any other folder.
error

A: This error is because you're using backslash, instead slash to the path. Try something like this:
...
workbook.save("C:/Users/HARSHIL/Desktop/Proxlight-Designer-main/Backend Logs/" + timestr + "_data.xlsx")


text:
Q: Proving that a particular submanifold of the cotangent space is Lagrangian I have the following problem in my differential topology class: Let $M$ be an $n$-dimensional manifold and let $\omega$ denote the standard symplectic form on the cotangent space $T^*M$. Let $f \in C^{\infty}(M)$ and put $L_f = \{(p,\mathrm{d}f_p) \in T^*M: p \in M\}$. Prove that $L_f$ is a Lagrangian submanifold of $T^*M$ and that $L_f$ is diffeomorphic to $M$.
I can prove that $L_f$ is a submanifold of $T^*M$ without any difficulty and the proof that $L_f$ is diffeomorphic to $M$ is similarly easy. I am having difficulty with the computation that $L_f$ is Lagrangian however, so I was hoping that someone could at least get me started in the right direction here.

A: Here's a proof of a more general result. Here I let $\alpha \in \Omega^1(M)$, I define
$$s_\alpha: M \longrightarrow T^\ast M,$$
$$p \mapsto (p, \alpha_p),$$
and I write $M_\alpha$ for the image of $s_\alpha$. Recall that the canonical symplectic form $\omega_{\text{can}}$ on $T^\ast M$ is exact,
$$ \omega_{\text{can}} = - d\lambda,$$
where $\lambda$ is the Liouville form given locally by
$$\lambda = \sum_{i = 1}^n \xi_i ~dx_i$$
and globally by
$$\lambda_{(x,\xi)} = (d\pi_{(x,\xi)})^\ast \xi,$$
where $\pi: T^\ast M \longrightarrow M$ is the bundle projection.
With the above setup, I claim that
$$s_\alpha^\ast \lambda = \alpha.$$
To see this, recall that by definition,
$$\lambda_p = (d\pi_p)^\ast \xi$$
where $p = (x, \xi) \in T^\ast X$ and $\pi: T^\ast X \longrightarrow X$ is the bundle projection. Then we have
$$\lambda_{s_\alpha(x)} = (d\pi_{s_\alpha(x)})^\ast \alpha_x,$$
and hence
\begin{align*}
 (s^\ast_\alpha \lambda)_x & = (ds_\alpha)^\ast_x \lambda_p \\
  & = (ds_\alpha)^\ast_x (d\pi_{s_\alpha(x)})^\ast \alpha_x \\
  & = (d\pi_{s_\alpha(x)} \circ (ds_\alpha)_x)^\ast \alpha_x \\
  & = d(\pi \circ s_\alpha)_x^\ast \alpha_x \\
  & = \alpha_x,
\end{align*}
since $s_\alpha$ is a section and thus $\pi \circ s_\alpha = \mathrm{Id}_X$. Therefore
$$s_\alpha^\ast \lambda = \alpha.$$

Theorem. Let $\alpha \in \Omega^1(M)$. Then $M_\alpha$ is a Lagrangian submanifold of $(T^\ast M, \omega_\mathrm{can})$ if and only if $\alpha$ is closed.

Proof. Since $M_\alpha$ is the image of the closed embedding $s_\alpha$, we have that
\begin{align*}
 M_\alpha \text{ is Lagrangian} & \iff s_\alpha^\ast \omega_\text{can} = 0 & & \\
  & \iff s_\alpha^\ast d\lambda = 0 & & (\omega_\text{can} = -d\lambda) \\
  & \iff ds_\alpha^\ast \lambda = 0 & & (d \text{ commutes with pullbacks}) \\
  & \iff d\alpha = 0, & & (s_\alpha^\ast \lambda = \alpha)
\end{align*}
from which the result follows.

A: Recall that $\omega$ is defined as $d\theta$ for a certain canonical 1-form $\theta$ on $T^*M$. You have a map (diffeomorphism) $s:M\to L_f$, given by $s(p)=(p,df_p)$. Prove that $s^*\theta=df$ and conclude what is $s^*\omega$.