text:
Q: Best way to get MS-SQL Connection with Python-Skrip from Ubuntu Server I have an Ubuntu 12.04.5 LTS Server, with the following package installed to get Python on this machine:
sudo apt-get install python-dev

Now I need to connect to a "Microsoft SQL-Server 2012".
I read something about pyodbc and pymssql, but I have no idea which one is better. Also I am wondering if there is an Ubuntu package which can be installed, or if I have to download and compile the module by my own (which I haven't done before).

A: A great tutorial that worked for me:
http://www.tryolabs.com/Blog/2012/06/25/connecting-sql-server-database-python-under-ubuntu/
I had only one little problem because of a missing c++ compiler. So i had to install this package befor following the tutorial:
sudo apt-get install build-essential


text:
Q: backward sorting array in php <?php
    function apache($b) {
        return $b;
    }

    $a = array(1, 2, 3, 4, 5, 6);
    $num = "";

    foreach ($a as $b) {
        $num = apache($b) . $num ;
    }

    echo $num;
?>

When you write it like this the output is 654321, but if you write it like this:
$num = $num . apache($b);

the output would be 123456. I don't understand why the results are like that. Can someone explain this?

A: one way you are appending to the string
the other way you are prepending to the string
which gives the effect of reversing it.
first way kind of looks like this
[1]
2[1]
3[21]
4[321]
5[4321]
6[54321]

the other way looks like this
[1]
[1]2
[12]3
[123]4
[1234]5
[12345]6

where the value outside the [] is the value being returned by your function and the value inside the [] is $num

A: This isn't really hard to understand.
This line:
$num = apache($b) . $num;

add the currently selected number and appends the current value of $num to it. The result will be written to $num.
So this will happen:
$b.    $num = $num
1 .      "" = 1
2 .       1 = 21
3 .      21 = 321
4 .     321 = 4321
5 .    4321 = 54321
6 .   54321 = 654321

If you write
$num =  $num . apache($b);

instead, you're adding the currently selected number behind $num:
$num  .$b = $num
""    . 1 = 1
1     . 2 = 12
12    . 3 = 123
123   . 4 = 1234
1234  . 5 = 12345
12345 . 6 = 123456

redpajama_set_name: RedPajamaStackExchange


text:
Q: AutoCompleteTextView force to show all items There is a moment in my app, that I need to force to show all items in the suggestion list, no matter what the user has typed. How can I do that?
I tried to do something with filtering, but for me as a beginner filtering is just way too complicated, I tried searching beginners tutorial for filtering without any luck. Maybe, there is a simpler way to force to show all the suggestion items?
EDIT:
Basically what was my idea, is that, when user types something whats not in the list, it shows all the available options he can have.
I've found the best way of checking weather the ACTV is beign shown or not, but onTextChangeEvent I compare the user typed text with my list, and then if no elements have been found show full list.
public void onTextChanged(CharSequence s, int start, int before, int count)
         {
           final EditText editText = (EditText) findViewById(R.id.vardsUserInput);
            String strValue = editText.getText().toString().toUpperCase();
            String temp;
            int Cc=0; //my count variable
            for(int i=0; i<vardi.length; i++)
            {
                temp = vardi[i].toUpperCase();
                if(temp.startsWith(strValue.toUpperCase()))
                {
                    Log.d("testing",vardi[i]);
                    Cc++;
                }
            }
        if(Cc == 0)
        {
        //Show all the available options
    textView.showDropDown();
         }
}

A: Basically, after 5-6 hours of experimentation to understand how the damn filter works, I wrote my own adapter which does exactly what I want:
    public class burtuAdapteris extends ArrayAdapter<String> implements Filterable {

       ArrayList<String> _items = new ArrayList<String>();
       ArrayList<String> orig = new ArrayList<String>();

       public burtuAdapteris(Context context, int resource, ArrayList<String> items) {
           super(context, resource, items);

           for (int i = 0; i < items.size(); i++) {
                orig.add(items.get(i));
            }
       }

       @Override
       public int getCount() {
           if (_items != null)
               return _items.size();
           else
               return 0;
       }

       @Override
       public String getItem(int arg0) {
           return _items.get(arg0);
       }

      @Override

      public Filter getFilter() {
          Filter filter = new Filter() {
              @Override
              protected FilterResults performFiltering(CharSequence constraint) {

                  if(constraint != null)
                      Log.d("Constraints", constraint.toString());
                  FilterResults oReturn = new FilterResults();

                /*  if (orig == null){
                    for (int i = 0; i < items.size(); i++) {
                        orig.add(items.get(i));
                    }
                  }*/
                  String temp;
                  int counters = 0;
                  if (constraint != null){

                      _items.clear();
                      if (orig != null && orig.size() > 0) {
                          for(int i=0; i<orig.size(); i++)
                            {
                                temp = orig.get(i).toUpperCase();

                                if(temp.startsWith(constraint.toString().toUpperCase()))
                                {

                                     _items.add(orig.get(i));
counters++;

                                }
                            }
                      }
                      Log.d("REsult size:" , String.valueOf(_items.size()));
                          if(!counters)
                          {
                             _items.clear();
                             _items = orig;
                          }
                      oReturn.values = _items;
                      oReturn.count = _items.size();
                  }
                  return oReturn;
              }

              @SuppressWarnings("unchecked")
              @Override
              protected void publishResults(CharSequence constraint, FilterResults results) {
                  if(results != null && results.count > 0) {
                        notifyDataSetChanged();
                        }
                        else {
                            notifyDataSetInvalidated();
                        }

              }

            };

          return filter;

      }

 }

And it's simple to use, just replace original adapter with this:
final burtuAdapteris fAdapter = new burtuAdapteris(this, android.R.layout.simple_dropdown_item_1line, liste);

In my case liste is: ArrayList<String> liste = new ArrayList<String>();

A: method forcefully show drop down list.
you need to call requestFocus(); to show keyboard otherwise keyboard does not pop up.
autocomptv.setOnTouchListener(new OnTouchListener() {

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
            // TODO Auto-generated method stub
            autocomptv.showDropDown();
            autocomptv.requestFocus();
            return false;
        }
    });

A: As "ArtOfWarfare" suggested, you can just sub-class and override performFiltering():
public class My_AutoCompleteTextView extends AutoCompleteTextView {
    public My_AutoCompleteTextView(Context context) {
        super(context);
    }
    public My_AutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public My_AutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void performFiltering(CharSequence text, int keyCode) {
        super.performFiltering("", 0);
    }
}

I'm using it successfully.

A: If you want to show the suggestions instantly, then you have to override enoughToFilter() to make it always return true. To ignore what is given as text input, you have to use performFiltering("", 0) with an empty filtering pattern. The AutoCompleteTextView then shows all suggestions.
This is solution I've combined from other StackOverflow posts:
public class InstantAutoComplete extends android.support.v7.widget.AppCompatAutoCompleteTextView {
    public InstantAutoComplete(Context context) {
        super(context);
    }

    public InstantAutoComplete(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public InstantAutoComplete(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean enoughToFilter() {
        return true;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);

        if (focused && getAdapter() != null) {
            performFiltering("", 0);
        }
    }
}

A: This is what worked for me:
    public class CustomAutoCompleteTextView extends AutoCompleteTextView {
    public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean enoughToFilter() {
        return true;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        if (focused) {
            performFiltering(getText(), 0);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        this.showDropDown();
        return super.onTouchEvent(event);
    }
}

A: Simple and easy answer is:
after autoCompleteTextView.setText("") simply remove filter from adapter like this:
autoCompleteTextView.adapter.filter.filter(null)
thats it, filtering is gone and whole dropdown list is shown.

A: You don't define the "moment" when you want to display all the results, so I hope this fits. But try something like this:
AutoCompleteTextView autoComplete;
String savedText;

public void showAll() {
    savedText = autoComplete.getText().toString();
    autoComplete.setText("");
    autoComplete.showDropDown();
}

public void restore() {
    autoComplete.setText(savedText);
}

A: This works for me perfectly, this is an easy way to resolve the problem:
final ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line, usernameLists);
    etUsername.setThreshold(1);
    etUsername.setAdapter(adapter);
    etUsername.setOnTouchListener(new View.OnTouchListener() {

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
            if (usernameLists.size() > 0) {
                // show all suggestions
                if (!etUsername.getText().toString().equals(""))
                    adapter.getFilter().filter(null);
                etUsername.showDropDown();
            }
            return false;
        }
    });

A: To stop adapter from filtering you can set high enough treshold on your textview:
autoCompleteTextView.setThreshold(100);

Hope it helps.

A: class InstantAutoComplete(context: Context?, attrs: AttributeSet?) : AutoCompleteTextView(context, attrs) {

override fun enoughToFilter(): Boolean {
    return true
}

override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
    super.onFocusChanged(focused, direction, previouslyFocusedRect)
    if (focused && filters != null) {
        performFiltering(text, 0)
    }
}

fun performFilter() {
    performFiltering(text, 0)
    showDropDown()
}

}
I need to show all data from autocompletetextview after click button dropdown(imageview). Using class extends AutoCompleteTextView and add this function, it works like magic.

A: *

*autoComplete.setText(" ")

*filter { it.contains(constraint.trim(), true) } }

Note: You have to set text for autoComplete with space text and in filter, you should trim constraint text input and it will show all dropdown list.


text:
Q: Is it possible to create and store a json file using phonegap's file system and javascript Am thinking of collecting user's data and store that user's data as a json file for retrival by javascript everytime the user uses the app, is it possible??

A: You can use the file API to write to the file system and store the JSON data.
Phonegap File API
Something as simple as this
function win(writer) {
    writer.onwrite = function(evt) {
        console.log("write success");
    };
    writer.write("some sample text");
};

A: yes, you can do it. ether by storing it in sqlite (html5 local storage) or by creating a separate file, it can be js file, xml file or any type ;)
check phonegap documentation


text:
Q: Why props given from parent don't actualise in child VueJS? I am a beginner in VueJS and I am facing a problem.
Here in main.js I pass the user variable to App.vue via a props.
By default its value is {}
In main.js the getLoginStatus() method listens to the firebase authentication status, when a user logs in or out main.js.this.user changes.
user in main.js is passed to App.vue thanks to template, but when it changes as a result of the getLoginStatus() call it is not changed in App.vue (the child), whereas in main.js it does change.
How can this be done?
Thanks
My main.js :
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import firebase from "firebase";
Vue.config.productionTip = false

var firebaseConfig = {
    CONFIGURATION
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();

new Vue({
    el: '#app',
    router,
    template: '<App :user="user" ></App>',
    components: { App },

    data(){
        return {
            user : {}
        }
    },
    methods:{
        getLoginStatus(){
            firebase.auth().onAuthStateChanged(function(u) {
                if (u) {
                    this.user = u
                    console.log("// User is signed in by Phone Number : ", u.phoneNumber)

                } else {
                    this.user = null
                    console.log("// No user is signed in.")
                }
            });
            console.log("this.user new value : "+this.user);
        },
    },
    updated(){
        this.getLoginStatus()
    },
    created(){
        this.getLoginStatus()
    }
})

App.vue :
<template>

            Navbar
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                        <router-link class="nav-link" to="/">Home</router-link>

                        <router-link class="nav-link" to="/register">Register/About old</router-link>

                        <router-link class="nav-link" to="/dashboard">Dashboard</router-link>

                        <button class="nav-link btn" @click="logout">Logout</button>

            <router-view />

logged{{user}}

not logged{{user}}

</template>

A: You're using an unbound function here:
firebase.auth().onAuthStateChanged(function(u) {

So when setting this.user inside this function, this is not pointing to your Vue instance. You can either .bind(this) your function or just use an arrow function which will auto bind:
firebase.auth().onAuthStateChanged(u => {


text:
Q: Discharging Circuit with LED indicators? I'd like to create discharging circuit with four LEDs indicating how much charge is left from the discharging battery. It needs to be a low cost solution (no Arduinos; only simple circuit components) I'm not entirely sure how to go about this theoretically; I can only imagine that there would be parallel branches of an LED in series with a resistor. I want each LED to be lit initially and indicate how much of the original voltage/current is left as each LED goes dim:

*

*4 lit LEDs = 100-75% charge

*3 lit LEDs = 75-50% charge

*2 lit LEDs = 50-25%

*1 lit LED = 25-0%

*0 lit LEDs = 0% charge left

EDIT: Let's says it's for a 9v battery

Edit #2: Let's say it's a lithium ion rechargeable battery.

A: Well, This is an interesting problem that can be tackled a variety of ways. Typically to accurately measure the remaining capacity of a battery you will use a coulomb counter, which basically integrates charge flowing across a shunt resistor in both directions. Essentially this gives you current/time bidirectionally and you can solve for remaining capacity based on your initial specifications for the battery in your system.
For less accurate gauging (which is what I am assuming you are doing) using the battery's discharge curve to relate the voltage of the battery with capacity remaining can be done with a resistor ladder and comparators at each branch, like was previously suggested. This is from google images, so you will have to change the resistors to produce voltages at the junctions that correspond to points along the discharge curve that you will use, this is also a liquid level indicator, but the principle is the same This however will cause some problems if the battery is a rechargeable type since aging effects will reduce accuracy of the gauge as the battery is repeatedly cycled. The voltage/capacity relationship also changes as the battery is put under different loads, so either you can do the math to take that in to account or just measure the battery voltage when you are under a very light or no load, take a look at the picture for a typical AA battery discharge curve.
If you don't always need to check the battery, you can put a tactile switch in series with the circuit to kill power, that way you will only ever have the LEDS enabled when you are actually checking the capacity

A: I'd probably use comparators. Use simple resistor dividers as one input for each of the comparators. Then use the battery voltage as the other input. The output of each of the comparators will drive the LEDs.
Now, you may find using this technique could not be as cheap as an Arduino by the time you buy the IC(s), wire everything together, package it, etc. Plus, like jonk commented, charge and voltage do not have a 1:1 relationship. There are other factors like temperature. It all depends how sophisticated you want your meter to be.
If the voltage only changes a very little for large changes in charge, you may need high precision resistors, some kind of amplifier, trim pots, or other sophistication.

A: Rechargeable makes it trickier. Discharge rate, discharge depth, and discharge cycles are also factors.
If the discharge amperage is low, and not discharged too often or deeply then the voltage divider comparator circuit will do the job.
Otherwise it cannot be done well without a micro-controller. Even at that it would need to be on 24/7 to count the number of discharge cycles and measure the depth of the discharge.
Li-ion Power Cell at a 2A, 10A, 15A and 20A discharge
Comparator Circuit
Simple $2 device with current sourced LED drivers. Use only the outputs needed.

A: If you want very simple; you can use zener diodes series with LEDs with small resistors for LEDs.
If you want simple; you can use comperators.


text:
Q: Not able to Format Date created by Facebook, Returns NULL date Facebook provides date objects in the format: 2010-12-01T21:35:43+0000
I want to convert this format to NSDate.
I am using the following code. Why does it return null.
NSDateFormatter *df = [[NSDateFormatter alloc] init];
dateString = [dateString stringByReplacingOccurrencesOfString:@"T" withString:@" "];
dateString = [dateString stringByReplacingOccurrencesOfString:@"+" withString:@" +"];
NSLog(@"%@", dateString);
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss '+'ZZZZ"];
NSLog(@"%@",df.dateFormat);
NSDate *date = [df dateFromString:dateString];

NSLog(@"%@ date",date);

A: Just replace '+'ZZZZ with +zzzz in your code..
    NSString *dateString=@"2010-12-01T21:35:43+0000";

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    dateString = [dateString stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    dateString = [dateString stringByReplacingOccurrencesOfString:@"+" withString:@" +"];
    NSLog(@"%@", dateString);
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss +zzzz"];
    NSLog(@"%@",df.dateFormat);
    NSDate *date = [df dateFromString:dateString];

    NSLog(@"%@ date",date);

Output is :
2016-04-30 14:52:10.118 date[2523:187669] 2010-12-01 21:35:43 +0000
2016-04-30 14:52:10.120 date[2523:187669] yyyy-MM-dd HH:mm:ss +zzzz
2016-04-30 14:52:10.153 date[2523:187669] 2010-12-01 21:35:43 +0000 date

A: You don't need to replace any character in string
Try out this code:
Objective-C
NSString *dateString=@"2010-12-01T21:35:43+0000";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
NSDate *date = [df dateFromString:dateString];
NSLog(@"%@ date",date);

Swift:
let dateString: String = "2010-12-01T21:35:43+0000"
let df: NSDateFormatter = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
let date: NSDate = df.dateFromString(dateString)!
print("date: \(date)")

A: Just use yyyy-MM-dd'T'HH:mm:ssZ for your dateFormat and don't mess around with the string manipulation at all.
The only thing you might want to do is set the locale as outlined in Apple's Technical Q&A 1480, so that this will work regardless of what sort of calendar settings the device might otherwise have:
df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];


text:
Q: How do I change the background colour and foreground colour using a button in Tkinter? So what I am trying to do is create a theme picker for my application
For example, the user could click on a the Green/Black button and it would change every widgets background to Black and it would change every widgets foreground to Green. Then they could click the Red/White button and it would do the same thing but change every widgets background to White and every widgets foreground to Red.
# Imports the tkinter library.
from tkinter import *
from tkmacosx import Button

# Pillow is a improved verison of PIL, stands for Python Image Library. Allows you to import image types like .jpg and .png
from PIL import ImageTk,Image

# Imports messagebox module from tkinter library.
from tkinter import messagebox

# Declare global variables
global selectedBackground
global selectedForeground

selectedBackground="white"
selectedForeground="red"

# Tk() helps to display the root window and manages all the other components of the tkinter application and assigns it to root.
root = Tk()
root.eval("tk::PlaceWindow . center")
root.configure(bg=selectedBackground)

cipherButton = Button(root, text="  Cipher  ", padx=40, pady=20, command=openCipher, borderwidth=0, fg="#22fd35", bg="black", highlightbackground="#22fd35").grid(row=1, column=0)
decipherButton = Button(root, text="Decipher", padx=40, pady=20, command=openDecipher, borderwidth=0, fg="#22fd35", bg="black", highlightbackground="#22fd35").grid(row=1, column=1)
spacer1 = Label(root, text="     ", padx=10, pady=1, background="black").grid(row=4, column=1)
quitButton = Button(root, text="Exit d3cryptt", padx=10, pady=5, command=root.quit, borderwidth=0, fg="#22fd35", bg="black", highlightbackground="#22fd35").grid(row=5, column=0, columnspan=2)
spacer2 = Label(root, text="     ", padx=10, pady=1, background=selectedBackground).grid(row=6, column=1)
changecolour = Button(root, text="change colour", padx=1, pady=5, background="black", command=changeColour).grid(row=7, column=0)

#Enter the event main loop
root.mainloop()

I have tried using a function. Something like this.
def changeColour():
    selectedBackground="black"
    selectedForeground="#22fd35"

changecolour = Button(root, text="change colour", padx=1, pady=5, background="black", command=changeColour).grid(row=7, column=0)

But that doesn't work. I think a function is the right way to go, but I may be wrong.
I will also need this 'theme' to carry on to any other windows that are created from this window. I think I can just do that by using lambda in the command section of the widget.

A: Widget.config(bg=color) is what your looking for.
Here is a small example of a theme-changing app:
from tkinter import *
from tkmacosx import Button

root = Tk()

def changethemetoblack():
    root.config(bg="#000000")

def changethemetowhite():
    root.config(bg="#ffffff")

def changethemetored():
    root.config(bg="#ff0000")

themeblackbutton = Button(root, text="Change Theme To Black", command=changethemetoblack, bg="#000000", fg="#ffffff")
themewhitebutton = Button(root, text="Change Theme To White", command=changethemetowhite)
themeredbutton = Button(root, text="Change Theme To Red", command=changethemetored, bg="#ff0000", fg="#ffffff")

themeblackbutton.pack()
themewhitebutton.pack()
themeredbutton.pack()

root.mainloop()

I'll try to change it so that it applies for your code.
However, your provided script does not seem to be a working one. I assume this is because it is only a snippet of the real one. I'm not pushing for your entire code, but edit it so we can run it. Ex. openCipher method is causing errors as we have not defined it.


text:
Q: cannot seem to get bitmap from view in android My problem is similar to the one in Android View.getDrawingCache returns null, only null.
My code used to work with the method
private Bitmap getBitmapFromView(View v) {
    v.setDrawingCacheEnabled(true);
    v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    v.buildDrawingCache(true);
    Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
    v.setDrawingCacheEnabled(false); // clear drawing cache
    return b;
}

But today I changed the xml layout file. Since the change I have been getting NullPointerException at the line Bitmap b = Bitmap.createBitmap(v.getDrawingCache()). So I tried changing the method getBitmapFromView to
public static Bitmap loadBitmapFromView(View v) {
    Bitmap b = Bitmap.createBitmap(v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
    v.draw(c);
    return b;
}

But that didn't help. I get the null in the very first line.
The situation is this: I am trying to convert the view into a bitmap. But I am doing this without first displaying the view on screen. Again, this all used to work until I changed the content of the xml layout file. The change was not even that big. I just moved stuff around and removed -- yes removed -- some of the subviews.
In any case, I know for certain there is no problem with my layout file because I can display it on screen if I want; which I have done as part of troubleshooting.
Someone suggested using a handler to call getDrawingCache(). If that's the answer, how would I write that code?
UPDATE
View view = activity.getLayoutInflater().inflate(R.layout.my_view, null, false);
    findViewsByIds(view);//where I inflate subviews and add content to them.

A: Execute createBitmapFromView when the view is measured.
public static void executeWhenViewMeasured(final View view, final Runnable runnable) {
    if(view.getMeasuredHeight() == 0 || view.getMeasuredWidth() == 0){
        view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                runnable.run();
                removeGlobalOnLayoutListener(view, this);
            }
        });
    } else {
        runnable.run();
    }
}

public static Bitmap createBitmapFromView(View view) {
    Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void removeGlobalOnLayoutListener(View view,
                                                ViewTreeObserver.OnGlobalLayoutListener listener) {
    try {
        view.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
    } catch (NoSuchMethodError e) {
        view.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
    }
}

executeWhenViewMeasured(view, new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = createBitmapFromView(view);
            }
        });

A: Since you are not showing the view it's easier to just draw the view on a canvas.
You are already trying to do that but I would merge both methods into one without using drawing cache.
private Bitmap getBitmapFromView(View v) {
    v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredWidth());
    Bitmap b = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredWidth(), Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    v.draw(c);
    return b;
}

Also check that MeasureSpec.UNSPECIFIED may not work well without the view in layout so you may need to specify a width and height.


text:
Q: Getting rid of progress indicator in status bar on ie8 On ie8 there is a green progress indicator below on the status bar, likely indicating download progression based on some static length value from somewhere. Unfortunately due to the nature of "modern" dynamic javascripts, ajax calls etc. this indicator often gets messed up and the bar stays at half full. Is there a way to turn that progress bar off through a javascript command or at least tell the browser we are done so please go away? I know the status bar can be turned off completely, however I still have a need for it to display my own status messages etc.

A: Alright, after some trial and errors I think I finally figured out how to trick ie8 to think it's done loading. I'm sure there might be other more elegant solutions out there, which I would be happy to hear about.
In the web page root root I created an empty html doc called blank.html
<!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>

    </body>
</html>

In the view/html for the form/page/window I create an invisible iframe
<iframe id="iframeHack" name="iframeHack" frameborder="0"
    style="height: 0; width: 0" src="blank.html">
</iframe>

in the javascript section of that view I place a timebomb
<script language="javascript" type="text/javascript">
    .
    .
    .

    setTimeout("document.getElementById('iframeHack').src = 'blank.html'", 100);
</script>


text:
Q: Can we get a ping when a downvoted Q/A was subsequently edited? I'm one of these people who tends to leave a comment when I downvote and every now and then, the OP edits their post and pings me back they did and then I remove my downvote most of the time and even upvote every once in a blue moon...  :-)
However, I noticed that one of my comments on one of my downvotes was upvoted 3 times and the answer was downvoted for the same amount of times but now it's actually a good answer. (and I have no way of contacting the additional 3 downvoters)
Can we have an additional option¹ to be pinged whenever an edit was made on one of our downvotes for the few times that I don't leave a comment?
Note¹: Optional because there might be people who don't want any extra pings because they get too many already.
Note²: It would be more welcoming to new users who generally don't know how the SE network works and get downvotes because of semantics and not because of their actual question or answer...
Note³: This one is similar and highly upvoted, but that one is asking to make it mandatory, whereas this is broader and optional.


text:
Q: Laravel vuejs SPA on localhost - cors fails I use laravel9 and vuejs3 with laravel sanctum SPA authentication on a Fedora 36 os.
I created 2 apache sites on local host with this virtual hosts
00-backend.conf in /etc/httpd/conf.d
<VirtualHost *:80>
    ServerName www.compagnon-backend.fr
    ServerAlias compagnon-backend.fr
    DocumentRoot /var/www/compagnon-backend/public
        <Directory /var/www/compagnon-backend/public>
            Options -Indexes +FollowSymlinks
            AllowOverride All
        </Directory>
</VirtualHost>

and 00-frontend.conf in  /etc/httpd/conf.d
<VirtualHost *:80>
    ServerName www.compagnon-frontend.fr
    ServerAlias compagnon-frontend.fr
    DocumentRoot /var/www/compagnon-frontend
        <Directory /var/www/compagnon-frontend>
            Options -Indexes +FollowSymlinks
            AllowOverride All
        </Directory>
</VirtualHost>

The relevant content in .env of backend
APP_DEBUG=true
APP_URL= www.compagnon-backend.fr

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN=compagnon-backend.fr
SANCTUM_STATEFUL_DOMAINS=*.compagnon-frontend.fr
SPA_URL=https://www.compagnon-frontend.fr

config.cors
<?php

return [

    'paths' => [
        'api/*',
        'login',
        'logout',
        'register',
        'user/password',
        'forgot-password',
        'reset-password',
        'user/profile-information',
        'email/verification-notification',
        'sanctum/csrf-cookie'
    ],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['https://www.compagnon-frontend.fr', 'https://compagnon-frontend.fr'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

config/session.php
    <?php
    use Illuminate\Support\Str;
    return [
        'driver' => env('SESSION_DRIVER', 'file'),
        'lifetime' => env('SESSION_LIFETIME', 120),
        'expire_on_close' => false,
        'encrypt' => false,
        'files' => storage_path('framework/sessions'),
        'connection' => env('SESSION_CONNECTION'),
        'table' => 'sessions',
        'store' => env('SESSION_STORE'),
        'lottery' => [2, 100],
        'cookie' => env(
            'SESSION_COOKIE',
            Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
        ),
        'path' => '/',
        'domain' => env('SESSION_DOMAIN', null),
        'secure' => env('SESSION_SECURE_COOKIE'),
        'http_only' => true,
        'same_site' => 'lax',

    ];

config/sanctum.php
<?php
use Laravel\Sanctum\Sanctum;
return [

    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
        '%s%s',
        'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
        Sanctum::currentApplicationUrlWithPort()
    ))),

    'guard' => ['web'],
    'expiration' => null,
    'middleware' => [
        'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
        'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
    ],

];

With this configuration both sites works but from the frontend trying to login I get this message

Response body is not available to scripts (Reason: CORS Failed)

I could not manage to fix this. I need help. Thank you.
ADDITIONAL EDIT AFTER FIRST COMMENT
In kernel.php
protected $middleware = [
     \Fruitcake\Cors\HandleCors::class,
     \App\Http\Middleware\TrustHosts::class,
    \App\Http\Middleware\TrustProxies::class,
    \Illuminate\Http\Middleware\HandleCors::class,
    \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];


text:
Q: GitBash can clone and pull but can't push, it show nothing while GitDesktop can I've just reinstall my operating system. But when i use git, I just can use clone and pull. When i use push, nothings happens, show no error. However, I use git desktop and it can push my repo. Could you help me, I have googling for this problem since last week :((
sorry for my bad English.


text:
Q: как изменить условия цикла while, находящегося в repeat_list , таким образом, чтобы массив обходился только два раза? def repeat_list(list_):
   list_values = list_.copy()
   while True:
       value = list_values.pop(0)
       list_values.append(value)
       yield value

for i in repeat_list([1, 2, 3]):
   print(i)

A: вот решение:
def repeat_list(list_):
 list_values = list_.copy()
 n = 0   while n < len(list_values) * 2:
 n += 1  value = list_values.pop(0)
 list_values.append(value)
    yield value
 for i in repeat_list([1, 2, 3]):
  print(i)

A: tio.run
def repeat_list(lst):
  lst = lst.copy()

  for _ in range(2):
    for x in lst:
      yield x

for i in repeat_list([1, 2, 3]):
  print(i)


text:
Q: Counting Number of Strominoes (Extension of Dominoes) The number of dominoes in a Sino-European set (0 to 6 dots) is
$$21 + 7 = 28,$$
where the $21$ is the number of pairs that can be formed, and $7$ is doubles.
Now suppose we extend this to Strominos ($3 \times 1$) rectangles, with 3 distinct squares.
Dominoes have rotational symmetry of order 2, and we want to keep the symmetry, so paint the dots on the strominos so that the tromino also has order of rotational symmetry 2.
Now, what is the number of distinct strominonoes where the number of dots is 0-6?
One method is to say:
There are 28 dominoes. In each distinct domino, introduce a middle square (7 possibilities), and hence the number of strominos is
$$28 \times 7=196$$
Second method is to say:
Number of distinct strominos is:
$$(7 \times 7 \times 7 - 7)/2 + 7 = 336/2 + 7 = 168 + 7 = 175,$$
where the single color strominos are not repeated, and do not need to be divided, but all others are overcounted by 2, and hence need to do be divided.
These two should give the same answer.
What is the actual (correct) answer?
Note: The stromino notation comes from https://artofproblemsolving.com/wiki/index.php/2020_INMO_Problems/Problem_6
But this problem is not related to that one.

A: When you remove the 'single color' strominoes (e.g. $000, 111$), you also need to remove the symmetric $010,020$, etc.., as these are also doubled up.
Your calculation then becomes:
$$\frac{(7^3-7^2)}{2}+7^2=\frac{(343-49)}{2}+7^2=\frac{294}{2}+49=147+49=196$$


text:
Q: Vista - wiped MBR and HEAD of disk - how to recover? I did something incredibly stupid.  I was trying to fix some booting issues with Vista and XP (this was a dual boot system with both OSes installed), and followed some advice online rather blindly and uncritically and now am in this position.
Basically, the advice was to use mbrwiz to wipe the MBR and have Vista repair it.  The steps I followed were:
Boot to Vista DVD and run at the command prompt:
MBRWiz /Wipe=MBR /DISK=0 /Result
MBRWiz /Wipe=HEAD /DISK=0 /Result

And no, very stupidly I also didn't back up the MBR.
What this did, according to the documentation of MBRWiz was:

*

*Firstly wipe out the MBR.  Should be recoverable with Windows though (which I have tried to do)

*Secondly wipe out the first 63 sectors of the first partition of the disk

What I've tried since:

*

*testdisk (can only see a single "FAT32 partition", rather than the three partitions that used to be there)

*bootrec /fixmbr (same as fixmbr. Claims it fixes things but then nothing boots)

*Windows repair (can't seem to do anything)

I have most of my files backed up, so it's not catastrophic, but I am keen to restore my system to how it was.  Any advice on how to recover from this?

A: Okay, I managed to fix this, so I figured I'd post the steps in case someone else gets in a similar situation.
Firstly, I determined the commands I ran overwrote the master boot record as well as the partition table.  Nothing else was damaged.
The Windows repair process had written some odd data to the partition table.  So I re-ran MBRWiz /Wipe=head and /Wipe=MBR to get back to zero.
After that I ran testdisk again.  This time it accurately detected there was no partition at all.  I had it run a deep scan and it found all the previous partitions, including the repair partition, XP and Vista.
After recreating the partitions (I did this simply by using the default settings from testdisk for the partitions it found automatically, and simply changed their status from "D" (deleted) to "P" (primary) or "*" (boot)) and seeing my data intact (huge relief!) I needed to make the partition bootable (since although I had marked the partition as bootable, it lacked the proper MBR).
To do this I booted from my Windows DVD.  I ran fixmbr and fixboot - which although didn't make the system bootable, did allow the Windows DVD to see the operating system.  I then ran the automated Windows Vista boot repair, which made some changes, and I then got a new error message.  So, I ran it a second time, and voila, all fixed and I was back in Vista.
The only negative side-effect was I could not boot into XP anymore, but it turns out having the dual boot with XP was what was stopping me from updating Vista to SP2 or Windows 7.  I got all my stuff off that partition, removed it, and I'm now running Windows 7 (running an upgrade, which worked flawlessly) with everything completely intact.
Thanks everyone for the help.

A: Boot from the windows XP CD, press the "R" key in the setup in order to start the restoration console. Select your windows XP installation from the list, and enter the administrator password.
Enter the command: "FIXMBR" (without the quotes) at the input prompt and confirm the next question with a "Y" (without the quotes). Use exit to restore the computer.
Source

A: You could try reinstalling Vista.  If it detects your existing install you should be able to install over the top of it to retain your existing settings.


text:
Q: Finding the centroid of a polygon I use the following code to find the centroid of a polygon (I didn't write the code, it's from another question).
Point compute2DPolygonCentroid(const std::vector<Point> vertices) {
    Point centroid;
    double signedArea = 0.0;
    double x0 = 0.0; // Current vertex X
    double y0 = 0.0; // Current vertex Y
    double x1 = 0.0; // Next vertex X
    double y1 = 0.0; // Next vertex Y
    double a = 0.0;  // Partial signed area

    // For all vertices except last
    for (int i = 0; i < vertices.size() - 1; ++i) {

        x0 = vertices[i].x;
        y0 = vertices[i].y;
        x1 = vertices[i + 1].x;
        y1 = vertices[i + 1].y;
        a = x0 * y1 - x1 * y0;
        signedArea += a;
        centroid.x += (x0 + x1) * a;
        centroid.y += (y0 + y1) * a;

    }

    // Do last vertex separately to avoid performing an expensive
    // modulus operation in each iteration.
    x0 = vertices.back().x;
    y0 = vertices.back().y;
    x1 = vertices.front().x;
    y1 = vertices.front().y;
    a = x0 * y1 - x1 * y0;
    signedArea += a;
    centroid.x += (x0 + x1) * a;
    centroid.y += (y0 + y1) * a;

    signedArea *= 0.5;
    centroid.x /= (6.0 * signedArea);
    centroid.y /= (6.0 * signedArea);

    return centroid;
}

The problem is that it works ONLY when the points in the input vector vertices are in clockwise order. When the points are in counterclockwise order it doesn't work. Here's a picture of what I mean by cw && ccw order:

I don't understand why it doesn't work when just the order of the points change but the points are still the same.

A: The problem, as it turns out, is that Point had unsigned members. There's also a potential secondary problem, regarding floating point rounding issues.
In this algorithm, if the wind order is the wrong way around, the computed area will be negative, and when you do something like
centroid.x += (x0 + x1) * a;

you'll get an incorrect value because a will be negative and centroid.x is unsigned.
You should store the intermediate centroid values as a floating point of some kind, so that a) you won't get these signed/unsigned issues and b) so that you won't get rounding errors on every vertex; I'm not sure if these errors would end up being large enough to cause you problems, but it seems silly to risk it when it can be so easily avoided. You should cast to unsigned int (or whatever) at the very end when you return.


text:
Q: svg transform matrix parser problem explain:
transform = "matrix(cos(a), sin(a), -sin(a), cos(a), -x1cos(a)+y1sin(a)+x2, -x1sin(a)-y1cos(a)+y2)"
can see 7.4 Coordinate system transformations
to be resolved:
in my work,i must resolve to parse matrix
example:
<?xml version="1.0" encoding="utf-8"?><svg width="800" height="500" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:PerfectSVG="http://www.perfectsvg.com/PerfectSVG" xml:space="preserve">
<defs>
<symbol overflow="visible" id="symbol1" connectPoints="15 70 50 0 87 68">
<g>
<line x1="300" y1="200" x2="309" y2="200" transform="matrix(1,0,0,1,0,0)" />
<line x1="311" y1="200" x2="320" y2="200" transform="matrix(1,0,0,1,0,0)" />
<line x1="300" y1="200" x2="304.75" y2="207.75" transform="matrix(1,0,0,1,0,0)" />
<line x1="315.75" y1="207" x2="320" y2="200" transform="matrix(1,0,0,1,0,0)" />
<line x1="309.25" y1="197.5" x2="309.25" y2="202.25" transform="matrix(1,0,0,1,0,0)"/>
<line x1="311" y1="197.25" x2="311" y2="202.5" transform="matrix(1,0,0,1,0,0)"/>
<line x1="313.75" y1="205.5" x2="318" y2="208.5" transform="matrix(1,0,0,1,0,0)"/>
<line x1="302.75" y1="209.5" x2="307.25" y2="206" transform="matrix(1,0,0,1,0,0)"/>
<line x1="303.75" y1="211" x2="308.25" y2="207.5" transform="matrix(1,0,0,1,0,0)"/>
<line x1="306" y1="209.25" x2="310.25" y2="215.5" transform="matrix(1,0,0,1,0,0)"/>
<line x1="312.75" y1="207.25" x2="317.25" y2="210.5" transform="matrix(1,0,0,1,0,0)"/>
<line x1="310.25" y1="215.25" x2="314.5" y2="208.75" transform="matrix(1,0,0,1,0,0)"/>
</g>
</symbol></defs><use xlink:href="#symbol1" transform="matrix(3.774,-2.246,2.246,3.774,-1562.468,-12.947)" stroke="#000000" fill="#FFFFFF" id="use3" stroke-width="0.2276867"/></svg>

Now:
i want to know In:transform="matrix(3.774,-2.246,2.246,3.774,-1562.468,-12.947)" out:(a:angle x1,y1:The original coordinates x2,y2:New coordinates) from the example
who can give suggestions or Some reference materials
tks.

A: It's impossible to get old x/y and new x/y only by transform data.
You must have two of the three data.
You can use getBBox method to get the outer box, and then you can get the box's dots.


text:
Q: Как программно составить список обслуживаемых хостов в NodeJS (нативно)? Как я узнал из англоязычного Stack Overflow, валидация HTTP-заголовка HOST с помощью регулярных выражений, учитывающая все возможные сценарии, может привести к довольно сложному регулярному выражению. Однако достаточно проверить, входит ли значение полученного HTTP-заголовка HOST в список поддерживаемых (тем более, что валидация с помощью регулярного выражения всё равно не избавляет от необходимости этой проверки). Чтобы реализовать эти проверки, необходимо знать всё возможные варианты валидного заголовка HOST для своего случая.
"Поддерживаемые хосты следует прописывать вручную"
Мне это говорили неоднократно, да я в полной мере этого и не отвергаю. Всё равно нужно прописать в явном виде основной хост, например example.com. А теперь представим, что у этого example.com - десятой-другой поддоменов, причём у каждого есть ещё одни поддомен под локаль. Плюс к этому, в режиме локальной разработки нужно, чтобы сервер не отвергал запросы , идущие на localhost. Наконец, есть какие-то редкие частные случаи типа example.com., которые по-хорошему тоже надо учитывать.
И что? Мне предлагается всё это прописать вручную?
[
  "example.com",
  "XXX.X.X.X", // IP-адрес сервера с "example.com"
  "example.com:8080",
  "XXX.X.X.X:8080",
  // + всё то же самое для localhost в режиме локальной разработки
  // + какие-то редкие частные случаи

  /* --- поддомены локали для "example.com" --- */
  "ru.example.com",
  "ru.XXX.X.X.X",
  "ru.example.com:8080",
  "ru.XXX.X.X.X:8080",
  // + всё то же самое для localhost в режиме локальной разработки

  "en.example.com",
  "en.XXX.X.X.X",
  "en.example.com:8080",
  "en.XXX.X.X.X:8080",
  // + всё то же самое для localhost в режиме локальной разработки

  // и так для всех поддерживаемых языков ...

  /* --- поддомен "cats" --- */
  "cats.example.com",
  "cats.XXX.X.X.X",
  "cats.example.com:8080",
  "cats.XXX.X.X.X:8080",
  // + всё то же самое для localhost в режиме локальной разработки

  /* --- поддомены локали для "cats.example.com" --- */
  "ru.cats.example.com",
  "ru.cats.XXX.X.X.X",
  "ru.cats.example.com:8080",
  "ru.cats.XXX.X.X.X:8080",
  // + всё то же самое для localhost в режиме локальной разработки

  // и так для всех поддерживаемых языков ...

  // и так для всех поддоменов
]

Очень надеюсь, что нет (по крайней мере, для третьего десятилетия 21 века).
Полагаю, что более рациональный подход состоит в том, чтобы прописать только какие-то исходные данные (это будут основной хост, например example.com, поддерживаемые поддомены, например cats, dogs и т. д. + поддерживаемые локали), а всё возможные варианты - вычислить программно. И тогда уже при каждом запросе будем проверять HTTP-заголовок HOST на совпадение с одним из допустимых вариантов.
Изложу всё, что сам узнал по данной тематике.
Режим локальной разработки
В режиме локальной разработке обычно используется localhost. Вроде как, им не обязательно должен быть IP-адрес 127.0.0.1, но при каких условиях localhost будет ссылаться на другие IP-адреса - мне неизвестно. Да и вообще, попытки узнать, как резолвить localhost в IP-адрес, пока не увенчались успехом. Была подсказка, что можно с помощью нативных утилит определить соответствие localhost и IP-адреса.
Таким образом, при обслуживании IP-адреса 127.0.0.1 и порта 80 (по умолчанию для HTTP), валидными будут следующие заголовки HOST:

*

*127.0.0.1

*localhost

*127.0.0.1:80

*localhost:80
При этом, перед сравнением присланного заголовка с одним из валидным из списка удобно будет:

*

*Добавить порт по умолчанию, если таковой не указан.

*Убрать нули в начале номера порта, если таковые имеются (например: 0080 -> 80).

В итоге, список обслуживаемых хостов сокращается до:

*

*127.0.0.1:80

*localhost:80
Для HTTPS, соответственно, порт по умолчанию будет 443.
Если же порт будет не умолчанию - то после двоеточия будет номер этого порта.
Если я правильно понял, что до меня хотели донести в одном из комментариев, то в режиме локальной разработки проверку заголовка HOST можно вообще опустить. Не уверен в этом по двум причинам:

*

*Нужно отладить механизм валидации заголовка HOST до деплоя

*Помимо безопасности, анализ заголовка HOST нужен в приложениях, обслуживающих несколько поддоменов.

Режим продакшена
Полагаю, с режиме продакшена localhost-а не будет, а вместо 127.0.0.1 будет тот IP-адрес, который выдал провайдер VPS.

*

*Если на этот IP-адрес зарегистрировано доменное имя, то в список нужно будет добавить валидный вариант с этим доменным именем (например, example.com:80).

*С портами всё остаётся так же.

Поддержка поддоменов
Думаю, список поддерживаемых поддоменов должен быть конечным. Если часть поддомена является параметризованной (например локаль, как ru в ru.stackoverflow.com), то все возможные значения должны быть заранее известны (прописаны в настройках). Тогда, для example.com с двумя поддоменами и IP-адрсом 000.0.0.0 получаем такой список:

*

*000.0.0.0:80

*example.com:80

*ru.000.0.0.0:80

*en.000.0.0.0:80

*ru.example.com:80

*en.example.com:80

Напоследок
Прошу Вас не рекомендовать никаких готовых решений типа express-плагинов, так как в данном вопросе речь идёт о именно о самостоятельной реализации механизма валидации HTTP-заголовка HOST.

A: Поддерживаемые хосты действительно следует прописывать вручную, однако это не подразумевает составления списка с перебором всех возможных вариантов. К этой задаче следует подходить с другой стороны - с разбора хоста. Хост предствляет собой запись вида
<ipv4|ipv6|domain>:<opt_port>

При этом доменное имя не может пересекаться с адресом ipv6, так как в нем не разрешается :, и не может пересекаться с адресом ipv4, так как домен верхнего уровня не может состоять только из чисел. т.е. вариантов вида ru.000.0.0.0:80 быть не может. А если используется адрес ipv6 и указывается порт, то адрес должен быть в квадратных скобках. Эти ограничения позволяют однозначно разобрать хост на компоненты за один проход не прибегая ни к каким регулярным выражениям. Причем разбор имеет смысл производить с конца, сразу определив опциональный порт, а затем перейдя к разбору адреса или домена. Получая адрес проверить его валидность тривиально по плоскому перечню разрешенных адресов. Доменное имя как раз тоже важно разбирать с конца, так как там находятся домены более высокого уровня, и получая домен
его валидность тоже несложно проверить по иерархическому перечню разрешенных доменов, начиная навигацию с домена верхнего уровня, например подобного:
{
   "com":
   {
       "option1":...
   ,   "subdomains":
       {
           "example":
           {
               "option1":...
           ,   "subdomain":
               {
                   "ru":
                   {
                       "option1":...
                   }
               ,   "en":
                   {
                       "option1":...
                   }
               }
           }
       }
   }
}

По сути это карта сайта по иерархии доменов. И в ней же можно сразу прописывать обработчики и какие-то нужные настройки для поддерживаемых доменов.


text:
Q: the static modifier make so huge difference,what's happening? i create a class as below:
public class NodeOne {

    NodeOne nodeone = new NodeOne();

    public NodeOne() {
        System.out.println("1");
    }

    public static void main(String[] args) {
        NodeOne nodeone = new NodeOne();
    }
}

once i run it i got exception "Exception in thread "main" java.lang.StackOverflowError
",which i know the reason for sure. but when i add the modifier "static" before the field nodeone, the result turn out to be fine. so what's the deep cause?
public class NodeOne {

    static NodeOne nodeone = new NodeOne();

    public NodeOne() {
        System.out.println("1");
    }

    public static void main(String[] args) {
        NodeOne nodeone = new NodeOne();
    }
}

output:
     1
1

A: In first case, each time you create new object NodeOne its default constructor is calling another contructor for its field nodeone. And it happens again, and again, and again... Till the stack is full.
When it's static, it is called only one time, with first usage of this class.

A: The problem with the first example is that the the NodeOne class contains an instance of the same class.
When the class is initialized the member field is initialized, wich in turn causes its own field to be initialized and so on, in a never ending loop (actually it ends when the jvm reaches the maximum stack size, as every constructor called uses a bit of it).
It's generally considered to be bad practice to have such a field in a class, as it can lead to this type or errors. Note that it is ok to instantiate the class in main.

A: Your problem here is that you're making a recursive call.  When you call the constructor NodeOne(), it tries to go to the class NodeOne and check for its attributes.  It finds the attribute nodeone there, which needs an instantiation using the constructor, which will allocate a new memory address for the new instance. This instance also contains the attribute nodeone, which also needs instantiation. Here it loops and loops until it consumes all the JVM memory. But if you use static it will allocate only a single memory address, whose content java will modify for every instantiation.


text:
Q: GNUPG: Suppress message while deleting public key I am using the GNUPG tool for performing encryption/decryption using the command line. While deleting the public key I am giving the following command :
gpg2 --quite --yes --delete-key "Solveon DB"
After the command gets executed I get the question
Delete this key from the keyring? (y/N)
I dont want this question to be asked. Can you suggest which option to use. I tried specifying the fingerprint but I couldn't figure out the use.
1 hour ago - 4 days left to answer. I had created a C# wrapper class to use the tool but when using delete option it hangs the application as its waiting for answer to the question.
Additional Details
Link for commands:
I have used the software which I downloaded from this site:
http://www.gpg4win.org/
http://www.linuxguide.it/command_line/linux-manpage/do.php?file=gpg

A: use following
gpg2 --batch --yes --delete-key "Solveon DB"

Please note that it will only work when you want to delete the public key .

A: You've got a typo in your question (it's --quiet, not --quite) but this won't quiet gpg2 down completely.  The option you need in this case is --batch.
To delete a key in batch mode, you'll have to specify it using the fingerprint.  You can find the fingerprints for your keys with this command:
$ gpg2 --list-keys --fingerprint
/home/joeschmoe/.gnupg/pubring.gpg
----------------------------------
pub   2048R/3C6033BD 2012-02-15
      Key fingerprint = EA8B 7339 D8AB 608D D9B6  BFA2 797B 679C 3C60 33BD
uid                  Joe Schmoe <jschmoe@example.com>
sub   2048R/8C61295F 2012-02-15

The fingerprint gets displayed in 4 character groups for easy reading, but when using it to identify the key to delete, drop the spaces and use just the 40 characters of the fingerprint:
$ gpg2 --batch --delete-key EA8B7339D8AB608DD9B6BFA2797B679C3C6033BD

A: Here is another solution to delete all secret keys and then "user123" keys, expired and non-expired.
First script is looking for fingerprint's and make a solid numeric string form their symbols (z.B., ADFG1HJH3JHG5HGTY6KJYY6KJHKK535JNNN).
gpg --list-keys --fingerprint | grep fingerprint | cut -c 25-74 | sed 's/ //g'
Other code is clear for understanding.
#!/bin/bash

function myfunc()
{

local SKEY=$(gpg --list-keys --fingerprint | grep fingerprint | cut -c 25-74 | sed 's/ //g')

echo "$SKEY"

}

SKEY1=$(myfunc)

#echo $SKEY1

gpg --batch --fingerprint --yes --delete-secret-key $SKEY1 <<EOF

$SKEY1

EOF

#rm -rf ex.txt

gpg --batch --yes --delete-key "user123"

A: After puzzling over this myself, I found you can use CMD to delete both public and private keys. Here's the code I used for this:
gpg --batch --yes --delete-key [keyID]
gpg --batch --yes --delete-secret-key [ClientKeyID]

Where the text+square brackets is replaced by the 40 digit key fingerprint, and the lines apply to public and private keys respectively. I call a batch file from within powershell to achieve this and it works perfectly.


text:
Q: Not generating BuildConfig when compiling with gradle command line I'm trying to assemble an apk for a flavor by executing something like:
gradlew installFlavourNameDebug

But I'm getting the following error:

Task :app:compileFlavourNameDebugJavaWithJavac FAILED

The point is that gradle doesn't seems to be generating the BuildConfig which I defined in gradle's app file, defining on the Flavour's definition something like:
buildConfigField "String", "Foo", "\"value\""

According to the official documentation this should be the way, but I don't have any clue of the reason this isn't working. Note that when I build the app with Android Studio by clicking 'Run' there is no problem.

A: Have you run the gradlew with a --stacktrace --debug to get more information? Usually I set the parameters in this way :
buildConfigField("String", "PARAMETER_NAME", '"test"')

A: I answer myself. After performing a clean of the project in Android Studio "gradlew installFlavourNameDebug" worked properly, but I guess that executing "gradlew clean"
should work ok also.


text:
Q: Combination of array items with loops I'm struggling with some loop in loop handling. I want to output one incremental item of the $additional array after each 3 items of the $items array. Also, when we arrive at item-15 in the $items array, I want to start from extra-1 again with $additional array.

$items = array(
    "item-1",
    "item-2",
    "item-3",

    "item-4",
    "item-5",
    "item-6",

    "item-7",
    "item-8",
    "item-9",

    "item-10",
    "item-11",
    "item-12",

    "item-13",
    "item-14",
    "item-15",
);

$additional = array(
    "extra-1",
    "extra-2",
    "extra-3",
    "extra-4",
);

In the end I want to end up with something like this:

    "item-1",
    "item-2",
    "item-3",
"extra-1",
    "item-4",
    "item-5",
    "item-6",
"extra-2",
    "item-7",
    "item-8",
    "item-9",
"extra-3",
    "item-10",
    "item-11",
    "item-12",
"extra-4",
    "item-13",
    "item-14",
    "item-15",
"extra-1"

I tried some stuff with different loops (for, foreach and while) in combination with different counters.
Any help is appreciated!

A: The following code does the job:
$length = count($items);
$additionalLength = count($additional);
for ($i = 1; $i <= $length; ++$i) {
    echo $items[$i - 1] . "\n";
    if ($i % 3 === 0) {
        echo $additional[(($i / 3) - 1) % $additionalLength] . "\n";
    }
}


text:
Q: Card flip doesn't work on Safari. I think it is because of CSS It works fine on Chrome, Firefox, MS Edge but it does not display properly on safari. Block is supposed to flip 360 degrees and display the image; however, it just become blank in safari, and I am not sure what is the problem. Thank you for reading this post!
This is my react script:
<div
              className={
                'aspect-w-1 aspect-h-1 bg-blue-500' + (img0 ? ' flip-card' : '')
              }
              onClick={() => setImg0(true)}
            >
              <img
                src={posts && posts[0].image}
                alt=''
                className={
                  'object-cover object-center max-w-6/4 transition ease-in duration-1000' +
                  (img0 ? ' opacity-100' : ' opacity-0')
                }
              />
            </div>

This is my CSS script:
@layer utilities {
  .flip-card {
    -ms-transform: rotateY(360deg);
    -webkit-transform: rotateY(360deg);
    -moz-transform: rotateY(360deg);
    -o-transform: rotateY(360deg);
    transform: rotateY(360deg);
    -webkit-transition: transform 2000ms;
    -ms-transition: transform 2000ms;
    -moz-transition: transform 2000ms;
    -o-transition: transform 2000ms;
    transition: transform 2s;
    -webkit-transform-style: preserve-3d;
    -ms-transform-style: preserve-3d;
    -moz-transform-style: preserve-3d;
    -o-transform-style: preserve-3d;
    transform-style: preserve-3d;
  }
}

A: I figured it out, and it was not visible on safari because of I didn't add perspective value
<div
    className={
      'aspect-w-1 aspect-h-1 bg-blue-500 card transition duration-[2000ms]' +
      (img0 ? ' flip-card' : '')
    }
    onClick={() => setImg0(true)}
  >
    <img
      src={posts && posts[0].thumb}
      alt=''
      className={
        'object-cover object-center max-w-[150%] transition delay-500 duration-1000' +
        (img0 ? ' opacity-100' : ' opacity-0')
      }
    />
</div>

.animation-delay-2000 {
    animation-delay: 2s;
  }
  .animation-delay-4000 {
    animation-delay: 4s;
  }

  .perspective {
    -webkit-perspective: 1800px;
    perspective: 1800px;
  }

  .card {
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    -webkit-transform: rotateY(0deg);
    transform: rotateY(0deg);
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
  }
  .flip-card {
    -webkit-transform: rotateY(360deg);
    transform: rotateY(360deg);
  }

A: Wrap the text inside front and back divs in another div and a p tag.
then in css, for the div put
{position: relative;
  -webkit-transform-style: preserve-3d;
  transform-style: preserve-3d;
  -webkit-backface-visibility: hidden;
  -moz-backface-visibility: hidden;
  -o-backface-visibility: hidden;
  backface-visibility: hidden;}

and for the p, put
position: relative;
  transform: translate3d(0, 0, 2px) perspective(2px);


text:
Q: Different results between matrix operations in MATLAB and Python I am implementing PCA between a set of generated images and suppressing the background of the images using the selected principal components.  I have implemented this in MATLAB and receive exactly the results I was expecting.  But when I implement this in Python my results are much different. The process is as follows, I first generate my image dataset, perform the PCA on the dataset, calculate and subtract the background from the images in the dataset, and then reshape my dataset and compare my results to the original.  Below is my function performing the PCA on the original dataset.
def pca_images(total_images, count, size, num_pcs):
    flat_images = np.empty([count, size*size])
    # unravel structure of the image
    for i in range(0,count):
        flat_images[i] = np.ravel(total_images[i])
    # calculate covariance matrix
    cov_mat = np.cov(flat_images.T)
    # eigenvectors and eigenvalues of the covariance matrix
    eig_val_cov, eig_vec_cov = np.linalg.eig(cov_mat)
    # sort the (eigenvalue, eigenvector) lists from low to high
    inds = eig_val_cov.argsort()
    # flip around and sort eigenvectors high to low
    eig_vec_cov = eig_vec_cov[inds[::-1]]
    # take num_pcs number of eigenvectors
    components = eig_vec_cov[:,0:num_pcs]
    # create list to store background for each image
    bg = []
    # find principal components
    for i in range(0,count):
        bg.append(np.dot(np.dot(components.T,flat_images[i]),components.T))
    # allocate array to hold filtered images
    images_suppressed = []
    # filter out background from each image and store
    for i in range(0,count):
        images_suppressed.append(flat_images[i] - bg[i])
    return images_suppressed

When I compare this to my MATLAB code the difference appears to be occurring in the bg matrix found in the pca_images function.  In MATLAB this matrix contains only real values but in Python it is filled with real and complex values.  In MATLAB the results show the images_suppressed pixels are all less then the original image pixel values since a bg value is being subtracted from the original image.  Yet in Python some of my images_suppressed values are larger then the original image pixel values despite the subtraction and this leads to noise actually being added to my images.  The MATLAB code used to find the bg matrix is below:
%// CALCULATE THE COVARIANCE MATRIX BETWEEN ALL IMAGES
total_cov = cov(total);
%// FIND THE 6 LARGEST MAGNITUDE EIGENVALUES
[V,D] = eigs(total_cov);
%// FIND PRINCIPAL COMPONENTS AND REMOVE BACKGROUND
proc_total = total;
v = V(:,1:m)';                      %'// TAKE TOP M EIGENVECTORS
for i=1:m
    z = proc_total(i,:);            %// TAKE ORIGINAL DATA
    [size(v), size(z')]             %'// VERIFY SIZES FOR MULTIPLICATION
    bg =  v * z';                   %'// FIND PRINCIPAL COMPONENT
    [size(bg'), size(v)]            %'// VERIFY SIZES FOR MULTIPLICATION
    bg = bg' * v;                   %'
    proc_total(i,:) = proc_total(i,:) - bg;  %// REMOVE BACKGROUND FROM ORIGINAL DATA
end

%// RESHAPE IMAGE 1
image_final = reshape(proc_total(1,:),n,n);

I know the issue has to do with this bg matrix and I haven't been able to find anything that would explain why the multiplication of my eigenvectors with the original dataset is giving me different results in MATLAB and Python.  Can anyone explain to me why this is happening ??


text:
Q: Is there a way to mark the end of each protobuf-net record I am saving a series of protobuf-net objects in a database cell as a Byte[] of length-prefixed protobuf-net objects:
//retrieve existing protobufs from database and convert to Byte[]
object q = sql_agent_cmd.ExecuteScalar();
older-pbfs = (Byte[])q;

// serialize the new pbf to add into MemoryStream m
//now write p and the new pbf-net Byte[] into a memory stream and retrieve the sum

var s = new System.IO.MemoryStream();
s.Write(older-pbfs, 0, older-pbfs.Length);
s.Write(m.GetBuffer(), 0, m.ToArray().Length); // append new bytes at the end of old
Byte[] sum-pbfs = s.ToArray();

//sum-pbfs = old pbfs + new pbf. Insert sum-pbfs into database

This works fine. My concern is what happens if there is slight db corruption. It will no longer be possible to know which byte is the length prefix and the entire cell contents would have to be discarded. Wouldn't it be advisable to also use some kind of a end-of-pbf-object indicator (kind of like the \n or EOF indicators used in text files). This way even if a record gets corrupted, the other records would be recoverable.
If so, what is the recommended way to add end-of-record indicators at the end of each pbf.
Using protobuf-netv2 and C# on Visual Studio 2010.
Thanks
Manish

A: If you use a vanilla message via Serialize / Deserialize, then no: that isn't part of the specification (because the format is designed to be appendable).
If, however, you use SerializeWithLengthPrefix, it will dump the length at the start of the message; it will then know in advance how much data is expected. You deserialize with DeserializeWithLengthPrefix, and it will complain loudly if it doesn't have enough data. However! It will not complain if you have extra data, since this too is designed to be appendable.
In terms of Jon's reply, the default usage of the *WithLengthPrefix method is in terms of the data stored exactly identical to what Jon suggests; it pretends there is a wrapper object and behaves accordingly. The differences are:

*

*no wrapper object actually exists

*the "withlengthprefix" methods explicitly stop after a single occurrence, rather than merging any later data into the same object (useful for, say, sending multiple discreet objects to a single file, or down a single socket)

The difference in the two "appendable"s here is that the first means "merge into a single object", where-as the second means "I expect multiple records".
Unrelated suggestion:
s.Write(m.GetBuffer(), 0, m.ToArray().Length);

should be:
s.Write(m.GetBuffer(), 0, (int)m.Length);

(no need to create an extra buffer)

A: (Note: I don't know much about protobuf-net itself, but this is generally applicable to Protocol Buffer messages.)
Typically if you want to record multiple messages, it's worth just putting a "wrapper" message - make the "real" message a repeated field within that. Each "real" message will then be length prefixed by the natural wire format of Protocol Buffers.
This won't detect corruption of course - but to be honest, if the database ends up getting corrupted you've got bigger problems. You could potentially detect corruption, e.g. by keeping a hash along with each record... but you need to consider the possibility of the corruption occurring within the length prefix, or within the hash itself. Think about what you're really trying to achieve here - what scenarios you're trying to protect against, and what level of recovery you need.


text:
Q: Why do branches of math vary in proof styles and what category are different branches in? Some branches of math seem to have reasoning which is more global.  There is a lot of efficiency in the proofs because the reasoning transfers easily between proofs. For other branches of math, a lot of truths seem to be more local.  The proofs tend to have lots of sub-cases and exceptions.  There are fewer general principles.  Does anybody know why branches of math vary like this?  Can you place different branches of math on this scale from being dominated by more ad hoc to being dominated by less ad hoc proofs?

A: The only thing this reminds me of is Tim Gowers's nice article on the two cultures of mathematics, in which he compares and contrasts "geometry" (very broadly defined) and combinatorics.
The categories in the article don't exactly match up with the categories in the question, but perhaps there's some point of contact.

A: This reminds me of Terry Tao's essay contrasting hard analysis and soft analysis:

At first glance, the two types of
  analysis look very different; they
  deal with different types of objects,
  ask different types of questions, and
  seem to use different techniques in
  their proofs.

and

I therefore feel that it is often
  profitable for a practitioner of one
  type of analysis to learn about the
  other, as they both offer their own
  strengths, weaknesses, and intuition,
  and knowledge of one gives more
  insight into the workings of the
  other.

A: Could some of it have to do with the difference between say considering very general structures versus working in a specific structure? For example, if one is trying to prove existence of a solution (in some sense) to PDEs, one may need to work on finding a priori bounds for some specific PDEs. The techniques used to find these bounds may or may not be able to be generalized (for example, many PDEs of interest have non-linear terms of differing "flavors"). Then on the other hand, is searching for a priori bounds alone something that the existence theories of these different PDEs have in common, if you will?
As far as "global reasoning," this type of reasoning would seem to be the correct approach when dealing with general structures (examples: Banach Spaces, Algebras, &c). If one is interested in proving statements about structures without imposing too many assumptions, then it would seem that thinking "globally" might be beneficial.


text:
Q: Como saber si una PK esta en otra tabla en sql server La consulta es la siguiente.
Tengo una tabla cultura con primary key CulturaID.
Lo que necesito es hacer un procedimiento almacenado, donde elimine un registro de la tabla cultura mediante el ID, pero para poder elimarlo no se tiene que estar referenciando en otra tabla y usando esa id.
Tengo lo siguiente que busca que tabla esta haciendo referencia y cual es la columna.
select OBJECT_NAME(f.parent_object_id),
    COL_NAME(fc.parent_object_id,fc.parent_column_id)
    from sys.foreign_keys as f
    inner join sys.foreign_key_columns as fc
    on f.object_id = fc.constraint_object_id
    inner join sys.tables as t
    on t.object_id = fc.referenced_object_id
    where OBJECT_NAME(f.referenced_object_id) = 'Cultura'

Pero ¿como hago para eliminar el registro de la tabla Cultura si no se esta usando en alguna otra tabla.?

A: El siguiente script borrará el registro solo si no tiene registros relacionados, si está relacionado, en cambio mostrará un mensaje de error indicando las tablas donde tiene registros relacionados.
declare @TableName nvarchar(128);
declare @ColumnName nvarchar(128);
declare @sSQL nvarchar(max);
declare @Contador bigint;
declare @ErrorMsg nvarchar(max) = '';
declare @idABuscar bigint = 16;

declare cLlaves cursor for
    select   OBJECT_NAME(f.parent_object_id) TableName
           , COL_NAME(fc.parent_object_id,fc.parent_column_id) ColumnName
     from sys.foreign_keys as f
          inner join sys.foreign_key_columns as fc on f.object_id = fc.constraint_object_id
          inner join sys.tables as t on t.object_id = fc.referenced_object_id
    where OBJECT_NAME(f.referenced_object_id) = 'Nomenclatura';

open cLlaves;

fetch next from cLlaves into @TableName, @ColumnName;

while @@FETCH_STATUS = 0
begin
  set @sSQL = 'select @Contador = count(1) from ' + QUOTENAME(@TableName) + ' where ' + QUOTENAME(@ColumnName) + ' = ' + cast(@idABuscar as nvarchar);
  exec sp_executesql @sSQL, N'@Contador bigint output', @Contador output;
  if @Contador > 0
    set @ErrorMsg = @ErrorMsg + ' ' + @TableName;
  fetch next from cLlaves into @TableName, @ColumnName;
end;

if @ErrorMsg = ''
  delete from Nomenclatura where idNomenclatura = @idABuscar;
else
begin
  set @ErrorMsg = 'No se puede eliminar porque tiene registros asociados en las siguientes tablas: ' + @ErrorMsg;
  raiserror(@ErrorMsg, 16, 1);
end;
close cLlaves;
deallocate cLlaves;

Dicho esto, debieras configurar tu integridad referencial, para que hacer algo como esto no sea necesario. De hecho, ya tienes declaradas llaves foráneas entre las tablas, de otra forma el query no devolvería filas. Para cada llave foránea puedes indicar una regla de borrado. Si es cascada, al borrar el registro maestro, se borrarán los detalles. En cambio, si la regla es bloquear, al haber registros relacionados, el motor mismo generará un mensaje de error apropiado.
Por otro lado, el script tiene la limitante que solo trabaja con llaves foráneas simples, es decir, con un solo campo de relación. No funcionará correctamente si hay una llave compuesta.


text:
Q: Python set variable from list to new value without pointing to new location Short version:
If x = [[True], [False]], and n = x[0], is it possible/how do I set x[0] to an integer using only n?
Long version:
I'm trying to write a voxel type script which is using a lot of recursive lists, and I'm wondering if there's an alternative to = that won't overwrite the value of a variable set to an item in the list.
Take this as a basic example:
l = [0, [[[2], 0], 0], 0]
path = [1, 0, 0]

cur = l
for i in path
    cur = cur[i]

print cur
#[2]

Here's some examples of what can be done to update the list:
cur.append(3)
print l
#[None, [[[2, 3], 0], 0], 0]

cur[0] = 3
print l
#[0, [[[3], 0], 0], 0]

However, I'd like to be able to set the [2] value to something else, so that in the style of the above examples, l becomes [0, [[3, 0], 0], 0]. A bit like the below code, which obviously won't work:
cur = 3
print l
#[0, [[[2], 0], 0], 0]

I could follow the path down again just removing one level each time, but for 5 levels of recursion, that would be 120 calculations as opposed to just 5. I was thinking there might be some sort of function like find_id(l).set_value(int, 3) that's built in but not commonly used. Apologies if this has an answer already but I'm not sure what to search for.

A: The best you can do is stop one short when processing the path, so rather than finding cur, you instead find prev.  You can then use the last index of path to modify cur within prev.  For example:
l = [0, [[[2], 0], 0], 0]
path = [1, 0, 0]

prev = l
for i in path[:-1]:
    prev = prev[i]

prev[path[-1]] = 3
print l

This prints:
[0, [[3, 0], 0], 0]

Of course, this only works if path is non-empty.


text:
Q: Python unit testing on class methods with no input arguments Given a class with class methods that contain only self input:
class ABC():
    def __init__(self, input_dict)
        self.variable_0 = input_dict['variable_0']
        self.variable_1 = input_dict['variable_1']
        self.variable_2 = input_dict['variable_2']
        self.variable_3 = input_dict['variable_3']

    def some_operation_0(self):
        return self.variable_0 + self.variable_1

    def some_operation_1(self):
        return self.variable_2 + self.variable_3

First question: Is this very bad practice? Should I just refactor some_operation_0(self) to explicitly take the necessary inputs, some_operation_0(self, variable_0, variable_1)? If so, the testing is very straightforward.
Second question: What is the correct way to setup my unit test on the method some_operation_0(self)?
Should I setup a fixture in which I initialize input_dict, and then instantiate the class with a mock object?
@pytest.fixture
def generator_inputs():
    f = open('inputs.txt', 'r')
    input_dict = eval(f.read())
    f.close()
    mock_obj = ABC(input_dict)

def test_some_operation_0():
    assert mock_obj.some_operation_0() == some_value

(I am new to both python and general unit testing...)

A: Those methods do take an argument: self.  There is no need to mock anything.  Instead, you can simply create an instance, and verify that the methods return the expected value when invoked.
For your example:
def test_abc():
    a = ABC({'variable_0':0, 'variable_1':1, 'variable_2':2, 'variable_3':3))
    assert a.some_operation_0() == 1
    assert a.some_operation_1() == 5

If constructing an instance is very difficult, you might want to change your code so that the class can be instantiated from standard in-memory data structures (e.g. a dictionary).  In that case, you could create a separate function that reads/parses data from a file and uses the "data-structure-based" __init__ method, e.g. make_abc() or a class method.
If this approach does not generalize to your real problem, you could imagine providing programmatic access to the key names or other metadata that ABC recognizes or cares about.  Then, you could programmatically construct a "defaulted" instance, e.g. an instance where every value in the input dict is a default-constructed value (such as 0 for int):
class ABC():
    PROPERTY_NAMES = ['variable_0', 'variable_1', 'variable_2', 'variable_3']

    def __init__(self, input_dict):
        # implementation omitted for brevity
        pass

    def some_operation_0(self):
        return self.variable_0 + self.variable_1

    def some_operation_1(self):
        return self.variable_2 + self.variable_3

def test_abc():
    a = ABC({name: 0 for name in ABC.PROPERTY_NAMES})
    assert a.some_operation_0() == 0
    assert a.some_operation_1() == 0


text:
Q: Fixing bad spelling suggestions Is there any way in macOS to fix or improve spelling suggestions that are very obviously wrong, like this one?

Is there some setting somewhere that can be tweaked to make spellcheck less dumb/aggressive?


text:
Q: How can I desc order in vectors C++ I have C++ code like below.
It works well but my output like this :
192.168.1.163 => 4 times
192.168.1.165 => 7 times
192.168.1.20 => 62 times

How can I make desc order like :
192.168.1.20 => 62 times
192.168.1.165 => 7 times
192.168.1.163 => 4 times

    std::map<std::string, int> stringCount; //str is ip and int is logged count

    while(std::getline(readIp, ipLine))//go line by line
    {
        std::istringstream ss(ipLine);
        ipLine.erase(std::remove(ipLine.begin(), ipLine.end(), '"'), ipLine.end()); //removed "

        stringCount[ipLine]++; //increment the count
    }
    readIp.close();
    std::cout<<"Total number of ip's are logged on the system :"<<stringCount.size()<<std::endl;
    std::ofstream outputFile("times.txt");

    for(std::pair<std::string, int> pairElement: stringCount)
    {
        std::cout<<pairElement.first<<" => "<<pairElement.second<<" times "<<std::endl;
        outputFile<<pairElement.first<<" => "<<pairElement.second<<" times \n";
    }

A: Since it is not possible to sort a std::map by its values you can use something like a std::vector as shown below. The program below writes the ip addresses in decreasing order of count values as you want.
#include <iostream>
#include <map>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm>
//create a function that will be used as comparator
bool sortInDecreasingOrder(std::pair<std::string, int> const &a, std::pair<std::string, int> const &b)
{
    return a.second > b.second;
}

int main() {

    //this map maps each word in the file to their respective count
    std::map<std::string, int> stringCount;
    std::string word, line;
    int count = 0;//this count the total number of words

    std::ifstream inputFile("log.txt");
    if(inputFile)
    {
        while(std::getline(inputFile, line))//go line by line
        {
            std::istringstream ss(line);

            //increment the count
            stringCount[line]++;

        }
    }
    else
    {
        std::cout<<"File cannot be opened"<<std::endl;
    }

    inputFile.close();

    std::cout<<"Total number of unique ip's are:"<<stringCount.size()<<std::endl;

    //since we cannot sort a std::map by its second value we can create a vector and sort that vector
    std::vector<std::pair<std::string, int>> vec(stringCount.begin(), stringCount.end());

    //now you can sort this vector
    std::sort(vec.begin(), vec.end(), sortInDecreasingOrder);

    //lets create a output file and write into it the unique ips
    std::ofstream outputFile("code.txt");

    for(std::pair<std::string, int> pairElement: vec)//note this time we go through vector vec instead of map
    {
        std::cout<<pairElement.first<<" => "<<pairElement.second<<" times "<<std::endl;
        outputFile<<pairElement.first<<" => "<<pairElement.second<<" times \n";

    }
    outputFile.close();
    return 0;
}

The output of the program can be seen here.


text:
Q: Automate whitelisting ip addresses in iptables via bash I am looking for the best way to automate whitelisting IP addresses into iptables. The list of ip addresses and ports comes from a JSON file /accept-rules.json which is formatted like:
[
  {
    "ip": "1.2.3.4",
    "cidr": 32,
    "protocol": "tcp",
    "port": 3306
  },
  {
    "ip": "2.4.5.6",
    "cidr": 32,
    "protocol": "tcp",
    "port": 80
  },
  {
    "ip": "5.6.7.8",
    "cidr": 32,
    "protocol": "tcp",
    "port": 443
  },
  {
    "ip": "6.8.3.1",
    "cidr": 32,
    "protocol": "tcp",
    "port": 53
  }
]

I need a bash or python script which reads the json file and creates ACCEPT iptables rules. Example ACCEPT rules based on the json above should look like:
iptables -A INPUT -s 1.2.3.4/32 -p tcp -m tcp --dport 3306 -j ACCEPT
iptables -A INPUT -s 2.4.5.6/32 -p tcp -m tcp --dport 80 -j ACCEPT
iptables -A INPUT -s 5.6.7.8/32 -p tcp -m tcp --dport 443 -j ACCEPT
iptables -A INPUT -s 6.8.3.1/32 -p tcp -m tcp --dport 53 -j ACCEPT

Any idea of the best way to code this up?

A: Pure bash based on syntax provided
There is a cleaner pure bash version. (without eval)
declare -A iptArray
iptArray[action]='A'
getval() {
    [[ "$@" =~  \"([^\*]*)\"\ *:\ *\"?([^\",]*)\"?[,\ ]*$ ]] && \
        iptArray[${BASH_REMATCH[1]}]=${BASH_REMATCH[2]}
}
while read line;do
    getval $line
    [[ "$line" =~ } ]] && \
        echo iptables -${iptArray[action]} INPUT -p ${iptArray[protocol]} \
            -s ${iptArray[ip]}/${iptArray[cidr]} \
            --dport ${iptArray[port]} -j ACCEPT
  done < ipt_whitelist.json
iptables -A INPUT -p tcp -s 1.2.3.4/32 --dport 3306 -j ACCEPT
iptables -A INPUT -p tcp -s 2.4.5.6/32 --dport 80 -j ACCEPT
iptables -A INPUT -p tcp -s 5.6.7.8/32 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 6.8.3.1/32 --dport 53 -j ACCEPT

(Delete echo for doing action instead of just printing it)
Working over json under bash, using jq tool
As you know have to found values named protocol, ip, cidr and port in each field, you could ensure ordering and extract values by using jq in something like:
i=0
while :;do
    for var in proto ip mlen port ;do
        read -r $var
        [ "${!var}" = "null" ] && break 2
    done < <(
      jq -r ".[$i].protocol,.[$i].ip,.[$i].cidr,.[$i].port" <whitelist.json
    )
    echo iptables -A INPUT -p $proto -s $ip/$mlen -dport $port -j ACCEPT
    ((i++))
done
iptables -A INPUT -p tcp -s 1.2.3.4/32 -dport 3306 -j ACCEPT
iptables -A INPUT -p tcp -s 2.4.5.6/32 -dport 80 -j ACCEPT
iptables -A INPUT -p tcp -s 5.6.7.8/32 -dport 443 -j ACCEPT
iptables -A INPUT -p tcp -s 6.8.3.1/32 -dport 53 -j ACCEPT

(Again: Delete echo for doing action instead of just printing it)

A: Here is a python code:
This will generate a bash script file 'accept.sh' with all the iptable entries.
# accept.py

fp = open("accept-rules.json", "r")

data = fp.readlines()
fp1 = open("accept.sh", "w")

for line in data:

    if "{" in line:
        datum = {}
    elif "}" in line:
        s = "iptables -A INPUT -s " + datum["ip"] + "/" + datum["cidr"] + " -p " + datum["protocol"] + " -m " + datum["protocol"] + " --dport " + datum["port"] + " -j ACCEPT\n"
        fp1.write(s)
    elif "[" in line or "]" in line:
        continue
    else:
        datum[line.split(":")[0].strip().strip('"')] = line.split(":")[1].strip().strip(",").strip('"')

fp1.close()
fp.close()

A: Note that iptables -A adds rules to the end of the table. When matching rules, iptables works from top to bottom and the first match wins so if you had previously blocked an address then white listing it with -A won't work (many default rulesets hav a blaket reject all at the end for example) It's better to use iptables -I to insert rules at the begining in this case.
#!/bin/bash

function getval {
    set -- $1
    RET=${2//[\",]/}
}
while read line
    do
        set -- $line
        if [[ "$1" == '"ip":' ]]
            then
                getval "$line"
                IPADDRESS=$RET
                read line
                getval "$line"
                CIDR=$RET
                read line
                getval  "$line"
                PROTOCOL=$RET
                read line
                getval "$line"
                PORT=$RET
                /sbin/iptables  -I INPUT -s "$IPADDRESS"/"$CIDR" -p "$PROTOCOL" -m "$PROTOCOL" --dport "$PORT" -j ACCEPT
             fi
    done <file.json

A: A cleaner Python version:
#!/usr/bin/env python
import json
import sys

for rule in json.load(sys.stdin):
    print("iptables -I INPUT -s {ip}/{cidr} -p {protocol} "
          "-m {protocol} --dport {port} -j ACCEPT".format(**rule))

Note: It uses -I to insert rules at the beginning.
Example
$ json2iptables < accept-rules.json

Output
iptables -I INPUT -s 1.2.3.4/32 -p tcp -m tcp --dport 3306 -j ACCEPT
iptables -I INPUT -s 2.4.5.6/32 -p tcp -m tcp --dport 80 -j ACCEPT
iptables -I INPUT -s 5.6.7.8/32 -p tcp -m tcp --dport 443 -j ACCEPT
iptables -I INPUT -s 6.8.3.1/32 -p tcp -m tcp --dport 53 -j ACCEPT

A: Python implementation:
import json
rules_file = open('accept-rules.json', 'r')
rules = json.load(rules_file)
rules_file.close()
iptables = open('iptavles.sh', 'w')
for rule in rules:
    rule_str = 'iptables -A INPUT -s %s/%s -p tcp -m %s --dport %s -j ACCEPT\n' % (rule['ip'], rule['cidr'], rule['protocol'], rule['port'])
    iptables.write(rule_str)
iptables.close()

accept-rules.json - start json file,
iptables.sh - goal file


text:
Q: Entity Framework - Crash on Detaching list of objects I am working on a winform application with EF 4.0.
Below code, crashes with issue 'The object cannot be detached because it is not attached to the ObjectStateManager.' when it tries to detach the list from context.
public List<Users> FindUserList()
        {
            List<Users> lstUsers = null;
            var q = from c in context.Users
                    select c;
            lstUsers = q.ToList();
            //context.Detach(lstUsers.First());
            context.Detach(lstUsers);
            return lstUsers;
        }

Surprisingly, it works fine if I detach only one object from the list as I have done in the commented code.
Can someone tell, why it crashes when it tries to detach a list? Also, How can we detach all objects of the list?

A: That is because lstUsers is not an entity. But the entity returned by lstUsers.First() is tracked by EF.

A: Try adding .AsNoTracking() to the Users DbSet to detach it from the context. See below.
List<Users> lstUsers = null;
var q = from c in context.Users.AsNoTracking()
       select c;
 lstUsers = q.ToList();
 return lstUsers;

MSDN Reference
https://msdn.microsoft.com/en-us/library/gg679352(v=vs.103).aspx
StackOverflow question regarding AsNoTracking
What difference does .AsNoTracking() make?


text:
Q: How can I set up a route just for my Account controller in ASP MVC5? I have the following route:
http://127.0.0.1:81/Account/Login

My route controller looks like this:
        routes.MapRoute(
            "Account",
            url: "Account/{action}/{id}",
            defaults: new { controller = "Account" }
            );

Can someone tells me if this is the correct way to set up a route. Do I need to even specify defaults: new { controller = "Account" } ?

A: You have to specify controller as well as action
       routes.MapRoute(
        "Account",
         url: "{controller}/{action}/{id}",
         defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
        );


text:
Q: Querying nested arrays in MongoDB & PHP I'm using MongoDB with PHP's own driver and I have saved multiple arrays under main document. Structure looks like this:
{
 _id: 234234234324,
 accounts: {
    0: {
        enabled: 1,
        name: 'asdf'
    },
    1: {
        enabled: 0,
        name: 'gfsd'
    }
}

Accounts are removed and added by the user so I have no control over the array key. I need to somehow get all accounts that have enabled: 1. I tried array("accounts.enabled"=>1) but it doesn't work. And suggestions?

A: In your schema accounts isn't nested array, it's actually complex object, because of this array("accounts.enabled"=>1) will not work (you actually can check only particular element -> array("accounts.0.enabled"=>1)).
Solution of your problem can be schema redesign as follows:
{
 _id: 234234234324,
 accounts: [
    {
        enabled: 1,
        name: 'asdf',
        id: 0
    },
    {
        enabled: 0,
        name: 'gfsd',
        id: 1
    }]
}

If you will make above changes, your query will work.


text:
Q: How to reduce the empty space in SVG React ant design circular progressbar? I wanted to reduce the empty space inside the SVG area and I tried to reduce the height but it not reflecting
<Progress
      width="180px"
      height="80px"
      type="dashboard"
      percent={75}
      gapDegree={130}
      strokeWidth={12}
    />


text:
Q: Node.js Buffers vs Typed Array - performance To send binary messages with WebSocket, I can use either Node.js Buffers or Typed Arrays.
Is there a significantly difference in term of performance between them ?

A: As they both utilise raw memory under the hood, I doubt you will find any noticeable performance differences in general. That being said, performance is usually more about how you use these structures.
As you should never prematurely optimise, it is unlikely that a choice between two with regards to performance is going to make any difference to your application. I would suggest choosing the type whose api best suits your needs, making your code more readable, and easier to debug. TypedArrays would allow you to have consistent code at both client and server, while Buffers don't need to be initialised to zero. Each would have other pros and cons.
If performance did eventually become an issue, these types could also easily be swapped out, and separately profiled.


text:
Q: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. when I run uwsgi In my virtual environment, when I use uwsgi --ini uwsgi.ini to run the uWSGI.
I get the bellow error:
mapped 543168 bytes (530 KB) for 20 cores
*** Operational MODE: threaded ***
Traceback (most recent call last):
  File "Qiyun02/wsgi.py", line 18, in <module>
    from 管理员后台.网站管理.admin_website_chat.views import sio
  File "./管理员后台/网站管理/admin_website_chat/views.py", line 2, in <module>
    from 管理员后台.用户管理admin_usermanage.models import User
  File "./管理员后台/用户管理/admin_usermanage/models.py", line 6, in <module>
    from django.contrib.auth.models import AbstractUser
  File "/home/lll/repo/myProject/venv_dist/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/home/lll/repo/QmyProjectyun02/venv_dist/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 52, in <module>
    class AbstractBaseUser(models.Model):
  File "/home/lll/repo/myProject/venv_dist/lib/python3.5/site-packages/django/db/models/base.py", line 110, in __new__
    app_config = apps.get_containing_app_config(module)
File "/home/lll/repo/myProject/venv_dist/lib/python3.5/site-packages/django/apps/registry.py", line 247, in get_containing_app_config
    self.check_apps_ready()
  File "/home/lll/repo/myProject/venv_dist/lib/python3.5/site-packages/django/apps/registry.py", line 125, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 32347)
spawned uWSGI worker 1 (pid: 32349, cores: 20)
spawned uWSGI http 1 (pid: 32350)

But in my virtual environment I use the python check, there is no issues.
(venv_dist) [ldl@www myProject]$ python3 manage.py check
System check identified no issues (0 silenced).

I also can python3 manage.py runserver in my virtual environment.
Why there get this AppRegistryNotReady error when I run uwsgi?

Or, does the uwsgi support non-latin characters? I have some Chinese characters there.

A: Traceback (most recent call last):
  File "Qiyun02/wsgi.py", line 18, in <module>
    from 管理员后台.网站管理.admin_website_chat.views import sio
  ...

you should not import things from your view in uwsgi.py, because django has not setup when uwsgi.py is loaded.

and when you run python3 manage.py runserver, it has nothing to do with uwsgi.py.

A: Because when use the the django has not setup, you should setup it before your code:
import django

django.setup()
... # your code

Hope this help you.