text:
Q: Zipping up individual files gets stuck in loop I am trying to zip up a shapefile. I have selected all the components of the shapefile bar the LOCK and .CPG files. These cant be uploaded on our website for some reason, and cause a problem.
I have tried using the following code, but its keeps getting stuck in a loop and crashes. I have a seperate folder which can be zipped up quite easily using the shutil method. However, as im trying to identify files to zip, I have to use the Zipfile module.
rtc_shp = r"path/to/shp

zip = zipfile.ZipFile(os.path.join(datafolder, "Real_Time_Closures.zip"), "w")

for f in glob.glob(rtc_shp.replace(".shp",".*")):
    if not f.endswith(".lock"):
        if not f.endswith(".cpg"):
            zip.write(f, basename(f))

shutil.make_archive(indivfolder, "zip", indivfolder)

A: I bypassed the loop by creating an empty list and then appending the filenames to the list. I then wrote the contents of the list to the zip file.
zip = zipfile.ZipFile(os.path.join(datafolder, "MMO_Real_Time_Closures.zip"), "w", zipfile.ZIP_DEFLATED)

shp_zip_list = []

for f in glob.glob(rtc_shp.replace(".shp",".*")):
    if not f.endswith(".lock"):
        if not f.endswith(".cpg"):
            shp_zip_list.append(f)

for f in shp_list:
    zip.write(f, basename(f))

zip.close()

shutil.make_archive(indivfolder, "zip", indivfolder)


text:
Q: How do you get rid of fog in the nether on Minecraft bedrock? I am trying to make a nether arena but from the back seats you can't see the stage what is the command, if there is one, to remove fog from the nether?

A: Unfortunately, this is not possible via the fog command due to how the remove operation works:
fog <victim: target> <mode: delete> <userProvidedId: string>

Take specific notice of the userProvidedId argument. This is created when you push fog onto an entity, for example:
fog @s push "minecraft:fog_hell" "someFog"

You would then remove the fog with the command:
fog @s remove "someFog"

Furthermore, there is no explicitly mentioned ID representing the fog of the nether.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java for Android - Read Text File and Display Data in List I'm trying to read a simple text file that is a list of words and numbers and display it in a scrollable list in an Android application.
I'm not having any issue using arbitrary string arrays that I specify in the code such as the string arrays "myStringArray" or "alphabts." However, when I try to read a text file and use it in one of the lists, my app crashes.
It could be something as simple as the format of the text file is wrong, or that I should have the file in a different location and be referencing it from there.
Thanks for the help!
Java Code:
package com.coderzheaven.pack;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class AlphabetListDemo extends Activity {
    //String of alphabets //
    String[] myStringArray = {"Calories","Protein","Carbs"};
    String[] alphabts = {"1","2","3"};
    ListView L1, L2;
    myAdapter myadp;
    myAdapter2 myadp2;
    String prod_arr[] = {};

    InputStream is = this.getResources().openRawResource(
            R.drawable.filetoread);

    DataInputStream myDIS = new DataInputStream(is);
    ArrayList<String> list = new ArrayList<String>();

    final String[] bob = list.toArray(new String[list.size()]);
    //final String[] bob = alphabts; Here if I comment out the four
    //lines above and and use the alphabts string it works fine

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    L1 = (ListView)findViewById(R.id.list1);
    L2 = (ListView)findViewById(R.id.list2);

    myadp = new myAdapter(this,alphabts);
    L2.setAdapter(myadp);

    L2.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            setProducts(arg2);

        }
    });

}

public void setProducts(int number){
    prod_arr = new String[25];
    // adding some dummy data //
    for(int i = 0; i < 25 ; i++){
        prod_arr[i] = bob[number];
    }
    //setting the adapter in listview //
     myadp2 = new myAdapter2(AlphabetListDemo.this,prod_arr);
     L1.setAdapter(myadp2);
}

class myAdapter extends ArrayAdapter<String>
{
   TextView label;
   ImageView image;
   View row;
   public myAdapter(Context context,String[] arr)
   {
        super(context, android.R.layout.simple_list_item_1, arr);
   }

   public View getView(final int position, View convertView, ViewGroup parent)
    {
           try{
                LayoutInflater inflater=getLayoutInflater();
                row = inflater.inflate(R.layout.lv_rows, parent, false);
                label = (TextView)row.findViewById(R.id.item_title);
                label.setText(myStringArray[position]);
                label.setTextColor(Color.YELLOW);
           }catch(Exception e){

           }
        return row;
    }
}
// adapter for second list.....
class myAdapter2 extends ArrayAdapter<String>
{
   TextView label;
   ImageView image;
   View row;
   public myAdapter2(Context context,String[] arr)
   {
        super(context, android.R.layout.simple_list_item_1, arr);
   }

   public View getView(final int position, View convertView, ViewGroup parent)
    {
           try{
                LayoutInflater inflater=getLayoutInflater();
                row = inflater.inflate(R.layout.lv_rows, parent, false);
                label = (TextView)row.findViewById(R.id.item_title);
                label.setText(prod_arr[position]);
                label.setTextColor(Color.WHITE);
           }catch(Exception e){

           }
        return row;
    }
}
}

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

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="5dp"
    android:orientation="horizontal">

    <!--  this list contains products -->

     <ListView
         android:id="@+id/list1"
         android:layout_width="192dp"
         android:layout_height="wrap_content"
         android:layout_marginBottom="5dip"
         android:layout_marginLeft="5dip"
         android:layout_marginRight="5dip"
         android:layout_marginTop="5dip"
         android:cacheColorHint="#00000000"
         android:dividerHeight="1px"
         android:drawSelectorOnTop="false"
         android:fadingEdge="vertical"
         android:padding="0dip"
         android:scrollbars="none"
         android:smoothScrollbar="true"
         android:soundEffectsEnabled="true" />

      <ListView
        android:id="@+id/list2"
        android:layout_weight="4"
        android:cacheColorHint="#00000000"
        android:scrollbars="none"
        android:fadingEdge="vertical"
        android:soundEffectsEnabled="true"
        android:dividerHeight="1px"
        android:padding="0dip"
        android:smoothScrollbar="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="false"
        android:layout_marginTop="5dip"
        android:layout_marginLeft="5dip"
        android:layout_marginRight="5dip"
        android:layout_marginBottom="5dip" />

</LinearLayout>

lv_rows.xml in the same location as main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="7dp"
    >
        <TextView
            android:id="@+id/item_title"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="2dp"
            android:text="Main Item"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textSize="14dp"
            android:textStyle="normal" />

</RelativeLayout>

A: Why you want to read a text file from your drawable folder?
The correct way is to put this file into the assets folder on your project.
If you are using Android Studio right click on your project -> New -> Folder -> Assets folder.
Then move your file into it and simply use the AssetManager to open it like that:
AssetManager assetsManager = getApplicationContext().getAssets(); // or getBaseContext()
    try{
        InputStream inputStream = assetsManager.open("yourfile.txt");
        // read inputStream ...
        // and do not forget to close it here when your read is completed!!!
    }catch (IOException ex){
        ex.printStackTrace();
    }

A: Got your problem you are forgetting the + sign.
InputStream is = this.getResources().openRawResource(
            +R.drawable.filetoread);

check here Android openRawResource() not working for a drawable


text:
Q: Best practice for instantiating a class and loading data from database I am building a WPF application (using MVVM) which, at its most fundamental, allows users to interact with an Oracle database.
The intention is that it's a multi-user application so I need to keep synchronised with the database as much as possible.
Initial thought is to have a single application-wide instance of a "repository" class which will periodically update it's data from the database and then notify (using MvvmLight.Messaging) when updates occur.
First question; is this a sensible approach, or is there a better way of achieve this?
Second question, if the first is sensible, what's the best way of periodically firing a method (in a background thread) to update this "repository" class?

A: It sounds like you are creating an in-memory cache (your repository) that may be out-of-date compared to the data on the database (otherwise you would not have to "periodically update" the data in the cache). This implies that the data on the database is not static and may change over time. If your users also need to update this data then this cache won't work, as your users will be attempting to update data that is already out of date.
Caches are OK when the data is reasonably static, otherwise it is better to go to the original source of the data--the database itself.
A well designed Oracle database should be able to easily handle multiple concurrent users; it is likely that your cache (unless you really know what you are doing) won't.

A: A more usual approach is to push notification of changes.
SignalR is an excellent candidate for this.
The usual pattern is:
All database updates go through an app server layer.
Each client registers interest in all or a subset of data on that.
Calls via this server then result in signalr sending all "interested" clients the new data.
An alternative is:
Calls to updates go via an app server and or a mechanism such as RabbitMQ. This "splits" the signal so updates go to the database and a redis cache or in memory database.
Clients poll the cache.
The advantage of this is you reduce load on the database server.
Three are numerous variations.
For example, you might have an application used in China, America and Europe. One database server holds everything. Maybe each area is only "interested" in it's own area's data.
You could have a local app server for each area with redis cache across a couple more local machines.
Each area is then semi independent. You can implement a queuing mechanism for each which caches changes and then if your connection to China goes down for half an hour, your Chinese office can still work.
Whether any of this is worth while, only you know.
Maybe you have many users.
Maybe you need to know about changes in seconds rather than minutes
I worked on an airport system some years back.
IIRC the upper expected limit was about 3,000 concurrent users.
This just used polling.


text:
Q: JQuery Show() all properties By default if you specify a speed jQuery adds a weird looking animation where it expands from the left end corner. I want it to just slide down. Is there a way to do that without importing something else like jQuery UI?

A:  $( "#yourId" ).slideDown( "slow", function() {
    // Animation complete.
 });

Or
$( "#yourId" ).slideDown( "slow" );

Or even just
$( "#yourId" ).slideDown();

Look at
http://api.jquery.com/slidedown/


text:
Q: Issue porting OpenExr (3rd party of OpenCV) to C++ Builder 32-bit compiler I'm trying to port OpenCV to C++ Builder (XE3 version).
I've encountered many compiler errors.
As I know, BCC 32-bit is not a clang complaint compiler, and does not follow C++11 standards. This is why I have met with so many issues.
I tried to resolve parts of these issues one by one with workarounds. However, I cannot resolve the following one. Can someone help me about this?
p.s. I know it is an issue with BCC32, as this code can be compiled successfully with Visual Studio, or even BCC64 compiler.
The following code is extracted from ImfBoxAttribute.cpp (in opencv 2.4.11\sources\3rdparty\openexr\IlmImf)
template <>
void
Box2iAttribute::writeValueTo (OStream &os, int) const
{
    Xdr::write <StreamIO> (os, _value.min.x);
    Xdr::write <StreamIO> (os, _value.min.y);
    Xdr::write <StreamIO> (os, _value.max.x);
    Xdr::write <StreamIO> (os, _value.max.y);
}

When I compile with C++ Builder XE3 32bit, I meet with the following compiler errors:
[bcc32 Error] ImfBoxAttribute.cpp(61): E2171 Body has already been defined for function 'Box2iAttribute::writeValueTo(OStream &,int) const'

and
[bcc32 Error] ImfBoxAttribute.cpp(62): E2451 Undefined symbol 'os'
  Full parser context
    ImfBoxAttribute.cpp(47): namespace Imf
    ImfBoxAttribute.cpp(61): parsing: void Box2iAttribute::writeValueTo(OStream &,int) const

Here is the definition of Box2iAttribute:
typedef TypedAttribute<Imath::Box2i> Box2iAttribute;
typedef Box <V2i> Box2i;

A: I don't see how this is valid code, in any pre-C++11 compiler.  You are trying to define a template specialized implementation for Box2iAttribute::writeValueTo(), but Box2iAttribute is just an alias for TypedAttribute<Imath::Box2i> and cannot be used to qualify an implementation like you are attempting. And where is the template parameter that you are trying to specialize? It is not attached to Box2iAttribute, it would have to be attached to writeValueTo() instead.  But where is the specialization actually declared? And the fact that the compiler is complaining about an existing body means that a TypedAttribute<Imath::Box2i>::writeValueTo() implementation has already been defined, so you cannot define a new one.
Maybe C++11 allows this weird code, which would explain VS and BCC64 accepting it. But you are certainly not going to get BCC32 to accept it.  If you want help porting this code to BCC32, or any other pre-C++11 compiler, you need to show a more complete example demonstrating exactly what you are trying to accomplish.  What you have shown is not complete.  Please don't ask people to go download external libraries just to see the code.  Post the relevant pieces here, or create a MCVE demonstrating the same concepts.


text:
Q: UISearchBar black lines/border I'm getting some odd black lines above and below a UISearchBar and I'm not quite sure how to get rid of them. Setting the style of the UISearchBar to minimal solves that problem, but then it doesn't have the background colour I'd like.
Any ideas what's causing this? I've looked over a few similar questions, but none seem to do what I want. Many thanks in advance!

A: Try this:
searchBar.layer.borderWidth = 1;
searchBar.layer.borderColor = [[UIColor blueColor] CGColor];

A: For Swift 3:
searchBar.layer.borderWidth = 1
searchBar.layer.borderColor = searchBar.barTintColor?.cgColor

A: By setting empty image to background will solve the issue
self.searchBar.backgroundImage = UIImage()


text:
Q: Force People Picker to Search Across Several Forests Is it possible to force people picker to search across two different forests?
In this example I enable search within only one forest:
stsadm -o setapppassword -password P@ssw0rd
stsadm -o setproperty -url 'http://portal'  -pn peoplepicker-searchadforests -pv "forest:contoso.ru,spfarm,P@ssw0rd;domain:contoso,spfarm,P@ssw0rd"
Set-SPSite -Identity 'http://portal' -UserAccountDirectoryPath ""

Can I, somehow, allow search across two forests at the same time?

A: You can add multiple forests and or domains by listing multiple domains or forests in the format Forest/Domain:DnsName,LoginName,Password separated by semicolons. For e.g.

STSADM.exe -o setproperty-propertyname peoplepicker-searchadforests
  -propertyvalue"forest:Contoso.com,Contoso\User1,PasswordofUser1; domain:Fabrikam.com,Fabrikam\User2,PasswordofUser2" -url http://webapp

Note : You can omit the username and password if the application pool identity already has access to Target domain or forest, this would be the case where application pool identity is from the Trusted forest or domain itself .
All you want to know about People Picker in SharePoint


text:
Q: Which addTarget actions can we take on UITextView? I want to use addTarget:action on UITextView like on (UITextField or UIButton).
I want to call a method on UITextView.
please give some possible solution...
Thank You...
UITextView  *TXT_First_Tag = [[UITextView alloc] initWithFrame:CGRectMake(5, textPosY, 350, 65)];
TXT_First_Tag.backgroundColor = [UIColor whiteColor];
TXT_First_Tag.font = [UIFont fontWithName:@"Arial-BoldMT" size:30.0];
TXT_First_Tag.editable =YES;
TXT_First_Tag.tag = i;
TXT_First_Tag.textColor = [UIColor blackColor];

[TXT_First_Tag addTarget:self action:@selector(C6Loop) forControlEvents:UIControlEventEditingDidEnd]; //  This Line I want to use, it's working fine on textfield...
[scrollview addSubview:TXT_First_Tag];

A: If your controller implements the UITextViewDelegate protocol, you can then set the controller as the text view's delegate in the controller's instance method, viewDidLoad():
yourTextView.delegate = self;

Then, if you want to perform a task before editing your text view, use:
-(void)textViewDidBeginEditing:(UITextView *)textView {}

And, if you want to do a task after editing your text view, use:
-(void)textViewDidEndEditing:(UITextView *)textView {}

A: We use UITextView delegate methods for this purpose.
Put this in your code.
UITextView  *TXT_First_Tag = [[UITextView alloc] initWithFrame:CGRectMake(5, textPosY, 350, 65)];
TXT_First_Tag.backgroundColor = [UIColor whiteColor];
TXT_First_Tag.font = [UIFont fontWithName:@"Arial-BoldMT" size:30.0];
TXT_First_Tag.editable =YES;
TXT_First_Tag.delegate  =   self;
TXT_First_Tag.tag = i;
TXT_First_Tag.textColor = [UIColor blackColor];
[scrollview addSubview:TXT_First_Tag];

- (void)textViewDidBeginEditing:(UITextView *)textView{
    NSLog(@"Begin editing");
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    NSLog(@"DidEndEditing");
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    NSLog(@"ShouldBeginEditing");
    return TRUE;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    NSLog(@"ShouldEndEditing");
    return TRUE;
}

A: Surely a better way of getting the "editing did end" message is by implementing the UITextViewDelegate?
TXT_First_Tag.delegate = self;

...

- (void)textViewDidEndEditing:(UITextView *)textView {
  // stuff you'd put in C6Loop

A: Chaps,
Even though your responses did not directly solve my problem, it helped me narrow it down.
I have textviews in each cell and needed to pass which text view was being edited so I could update the database.
In a nutshell I set each textview tag in each cell to the indexpath.row.  I  then reference that cell in the delegate by textview.tag
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {

    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil)
    {
    [[NSBundle mainBundle] loadNibNamed:@"frontCell" owner:self options:nil];
    cell = mainPageCell;
    self.mainPageCell = nil;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    UITextView *trackDetails;
    trackDetails = (UITextView *)[cell viewWithTag:22];
    trackDetails.text = [[myArray objectAtIndex:indexPath.row] objectAtIndex:0];
    trackDetails.delegate = self;
    trackDetails.tag = indexPath.row;

    }

    - (void)textViewDidEndEditing:(UITextView *)textView
    {
    NSLog(@"%d",textView.tag);
    UPDATE DATABASE WITH CHANGED TEXT
    [textView resignFirstResponder];
    [self.tableView reloadData];
    }


text:
Q: JAvascript validation not quite functioning correctly Below I have a table and a javascript validation function:
HTML Table:

New Course Details:

<input type='hidden' id='newCourseId' name='CourseIdnew' value='' />

Course ID:
<input type='text' id='newCourseNo' name='CourseNoNew' value='' />

Course Name:
<input type='text' id='newCourseName' name='CourseNameNew' value='' />

Duration (Years):
{$durationHTML}

Javascript:
  function editvalidation() {

                var isDataValid = true;

                var newCourseNoO = document.getElementById("newCourseNo");
                var newCourseNameO = document.getElementById("newCourseName");
                var newCourseDurationO = document.getElementById("newDuration");

            var newCourseIdMsgO = document.getElementById("courseidAlert");
            var newCourseNameMsgO = document.getElementById("coursenameAlert");
            var newDurationMsgO = document.getElementById("durationAlert");

  if (currentCourseO.value == ""){
          $('#targetdiv').hide();
          currentCourseMsgO.innerHTML = "Please Select a Course to edit from the Course Drop Down Menu";
          newCourseIdMsgO.innerHTML = "";
          newCourseNameMsgO.innerHTML = "";
          newDurationMsgO.innerHTML = "";
          isDataValid = false;
    }else{
  if (newCourseNoO.value == ""){
          $('#targetdiv').hide();
          newCourseIdMsgO.innerHTML = "Please fill in the Course ID in your Edit";
          isDataValid = false;
  }if (newCourseNameO.value == ""){
          $('#targetdiv').hide();
          newCourseNameMsgO.innerHTML = "Please fill in the Course Name in your Edit";
          isDataValid = false;
  }if (newCourseDurationO.value == ""){
          $('#targetdiv').hide();
          newDurationMsgO.innerHTML = "Please select a Course Duration in your Edit";
          isDataValid = false;
            }else{
          newCourseIdMsgO.innerHTML = "";
          newCourseNameMsgO.innerHTML = "";
          newDurationMsgO.innerHTML = "";
        }

        return isDataValid;

        }
    }

I have 2 problems with the above validation.
Problem 1: It is not displaying the errors below the relevant form features, the errors are being displayed above the form. It should be like if the user has not entered in a courseid then the error should be displayed below the course id text input for example.
Problem 2:
If I leave the form/table blank then all the errors are displayed, but then if I fill in one of the text inputs for example and resubmit, it still displays all the errors, it should of removed the releavnt error as the text input is not empty. Why is it still displaying the errors even though there is no error?
Only javascript answers please thanks

A: *

*Your DIVs to display error messages must be within the TD. Anything outside TDs will be displayed on top of the table.

*Clear all your error messages by first writing this code outside the IF conditions
newCourseIdMsgO.innerHTML = "";
newCourseNameMsgO.innerHTML = "";
newDurationMsgO.innerHTML = ""


text:
Q: Mysql union, get 2 information I have 2 tables
Table 1:
T1ID, Info
1,A
2,B
3,C

Table 2
T2ID, Info
1,D
2,E
3,F

Now I want a union of these with the following result
T1ID,T2ID,Info
1,null,A
2,null,B
3,null,C
null,1,D
null,2,E
null,3,F

Thank you

A:   select T1ID, null as T2ID, Info from T1
  union all
  select null as T1ID, T2ID, Info from T2

A: Simply use:
select T1ID,null,Info from table1
Union
select null,T2ID,Info from table2

A: You can also do it that way by simulating a FULL OUTER JOIN, to avoid specifying the null in the query :
SELECT T1ID, T2ID, T1.INFO AS INFO
FROM TABLE1 T1 LEFT JOIN TABLE2 T2 ON T1.INFO=T2.INFO
UNION ALL
SELECT T1ID, T2ID, T2.INFO AS INFO
FROM TABLE1 T1 RIGHT JOIN TABLE2 T2 ON T1.INFO=T2.INFO

SQL Fiddle
With FULL OUTER JOIN support it would have been simpler :
SELECT T1ID, T2ID, COALESCE(T1.INFO, T2.INFO) AS INFO
FROM TABLE1 T1 FULL OUTER JOIN TABLE2 T2 ON T1.INFO=T2.INFO


text:
Q: javascript regular expression (end of word) I think I've a problem with regular expression:
I want a string wich can contains all the characthers in the first rounded parenthesis and eventually a [ and finally a ].
the regex is the following:
    var pattern = /^(([a-zA-Z0-9\.\_\-\(\)\\'\xE0\xE8\xE9\xF9\xF2\xEC\x27\,\/]\s?)*\[?([a-zA-Z0-9\.\_\-\(\)\\'\xE0\xE8\xE9\xF9\xF2\xEC\x27\,\/]\s?)*\]?)+$/;

the problem is that if I try to test the following string Maionese [dfvdfv]@
my program will loop forever :-|
the function that I use to test is the following:
//the alert doesn't works
alert(checkSpecialIngredienti("Maionese [dfvdfv]@"));
function checkSpecialIngredienti(s) {

var pattern = /^(([a-zA-Z0-9\.\_\-\(\)\\'\xE0\xE8\xE9\xF9\xF2\xEC\x27\,\/]\s?)*\[?([a-zA-Z0-9\.\_\-\(\)\\'\xE0\xE8\xE9\xF9\xF2\xEC\x27\,\/]\s?)*\]?)+$/;
if (!pattern.test(s)) {
    alert("Attenzione, il campo "+s+"" +
            " che hai inserito non va bene!" +
            "\nIn questo campo puoi inserire " +
            "lettere, numeri, lettere accentate," +
            "punteggiatura classica, singoli spazi e" +
            "\nuna sola coppia di parentesi quadre." +
            "\nRiprova!");
    return (false);
} else
    return true;
}

A: You're running into catastrophic backtracking because you have nested quantifiers (((...)*)+), and the resulting combinatorial explosion will blow up your regex engine when the subject string cannot be matched.
Now, how to fix this? Let's first simplify your regex. There's a lot of irritating cruft in there - the following regex matches exactly the same strings as yours, but it's easier to read:
/^(([\w\s.,()\\\/'\xE0\xE8\xE9\xF9\xF2\xEC\x27-])*\[?([\w\s.,()\\\/'\xE0\xE8\xE9\xF9\xF2\xEC\x27-])*\]?)+$/

The problem now becomes clear: The []s are both optional, and the @ in your test string is not part of the allowed character range. This means that upon encountering the @, the regex engine needs to backtrack into the match and check if there is any other way to match the preceding part - and there are lots of ways that it has to try.
According to your specs, you don't need the final + at all, since you seem to be wanting to match a string that contains any of the allowed characters plus one optional, [...]-enclosed string of the same characters at the end. In that case, use
/^([\w\s.,()\\\/'\xE0\xE8\xE9\xF9\xF2\xEC\x27-]*)(\[[\w\s.,()\\\/'\xE0\xE8\xE9\xF9\xF2\xEC\x27-]*\])?$/


text:
Q: Ant: How do I set a properties from a comma-separated list passed in on command line? I'm using Ant 1.8.1.  If I passed in an argument on the command line ...
-DenableProperties=abc,def,ghi,jkl

How do I set individual properties (to true/false) in my Ant script?
<property name="abc" value="???" />
<property name="def" value="???" />

Note that in the above example, I'd want Ant to have access to a property "${abc}" that is set to true, whereas if it tried to access the property "${mno}" that property would be false, or at least some value other than true.
Thanks, - Dave

A: Can't think of a way to do this in core Ant. You could do it with the For task of ant-contrib.
<project default="test">

  <taskdef resource="net/sf/antcontrib/antlib.xml">
    <classpath>
      <pathelement location="C:/lib/ant-contrib/ant-contrib-1.0b3.jar"/>
    </classpath>
  </taskdef>

  <target name="test">
    <for list="${enableProperties}" param="prop">
      <sequential>
         <property name="@{prop}" value="true"/>
      </sequential>
    </for>
    <for list="${enableProperties}" param="prop">
      <sequential>
         <echo message="@{prop}=${@{prop}}"/>
      </sequential>
    </for>
  </target>

</project>

Output:
$ ant -DenableProperties=abc,def,ghi,jkl
Buildfile: build.xml

test:
     [echo] abc=true
     [echo] def=true
     [echo] ghi=true
     [echo] jkl=true

BUILD SUCCESSFUL
Total time: 0 seconds

A: How to decide when an item of your property $enableproperties is to be set to false or true ? Some criteria missin.. From my understanding of your question you might try something like that, my solution is based on Ant plugin Flaka
starting with ant -f demo.xml -Denableproperties=abc#t,def#t,ghi,jkl#t,mno
means all items in the list that should be set to true in your script have to be propertyname#t others will be set to false
<project name="demo" xmlns:fl="antlib:it.haefelinger.flaka">

    <fl:for var="p" in="split('${enableproperties}', ',')">
      <fl:let>#{split(p, '#')[0]} := #{split(p, '#')[1] == 't' ? 'true' : 'false'}</fl:let>
    </fl:for>

    <echo>
$${abc} = ${abc}
$${def} = ${def}
$${ghi} = ${ghi}
$${jkl} = ${jkl}
$${mno} = ${mno}
    </echo>

</project>

output
 [echo] ${abc} = true
 [echo] ${def} = true
 [echo] ${ghi} = false
 [echo] ${jkl} = true
 [echo] ${mno} = false

Disclosure = i'm participating as committer in the Flaka project


text:
Q: How to resolve alias in Parceljs? I'm migrating from Webpack to Parcel and I use folder aliases like this in my component:
import * as authActions from 'actions/authActions';

I get this error: Cannot find module 'actions/authActions'
The weird thing is, it only shows when using build, it works in development mode but not in production.
I've set up my aliases in package.json like the docs say:
{
  "scripts: {
      "build-client": "parcel build client/index.html dist/client",
      "build-server": "parcel build server/index.js --target node -d dist/server",
      "build-test": "yarn build-server && node ./dist/server/index.js"
  },
  "alias": {
      "actions": "./client/actions"
  }
}

It's a server-side rendered app, I'm importing the component in different places and I can't use the default Parcel root, because it's relative to the entry file.
How can I get this to properly resolve aliases?

A: This question was asked when parcel1 was the current version, so for anyone arriving here in the future, it's worth pointing out that Parcel 2 supports this through glob aliases
Your package.json would include an entry like this:
{
  "alias": {
    "actions/*": "./client/actions/$1"
  }
}

Then, to import all the exports of ./client/actions/authActions, you could write:
import * as authActions from "actions/authActions";


text:
Q: Change the color of a material-ui Button when it's active

I am trying to change the color of a material-ui Button when it's clicked.
I have multiple buttons. When I click on a Button, The color changes for all of them at the same time. How can I only change the one that is clicked. I have the following code, but it's not doing the work, it's supposed to do.
   constructor(props){
      super(props);
      this.state={
      videos : data,
      filtered: data,
      color : "primary"
    };
   }

   handleClick = (event) => {
    const value = event.currentTarget.value;
    console.log(event);
    this.setState({
      filtered: this.state.videos.filter(item => {
          return item.category === value
      }),
      color: "secondary"
    });
  }

  <Button value="java" onClick={this.handleClick} variant="contained"
   color={this.state.color} >java</Button>
  <Button value="React" onClick={this.handleClick}
   variant="contained" color={this.state.color}>React</Button>
  <Button value="C#" onClick={this.handleClick}
   variant="contained" color={this.state.color}>C#</Button>

A: It looks like this state change is not in the object being passed to setState(), it should be:
this.setState({
    filtered: this.state.videos.filter(item => {
        return item.category === value
    }),
    Color: "secondary"
});

A:     handleClick = (event) => {
        const value = event.currentTarget.value;
        this.setState({ filtered: this.state.videos.filter(item => {
                return item.category === value
            }), {Color: "secondary"}
        })
   }

you just inserted your color inside filter's callback function,
just change that it will work

A: Please check this example:
import React, {useState} from 'react';
import {makeStyles} from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

export default function ContainedButtons() {
    const [color, setColor] = useState('primary');

    return (
        <div>
            <Button variant="contained" color={color} onClick={() => {setColor('secondary')}}>
                Click Me
            </Button>
        </div>
    );
}


text:
Q: What is a good way to protect the home button on my iphone 4 so it doesn't get dust in it? I've already replaced a home button on my iphone 4 and I'd prefer not to have to do it on my iphone 4s coming next week.
I'm looking for a way to protect the home button while obviously still making it usable.  Most screen protectors don't cover the home button.

*

*I'm not interested in a total case (otterbox is too big)

*I don't want a screen cover per-se.

I think something like a screen protector that has some elasticity just over the home button/bottom of the front would work.
Does anyone know a good solution?

A: I really like Gelaskins (http://gelaskins.com/) for this and have them on my 4 and iPad.  They're nothing but removable decals that help avoid scratching the device (no screen protection), so they don't get in the way of cases, sleeves, pockets, or whatever.  You'll see on their product shots the there is a little gap around the home button.  You don't have to take this off, which actually looks better anyway with an artistic skin.
Plus, you can easily tell which phone is yours without doing something that would lower the resale value, such as engraving.


text:
Q: CSS and images - why picture isn't resized Why when I want to resize div, image in div doesn't change its size !? It's CASCADE style sheets, isn't it?
--EDIT--
.box{padding:0px;margin-left:10px;display:inline-block;margin-right:auto;width:20px;height:20px;border:1px solid red;}

A: It's cascade, but width and height are not inherited.
You might want to do something to make the image follow the size of its parent.
Like
div.box img { width: 100%; height: 100%; }

A:  tags have an implicit width of either the image's natural width or the width attribute of the tag that must be overriden with css. Try this to make the image 100% of the width of its parent
:
div img{
    width: 100%;
}

I think you have a bit of a misunderstanding of what cascading actually is. I'd recommend reading the part of the spec that deals with the cascade.

A: Your style selector only matches elements with the class box.  The div has that class, but the img doesn't.  Thus, the div has the style applied and the img doesn't.  Try:
.box
{
  padding:0px;
  margin-left:10px;
  display:inline-block;
  margin-right:auto;
  border:1px solid red;
}
.box, .box img
{
  width:20px;
  height:20px;
}


text:
Q: Django 1.6 get filename of a file from database I have a django 1.6.2 project with an app which is a store with products and a postgresql database. Everything is configured and goes well though getting images to show does not happen.
using
>  p.mainphoto.name }}">

results in source showing this:

which clearly doesn't work with displaying an image.
here is what my models looks like
class ProductImage(models.Model):
    property = models.ForeignKey('Product', related_name='images')
    image = models.ImageField(upload_to='/static/images', blank=True)
    def filename(self):
        return os.path.basename(self.image.name)

class Product(models.Model):
    name = models.CharField(max_length=300)
    designers = models.ManyToManyField(Designer, blank=True, verbose_name = 'designer/artist')
    width = models.DecimalField(blank=True, max_digits = 8, decimal_places=1, null=True)
    height = models.DecimalField(blank=True, max_digits = 8, decimal_places=1, null=True)
    depth = models.DecimalField(blank=True, max_digits = 8, decimal_places=1, null=True)
    diameter = models.DecimalField(blank=True, max_digits = 8, decimal_places=1, null=True)
    description = models.TextField()
    colors = models.ManyToManyField(Color, blank=True)
    materials = models.ManyToManyField(Material, blank=True)
    mainphoto = models.ImageField(upload_to='/static/images', blank=True)
    morephotos = models.ManyToManyField(ProductImage, blank=True)
    manufacturer = models.CharField(max_length=300, blank=True)
    price_in_dollars = models.DecimalField(max_digits=6, decimal_places=2)
    type = models.ManyToManyField(FurnitureType, verbose_name = 'furniture/art type')
    def __unicode__ (self):
        return self.name
    def filename(self):
        return os.path.basename(self.mainphoto.name)

here is what views looks like:
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import RequestContext
from django.views.generic.list import ListView
from django.utils import timezone
from store.models import Product

def home(request):
        return render_to_response('homepage.html')

def designhomepage(request):
        return render_to_response('designserviceshome.html')

def eventspage(request):
        return render_to_response('events.html')

def aboutpage(request):
        return render_to_response('about.html')

def returnpage(request):
        return render_to_response('returnpolicy.html')

def privacypage(request):
        return render_to_response('privacypolicy.html')

def hello(request):
        name = ""
        html = "Hi %s. " % name
        return HttpResponse(html)

def hellonew(request):
        name = ""
        t = get_template('hello.html')
        html = t.render(Context({'name': name}))
        return HttpResponse(html)

def inventory(request):
        products = Product.objects.all()

        productinfo = {
        "product_detail": products
        }
        return render_to_response('inventory.html', productinfo, context_instance=RequestContext(request))

and urls file:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from store.models import Product
admin.autodiscover()

urlpatterns = patterns('',
# Examples:

    ... urls
    )

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

utlimately I will just want to get "14333.jpg" from the code below and add the website url before it and then let the python auto add the image name with the for loop let us know with your ideas of getting that thing in quotes

A: I solved this by doing the following:
class ProductImages(models.Model):
product = models.ForeignKey('Product3', related_name='images')
image = models.ImageField(upload_to='/webapps/static', blank=True)

def __unicode__(self):
    return os.path.basename(self.image.name)

def filename(self):
    return os.path.basename(self.image.name)

class Product3(models.Model):
category = models.CharField(max_length=300)
slug = models.SlugField(max_length=150, blank=True)
name = models.CharField(max_length=300)
designers = models.CharField(max_length=300, blank=True)
manufacturer = models.CharField(max_length=300, blank=True)
description = models.TextField()
quantity = models.DecimalField(max_digits=6, decimal_places=2, blank=True)
price_in_dollars = models.DecimalField(max_digits=6, decimal_places=2)
width = models.DecimalField(max_digits=6, decimal_places=2, blank=True)
depth = models.DecimalField(max_digits=6, decimal_places=2, blank=True)
diameter = models.DecimalField(max_digits=6, decimal_places=2, blank=True)
height = models.DecimalField(max_digits=6, decimal_places=2, blank=True)
photo = models.ImageField(upload_to='/webapps/static', blank=True)
materials = models.CharField(max_length=300, blank=True)
style = models.CharField(max_length=300, blank=True)
timeperiods = models.CharField(max_length=300, blank=True)
country = models.CharField(max_length=300, blank=True)
additionalphotos = models.ManyToManyField(ProductImages, blank=True)

def __unicode__(self):
    return self.name

def filenamemain(self):
    return os.path.basename(self.photo.name)

Thats what the model looks like this important part is the def filename(self) part
Next was to add the correct call in the template as follows: (notice the {{p.filename}})
{%block body_content %}

            {% for p in itemdetail %}

            {% endfor %}

{% endblock %}
this properly goes through the whole database with the proper primary key and displays all images available.
the view for this looks like this:
def itemdetailpage(request, id):
    property = Product3.objects.get(pk=id)
    property1 = property.images.all()
    itemin = {"itemdetail": property1 }
    return render_to_response('details.html', itemin, context_instance=RequestContext(request))


text:
Q: I can't seem to get strcmp working correctly I'm trying something very simple; comparing a user inputted string to "hello" but strcmp does not want to work. I know I'm missing something obvious and I think it has to do with the way I declared my string. All help is greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void)
{
    char command[4555], compare[] = "hello";
    fgets (command, sizeof (command), stdin);
    printf ("%s\n%s\n", command, compare);
    if (strcmp (command, compare) == 0)
    {
        printf ("The strings are equal");
    } else {
        printf ("The strings are not equal");
    }
}

A: fgets will leave the newline in the buffer and then null terminate while command will have no newline and just be null terminated.

A: By using fgets you add a '\n' before the '\0' in your string.
By using :
if(command[strlen(command)-1]=='\n')
    command[strlen(command)-1]='\0';

You will delete it and effectively compare your strings

A: Well, just to add something, Yes fgets appends a '\n' char to the input string.
So, its better to use strncmp function which is also in the same library.
strncmp (command, compare,strlen(command)-1) .
It works fine.


text:
Q: how to attach a file so it generates into a url? I made this other thread a little while ago and one of the problems was solved which is uploading the image and converting it into a url. Unfortunately it only works for images not files so I wanted to ask on here if someone knew a way to upload files on a form so that the file is automatically generated into a url that a user can view by pasting into their address bar.
how to make file or image attachment like SO on a form
If there is a script I could make in the backend that uploads the pics to my webhost folder and view using that url, wouldn't be a bad idea....what do you think?
Any ideas on what to do?

A: If you're able to do the thing with images(they're files) you should be fine with about any file as long as you modify your code which should be hardcoded to accept only images.


text:
Q: django error to scroll through a list to send email users I have an error when users scroll through the list of my Users in django to send a message to a template, you have any other form or documentation, agreadeceria
anyone help me, please
    # -*- coding: utf-8 -*-
    from django.shortcuts import render
    from django.views.generic import TemplateView
    from .models import Subscriber
    from django.core.mail import EmailMessage
    from django.core.mail import EmailMultiAlternatives
    from django.template import Context
    from django.template.loader import render_to_string
    from apps.users.models import User

html_content = render_to_string('mails/mailplantilla.html')
html_content = render_to_string('mails/email.txt'
email = EmailMultiAlternatives('hello')
usuarios = User.objects.all()
email.attach_alternative(html_content, "text/html")
email.frw = ['moises@cambio90.com']
    for u in usuarios:
        print(u.email)
        email.to = u.email
        email.send()

error :this is the view I get error q
> Internal Server Error: /favicon.ico Traceback (most recent call last):
> File
> "/home/root-master/workspace/projectdjango/env/menu/local/lib/python2.7/site-packages/django/core/handlers/base.py",
> line 87, in get_response
>     response = middleware_method(request)   File "/home/root-master/workspace/projectdjango/env/menu/local/lib/python2.7/site-packages/django/middleware/common.py",
> line 72, in process_request
>     if (not urlresolvers.is_valid_path(request.path_info, urlconf) and   File
> "/home/root-master/workspace/projectdjango/env/menu/local/lib/python2.7/site-packages/django/core/urlresolvers.py",
> line 619, in is_valid_path
>     resolve(path, urlconf)   File "/home/root-master/workspace/projectdjango/env/menu/local/lib/python2.7/site-packages/django/core/urlresolvers.py",
> line 494, in resolve
>     return get_resolver(urlconf).resolve(path)   File "/home/root-master/workspace/projectdjango/env/menu/local/lib/python2.7/site-packages/django/core/urlresolvers.py",
> line 343, in resolve
>     for pattern in self.url_patterns:   File "/home/root-master/workspace/projectdjango/env/menu/local/lib/python2.7/site-packages/django/core/urlresolvers.py",
> line 372, in url_patterns
>     patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)   File
> "/home/root-master/workspace/projectdjango/env/menu/local/lib/python2.7/site-packages/django/core/urlresolvers.py",
> line 366, in urlconf_module
>     self._urlconf_module = import_module(self.urlconf_name)   File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
>     __import__(name)   File "/home/root-master/workspace/projectdjango/codigo/spoonrocket/spoonrocket/spoonrocket/urls.py",
> line 10, in <module>
>     url(r'^', include('apps.mails.urls')),   File "/home/root-master/workspace/projectdjango/env/menu/local/lib/python2.7/site-packages/django/conf/urls/__init__.py",
> line 28, in include
>     urlconf_module = import_module(urlconf_module)   File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
>     __import__(name)   File "/home/root-master/workspace/projectdjango/codigo/spoonrocket/spoonrocket/apps/mails/urls.py",
> line 3, in <module>
>     from views import IndexView   File "/home/root-master/workspace/projectdjango/codigo/spoonrocket/spoonrocket/apps/mails/views.py",
> line 44, in <module>
>     email.send()   File "/home/root-master/workspace/projectdjango/env/menu/local/lib/python2.7/site-packages/django/core/mail/message.py",
> line 282, in send
>     if not self.recipients():   File "/home/root-master/workspace/projectdjango/env/menu/local/lib/python2.7/site-packages/django/core/mail/message.py",
> line 278, in recipients
>     return self.to + self.cc + self.bcc TypeError: coercing to Unicode: need string or buffer, list found

A: I think the easiest will be to format your code like this, please not I have changed how the code is formatted and edited a few lines, works for me
html_content = render_to_string('mails/mailplantilla.html')
text_content = render_to_string('mails/email.txt')
usuarios = User.objects.all()
email.attach_alternative(html_content, "text/html")
from_email = 'moises@cambio90.com'
subject = 'My Subject'
for u in usuarios:
    to_email = ['%s' % u.email ]
    text_content = plaintext.render(d)
    html_content = htmly.render(d)
    msg = EmailMultiAlternatives(subject, text_content, from_email, to_email)
    msg.attach_alternative(html_content, "text/html")
    msg.send()

Should do it


text:
Q: Problems understanding error of approximation

I am to use Corrollary C to find a better approximation for my problem. I'm trying to understand what exactly is going on but I'm having severe problems understanding it.
I sort of understand the error formula, what I don't get is how to choose this M and N and what exactly is means that $g(2) = 1$ and all that..

A: Suggestion: In your problem $a=2$ and $x=1.8$. Since $$|g''(t)|<1+(t-2)^2$$ you have that $$-1-(t-2)^2<g''(t)<1+(t-2)^2$$ which should give you $M,N$. But $M$ and $N$ should be constants so that the inequality holds for all $t$ between $a=2$ and $x=1.8$. I think (but please doublecheck it) that $$|g''(t)|<1+(t-2)^2<1+(1.8-2)^2=1.04$$ So your constants $M$ and $N$ are equal to $-1.04$ and $1.04$ respectively. You cannot plug in $2$ in the above inequality to obtain narrower bounds, since according to Corollary C, you need constants that work for every $t$ in the interval $(1.8, 2)$. Unfortunately $M$ and $N$ do not have the same sign, so you cannot use the better approximation stated in Corollary C. Your approximation is given by $$g(1.8)=g(2)+g'(2)(1.8-2)$$ Your error can be as big as the half the length of the interval, that is $$\frac{N-M}{2}(1.8-2)^2$$ and not $$\frac{N-M}{4}(1.8-2)^2$$ as the better approximation would have yielded.


text:
Q: #Define macro in a function C++ I wonder if there's a way to use a macro inside a function, for example if we have piece of code like this:
struct SomeStruct{
   int fancyVariableNumberOne;
   int notSoFancyVar;
};

void SomeFunction(SomeStruct *array)
{
   #define w(i) array[i].fancyVariableNumberOne;

   ...

}

I don't want to write array[i].fancyVariableNumberOne each time, can I somehow shorten it without changing struct?

A: Yes, you can define and use a macro like this. The only problem is that the macro will not be scoped to just that function. It will be visible from that point on in the entire translation unit (unless, as @MichaelKohne points out, you use undef to remove it.)
Rather than using a macro, try using an in-line function. It will be more flexible, and have fewer unintended side effects.

A: Dont use macro, you might have some nasty unexpected side effects.
Instead use a lambda to capture array by reference and make it return fancyVariableNumberOne. C++11 is required
void SomeFunction(SomeStruct *array)
{
    auto w=[&array](int i){return array[i].fancyVariableNumberOne;};
    std::cout<<w(0)<<std::endl;
}

A: Macros are defined prior to compilation. Simply define your macro above and use it in your function. The pre-processor will paste whatever you've defined in the function.
For example:
#define w(i) array[i].fancyVariableNumberOne

void someFunction(SomeStruct *array)
{
    w(i);
}

A: You can make class that contains SomeStruct array and override [] operator to return fancyVariableNumberOne of each.
class SomeArray
{
SomeStruct *array;

public:
...
int operator[](int index)
{
return array[index].fancyVariableNumberOne;
}

};

SomeArray a;
...
int b = a[i];


text:
Q: MongoError: can't get query executor with geoNear Mongoose I am trying to get results from DB using geoNear in Moongose but it is giving "can't get query executor" error.

// Schema
let dealSchema = new Schema({
userId: {type: String, required: true},
images: {type: [String], required: true},
location: {
    lng: {type: Number},
    lat: {type: Number},
    name: {type: String, required: true}
},
description: {type: String, required: false, default: ""},
expiredReports: {type: [String], required: false},
inappropriateReports: {type: [String], required: false},
likes: {type: [String], required: false},
dislikes: {type: [String], required: false},
comments: {type: [commentSchema], required: false},
creationDate: {type: Date, default: new Date()},
updationDate: {type: Date, default: new Date()}
}, {collection: TableName.DEAL});

function getAll(radius) {
var point = {type: "Point", coordinates: [9, 9]};

        let distance = parseInt(radius);
        if (isNaN(distance)) {
            return callback(new Error("Invalid Radius"), null)
        }

        var geoOptions = {
            spherical: true,
            maxDistance: distance,
            num: 10
        };

        DealData.geoNear(point, geoOptions, function (err, docs, stats) {
                console.log(docs);
            }
        );

}

This is my model of Mongoose and My code to get data from Database.

A: geoNear method requires 2dsphere index, after creating that index you'll be able to querying data by coords.
Example:
var mySchema = new mongoose.Schema({
    name: {type: String, required: true},
    location: {type: [Number], index: '2dsphere'}
  });

The first item of the location field is longtitude and the second one is latitude


text: Q: Can we convert JSON file into Gherkin Script By using selenium IDE extension I have recorded some steps and saved JSON file from the project. Now my requirement is to convert this JSON file into Gherkin Script. Can we do it?


text:
Q: the right design approach for creating different User classes I am trying to create chat app that will have different users:simple user, vip users and etcetera.
all types of users will have the data that simple user have, like:name,password,email and so on however all the other users type have uniqe options only to them.
I thought to create class SimpleUser that will have the basic functionality that achieved by using private variables, getters/setters,and so on, while all other user types will have their own classes that extends the SimpleUser class and add their uniqe functionality.
but after I seen this article
 Do subclasses inherit private fields?  its just doesn't seems the right approach.
I am not sure that using Interface to provide optional functionality will help, because i still have private variabels in each user type that I access using getters/setters.
also currently I am cheking in every screen what the type of the user (in order to choose the rigth options for him), its seems clunky, is there a way to check the type of the user only once (when the user logs in) and in all screens simply use his uniqe functions?

*

*what is the correct way to design my classes?

*is their one solution for both my problems?

A: Perhaps approach things from the other side, rather than think about user, perhaps think about screens, each user has a "level" and the screens provide the per level functionality, as really the functionality isn't really the users its the screens, the screen just decides based on the user.
I think I would stat with an enum with Simple VIP etc and this enum would have methods that do the appropriate thing for that level of user.


text:
Q: When, where and **how often** do you find polynomials of higher degrees than two in mathematical, pure/applied, research? A formula for solving a polynomial of degree three, see this link; $ax^3+bx^2+cx+d=0$, is
$$\begin{align}
x\quad&=\quad
      \sqrt[3]{
          \left(
              \frac{-b^3}{27a^3} + \frac{bc}{6a^2} - \frac{d}{2a}
          \right)
          +
          \sqrt{
              \left(
                  \frac{-b^3}{27a^3} + \frac{bc}{6a^2} - \frac{d}{2a}
              \right) ^2
              +
              \left(
                  \frac{c}{3a} - \frac{b^2}{9a^2}
              \right) ^3
          }
      }\\
      &+\quad
      \sqrt[3]{
          \left(
              \frac{-b^3}{27a^3} + \frac{bc}{6a^2} - \frac{d}{2a}
          \right)
          -
          \sqrt{
              \left(
                  \frac{-b^3}{27a^3} + \frac{bc}{6a^2} - \frac{d}{2a}
              \right) ^2
              +
              \left(
                  \frac{c}{3a} - \frac{b^2}{9a^2}
              \right) ^3
          }
      }
      \;-\;\frac{b}{3a}
\end{align}$$

Unlike quadratic, cubic, and quartic polynomials, the general quintic
  cannot be solved algebraically in terms of a finite number of
  additions, subtractions, multiplications, divisions, and root
  extractions, as rigorously demonstrated by Abel (Abel's impossibility
  theorem) and Galois. However, certain classes of quintic equations can
  be solved [...] Source: http://mathworld.wolfram.com/QuinticEquation.html

At levels of $5^{\text{th}}$ degree polynomials, things are starting to look really serious in my eyes. My question is:

If it is possible to not answer subjectively: When, where and how often do you find polynomials of higher degrees than two in mathematical, pure/applied, research?

A: From the applied math side of things, I come across higher order polynomials all the time.  Here are some examples of when:
Eigenvalue problems for large matrices
Linear constant coefficient higher-order ODEs (think characteristic equation, or Laplace transform to transform ODE to solving a polynomial)
Numerical analysis - interpolation, cubic splines, higher accuracy integration schemes
Many times we expand analytic functions by their Taylor series, which as you know are polynomials of whatever degree we choose to stop expanding at.
Polynomials are ubiquitous throughout probably every field of higher mathematics  :)

A: Well a lot of modern cryptographic algorithms involve finite fields, and a practical way to construct a finite field of size $q = p^n$ where $p$ is a prime is as the set of polynomials over $\def\ff{\mathbb{F}}$$\ff_p$ of degree less than $n$, with addition and multiplication modulo some fixed irreducible polynomial over $\ff_p$ of degree $n$.
Note also that your question is (seemingly) based on a false dichotomy, namely that either you do not encounter a polynomial of degree higher than two, or you need to find its roots. As my above example application shows, this dichotomy is false with a certain irony; the irreducible polynomial has a trivial root in the constructed field, just $X$ where $X$ is the indeterminate, and we do not care about the other roots! (Just for kicks, consider $\ff_8$ constructed from $\ff_2$ using the irreducible cubic $(X^3+X+1)$. The roots are $X$ and $X^2$ and $X^2+X$, which you can prove easily by evaluating the cubic on each of them.)

A: To expand the comment, in digital signal processing a digital filter can be described by it's $\mathcal Z$-transform, which is a polynomial in as many dimensions (variables) as the signal has (in this case $N$):
$${\mathcal Z}\{f\}(z) = \sum_{(i_1,\cdots,i_N )\in {\mathbb Z}^N}c_{i_1,i_2,\cdots,i_N}\prod_{k=1}^N{(z_k)}^{i_k}$$
where the coefficients $c_{i_1,i_2,\cdots,i_N}$ are elements of an $N$ index tensor.
Polynomials of higher dimension than 1 are in the general case really difficult to factor because there are so many ways to factor them. Their theory is much more complicated than linear algebras ( "straight lines equations" in many dimensions ). But they occur almost everywhere. Geometric surfaces like found in graphics and computer aided design ("CAD" models) in mechanical engineering and filter factorization in signal processing are two examples.

A: Vaughan Jones won the Fields Medal for finding a polynomial, which is usually  not of degree two.

A: An example in engineering: solving a thermal problem involving radiation.
Heat transfer is a combination of conduction, convection and radiation.
Simplifying things a lot, conduction and convection correspond to a first-degree polynomial in temperature $T$, but radiation corresponds to a term $T^4$ according to the Stefan-Boltzmann law.
The equation for finding the temperature of a solid can therefore be written as (again, simplifying a lot)
$$T^4+a T + b = 0,$$
where $a$ and $b$ are determined by material properties, external temperatures, geometry, and so on.
From memory: $a$ is always positive and $b$ is always negative. This equation has 4 complex roots, but only one positive real, and that is the temperature of the solid.
I encountered this example in my real work, and suprised my coworkers by solving this explicitly without a need for approximations. This was five years ago, and I still remember it; this shows that at least for me personally, higher-order polynomials are a rarity in engineering.
In engineering, some of the input always has some inaccuracy (from measurement errors or because they are specified within a range). If polynomials are encountered, it therefore makes no sense to try to find exact solutions; good approximations are ok. Numerical analysis has given tools to find roots for equations quickly.
One of the equations below has a closed-form solution in elementary functions, the other one not.
$$x^3-3x^2+16x-4=0$$
$$e^{-x}-x-\arctan(x)=0$$
If $x$ represents an unkown in engineering (e.g. the optimal length in meters for your machine), you don't care about a closed form: if you can get the solution to within 0.0001, it is enough.

A: The characteristic polynomial of an $n \times n$ matrix has degree $n$. We often care about matrices larger than $2 \times 2$.

A: Two more examples (that are both post-1950s mathematics):

*

*In CAD (Computer Assisted Design), there is a growing concern about "offset curves", also named "wavefront curves", "dilated curves"... issued from the (mathematical morphology) dilation of curves defined by polynomials with degree $ \leq n$, i.e., with parametric equations

$$x=p(t); y=q(t) \ \ \ \text{with} \ \ \ \max(deg(p),deg(q))=n.$$
(if $n=2$ for example it is a parabola, that can be studied as a quadratic Bezier curve).
These curves are still polynomially defined but undergo an important degree elevation, for example have degree $8$ when $n=2$.
For explanations, I refer you to the very nice introduction here.
Remark: these types of curves are generally studied as circle envelopes.

*

*In a different category (though with a certain connection) are Erhard polynomials that count the number of points with integer coordinates situated inside a polyhedron (https://en.wikipedia.org/wiki/Ehrhart_polynomial
).

[I had the privilege to meet their author at his home in Strasbourg in 1976].

A: Well, since any polynomial of order $N$ with real coefficients can be factored into $N_1$ first-order binomial factors and $N_2$ quadratic factors where
$$ N = N_1 + 2 N_2 $$
then one might make a case that they never have to come across polynomials of higher degree than 2.
In practice, I seldom come across polynomials of higher order than 3 (I sometimes use cubic Hermite splines for better-than-linear interpolation with look-up tables).  I have used 7th-order polynomials for approximating vacuum-tube distortion curves (with 4x oversampling) in audio.  Once I used a function
$$ f(x) = \alpha x + x^9 $$
it was meant to be just a linear feedback term, but the $x^9$ was meant to be a !!wake up!! factor that didn't kick in until $x$ got large.
But otherwise, it's pretty much all biquads for me.  If I need roots it's pretty easy:
$$ f(x) = x^2 \ - \ 2b\, x \ + c = (x-r_1)(x-r_2)  $$
where $ r_n = b + (-1)^n \sqrt{b^2-c} $ or if the roots are complex conjugate $ r_n = b + i (-1)^n \sqrt{c-b^2} $.
It almost never needs to be more complicated than that.

A: For the implementation of some Jacobi polynomial
integration code I had to prove
\begin{equation}
2^{-(\sigma+\tau+1)}
\int\limits_{-1}^{+1}
p_{n+r}^{(\lambda,\tau)} (t)
p_n^{(\sigma,\tau)} (t)
(1-t)^{\sigma}
(1+t)^{\tau}
\: dt\\
\ = \
\frac{\Gamma(\sigma+n+1)\Gamma(\tau+(n+r)+1)}{\Gamma(\sigma+\tau+n+(n+r)+2)}
\cdot
\frac{(\lambda+\tau+(n+r)+1)_n}{n!}
\cdot
\frac{(\sigma-\lambda-r+1)_r}{r!}
\end{equation}
with $n,r \ge 0$ integers, $\sigma,\tau > -1$ and $\lambda$ real numbers.
Essentially this boiled down showing
\begin{equation}
(\lambda+\tau+2n+2r)
(\sigma+\tau+n+1)
(\sigma+n+1)
(\lambda+\tau+2n+r)
r\\
+ (\lambda+\tau+2n+2r)
(\tau+n)
(\sigma+\tau+2n+r+1)
n
(\sigma-\lambda-r+1)\\
- (\lambda+n+r)
(\sigma+\tau+2n+1)
(\sigma+\tau+2n+r+1)
(\lambda+\tau+n+r)
r
\\
\ = \
(n+r)
(\sigma+\tau+2n+1)
(\tau+n+r)
(\lambda+\tau+2n+r)
(\sigma-\lambda-r+1),
\end{equation}
which is an equality of fifth degree polynomials.
A more general formula can be found in Erdelyi's Tables of Integral Transforms vol. 2, p. 287, 16.4.16.
Jacobi polynomials are hypergeometric polynomials, a kind of special functions.
There is a vast literature finding proofs for special functions or combinatorical identities (semi-)automatically using the Wilf-Zeilberger method, see https://en.wikipedia.org/wiki/Wilf%E2%80%93Zeilberger_pair.
Many proof certificates contain polynomials of high degree.

A: It's actually (somewhat) rare in research that you are lucky enough to have a polynomial that is only degree one or two. Some examples I haven't seen mentioned already: cyclotomic polynomials, irreducible polynomials used to construct field extensions, all sorts of polynomials used to construct algebraic curves used in cryptography.
While we don't always have nice formulas to explicitly find the roots, we have other ways to work with them. For example, we can choose nice polynomials that have a special form, or construct a polynomial so we already know the roots. We can use computational techniques to approximate the roots. We can use them in applications where we don't care what the roots are.

A: Cubic polynomials are ubiquitous in computer-aided design and computer graphics.
They also are the basis for computer fonts.
Finite element analysis is based on polynomial functions. Isogeometric analysis uses NURBS.

A: Gaussian quadrature is a class of methods of numerical integration based on polynomial approximation. Typically, polynomials of degree $5$ or $10$ are employed. For many of the functions that arise in applied mathematics, these give very accurate results. Polynomials of arbitrarily high degree can in principle be used, but the additional accuracy is seldom relevant or worth the extra complexity entailed.

A: In combinatorics and linear algebra and adjacent fields, finding eigenvalues of matrices is extremely important. Eigenvalues of matrices are solutions to polynomials with degree equal to the dimension of the matrix. Note that we can say "the dimension" because eigenvalues are only defined for square matrices. This is sufficiently important that it's its own topic in graph theory, known a spectral graph theory.
I'm currently working on an applied problem in spectral graph theory where I am dealing with matrices with dimensions ranging from $3$ to $96$ (most are around $45$).


text:
Q: como puedo extraer el codigo a una funcion? quisiera poder extraer el codigo del return que es un buscador y ponerlo en una funcion, e provado varias maneras pero no se llamar a la funcion para poder luego mapear.
import React, { useState, useEffect } from "react";
import "./App.css";
import axios from "axios";

function App() {
  const [loading, setLoading] = useState(false);
  const [posts, setPosts] = useState([]);
  const [searchTitle, setSearchTitle] = useState("");

  useEffect(() => {
    const loadPosts = async () => {
      setLoading(true);
      const response = await axios.get(
        "https://jsonplaceholder.typicode.com/posts"
      );
      setPosts(response.data);
      setLoading(false);
    };

    loadPosts();
  }, []);

return (

Search Filter

      <input
        style={{ width: "30%", height: "25px" }}
        type="text"
        placeholder="Search..."
        onChange={(e) => setSearchTitle(e.target.value)}
      />
      {loading ? (

Loading ...

      ) : (
        posts
          .filter((value) => {
            if (searchTitle === "") {
              return value;
            } else if (
              value.title.toLowerCase().includes(searchTitle.toLowerCase())
            ) {
              return value;
            }
          })
          .map((item) =>
{item.title}
)
      )}

  );
}

export default App;

A: Te refieres a que quieres hacer tu código más granular y separado?
Creo que podrías seccionarlo así:
import React, { useState, useEffect } from 'react';
import './App.css';
import axios from 'axios';

// search filter component - separado
function SearchFilter({ value, onFilterChange }) {
  return (

Search Filter

      <input
        value={value}
        style={{ width: '30%', height: '25px' }}
        type="text"
        placeholder="Search..."
        onChange={(e) => onFilterChange(e.target.value)}
      />

  );
}

// hook para cargar los posts - separado del componente
function usePosts() {
  const [loading, setLoading] = useState(false);
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const loadPosts = async () => {
      setLoading(true);
      const response = await axios.get(
        'https://jsonplaceholder.typicode.com/posts',
      );
      setPosts(response.data);
      setLoading(false);
    };

    loadPosts();
  }, []);

  return { loading, posts };
}

// posts component - separado
function Posts() {
  const [searchTitle, setSearchTitle] = useState('');
  const { loading, posts } = usePosts(); // usa el hook de los posts

  // filtra los posts
  const filter = searchTitle.toLowerCase().trim();
  const filteredPosts = posts.filter((value) => {
    if (!searchTitle) return true;
    return value.title.toLowerCase()
      .includes(filter);
  });

  return (

      {/* Usa SearchFilter component */}
      <SearchFilter value={searchTitle}
                    onFilterChange={setSearchTitle} />
      {/* Renderiza los posts */}
      {loading ? (

Loading ...

      ) : (
        filteredPosts.map((item) =>

{item.title}
)
      )}

  );
}

function App() {
  return (

      <Posts />

  );
}

export default App;


text:
Q: Angular checkbox state check fires too often In my UI, I have too many checkboxes arranged in the form of a grid. Their checked status should be determined from the one time logic which is present in the component. Once updated their status are never going to get changed.
I have updated the checked status by calling a function as below.
[checked]="getCheckedStatus()"
Simplified problem is present in this stackblitz - https://stackblitz.com/edit/angular-o622bw?embed=1&file=src/app/app.component.html
Problem - console.log() (or say getCheckedStatus()) gets fired too often whenever Update button is clicked which is slowing down the performance.

A: Since getCheckedStatus is called from the template, it will be called each time the Angular change detection is performed.
You could change the changeDetectionStrategy to "onPush" if you want to handle the change detection on your own.
Read more about this here: https://angular.io/api/core/ChangeDetectionStrategy
The example bellow solves the problem:
// ...
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  changeDetection:  ChangeDetectionStrategy.OnPush // <--
})
// ...

A: I think that you problem is calling a function from the view. This makes Angular call the function every type it checks the view. So calling function from the view can be a performance problem. If you need to transform thing based on things in the view you can use a pipe. Now it will not be called every time, and is handled by Angular.
I hope it's ok but I took a copy of you stackbliz and made a version using a pipe called selectStatus.
[checked]="{accnt:accnt, itm:itm} | selectStatus"
https://stackblitz.com/edit/angular-hzdt4n


text:
Q: Expand line to a polygon I would like to expand a line to a wider polygon. Add 10 meter on both sides of the line for example.
Here is an example of what I would like
Take this line

And expand it to a wider polygon, like this

I did this manually, is there a way to do this automaticly?
Changing the KML or using a program?
Thanks
Vincent

A: Depending on how accurate you need this – this is not trivial.
One possible algorithm could be:
for each segment do
    expand segment to rectangle with width 2r
    targetShape.join(rectangle)
next
for each point do
    expand point to circle with radius r
    targetShape.join(circle)
next
targetShape.outerHull(precision)

Each single line in this routine is tricky and depends on your expectations.
You could leave out the circles and instead make the rectangles longer, but this wil not work on sharp turns.
All of this involves ugly calculations to figure orthogonal lines etc.
You could try it in an graphic tool, gimp or inkskape :-)


text:
Q: When the user clicks on an UltraGrid cell that contains multiple lines of text, the selected text loses the CRLFs I have a C# program that uses an Infragistics UltraWinGrid to display comments. A comment can be multiple lines. That is, it can contain carriage return/line feeds (CRLFs). (See the upper portion of the attached screenshot.) But when the user selects the text of the comment by clicking on the cell, it loses the CRLFs. (See lower portion.) This is a problem, because comments can be very long and the user may want to copy and paste a comment somewhere else without losing the formatting.
From what I understand, this problem results because the grid uses a Windows textbox as an editor when the user clicks on a cell. Is there some way that I can either make the textbox keep the CLRFs or replace the textbox with an editor that does? Thanks.

A: Turns out there are a few stars that need to align for this.
Of course CellMultiLine needs to be set for the column like wnvko pointed out.
But also, you must make sure your Column Style is NOT FormattedText or FormattedTextEdit.  (If that's required for editing i think you are out of luck).  Just use Default style.
And finally make sure you CRLFs are actually truly CRLFs.  My best suggestion is to use Environment.NewLine.  If you are pulling the data from the DB, make sure you use CHAR(13) + CHAR(10) in that specific order. See Differences Between vbLf, vbCrLf & vbCr Constants
Hope this helps 4 years later.  :-)  But wanted to share for others since i found no solution elsewhere.

A: My suggestion is to use Templates. Have a look at the official Infragistics UltraWebGrid help book that is explaining in depth how to configure features like Row and Column Templates.
Go to page 74 for more information regarding the templating.

A: You should set CellMultiLine of the column to True. Here is how it is working when I set it in my grid

A: I never found a real answer to this question, but I was able to do a workaround by capturing the click event and having it open a small dialog box containing the cell text. I had the dialog box open at the point the user clicked, so that it appeared over the cell. After a few minor adjustments to take care of border conditions, it worked surprisingly well, so I'm calling this one solved. Thanks, everyone, for your suggestions.


text:
Q: Multiple column/gutter sizes across Bourbon Neat breakpoints I'd like to create a flexible responsive grid using Bourbon/Neat, that not only varies the number of columns, but also allows me to configure the gutter spacing between columns, across breakpoints.
So in theory, something like this would work:
@import "mixins/neat/neat-helpers";

$visual-grid: true;
$visual-grid-color: yellow;
$visual-grid-index: front;
$visual-grid-opacity: 0.3;

$gutter: 5%;
$column: 5%;
$gridS: new-breakpoint(min-width 0 32);

$gutter: 1.5625%;
$column: 3.515625%;
$gridL: new-breakpoint(min-width 48em 20);

This currently gives me a flexible column count, but the column:gutter proportion remains the same.
I've investigated singularity.gs but would rather not introduce Compass as a dependency.
Does anybody have a fix/workaround?

A: if you look at the core of neat, you see
// Flexible gutter
@function flex-gutter($container-columns: $fg-max-columns, $gutter: $fg-gutter) {
  $container-width: $container-columns * $fg-column + ($container-columns - 1) * $fg-gutter;
  @return percentage($gutter / $container-width);
}

and if you look at _span-columns.scss you see:
margin-#{$direction}: flex-gutter($container-columns);

so you could take a grid and if you make the columns larger than 12.  ie 24 you half the size of that margin.   and if you double that to 48 its 1/4 the original. etc..  so you have the ability to size your columns to any total size and get your gutters flexible based on that.  you could always reverse the effects or try different column sizes to get various results.  would this help any? or at least the theory behind it?
div.container {
@include outer-container()
}

div.small {
background: red;
@include span-columns(3 of 12);
}

div.small-alt {
background: blue;
@include span-columns(6 of 24);
}

div.small-crazy {
background: green;
@include span-columns(36 of 144);
}

1

2

3

4

1

2

3

4

1

2

3

4


text:
Q: proof that metric on $\mathbb{R}^2$ cannot have counterintuitive property Suppose $d$ is a metric on $\mathbb{R}^2$ whose induced topology is the same as the euclidean topology and such that $$\left\{w \in \mathbb{R}^2 : d (w,0)=1\right\}$$is nonempty and compact. Assume that for arbitrary $w=\begin{pmatrix}u\\v\end{pmatrix}\in \mathbb{R}^2$ with $d(w,0)=1$ there is $1>t_0^w > 0$ such that $$d\left( t\cdot \begin{pmatrix}u\\v\end{pmatrix} , 0\right)>d\left( s\cdot \begin{pmatrix}u\\v\end{pmatrix} , 0\right)\quad\forall t_0^w>t>s>0.$$Is there a global $t_0>0$, such that $t_0^w > t_0$ for all $w \in \mathbb{R}^2$ with $d (w,0)=1$?

A: No, there is no positive $t_0$ in general, and there exists a distance function $d$ such that $t_0$ cannot be positive, no matter how the $t_0^w$ are chosen.
Consider the continuous function
$$f(x_1, x_2) := \begin{cases}2 x_2\cdot \max(0, (1-|x_2^2/x_1-1|)) & \text{ if }x_1 \neq 0\\ 0 & \text{otherwise}\end{cases}$$
 on $\mathbb R^2$.
Now use this $f$ to define the metric $d(x,y) := |x_1-y_1| + |x_2-y_2| + |f(x) - f(y)|$. This metric induces the usual euclidean topology on $\mathbb R^2$. This can be seen by the fact that $d(x,y) = d_1((x,f(x)), (y,f(y)))$, where $d_1$ is the taxicab metric on $\mathbb R^3$ and the map $x \mapsto (x,f(x))$ is an embedding of $\mathbb R^2$ into $\mathbb R^3$.
Now consider any $w = (u, v)$ with $d(w,0) = 1$. Then for sufficiently small $t$, $$d(tw, 0) = t|u| + t|v| + 2t\left|v \cdot \max(0, (1-|tv^2/u-1|))\right|$$
$$= t\cdot(|u|+|v|) + \begin{cases}2t^2|v^3/u| & \text{ if } u > 0 \\ 0 & \text{ otherwise}\end{cases}$$
which is strictly ascending in $t$. So there does exist a $t^w_0$ as desired.
Fix a choice of all $t^w_0$, and let $t_0$ be the infimum of all $t^w_0$.
However, for every small $\varepsilon > 0$, consider the vector $\tilde w := (\varepsilon, 1)$, and let $w := \frac{1}{1+\varepsilon}\tilde w$.
For sufficently small $\varepsilon$, we have $0 < \varepsilon < 2\varepsilon < 1 < \frac{1}{1+\varepsilon}$.
Then it is true that $d(0, \varepsilon \tilde w) = \varepsilon + \varepsilon^2 + 2\varepsilon$, but $d(0, 2\varepsilon \tilde w) = 2\varepsilon + 2\varepsilon^2 + 0 < d(0, \varepsilon \tilde w)$ and $d(0, w) = 1$.
Choosing $t = 2\varepsilon(1+\varepsilon), s = \varepsilon(1+\varepsilon)$, we just found out that $t > s$ but $d(0, sw) > d(0,tw)$.
Therefore $t_0^w$ must be smaller than $2\varepsilon(1+\varepsilon)$, and $t_0$ must be smaller than that. Unfortunately, when $\varepsilon$ goes to $0$, so does $\varepsilon(1+\varepsilon)$, so $t_0$ cannot be positive. $~~~~\square$
Here's a plot of $f$ for reference:


text:
Q: nginx reverse proxy websockets nginx now supports proxying websockets, but I was unable to find any information on how to do this without having a separate location block that applies to URIs on which websockets are used.
I've seen some folks recommending some variations of this approach:
location / {
    proxy_http_version 1.1;

    proxy_set_header    Upgrade     $http_upgrade;
    proxy_set_header    Connection  "upgrade";

    proxy_pass  http://host:port;
}

Would that be the correct way to proxy standard HTTP as well as websockets?
I don't want the Upgrade header or Connection being set to upgrade unless that's what the browser sent, but these proxy_set_header lines are required for websockets to work.
Why doesn't nginx just forward the original Upgrade/Connection headers?
I've experimented with this and found that nginx does not proxy the Upgrade header and changes the Connection header to close from upgrade if running without the two proxy_set_header lines. With them, Connection is upgrade for non-websocket requests, which is also bad.

A:
Why doesn't nginx just forward the original Upgrade/Connection headers?

From the official documentation: since the "Upgrade" is a hop-by-hop header, it is not passed from a client to proxied server
See RFC 2616.

I don't want the Upgrade header or Connection being set to "upgrade" unless that's what the browser sent,

There is also an example:
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    ...

    location /chat/ {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}

Connection is 'upgrade' for non-websocket requests, which is also bad.

Do you actually know what the Connection header means? Just a quote from RFC: for each connection-token in this field, remove any header field(s) from the message with the same name as the connection-token.
How it can be bad?

A: Solution:
For k8s nginx ingress configuration, I've used:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  namespace: prod-env
  name: core-backend
  labels:
    app: core-backend
  annotations:
    ingress.kubernetes.io/rewrite-target: /
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
    nginx.ingress.kubernetes.io/server-snippets: |
      location / {
        proxy_set_header Upgrade $http_upgrade;
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header Connection "upgrade";
        proxy_cache_bypass $http_upgrade;
        }


text:
Q: How can I decrypt this m3u8 and key file to mp4, Maybe its use javascript to decryptdata THIS is the video website:
the video website link
From this video link, I download the m3u8, key.key and ts video files, and use FFMPEG to transform these files to mp4.
but Error:
ffmpeg -allowed_extensions ALL -i a.m3u8 -c copy 01.mp4
ffmpeg version N-94813-g85386c36e3-ffmpeg-for-N_m3u8DL-CLI Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 8.2.0 (GCC)
  libavutil      56. 35.100 / 56. 35.100
  libavcodec     58. 56.101 / 58. 56.101
  libavformat    58. 32.104 / 58. 32.104
  libavfilter     7. 58.102 /  7. 58.102
  libavresample   4.  0.  0 /  4.  0.  0
  libswresample   3.  6.100 /  3.  6.100
[hls @ 007e3000] Skip ('#EXT-X-VERSION:3')
[hls @ 007e3000] Skip ('#EXT-X-ALLOW-CACHE:YES')
[hls @ 007e3000] Opening 'a.key' for reading
[hls @ 007e3000] Opening 'crypto:43924590506ad94e644d0bfac89e14b9_2_0.ts' for reading
[hls @ 007e3000] Opening 'crypto:43924590506ad94e644d0bfac89e14b9_2_1.ts' for reading
[hls @ 007e3000] Error when loading first segment '43924590506ad94e644d0bfac89e14b9_2_0.ts'
a.m3u8: Invalid data found when processing input

The key file is
00000000h: 46 F5 50 A3 7A 46 85 B5 8C 17 5B 0E 4B 8D F5 49 ; F鮌F叺?[.K嶕I
00000010h: F1 02 79 41 58 C7 A3 D3 17 90 0D D6 27 67 D6 D0 ; ?yAX牵???g中

and the IV value in the m3u8 file is
IV=0x786d9270e353d8758b621c1f775491f2

Too long bytes to FFMPEG.

In my limited experience with html and javascript, I found the Chrome blob a random named javascript file when the website page freshed.
Chrome - Network log:
XHR:43924590506ad94e644d0bfac89e14b9_2.m3u8?pid=1608691204584X1511260&device=desktop
XHR:43924590506ad94e644d0bfac89e14b9_2.key?token=1df110e5-ff1d-42de-bd39-b63304bb3062-53648385
XHR:43924590506ad94e644d0bfac89e14b9_2_0.ts?pid=1608691204584X1511260&device=desktop
Other:blob:https://www.sciconf.cn/93ebcbe3-0211-4ec0-94df-421024e8b505

Some codes in the javascript file (blob:https://www.sciconf.cn/93ebcbe3-0211-4ec0-94df-421024e8b505)like:
o = function() {
                function t(t, e, i, n) {
                    this.decryptdata = i,
                    this.discardEPB = n,
                    this.decrypter = new v.a(t,e,{
                        removePKCS7Padding: !1
                    })
                }
                var e = t.prototype;
                return e.decryptBuffer = function(t, e) {
                    this.decrypter.decrypt(t, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, e)
                }

I think the website use this js file to decrypt the key file and the IV value, but I can't add breakpoint to the random named js file.

I am studying this for a long time, but no use.
Please help or try to give some ideas how to achieve the decrypted key and IV?
Thanks in advance.


text:
Q: VPAID & VAST standard Does videojs support vpaid in the future?
All major AdCompanies switch to VPAID with VAST 2.0. So it's impossible to run Ads with the standard VAST plugin.
I'm looking for a solution to implement this. With this feature, videojs would be unbeatable.

A: Check out the videojs-vast plugin from The Onion.
https://github.com/theonion/videojs-vast-plugin

A: I'm currently working in a plugin for video.js for adding support to VPAID: https://github.com/MailOnline/videojs-vast-vpaid
demo: http://mailonline.github.io/videojs-vast-vpaid/
if someone has some issues with the FLASH VPAID please report here: https://github.com/MailOnline/VPAIDFLASHClient
if someone has some issues with the HTML5 VPAID please report here: https://github.com/MailOnline/VPAIDHTML5Client


text:
Q: (this).attr() stops working after jquery.noConflict() I had this code initially that worked on one project but when i decided to port it to another project, it has issues with the $.
So i decided to use the jQuery.noConflict() method to resolve it. It resolved alright but the .attr() method now returns undefined.
Initial Code
    $(".sharebtn").click(function(event)
{
    event.preventDefault();
    content = $(this).attr("data-share-content"); content_id = $(this).attr("data-share-contentid"); medium=$(this).attr("data-share-medium");
    cur_count = parseInt($("#share_count_holder_"+content_id).val());
    if(cur_count<=999){$("#post-share-count").html((cur_count+1));}
    if(cur_count>999 && cur_count<=1000000){ disp=parseFloat(Math.round((cur_count/1000)+'e1')+'e-1'); $("#post-share-count").html(disp+"K"); }
    if(cur_count>1000000){ disp=parseFloat(Math.round((cur_count/1000000)+'e1')+'e-1'); $("#post-share-count").html(disp+"M"); }

    $("#share_count_holder").val((cur_count+1));
    window.open($(this).attr("data-share-link"),"popupWindow","width=600,height=400,scrollbar=yes");
    var url = bh_url+'/admin-2/modules/blog/candor_blogger_ajax.php?action=run_share';
    $.post(url,{ content_type:content, content_id:content_id, medium:medium} ,function(data) { },"json");

});

After noConflict()
var bh = jQuery.noConflict();

bh(".sharebtn").click(function(event)
{
    event.preventDefault();
    content = bh(this).attr("data-share-content"); content_id = bh(this).attr("data-share-contentid"); medium=bh(this).attr("data-share-medium");
    cur_count = parseInt(bh("#share_count_holder_"+content_id).val());
    if(cur_count<=999){bh("#post-share-count").html((cur_count+1));}
    if(cur_count>999 && cur_count<=1000000){ disp=parseFloat(Math.round((cur_count/1000)+'e1')+'e-1'); bh("#post-share-count").html(disp+"K"); }
    if(cur_count>1000000){ disp=parseFloat(Math.round((cur_count/1000000)+'e1')+'e-1'); bh("#post-share-count").html(disp+"M"); }

    bh("#share_count_holder").val((cur_count+1));
    window.open(bh(this).attr("data-share-link"),"popupWindow","width=600,height=400,scrollbar=yes");
    var url = bh_url+'/admin-2/modules/blog/candor_blogger_ajax.php?action=run_share';
    bh.post(url,{ content_type:content, content_id:content_id, medium:medium} ,function(data) { },"json");

});

The click event fires but when i log the content to console i get undefined. - When I restore the $, it works fine in the old project.
What could be my problem.

A: Try using an IFFE and passing in jQuery  like this:
jQuery.noConflict(); // releases $ back to any other library that might be using it

(function($) { // IIFE passing in jQuery as $, inside the scope of this function $ is an now alias for jQuery
  $(".sharebtn").click(function(event) {
    event.preventDefault();
    content = $(this).attr("data-share-content");
    content_id = $(this).attr("data-share-contentid");
    medium = $(this).attr("data-share-medium");
    cur_count = parseInt($("#share_count_holder_" + content_id).val());
    if (cur_count <= 999) {
      $("#post-share-count").html((cur_count + 1));
    }
    if (cur_count > 999 && cur_count <= 1000000) {
      disp = parseFloat(Math.round((cur_count / 1000) + 'e1') + 'e-1');
      $("#post-share-count").html(disp + "K");
    }
    if (cur_count > 1000000) {
      disp = parseFloat(Math.round((cur_count / 1000000) + 'e1') + 'e-1');
      $("#post-share-count").html(disp + "M");
    }

    $("#share_count_holder").val((cur_count + 1));
    window.open(bh(this).attr("data-share-link"), "popupWindow", "width=600,height=400,scrollbar=yes");
    var url = bh_url + '/admin-2/modules/blog/candor_blogger_ajax.php?action=run_share';
    $.post(url, {
      content_type: content,
      content_id: content_id,
      medium: medium
    }, function(data) {}, "json");

  });

}(jQuery)); // pass in jQuery


text:
Q: matrix-calculus - Understanding numerator/denominator layouts Consider the following machine-learning model:

Here, $J = \frac{1}{m} \sum_{i = 1}^{m} L(\hat{y}^{(i)}, y^{(i)})$, and $m$ is the number of training-examples.

While performing reverse-mode differentiation (or back-propagation), I have the following questions:

Using the numerator-layout.

*

*What would be the dimension of the derivative $\frac{\mathrm{d} J}{\mathrm{d} \mathbf{L}}$?

*

*Should it be a column-vector of dimension $(m, 1)$, because $\mathbf{L}$ is a row-vector of dimension $(1, m)$ (Source: here)

*

*However, using this notation causes issues while computing the derivative $\frac{\mathrm{d} J}{\mathrm{d} \mathbf{a}} = \frac{\mathrm{d} J}{\mathrm{d} \mathbf{L}} \frac{\mathrm{d} \mathbf{L}}{\mathrm{d} \mathbf{a}}$; since, $\frac{\mathrm{d} \mathbf{L}}{\mathrm{d} \mathbf{a}}$ would be an $(m, m)$ matrix, while $\frac{\mathrm{d} J}{\mathrm{d} \mathbf{L}}$ is an $(m, 1)$ vector.

*But, this notation does serve well when computing the derivatives of the form $\frac{\mathrm{d}y}{\mathrm{d}\mathbf{X}}$, where $y = f(X)$; $\mathbf{X}$ is a matrix of dimension $(m, n)$; and $f(\mathbf{X})$ is a scalar-valued function.

*Or should it be a row-vector, because according to the numerator-layout the derivative has the dimensions --> $\text{numerator-dimension} \times (\text{denominator-dimension})^\intercal = (1,1)\times(m, 1)$ (Source: here)

*

*Also, (for this point) is my understanding even correct?

PS: also, is there any definitive guide from which I can learn matrix-calculus from the first principals. Although, the following sources are good, they still leave a lot of gaps:

*

*Matrix-Calculus

*The Matrix-cookbook

*Old and New Matrix Algebra Useful for Statistics, by T. P. Minka

*The Matrix Calculus You Need For Deep Learning

A: Unfortunately, I didn't come across a resource that doesn't leave gaps. It's a disputed area. Even the chain rule may sometimes not make a lot sense, e.g. some terms might be 3D tensors that the matrix multiplication is not well-defined because of matrices differentiated by vectors or vice versa.
Having said that, these rules are also very useful if you comply. For ex, define your vectors as column vectors, i.e. $n\times 1$. The chain rule looks like:
$$\frac{\partial J}{\partial \mathbf a^T} = \frac{\partial J}{\partial \mathbf L^T}\frac{\partial \mathbf L^T}{\partial \mathbf a^T}$$
where all the row vectors are transposed. Then, the matrix multiplication sizes would match. All equations you see in the sources assume a harmony, e.g. a chain rule expanding right as above would not make sense with denominator notation, so it'd expand left instead, but the sources rarely mention it. Therefore, whenever a vector is of concern, it'd be better to assume it's a column vector (wikipedia equations note this).

A: If you think of $L$ as a column vector, then I think both your sources agree that  $\frac{dJ}{dL}$ should be a row vector.
But what if you really want $L$ as a row vector. Surely, the math shouldn't "care" about how you arrange your collection of numbers. One way to clarify this is by designating dimensions of your objects as "covariant" or "contravariant".
Many things are contravariant, meaning they change opposite to a change in basis (if you go from a bigger unit, "hours" to a smaller unit "seconds", your measurements become bigger). On the other hand, a derivative, like "m/hour" becomes smaller when you change the units to "m/second", hence "co".
Things which are "co" can be multiplied with things which are "contra", e.g. 5 m/second * 10 seconds = 50m. Yet it makes much less sense to multiply two "contra" or two "co" together (admittedly, second^2 or m^2/second^2 are sometimes useful units, but this is not always the case).
So yes, you could say that $\frac{dJ}{dL}$ is a "column" covector with size $m$, and $\frac{dL}{da}$ is a matrix with shape (contra-$m$, co-$m$). We could write $\left(\frac{dJ}{dL}\right)^i = \frac{\partial J}{\partial L_i}$, and $\left(\frac{dL}{da}\right)_i^j = \frac{\partial L_i}{ \partial a_j}$ (we give superscripts to "co" dimensions, and subscripts to "contra", to make things clear). Then, following our rule that co can only be multipled by contra, we see that
$$\left(\frac{dJ}{da}\right)^j = \sum_{i=1}^m \left(\frac{dJ}{dL}\right)^i \left(\frac{dL}{da}\right)_i^j = \left(\frac{dJ}{dL}^T \frac{dL}{da} \right)^j$$
So even if you "force" $\frac{dJ}{dL}$ into a column, if you want to respect our new multiplication rule, you need to transpose before applying matrix mult.
To take this a step further, let's say we are interested in $\frac{da}{dX}$, which has shape (contra-$m$, co-$(n,m)$): $\left( \frac{da}{dX} \right)_j^{u,v} = \frac{\partial a_j}{\partial X_{u,v}}$. Then we have
$$\left(\frac{dJ}{dX}\right)^{u,v} = \sum_{j=1}^m \left(\frac{dJ}{da}\right)^j \left(\frac{da}{dX}\right)_j^{u,v}$$

To translate this back to "numerator layout" matrix calculus terms, you could say that column vectors are always contravariant, row vectors are always covariant or "covectors", gradients are covariant, hence always row vectors. An $m$ by $n$ Jacobian matrix is contra-$m$, co-$n$. This works nicely because if you think of a column vector as a (contra-$n$, co-1) matrix or a row vector as a (contra-1, co-$m$) matrix, notice that by following the ordinary rules of matrix mutliplcation, you'll never accidentally multiply two contra / two co together, and the product of two objects will always be in a (contra, co) form. On the other hand, "denominator layout" has everything in (co, contra) form, which is just as fine and accomplishes the same thing.
However, if you start working with less standard objects, like the derivative of a matrix with respect to a vector, or the derivative of a row vector with respect to a column vector (as in our example above), then you'll need to keep track for yourself what is covariant and what is contravariant.


text:
Q: Team Build 2010: Write to text file using WF I'm interested in appending some arbitrary information to a text file during a Team Build execution, however I don't have a lot of experience with Windows Workflow. My options seem to be:

*

*Write my own CodyActivity and import into my process template.

*Perhaps call some .NET IO methods inside an InvokeMethod activity.

*Use some sort of File-specific activity library I don't know about?

I'd like to keep this as close to "pure" WF as possible for maintenance and portability purposes, but I'm not sure where to start. It seems like there should be activities already for things as basic as file IO, but I haven't found them yet. Do these exist? If not, is something like this possible with InvokeMethod, or do I have to write my own activity?

A: Use WriteToFile activity from TFS Build Extensions. Here is documentation how to use it.