text:
Q: Vba vba runtime error -1802485755(94904005) i have a strange problem, vba return me the error vba runtime error -1802485755(94904005) and i searched on internet and i found nothing, so i am tring to ask here if someone can help me
here is the code
Private Sub CommandButton3_Click()
    Dim str As New Classe1
    Dim ricerca As String
    Dim dmi As outlook.MailItem
    Dim UTCdate As Date, UTCdate2 As Date
    Dim out As outlook.Application
    Dim DATA1 As Date
    Dim DATA2 As Date
    Dim errorN As Long

    On Error GoTo FormatoErrato:
    DATA1 = DateAdd("h", 1, Res.DataStart.Value)
    DATA2 = DateAdd("h", 23, Res.DataEnd.Value)
    On Error GoTo 0
    Set out = New outlook.Application
    Set dmi = out.CreateItem(olMailItem)

    UTCdate = dmi.PropertyAccessor.LocalTimeToUTC(DATA1)
    UTCdate2 = dmi.PropertyAccessor.LocalTimeToUTC(DATA2)

    ricerca = "@SQL=""urn:schemas:httpmail:subject"" LIKE '%sometext%'" & _
    " AND ""urn:schemas:httpmail:datereceived"" <= '" & UTCdate2 & "'" & _
    " AND ""urn:schemas:httpmail:datereceived"" >= '" & UTCdate & "'"

    str.prova (ricerca)

FormatoErrato:
    errorN = Err.Number
    If errorN = 13 Then
        MsgBox "invalid format", vbCritical
    End If
End Sub

this code (in a class module) is on a userform button where you set two dates and then the following code search the emails that strike the requirments
Sub prova(val As String)
    Res.Mezzi.Clear

    Dim fol As outlook.Folder
    Dim arr, arr2
    Dim ricerca As String, txt As String
    Dim n As Long, s As Long, tot As Long, l As Long
    Dim mi As outlook.MailItem
    Dim i As Object
    Dim doc As Word.Document

    Set fol = 'outlook folder path'
    s = 0
    n = 1

    ReDim Preserve arr2(0 To s)

    For Each i In fol.Items.Restrict(val)
        If i.Class = olMail Then
        Set mi = i

        Set doc = mi.GetInspector.WordEditor
            If doc.Tables.Count > 0 Then
                For tot = 1 To doc.Tables.Count
                    arr2(s) = Application.WorksheetFunction.Clean(doc.Tables(tot).Cell(2, 2).Range.Text)
                    s = s + 1
                    ReDim Preserve arr2(0 To s)
                Next tot
            End If
        End If
    Next i

    For s = 0 To UBound(arr2)
        If IsEmpty(arr2(s)) = False And arr2(s) <> "" Then
            Res.Mezzi.AddItem arr2(s)
        End If
    Next s
End Sub

the email that i'm looking for has a table, one or more in it so i used getinspector.wordeditor to check if the table exist and then take the data that i need from it.
the sub works fine if the difference between the dates is just few days if i put a week give that error
coudl you help me to solve the problem or work around it?
thanks in advance

A: I didn't find any information which Office version is installed on the system. So, if you have a pretty old version of MS Office installed the following case makes sense - the WordEditor property is only valid if the IsWordMail method returns True and the EditorType property is olEditorWord.
The most-likely possible reason for such errors at runtime is security settings when dealing with the Outlook object model. The message body is a protected property in the Outlook object model which can generate errors when Outlook is automated from an external application. You can find the list of protected properties described on the Protected Properties and Methods page.
So, the Object Model Guard warns users and prompts users for confirmation when untrusted applications attempt to use the object model to obtain email address information, store data outside of Outlook, execute certain actions, and send email messages. If, for any reason, the warning is not appropriate or can't be displayed, the Outlook object model may generate errors when accessing protected properties.
In your scenario you can:

*

*Use a low-level API which doesn't trigger security issues in the Outlook object model - Extended MAPI or any other third-party wrapper around that API.

*Create a COM add-in which has access to the trusted Application object and which doesn't trigger security issues.

*Install any AV with the latest updates.

*Use group policy settings to setup security settings to not trigger security issues.

A: after many trials i think i solved
to avoid to raise the error i should close the inspector.
in this way:
If i.Class = olMail Then
    Set mi = i
    Set insp = mi.GetInspector
    Set doc = insp.WordEditor
        If doc.Tables.Count > 0 Then
            For tot = 1 To doc.Tables.Count
                arr2(s) = Application.WorksheetFunction.Clean(doc.Tables(tot).Cell(2, 2).Range.Text)
                s = s + 1
                ReDim Preserve arr2(0 To s)
            Next tot
        End If
    End If
     insp.Close olSave

now all seems to work fine even with range of 10 days of emails


text:
Q: html empty select resizes when an element is added I have an empty select component with a fixed width that has options added to it by Javascript. It uses a scrollbar by default. When the page loads, this element isn't quite the right height. When an option is added, the select element resizes to the correct height and stays that way until the page is reloaded or the list of options cleared. Is there a way I can make the selector load at the correct height without initializing it with an option?

function addOpt() {
  let selector = document.getElementById("selector");
  let opt = document.createElement("option");
  opt.innerHTML = "New option";
  selector.appendChild(opt);
}
<select size="8" style="width: 250px;" id="selector">
</select>

<button type="button" onclick="addOpt()">Click me</button>

A: Try this:
<!DOCTYPE html>

    <select size="8" style="width: 250px" id="selector"></select>

    <button type="button" onclick="addOpt()">Click me</button>

getSelectHeight give us the real height of the selector with the specified rowsCount. Here we add a non visible selector with rowsCount items, get the real height of it and remove the selector.
On body onload we run setSelectorHeight: find our selector, check the number of rows (size attribute) and set the height of the selector. I use the style because setting offsetHeight doesn't work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do i find the iloc of a row in pandas dataframe? I have an indexed pandas dataframe. By searching through its index, I find a row of interest. How do I find out the iloc of this row?
Example:
dates = pd.date_range('1/1/2000', periods=8)
df = pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])
df
                   A         B         C         D
2000-01-01 -0.077564  0.310565  1.112333  1.023472
2000-01-02 -0.377221 -0.303613 -1.593735  1.354357
2000-01-03  1.023574 -0.139773  0.736999  1.417595
2000-01-04 -0.191934  0.319612  0.606402  0.392500
2000-01-05 -0.281087 -0.273864  0.154266  0.374022
2000-01-06 -1.953963  1.429507  1.730493  0.109981
2000-01-07  0.894756 -0.315175 -0.028260 -1.232693
2000-01-08 -0.032872 -0.237807  0.705088  0.978011

window_stop_row = df[df.index < '2000-01-04'].iloc[-1]
window_stop_row
Timestamp('2000-01-08 00:00:00', offset='D')
#which is the iloc of window_stop_row?

A: While pandas.Index.get_loc() will only work if you have a single key, the following paradigm will also work getting the iloc of multiple elements:
np.argwhere(condition).flatten()   # array of all iloc where condition is True

In your case, picking the latest element where df.index < '2000-01-04':
np.argwhere(df.index < '2000-01-04').flatten()[-1]  # returns 2

A: You want the .name attribute and pass this to get_loc:
In [131]:
dates = pd.date_range('1/1/2000', periods=8)
df = pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])
df

Out[131]:
                   A         B         C         D
2000-01-01  0.095234 -1.000863  0.899732 -1.742152
2000-01-02 -0.517544 -1.274137  1.734024 -1.369487
2000-01-03  0.134112  1.964386 -0.120282  0.573676
2000-01-04 -0.737499 -0.581444  0.528500 -0.737697
2000-01-05 -1.777800  0.795093  0.120681  0.524045
2000-01-06 -0.048432 -0.751365 -0.760417 -0.181658
2000-01-07 -0.570800  0.248608 -1.428998 -0.662014
2000-01-08 -0.147326  0.717392  3.138620  1.208639

In [133]:
window_stop_row = df[df.index < '2000-01-04'].iloc[-1]
window_stop_row.name

Out[133]:
Timestamp('2000-01-03 00:00:00', offset='D')

In [134]:
df.index.get_loc(window_stop_row.name)

Out[134]:
2

get_loc returns the ordinal position of the label in your index which is what you want:
In [135]:
df.iloc[df.index.get_loc(window_stop_row.name)]

Out[135]:
A    0.134112
B    1.964386
C   -0.120282
D    0.573676
Name: 2000-01-03 00:00:00, dtype: float64

if you just want to search the index then so long as it is sorted then you can use searchsorted:
In [142]:
df.index.searchsorted('2000-01-04') - 1

Out[142]:
2

A: IIUC you could call index for your case:
In [53]: df[df.index < '2000-01-04'].index[-1]
Out[53]: Timestamp('2000-01-03 00:00:00', offset='D')

EDIT
I think @EdChums answer is what you want. Alternatively you could filter your dataframe with values which you get, then use all to find the row with that values and then pass it to the index:
In [67]: df == window_stop_row
Out[67]:
                A      B      C      D
2000-01-01  False  False  False  False
2000-01-02  False  False  False  False
2000-01-03   True   True   True   True
2000-01-04  False  False  False  False
2000-01-05  False  False  False  False
2000-01-06  False  False  False  False
2000-01-07  False  False  False  False
2000-01-08  False  False  False  False

In [68]: (df == window_stop_row).all(axis=1)
Out[68]:
2000-01-01    False
2000-01-02    False
2000-01-03     True
2000-01-04    False
2000-01-05    False
2000-01-06    False
2000-01-07    False
2000-01-08    False
Freq: D, dtype: bool

In [69]: df.index[(df == window_stop_row).all(axis=1)]
Out[69]: DatetimeIndex(['2000-01-03'], dtype='datetime64[ns]', freq='D')

A: You could try looping through each row in the dataframe:
    for row_number,row in dataframe.iterrows():
        if row['column_header'] == YourValue:
            print row_number

This will give you the row with which to use the iloc function


text:
Q: Highcharts.js: how can stacked area graph animations be smooth? I'm trying to make a realtime-updating stacked area graph in Highcharts.js. The problem is that the "area" of the graph disappears during .addPoint() animation.
I'm trying to achieve this effect: http://jsfiddle.net/DgKKX/5/
...But when I try it for area graphs, this happens: http://jsfiddle.net/DgKKX/6/
Anyone got a clue on how to make the "area" animate as well?

A: Try duration and easing options of animation property similar to jsfiddle.net/DgKKX/5
Maybe you could also change area to 'areaspline' so that graph will be smooth


text:
Q: SQL Server Cross Apply speed issue I have two views on separate servers that I am joining together into one view.
This is my query:
SELECT *
FROM
(
 SELECT v1.Name COLLATE DATABASE_DEFAULT as Name, v1.Year as Year
 FROM AgentCallsByMonth v1
 UNION
 SELECT v2.Name as Name, v2.Year as Year
 FROM BH1PCIMD01.eGActiveDB.dbo.AgentChatsByMonth v2
 ) as u CROSS APPLY (
              SELECT
                     ISNULL(v1.[Month],v2.[Month]) as [Month],
                     ISNULL(v2.[Chats], 0) AS [Chats], ISNULL(v1.[Calls], 0) AS [Calls]
              FROM master..spt_values v
                LEFT JOIN AgentCallsByMonth v1 ON v.number = v1.[MM] AND v1.Name = u.Name and v1.Year=u.Year
                LEFT JOIN BH1PCIMD01.eGActiveDB.dbo.AgentChatCountByMonth v2 ON v.number = v2.[MM] AND v2.Name = u.Name and v2.Year=u.Year
              WHERE v.type = 'P' AND v.number < 12 and u.Year = 2012
              ) o

For some reason this is taking forever. If I pull the data from the tables individually it takes less than 30 seconds. Last run of the query above is at 24 minutes and counting.
A little background on what needs to happen.
I have two tables that have a user name, month in a 00-mon format, and a count. Now some months are null as the user did not have any items in count, thus they do not populate. So we are creating the months and putting 0's in there. However in the other table they could have some items in count for a month they did not have a count in the other table.
For example.
Table 1
JoeUser 01-Jan 48
JoeUser 03-Mar 12
JoeUser 09-Sep 3

Table 2
JoeUser 01-Jan 12
JoeUser 02-Feb 4
JoeUser 05-May 6

This is the resulting output:
JoeUser 01-Jan 48 12
JoeUser 02-Feb 0 4
JoeUser 03-Mar 12 0
JoeUser 04-Apr 0 0
JoeUser 05-May 0 6
JoeUser 06-June 0 0
etc

A: I agree with all the comments before mine, but something else I should point out is that adding the collation using "COLLATE DATABASE_DEFAULT" - will most prob cause a slow down, especially if you table is rather large. Remember, it has to do this for every single row returned.


text:
Q: Format input text file strictly using sed I have this text file named file.txt with the content bellow:
Name,Height,Width,Area,Colour
Rec1,5,10,50,Black
Rec2,8,11,88,Red
Rec3,9,13,117,Red
Rec4,13,16,208,Blue
Rec5,15,17,262,Red
Rec6,17,19,341,Green
Rec7,20,21,430,Black
Rec8,22,23,528,Red
Rec9,25,25,637,Blue
Rec10,27,27,756,Green
Rec11,30,29,885,Black
Rec12,32,31,1023,Blue
Rec13,35,33,1172,Red
Rec14,37,35,1331,Blue
Rec15,40,37,1500,Black
Rec16,42,39,1678,Green
Rec17,45,41,1867,Red
Rec18,47,43,2066,Blue
Rec19,50,45,2275,Black
Rec20,52,47,2493,Red

I need to format it to have to output from the attached picture, using a bash script and pretty much only using linux sed command

What I came up with so far:
sed -n '/Name/{h}; /Rec/{x; s/,/:/g; s/Height.*$//g; p; x; p}' file.txt

A: Try this:
sed 1d file.txt | sed -E 's/([^,]+),([^,]+),([^,]+),([^,]+),([^,]+)/Name: \1\tHeight: \2\tWidth: \3\tArea: \4\tColour: \5\t/'

Thanks,
Stefan


text:
Q: Absolute value of a generator of the different Let $K$ be an algebraic function field over $\mathbb F_q$, in other words $K$ is a finite extension of $\mathbb F_q(t)=F$; furthermore fix a valuation $v$ on $K$.
Consider the relative different ideal $\mathfrak D_v$  with respect to $K|F$. It tourns out that $\mathfrak D$ is a principal ideal of the valuation ring $\mathcal O_v$, so suppose that $\mathfrak D=d\mathcal O_v$.
I would like to know a way to calculate $|d|_v$ where $|\cdot|_v$ is the  absolute value associated to $v$.
Many sources (mainly texts on Tate's thesis) claim that $|d_v|=\frac{1}{\#(\mathcal O_v/\mathfrak D_v)}$, but I don't understand why this is true. Also it is not clear why $\#(\mathcal O_v/\mathfrak D_v)$ is finite.


text:
Q: Django save image from url and connect with ImageField I have in models.py:
class Item(models.Model):
    image_file = models.ImageField(upload_to='images')
    image_url = models.URLField()

I want django automatically download and locally save image from image_url and "connect" it with image_file
How it should act:

*

*I Paste https://docs.djangoproject.com/s/img/site/hdr_logo.gif
into image_url field in admin

*Click "save"

*In templates write <img src="{{ item.image_file.url }}">. It shows
image from my server, not djangoproject.com
What I've tried:
I've overwritten save method of Item class. I saved image locally via urllib, but I am stuck on connecting this saved image with image_file field

A: For python3
from django.core.files import File
from urllib import request
import os

class Item(models.Model):
    image_file = models.ImageField(upload_to='images')
    image_url = models.URLField()

...

def get_remote_image(self):
    if self.image_url and not self.image_file:
        result = request.urlretrieve(self.image_url)
        self.image_file.save(
                os.path.basename(self.image_url),
                File(open(result[0], 'rb'))
                )
        self.save()

from here: http://stackoverflow.com/questions/17960942/attributeerror-module-object-has-no-attribute-urlretrieve

A: Python3
from django.db import models
from django.core.files import File
from urllib.request import urlopen
from tempfile import NamedTemporaryFile

class Item(models.Model):
    image_file = models.ImageField(upload_to='images')
    image_url = models.URLField()

    def save(self, *args, **kwargs):
        if self.image_url and not self.image_file:
            img_temp = NamedTemporaryFile(delete=True)
            img_temp.write(urlopen(self.image_url).read())
            img_temp.flush()
            self.image_file.save(f"image_{self.pk}", File(img_temp))
        super(Item, self).save(*args, **kwargs)

It`s similar but with automated save 'image_file', when add 'image_url'

A: from django.core.files import File
import os

class Item(models.Model):
    image_file = models.ImageField(upload_to='images')
    image_url = models.URLField()

...

def get_remote_image(self):
    if self.image_url and not self.image_file:
        result = urllib.urlretrieve(self.image_url)
        self.image_file.save(
                os.path.basename(self.image_url),
                File(open(result[0]))
                )
        self.save()

You can override the default save() method to automatically invoke get_remote_image().
See: https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-model-methods

A: from django.db import models
from django.core.files import File
from urllib.request import urlopen
from tempfile import NamedTemporaryFile

class Item(models.Model):
    image_file = models.ImageField(upload_to='images')
    image_url = models.URLField()

...

def get_remote_image(self):
    if self.image_url and not self.image_file:
        img_temp = NamedTemporaryFile(delete=True)
        img_temp.write(urlopen(self.image_url).read())
        img_temp.flush()
        self.image_file.save(f"image_{self.pk}", File(img_temp))
    self.save()

This solution avoid any utf-8 errors received during url process.
It works only with python 3.6+ because the f string.
Check this link: https://twigstechtips.blogspot.com/2012/04/django-programmatically-saving-image.html


text:
Q: Could not find a generator for route RouteSettings("/GeneralAnnouncements", null) in the _WidgetsAppState When i run this and press on the button it gets the error (Could not find a generator for route RouteSettings("/GeneralAnnouncements", null) in the _WidgetsAppState. So can I know what is the problem here? As i want to use only named routes so please don't recommend for me to use .push as it doesn't suit me. The problem is in this Navigator.pushNamed(context, '/GeneralAnnouncements'); line but I don't know why?
This is my code:
class home extends StatelessWidget {
  const home({key}) : super(key: key);
  static const routeName = '/home';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Color(0xFF6D0131),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            CircleAvatar(
                radius: (100),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(110),
                  child: Image.asset('images/logo.png'),
                )),
            SizedBox(
              height: 10.0,
            ),
            GestureDetector(
              onTap: () {
                Navigator.pushNamed(context, '/GeneralAnnouncements');
              },
              child: Padding(
                padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
                child: Container(
                  height: 100.0,
                  decoration: BoxDecoration(
                    color: Color(0xFF8D0235),
                    borderRadius: BorderRadius.circular(20.0),
                  ),
                  margin: EdgeInsets.only(bottom: 10.0),
                  padding: EdgeInsets.only(left: 18.0),
                  child: Center(
                    child: Text(
                      '        General \nAnnouncements',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 35.0,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ),
            ),

          ],
        ),
      ),
    );
  }
}

This is the MaterialApp:
runApp(MaterialApp(
    initialRoute: '/homepage',
    routes: {
      "/homepage": (context) => MyHomepage(),
      '/login': (context) => LoginScreen(),
      '/registration': (context) => RegistrationScreen(),
      "/GeneralAnnouncements": (context) => GeneralAnnouncements(),
      '/MyCalendar': (context) => MyCalendar(),
      "/home": (context) => home(),
    },
  ));

A: Remove MaterialApp from your class Home. Your code like this:
class home extends StatelessWidget {
  const home({key}) : super(key: key);
  static const routeName = '/home';

    @override
      Widget build(BuildContext context) {
        return MaterialApp( // Remove this and return Scaffold directly
          home: Scaffold(
            backgroundColor: Color(0xFF6D0131),
            body: Column(


text:
Q: Inserting another EditText Value into a Database for Android? I have the following code below which I believe sets up my database. Everything works as it should but it only allows me to insert one edit text value and then be displayed in the list view.
Ideally I would like to add time and another edit text field into the database can anyone please help me.
SQLiteOpenHelper
public class TaskDBHelper extends SQLiteOpenHelper {

public TaskDBHelper(Context context) {
    super(context, TaskContract.DB_NAME, null, TaskContract.DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase sqlDB) {

    String sqlQuery =
            String.format("CREATE TABLE %s (" +
                            "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                            "%s TEXT)", TaskContract.TABLE,
                    TaskContract.Columns.TASK);

    Log.d("TaskDBHelper", "Query to form table: " + sqlQuery);

    sqlDB.execSQL(sqlQuery);
}

@Override
public void onUpgrade(SQLiteDatabase sqlDB, int i, int i2) {
    sqlDB.execSQL("DROP TABLE IF EXISTS "+TaskContract.TABLE);
    onCreate(sqlDB);
}

}
MainActivity which updates UI etc, dialogue box works fine
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_meds2);

    updateUI();

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            AlertDialog.Builder builder = new AlertDialog.Builder(Meds2.this); //start builder

            LayoutInflater inflater = Meds2.this.getLayoutInflater();
            final View dialogView = inflater.inflate(R.layout.alert_box, null);
            builder.setView(dialogView);
            final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
            final EditText edt2 = (EditText) dialogView.findViewById(R.id.edit2);

            builder.setTitle("Add a task");
            builder.setMessage("What do you want to do?");

           // final EditText inputField = new EditText(Meds2.this);
          //  final EditText inputField2 = new EditText(Meds2.this);
           // builder.setView(inputField);
           // builder.setView(inputField2);

            builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    String task = edt.getText().toString(); //retrieve vales from fields
                    String task2 = edt2.getText().toString();

                    TaskDBHelper helper = new TaskDBHelper(Meds2.this);

                    SQLiteDatabase db = helper.getWritableDatabase();
                    ContentValues values = new ContentValues();

                    values.clear();
                    values.put(TaskContract.Columns.TASK, task); //place values in db
                    values.put(TaskContract.Columns.TASK, task2);

                    db.insertWithOnConflict(TaskContract.TABLE, null, values,
                            SQLiteDatabase.CONFLICT_IGNORE);

                    updateUI(); //refresh list view
                }
            });

            builder.setNegativeButton("Cancel", null);

            builder.create().show();
        }
    });

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    SQLiteDatabase sqlDB = new TaskDBHelper(this).getWritableDatabase();
    Cursor cursor = sqlDB.query(TaskContract.TABLE,
            new String[]{TaskContract.Columns.TASK},
            null,null,null,null,null);

    cursor.moveToFirst();
    while(cursor.moveToNext()) {
        Log.d("MainActivity cursor",
                cursor.getString(
                        cursor.getColumnIndexOrThrow(
                                TaskContract.Columns.TASK)));
    }
}

private ListAdapter listAdapter;

public void onDoneButtonClick(View view) {
    View v = (View) view.getParent();
    TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
    String task = taskTextView.getText().toString();

    String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
            TaskContract.TABLE,
            TaskContract.Columns.TASK,
            task);

    helper = new TaskDBHelper(Meds2.this);
    SQLiteDatabase sqlDB = helper.getWritableDatabase();
    sqlDB.execSQL(sql);
    updateUI();
}

private void updateUI() {
    helper = new TaskDBHelper(Meds2.this);
    SQLiteDatabase sqlDB = helper.getReadableDatabase();
    Cursor cursor = sqlDB.query(TaskContract.TABLE,
            new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK},
            null, null, null, null, null);

    listAdapter = new SimpleCursorAdapter(
            this,
            R.layout.task_view,
            cursor,
            new String[]{TaskContract.Columns.TASK},
            new int[]{R.id.taskTextView},
            0
    );

    this.setListAdapter(listAdapter);
}

Custom Listview layout
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/taskTextView"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:textSize="20dp"
    android:layout_toLeftOf="@+id/doneButton"
    android:layout_alignBottom="@+id/doneButton"
    android:gravity="center_vertical" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Delete"
    android:id="@+id/doneButton"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:onClick="onDoneButtonClick"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/time"
    android:textSize="20dp"
    android:layout_marginLeft="94dp"
    android:layout_marginStart="94dp"
    android:layout_alignBottom="@+id/taskTextView"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_toRightOf="@+id/doneButton"
    android:gravity="center_vertical"
    />

A: do this
//insert first edittext value
values.put(TaskContract.Columns.TASK, task);
db.insertWithOnConflict(TaskContract.TABLE, null, values,SQLiteDatabase.CONFLICT_IGNORE);

values.clear();

//insert seco edittext value
values.put(TaskContract.Columns.TASK, task2);
db.insertWithOnConflict(TaskContract.TABLE, null, values,SQLiteDatabase.CONFLICT_IGNORE);


text:
Q: How do I uninstall bitdefender? I followed this tutorial to install Bitdefender and now I can't update or upgrade because I'm getting a whole bunch of different erorrs. Screenshot deleted.
I still am getting some errors in my terminal when I try sudo apt update, I followed the tutorial that the previous answer had and it cleared alot of the messages. Screenshot deleted.
Sorry Soren A, I did not know I was not allowed to use screenshots. It won't happen again :)
Here is the output using the grep -nr bitdefender /etc/apt/sources* command : /etc/apt/sources.list.save:58:deb http://download.bitdefender.com/repos/deb/ bitdefender non-free

A: Following an 8 year old tutorial installing some superfluent (if not harmful) piece of software is not a very good idea I guess ;-)
Fix by deleting the file created in the tutorial:
sudo rm /etc/apt/sources.list.d/bitdefender.list

Then you should be able to sudo apt update again.
Note, that some of your warnings are unrelated to that tutorial and won't go away but also won't be a problem (just warnings). Check here how to fix this.


text:
Q: find files recursive and save in dymanic array (VBA) I want to make use of dynamic arrays in VBA in order to save the found strings and use the FileSystemObject to find the files.
The code I currently use is this one
Private Sub cmdStartSearch_Click()
    Dim resultList(0) As String
    Call FindFile(resultList, ".png", "Q:\", True)
End Sub

Private Sub FindFile(ByRef resultList() As String, target As String, ByVal aPath As String, useSubfolders As Boolean)
    Dim myFileSystemObject As FileSystemObject, curFolder As folder, folder As folder
    Dim folColl As Folders, file As file, fileColl As Files
    Set myFileSystemObject = New FileSystemObject
    Set curFolder = myFileSystemObject.GetFolder(aPath)
    Set folderList = curFolder.SubFolders
    Set fileList = curFolder.Files

    For Each file In fileList
        ReDim Preserve resultList(1 To UBound(resultList) + 1) As String
        If InStr(file.Name, target) > 0 Then
            resultList(UBound(resultList)) = file.Name
            Debug.Print file.Name
        End If
    Next

    If useSubfolders Then
        For Each folder In folderList
            DoEvents        'Yield execution so other events may be processed
            If Not foundTarget Then
                 FindFile resultList, target, folder.Path, useSubfolders
            End If
        Next
    End If
    Set myFileSystemObject = Nothing
    Set curFolder = Nothing
    Set folderList = Nothing
    Set fileList = Nothing
End Sub

This fails however with Array is fixed or or temporarily locked.
How can I get around this problem, or solve the original one?

A: I feel this has a far better/easier solution. What you do is loop through the file list as you did but then return a long string with the file names and then finally break it using the Split function which will yield you a String array anyway.
Your code could simply change as,
Private Sub cmdStartSearch_Click()
    Dim resultList() As String
    resultList = Split(FindFile(".png", "Q:\", True), ";")
End Sub

Private Function FindFile(target As String, ByVal aPath As String, useSubfolders As Boolean) As String
    Dim retStr As String
    Dim myFileSystemObject As FileSystemObject, curFolder As folder, folder As folder
    Dim folColl As Folders, file As file, fileColl As Files
    Set myFileSystemObject = New FileSystemObject
    Set curFolder = myFileSystemObject.GetFolder(aPath)
    Set folderList = curFolder.SubFolders
    Set fileList = curFolder.Files

    For Each file In fileList
        If InStr(file.Name, target) > 0 Then
            retStr = retStr & ";" & file.Name
            Debug.Print file.Name
        End If
    Next

    If useSubfolders Then
        For Each folder In folderList
            DoEvents        'Yield execution so other events may be processed
            If Not foundTarget Then
                retStr = retStr & ";" & FindFile(target, folder.Path, useSubfolders)
            End If
        Next
    End If

    Set myFileSystemObject = Nothing
    Set curFolder = Nothing
    Set folderList = Nothing
    Set fileList = Nothing

    If Len(retStr) > 0 Then retStr = Right(retStr, Len(retStr)-1)

    FindFile = retStr
End Function

Why are the variables folderList, fileList, foundTarget not declared in the context?


text:
Q: To build a docker image in drone get an error "/bin/sh: 1: base64: not found ". How to solve it? My .drone.yml file is defined as follows
branches:
  include: [ master, dev ]
  exclude: [ develop, feature/* ]
clone:
  git:
    image: plugins/git
    depth: 50
workspace:
  base: /go
  path: src/xx.com/metis
pipeline:
  build:
    when:
      branch: master
    image: golang:alpine
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - CGO=0
      - GOOS=linux
      - GOARCH=amd64
      - PATH=$PATH:/go
      - GOPATH=/go
    commands:
      - go env
      - go build -v -o metis

To built by drone got error as follows pictures.
"/bin/sh: 1: base64: not found "

A: This problem was solved ! In .drone.yml file at "environment" node - PATH=$GOPATH/bin:/usr/local/bin:$PATH destroyed PATH environment . So delete - PATH=$PATH:/go line code will be ok.
https://github.com/drone/drone/issues/2296


text:
Q: function for counting digits and char in string in Matlab R2015 I have a string inside a cell, for example '5a5ac66'. I want to count the number of digits and chars in that string.
'5a5ac66'= 4 digits (5566) and 3 chars (aac)
How can I do that? Is there any function in MATLAB?

A: Yes, there's a built-in function for that,  isstrprop. It tells you which characters are within the given range, in your case 'digit' or 'alpha'. You can then use nnz to obtain the number of such characters:
str = {'5a5ac66'};
n_digits = nnz(isstrprop(str{1},'digit')); %// digits
n_alpha = nnz(isstrprop(str{1},'alpha')); %// alphabetic

If you have a cell array with several strings:
str = {'5a5ac66', '33er5'};
n_digits = cellfun(@nnz, isstrprop(str,'digit')); %// digits
n_alpha = cellfun(@nnz, isstrprop(str,'alpha')); %// alphabetic

A: A simple (not necessarily optimal) solution is the following:
digits = sum(x >= '0' & x <= '9');
chars = sum((x >= 'A' & x <= 'Z') | (x >= 'a' & x <= 'z'));

A: You could do it with regular expressions. For example:
s = '5a5ac66';
digit_indices = regexp(s, '\d');  %find all starting indices for a digit
num_digits = length(digit_indices); %number of digits is number of indices

num_chars = length(regexp(s, '[a-zA-Z]'));


text:
Q: Using AES encryption with binary FileStream, read + write I've hacked up some other code I've found thanks to SO.  I'm not getting any errors when writing my encrypted data to disk, but I get an "index of bounds" error inside the RijndaelManaged class when reading data back.
This is my class I'm using to create a read and write stream wrapped with AES encryption (this is my actual salt, but I'll be sure to change it before release):
public class Crypto
{
    private static byte[] _salt = Encoding.ASCII.GetBytes("42kb$2fs$@#GE$^%gdhf;!M807c5o666");

    public static Stream CreateCryptoStreamAESWrite(string sharedSecret, Stream stream)
    {
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        // generate the key from the shared secret and the salt
        Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

        // Create a RijndaelManaged object
        RijndaelManaged aesAlg = new RijndaelManaged();
        aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

        // Create a decryptor to perform the stream transform.
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

        // prepend the IV
        stream.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
        stream.Write(aesAlg.IV, 0, aesAlg.IV.Length);

        CryptoStream csEncrypt = new CryptoStream(stream, encryptor, CryptoStreamMode.Write);
        return csEncrypt;
    }

    public static Stream CreateCryptoStreamAESRead(string sharedSecret, Stream stream)
    {
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        // generate the key from the shared secret and the salt
        Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

        // Create a RijndaelManaged object
        // with the specified key and IV.
        RijndaelManaged aesAlg = new RijndaelManaged();
        aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

        // Get the initialization vector from the encrypted stream
        aesAlg.IV = ReadByteArray(stream);

        // Create a decrytor to perform the stream transform.
        ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
        CryptoStream csDecrypt = new CryptoStream(stream, decryptor, CryptoStreamMode.Read);
        return csDecrypt;
    }

    private static byte[] ReadByteArray(Stream s)
    {
        byte[] rawLength = new byte[sizeof(int)];
        if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
            throw new SystemException("Stream did not contain properly formatted byte array");

        byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
        if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
            throw new SystemException("Did not read byte array properly");

        return buffer;
    }
}

Here is some test usage code I wrote:
        FileStream fs = new FileStream("c:\\temp\\test.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.None);
        Stream cs = Crypto.CreateCryptoStreamAESWrite("test", fs);
        BinaryWriter bw = new BinaryWriter(cs);
        bw.Write("test");
        cs.Flush();
        fs.Close();
        fs = new FileStream("c:\\temp\\test.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        cs = Crypto.CreateCryptoStreamAESRead("test", fs);
        BinaryReader br = new BinaryReader(cs);
        string test = br.ReadString();
        if (test != "test")
            throw new Exception("Your Kungfu is not good!");
        fs.Close();

This is the error I get on the br.ReadString() line:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 out
putOffset, PaddingMode paddingMode, Boolean fLast)
   at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(
Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
   at System.Security.Cryptography.CryptoStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.Stream.ReadByte()
   at System.IO.BinaryReader.ReadByte()

A: Looks like I needed to call Close on my Crypto stream.  I was calling Flush, but not Close.  I replaced cs.Flush() with cs.Close() and now it is working.
Hopefully someone can at least learn from the example code in my question, although I imagine there is an easier way to just read/write AES encrypted streams (to/from file or otherwise).


text:
Q: How to direct a user from a page in a Django app to a static web page found on the same server Assume that I have my Django app running at '/var/project/my_django_project/' and I want to direct the user to '/var/project/static_website/index.html' when a button is clicked in a template located at '/var/project/my_django_project/templates/my_template.html'. How can I achieve this?
Edit: I am using apache2 web server


text:
Q: Is string::iterator necessarily a random_access_iterator? This page states that string::iterator and string::const_iterator are "compiler specific iterator types." Does this mean that that string::iterator made be in a category other than random_access_iterator?

A: Looking at N3376 21.4/3

The iterators supported by basic_string are random-access iterators.

For such tasks its always a good idea to have a standard (or draft) at hand. It takes a while to get used to looking up things there, but it is the first hand resource.

A: This page says std::string::iterator is a RandomAccessIterator, and is a lot more trustworthy than cplusplus.com.

A: It doesn't mean it's not a random access iterator (as other answers have said, the standard requires it to be a random access iterator.)
What it means is the exact iterator types are unspecified, i.e. they could be char* or they could be std::string::__iterator or __gnu_cxx::__normal_iterator<char, std::string> or something else.  Any of those implementation choices is allowed, as long as it meets the requirements of a random access iterator and can be referred to by the name string::iterator

A: ISO C++03, 21.3-2 states:

(...)Additionally, because the iterators supported by basic_string are
  random access iterators(...)

So yes, those are necessarily random access iterators.


text:
Q: Listfragment in android How can i trigger new fragment or class opens up when each list item is selected?
Basically i want new fragment to be youtube fragment. when "Android" is selected particular youtube link is pass to that fragment. Same goes to other list items.
import android.R.string;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AddingList extends ListFragment implements OnItemClickListener{
  String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
            "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
            "Linux" };

  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
        android.R.layout.simple_list_item_1, values);
    setListAdapter(adapter);
  }

 @Override
 public void onItemClick(AdapterView adapter, View view, int position, long id) {

  Toast.makeText(getActivity().getBaseContext(), "Item clicked: " + values[position], Toast.LENGTH_LONG).show();

   }
}

have some errors:
import android.R.string;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AddingList extends ListFragment implements OnItemClickListener{
  String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
            "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
            "Linux" };

  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
        android.R.layout.simple_list_item_1, values);
    setListAdapter(adapter);
  }

 @Override
 public void onItemClick(AdapterView adapter, View view, int position, long id) {
     FragmentTransaction ft = FragmentManager.beginTransaction();
     ft.replace(R.id.yourcontainer, new Home());
  //Toast.makeText(getActivity().getBaseContext(), "Item clicked: " + values[position], Toast.LENGTH_LONG).show();

   }
}

A: setonItemClickListner(), and then call fragment
like
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.yourcontainer, new YourClass()).commit();

Regards


text:
Q: how to upload one file many times into folder I want to upload one file many times into folder. Here my code...
foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
{
    string filename = Path.GetFileName(postedFile.FileName);
    string FileExtension = Path.GetExtension(postedFile.FileName);
    for(int i = 1; i <= data.Count;i++)
    {
        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/InvoiceUploads/") + "Invoice "
        + id + "_" + i + FileExtension);
    }
}

this code was to upload one file many times, but the problem is that only one file can open perfectly and the other is given an error and it says empty file.
what's the problem that I don't know?
please anybody help me.
Thank You.

A: why FileUpload1.PostedFile.SaveAs? Use HttpPostedFile .SaveAs(...) instead.
foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(postedFile.FileName);
string FileExtension = Path.GetExtension(postedFile.FileName);
for(int i = 1; i <= data.Count;i++){
     postedFile .SaveAs(Server.MapPath("~/InvoiceUploads/") + "Invoice " + id + "_" + i + FileExtension);
}
}

A: Need to Change code
foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
      {
        string filename = Path.GetFileName(postedFile.FileName);
        string FileExtension = Path.GetExtension(postedFile.FileName);
        string CurrDate = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");

        for(int i = 1; i <= data.Count;i++)
           {
             FileUpload1.PostedFile.SaveAs(Server.MapPath("~/InvoiceUploads/") +
             "Invoice "
              + id + "_" + i + CurrDate + FileExtension);
           }
      }

A: void SendFile()
{
   foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
   {
      string filename = Path.GetFileName(postedFile.FileName);
      string FileExtension = Path.GetExtension(postedFile.FileName);

      // Add a delay
      Thread.Sleep(100);

      for(int i = 1; i <= data.Count;i++){
        postedFile.SaveAs(Server.MapPath("~/InvoiceUploads/") + "Invoice " + id + "_" + i + FileExtension);
    }
}

}


text:
Q: Angular Material Flex-layout when using fxFlex with mat-form-field, the element does not appear in Internet explorer 11 I am using Angular 6 with Material 6 & flex-layout 6-beta , I am currently facing a strange issue, the form fields that have fxFlex property don't appear at all in the IE although they appear & work fine in all other major browsers.
I have already configured the polyfills.ts so that the app work on Internet explorer but I don't have any clue how to fix this issue.
For example, consider the 2 form fields below, the one that doesn't have fxFlex will appear in IE but the other one is not shown
For the 2 paragraphs here, both are shown (even the one having fxFlex), it seems the issue is specifically between (fxFlex, mat-form-field & IE)
  <mat-form-field  fxFlex="25">
      <input matInput name="dob_day" placeholder="{{'dob_day'| translate}}" [(ngModel)]="data.dob_day" pattern='(0?[1-9]|[12][0-9]|3[01])'
        maxlength="2" required>
    </mat-form-field>

    <mat-form-field  >
        <input matInput name="dob_day" placeholder="{{'dob_day'| translate}}" [(ngModel)]="data.dob_day" pattern='(0?[1-9]|[12][0-9]|3[01])'
          maxlength="2" required>
      </mat-form-field>

hello , how are you?

hello , how are you?

My current polyfills.ts:
/***************************************************************************************************
     * BROWSER POLYFILLS
     */

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';

/** IE10 and IE11 requires the following for NgClass support on SVG elements */
import 'classlist.js';  // Run `npm install --save classlist.js`.

/** IE10 and IE11 requires the following for the Reflect API. */
import 'core-js/es6/reflect';

/** Evergreen browsers require these. **/
// Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove.
import 'core-js/es7/reflect';

/**
 * Required to support Web Animations `@angular/platform-browser/animations`.
 * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation
 **/
import 'web-animations-js';  // Run `npm install --save web-animations-js`.

/**
 * By default, zone.js will patch all possible macroTask and DomEvents
 * user can disable parts of macroTask/DomEvents patch by setting following flags
 */

 // (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
 // (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
 // (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames

 /*
 * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
 * with the following flag, it will bypass `zone.js` patch for IE/Edge
 */
// (window as any).__Zone_enable_cross_context_check = true;

/***************************************************************************************************
 * Zone JS is required by default for Angular itself.
 */
import 'zone.js/dist/zone';  // Included with Angular CLI.

/***************************************************************************************************
 * APPLICATION IMPORTS
 */

Any help is appreciated.

A: I have found that in order for IE11 to work correctly with the mat-form-field, you need to wrap the form field in a div tag.  No need to add any attributes to this div tag.
In order to achieve this form layout in IE 11...
IE 11 Form Layout...
Here is the code I used:

    <mat-form-field fxFlex appearance="outline">
      <mat-label>First Name</mat-label>
      <input matInput formControlName="firstName">
    </mat-form-field>
    <mat-form-field fxFlex appearance="outline">
      <mat-label>Last Name</mat-label>
      <input matInput formControlName="lastName">
    </mat-form-field>

    <mat-form-field fxFlex appearance="outline">
      <mat-label>Title</mat-label>
      <input matInput placeholder="Title" formControlName="title">
    </mat-form-field>

Notice the div tag around the "Title" form field.
With this addition, IE 11 behaved nicely and had no affect on rendering by other browsers.


text:
Q: how can i make a key dynamic in a pydantic model i have an api entrypoint:
@app.get('/dealers_get_users/', response_model = schemas.SellSideUserId, status_code=200)
def getdata(db: database.SessionLocal = _Depends(database.get_db)):
    result = {}
    i =  db.query(models.sellSideUser).all()
    for dealer_users in i:
        result[str(dealer_users.user_id)] = {
            'user_name'  :     dealer_users.user_name,
            'user_pass'  :     dealer_users.user_pass,
            }
    m = schemas.SellSideUserId(user_id=result)
    return m

the data coming in from the db is just 3 fields: user_id,user_name,user_pass
when i call the api, i get this:
{
"user_id": {
            "1": {
                  "user_name": "testname",
                  "user_pass": "testpass"
                  }
            }
}

ok, cool - i got my data.  but i'm still trying to understand how these models work, and am not really grasping how to move in or out of a nested dictionary.
for example, i would like it to look like this, instead:
{
            "1": {
                  "user_name": "testname",
                  "user_pass": "testpass"
                  }
}

but i'm not sure how to pass the 'result' variable into this class - any way i do it, i'm met with an error.
my model:
class SellSideUserId(_BaseModel):
    user_id     : dict
    class Config:
        orm_mode = True

am i supposed to build two pydantic models - one being based on another? could use some help with this
thanks!

A: You can easily make a model with dynamic keys using a dict as custom root type:
class User(BaseModel):
    name: str
    password: str

class ProductModel(BaseModel):
    __root__: Dict[str, User]

Moreover, you can constrain dictionary keys using constr сapabilities, such as regex pattern:
UserId = constr(regex=r'^\d+$')

class ProductModel(BaseModel):
    __root__: Dict[UserId, User]

This will work well for validating returned responses against your model. But generated OpenAPI schema will be rather scanty, since at the moment FastAPI 0.68 and swagger UI does not support yet OpenAPI 3.1, which contains such keyword as patternProperties or propertyNames.


text:
Q: Order of hoisting in JavaScript function g () {
    var x;
    function y () {};
    var z;
}

I would like to know exactly what order the above code becomes when hoisted.
Theory 1: Order between vars and functions remains as-is:
function g () {
    var x;
    function y () {};
    var z;
}

Theory 2: vars come before functions:
function g () {
    var x;
    var z;
    function y () {};
}

Theory 3: functions come before vars:
function g () {
    function y () {};
    var x;
    var z;
}

Which theory is correct?

A: Although the order was fixed by the specification, as the accepted answer points out, that order really is not that important.

*

*var declarations are hoisted, but not their initialisation (if there is one). A var declaration is without effect if the name is already taken by a function or other var declaration.

*function definitions are hoisted -- not only declaring the name, but also their value, i.e. the function.

So the following two pieces of code:

(function () {
    console.log(typeof a);
    var a = 1;
    function a() { }
})();

and:

(function () {
    console.log(typeof a);
    function a() { }
    var a = 1;
})();

... translate to:

(function () {
    function a() { }
    var a;
    console.log(typeof a);
    a = 1;
})();

and respectively:

(function () {
    var a;
    function a() { }
    console.log(typeof a);
    a = 1;
})();

The latter two are the same thing really. If the engine processes the hoisted var declaration first, then a is first undefined but then immediately overwritten as function. If on the other hand the function definition is processed first, then the var declaration has no effect. In both scenarios the outcome is the same.

A: Functions are hoisted first, then variable declarations, per ECMAScript 5, section 10.5 which specifies how hoisting happens:
We first have step 5 handling function declarations:

For each FunctionDeclaration f in code, in source text order do...

Then step 8 handles var declarations:

For each VariableDeclaration and VariableDeclarationNoIn d in code, in source text order do...

So, functions are given higher priority than var statements, since the later var statements cannot overwrite a previously-handled function declaration.
 (Substep 8c enforces the condition "If varAlreadyDeclared is false, then [continue...]" so extant variable bindings are not overwritten.)
You can also see this experimentally:

function f(){}
var f;
console.log(f);

var g;
function g(){}
console.log(g);

Both log calls show the function, not an undefined value.


text:
Q: Load image from WebBrowser without redownloading or copying I am currently copying from clip board to load image from browser
IHTMLDocument2 doc = (IHTMLDocument2) webBrowser1.Document.DomDocument;
IHTMLControlRange imgRange = (IHTMLControlRange) ((HTMLBody) doc.body).createControlRange();

foreach (IHTMLImgElement img in doc.images)
{
  imgRange.add((IHTMLControlElement) img);

  imgRange.execCommand("Copy", false, null);

  using (Bitmap bmp = (Bitmap) Clipboard.GetDataObject().GetData(DataFormats.Bitmap))
  {
    bmp.Save(@"C:\"+img.nameProp);
  }
}

But it has some problems using clipboard. Is there any other way to do that. In internet explorer all images go to temp directory, if same happens here is there any way to get path of that saved image?

A: For each image on the page, you can collect its URL then call the WinINET cache enumeration functions (e.g. FindFirstURLCacheEntry) to locate the backing cache file in the Temporary Internet Files folder. However, there's no guarantee that the file will be in the cache because it may have been delivered with headers that forbid caching, etc.
One approach you could consider is using FiddlerCore (www.fiddler2.com/core) in your application; you could then snag all transferred images "off the wire" and do whatever you want with them.


text:
Q: Visual Studio indent HTML tag contents I have Resharper and Web Essentials installed in Visual Studio 2013, and would like to have the contents of an HTML tag in my .cshtml files be indented.
So what I do NOT want (and seems to be the default):

Hello!

I DO want it to look like:

Hello!

I've removed everything from Resharper -> Options -> Code Editing -> HTML -> Formatting Style -> Do Not Indent Children Of.
I've also checked Tools -> Options -> Text Editor -> HTML (Web Forms) -> Formatting -> Tag Specific Options -> Client Specific Tags -> html -> Indent Contents to no avail.
Note that I don't have a Tools -> Options -> Text Editor -> HTML -> Formatting, instead I have two subtrees, HTML and HTML (Web Forms), where only HTML (Web Forms) has the Formatting option.
Anyone know of a way to get Visual Studio to do this? It's very annoying to see my perfectly formatted HTML document go out the window whenever I add a new tag. Thanks!

A: I'm a bit late to the party, but it looks like you can fix this by removing "html, body" from "HTML -> Formatting Style -> (Around tags) Do not indent children of"
See here:

A: One more reason why Resharper doesn't indent tag content - size of tag.
Look for option
Resharper -> Options -> Code Editing -> HTML -> Formatting Style -> Do not indent children if tag size more than
If count of lines too much, Resharper' formatter doesn't indnent it. Try to set value e.g. 10000


text:
Q: How to download a text data set from a website I am interesting in a yeast dataset from UCI (please see the link). The data is saved in text formula. I would like to load it into Rstudio. I saved it in office word (copy and paste). Then, I tried to load it into R studio but I got unclear words instead of the data.
https://archive.ics.uci.edu/ml/datasets/Yeast
Any help please?

A: Grabbing the data is pretty easy; you can just pass the file URL directly to read.table. Getting the names is a lot more work, as they're buried in a text file. If you like, you can extract them with regex:
library(tidyverse)

yeast <- read.table('https://archive.ics.uci.edu/ml/machine-learning-databases/yeast/yeast.data', stringsAsFactors = FALSE)

l <- readLines('https://archive.ics.uci.edu/ml/machine-learning-databases/yeast/yeast.names')
l <- l[(grep('^7', l) + 1):(grep('^8', l) - 1)]
l <- l[grep('\\d\\..*:', l)]

names(yeast) <- make.names(c(sub('.*\\d\\.\\s+(.*):.*', '\\1', l), 'class'))

str(yeast)
#> 'data.frame':    1484 obs. of  10 variables:
#>  $ Sequence.Name: chr  "ADT1_YEAST" "ADT2_YEAST" "ADT3_YEAST" "AAR2_YEAST" ...
#>  $ mcg          : num  0.58 0.43 0.64 0.58 0.42 0.51 0.5 0.48 0.55 0.4 ...
#>  $ gvh          : num  0.61 0.67 0.62 0.44 0.44 0.4 0.54 0.45 0.5 0.39 ...
#>  $ alm          : num  0.47 0.48 0.49 0.57 0.48 0.56 0.48 0.59 0.66 0.6 ...
#>  $ mit          : num  0.13 0.27 0.15 0.13 0.54 0.17 0.65 0.2 0.36 0.15 ...
#>  $ erl          : num  0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 ...
#>  $ pox          : num  0 0 0 0 0 0.5 0 0 0 0 ...
#>  $ vac          : num  0.48 0.53 0.53 0.54 0.48 0.49 0.53 0.58 0.49 0.58 ...
#>  $ nuc          : num  0.22 0.22 0.22 0.22 0.22 0.22 0.22 0.34 0.22 0.3 ...
#>  $ class        : chr  "MIT" "MIT" "MIT" "NUC" ...

...or just copy them all out by hand.


text:
Q: How to right align text with linebreaks in HTML FlexBox I'm working on a website with HTML and want to vertical align the content of a label using FlexBox.
As long as the contents have no  inside it works fine.
But when i got a content like

Right
Bottom
24

the content is handled as a block which is right aligned, but the individual parts of the content are not right aligned at all.
I get per example:
Right
Bottom
24

instead of
Right
Bottom
    24

Here the style which i'm using for the label:

display: flex; justify-content: flex-end; align-items: flex-end;

Have i forgotten something in the style?

A: you should put your content inside HTML element's because flexbox is not ment to work with just text if you wanna aplly your structure on a text use css columns instead of flexbox.


text:
Q: linux bash - ps uax - can not see running script? it is very very strange and i can't figure this ought-to-be-simple thing out:

*

*login as non-root user

*create a script

    user@debian:~$ vim loop.sh

    while true; do
    echo "Yeah!";
    sleep 1;
    done;

    chmod u+x loop.sh; # mark it runnable
    ./loop.sh; # run the script

    Yeah!
    Yeah!
    Yeah!
    ...

*login as root user on a different terminal

    ps uax|grep loop
    -> no result - is this script "invisible" even to root?
tested on:
uname -a
Linux debian 3.16.0-4-686-pae #1 SMP Debian 3.16.39-1+deb8u2 (2017-03-07) i686 GNU/Linux

vim loop.sh
#!/bin/bash <- added this line
while true; do
echo "Yeah!";
sleep 1;
done;

ps uax|grep loop
user      1282  0.0  0.2   5084  2736 pts/0    S+   14:30   0:00 /bin/bash ./loop.sh <- now i can see it

... if this is not mysterious - it seems to be a little strange - and even might have security implications? :-D root can't see what scripts are run by logged in users?
or i am missing something here...
thanks for looking into it.

A: Your tty spawns a new process for bash script to run. Also, as it contains sleep command a new child process for each sleep command gets spawned.
while true do
echo "Yeah!"
echo $$  #Prints pid of running script
sleep 1
done

Once you get PID value from this script output. You can do a grep on the same and you will get the process running.

Script response
Yeah!
54126
Yeah!
54126
Yeah!

ps -eaf | grep 54126
503 54126 21882   0  6:10PM ttys000    0:00.07 -bash
503 54278 54126   0  6:11PM ttys000    0:00.00 sleep 1
503 54294   425   0  6:11PM ttys001    0:00.00 grep 54126

A: When there is no shebang the current shell opens the script an interprets the content so the process information at os level doesn't have the name of script as when the command is called bash ./loop.sh
To retrieve the pid from opened file script file name :
fuser ./loop.sh


text:
Q: How to compare two values of two different child in firebase database I want to display the data based on the scheduled date saved on the database, i tried comparing it to the current date of the device, but it didn't work. This is my saved data from firebase:

This is the Logcat

This is the Adapter class:
 public class ListAdapter extends RecyclerView.Adapter<ListAdapter.MyViewHolder> {

        Context context;

        ArrayList<Reminder> list;

        public ListAdapter(Context context, ArrayList<Reminder> list) {
            this.context = context;
            this.list = list;
        }

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
            return new MyViewHolder(v);
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

            Reminder Reminder = list.get(position);
            holder.t.setText(Reminder.gett());
            holder.d.setText(Reminder.getd());
            holder.tm.setText(Reminder.gettm());
            holder.dt.setText(Reminder.getdt());
            holder.currentDate.setText(Reminder.getcurrentDate());

        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        public static class MyViewHolder extends RecyclerView.ViewHolder {

            TextView t, d, tm, dt, currentDate;

            public MyViewHolder(@NonNull View itemView) {
                super(itemView);

                t = itemView.findViewById(R.id.tvtitle);
                d = itemView.findViewById(R.id.tvdesc);
                tm = itemView.findViewById(R.id.tvtime);
                dt = itemView.findViewById(R.id.tvdate);
                currentDate = itemView.findViewById(R.id.tvcdate);

            }
        }

    }

This is my code to retrieve the data from the database:
 public class ReminderMainActivity extends AppCompatActivity {

RecyclerView recyclerView;
DatabaseReference database;
Calendar calendar = Calendar.getInstance();
String currentdate = DateFormat.getDateInstance().format(calendar.getTime());
com.example.luntian.adapter.ListAdapter ListAdapter;
ArrayList<Reminder> list;

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

    recyclerView = findViewById(R.id.userList);
    database = FirebaseDatabase.getInstance().getReference("Reminder");
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    list = new ArrayList<Reminder>();
    ListAdapter = new ListAdapter(this,list);
    recyclerView.setAdapter(ListAdapter);

    database.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                    Reminder reminder = dataSnapshot.getValue(Reminder.class);
                    list.add(reminder);

                }
                ListAdapter.notifyDataSetChanged();

        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });


text:
Q: Realm class is not part of the schema object Android I have run into this error everytime I make "Clean and rerun app" in Android Studio.
Even though I have the proxy classes, I still have an "Order is no part of the schema object"
I have tried:
1.Clean and rebuild project.
2.Deleted generated build files manually.
3.Uninstall app before deploying.
4.I have realm in my project gradle and app gradle. (version 1.1.0)
5.I have tried with Order extending RealmObject and implementing RealmModel.
6.RealmConfiguration has deleteRealmIfMigrationNeeded.
The only solution I had, was renaming each file but it is really harsh to do it each time I do a clean and re run.
        RealmConfiguration realmConfig = new RealmConfiguration
            .Builder(getApplicationContext())
            .deleteRealmIfMigrationNeeded()
            .name("myRealmFile")
            .build();

        Realm.setDefaultConfiguration(realmConfig);

        Realm realm = Realm.getDefaultInstance();

        RealmResults<Order> orders = realm.where(Order.class).equalTo("finished", false).findAll();

        mHasActiveOrder = orders != null && orders.isValid() && orders.size() > 0;

        realm.close();


text:
Q: Ant Task to FTP only specified files I have an Ant task that FTPs all files in a specified directory, and it uses a fileset:
<fileset dir="${publicDirectory}">
  <include name="media/**/*" />
</fileset>

I have a file that contains all the files that I would like to include:
media/some/dir/1.txt
media/some/other/2.txt
...

How can I have the fileset read the file and only include whatever I've listed there?

A: I've tried quite a few things, but nothing seems to be able to get around a basic issue: The <ftp> task works only on filesets and not other types of resources. I've tried various filterchains, but to no avail.
The best I could come up with was using the Ant-Contrib <for> or <foreach> task to loop through the file and then use an <exec> task to execute the command line version of ftp.


text:
Q: What is the maximum pulse current from a watch battery? I know that a comprehensive answer probably spans 1-2 orders of magnitude. Reasons include different battery sizes, chemistry, etc.
I can't access a lab at the moment or I would just measure it.
I want to draw 10 mA from a watch battery, but only for a few seconds.  The duty cycle is < 10%. The series resistances I've been able to find seem to be < 8 Ohms, so the voltage drop due to internal impedance should be < 0.08 V typically, which is fine.
As far as continuous current goes, the numbers I've been able to find range from 0.01 mA to 0.1 mA. I don't think that 10X that for pulsed is asking a lot, but 100X might be a stretch which is why I'm asking the question.
I know not to actually short the battery for more than a fraction of a second, but if you do short it, is 10 mA a current that most watch batteries can meet or exceed? Duty cycle will be < 10% for about 10 seconds. After that, device shuts off and condition of battery is irrelevant. Is this feasible?
My 2nd question concerns power. It would be nice to draw 12 mW during that short time battery is sourcing power. I realize that's a lot but, is it doable?
I assume larger batteries have a better chance of hitting these numbers than smaller batteries, but if some battery chemistry makes this especially easy that might be more important than mass. Chemistry is also a weak point of mine so pretend you're talking to a 6 year old if you get into chemistry.

A: Requirements:
3V Primary button cell: 10 mA Duty cycle < 10% for about 10s only.
The question rephrased could be what size button or coin cell will guarantee this at room temp?
From my research in electrolytic capacitors and batteries, I have come to realize power density vs ESR has a fairly constant product within a family of slightly different sizes.
Based on Panasonic Specs for a new battery

CR2032  0.19 mAh, Isc=190 mA, ESR 15.8 Ohms , ESR * mAh= 3.0
CR2025  0.163 mAh, Isc=140 mA, ESR 21.4 Ohms, ESR * mAh= 3.5
CR-AGZ  2700 mAh,  Isc=3000mA, ESR = 1 mOhm,  ESR * mAh= 2.7

I use ESR*mAh as a constant with some tolerance.
For maximum power transfer Load if R = ESR, for a 10 mA load, 2*ESR=3V/10mA, ESR=150 Ohms  @ Vbat = 1.5V for MPT
Thus pulse power is \$Pd=V^2/(2*ESR)\$= 7.5 mW  (?)

*

*Your 10 mA load possibly assumed Vbat=3V which at max. power transfer is only 50% or 1.5V may not fit your assumption.
Conclusion
From this, you can decide what size you need by computing Max Power Point (MPP) or Vmin vs Rload to determine ESR max from mAh using ESR*mAh=3  and compute what is possible.  Then test to verify margin with samples and compute confidence level or success from Std Dev and design thresholds.
other info
For LED's I know you can get about the same brightness of RED LED and White LED from a CR2032 5mm right across the cell. The voltage decays in a day approx. with gradual declining current limited by the rising ESR of the cell and slight reduction in Voc.
For low ESR e-caps in the < 100 uF range ESR*C = 1 to 20 us for a good product.  For Std. e-caps it is ESR = 100 to 250 us.  Since RC=T , size and voltage will impact results.


text:
Q: Cox proportional model w/ multiple failures for same subjects I have a data set that I'm trying to model using survival analysis, specifically cox proportional hazard models. The data has patient IDs and several attributes about the patients (including time till failure). Due to the nature of the data, a patient could fail and then fail again later several times. This means that some of the patients are repeated in the data due to multiple failures. However, patients aren't all repeated and when they are, they aren't all repeated the same number of times.
My question is: how should this be handled in cox proportional hazard modeling?
Should each instance be treated as independent (I don't think that would make too much sense)?
Should the patient data be aggregated in some way so that each patient is being included once in the model while still utilizing his/her data from the multiple failures?
Thanks!


text:
Q: do_POST executed more than once when there's an exception I'm building a simple web app using Python as part of an online course, currently I'm trying to implement some CRUD operations. This app is a simple restaurant menu server that connects to an SQLite database (using SQLAlchemy) and executes some CRUD operations on it.
Part of the app serves a simple html form to modify a restaurant name (using POST method), when implementing this operation, an error causes the server to return an empty response, and when looking at the log, no POST request was issued and the do_POST body was executed 3 times.
Here's the body of the do_POST method.
def do_POST(self):
    try:
        if self.path.endswith(....):
            (.....)

        if self.path.endswith('/edit'):
            print('inside post ' + self.path) # debugging message
            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
            if ctype == 'multipart/form-data':
                fields = cgi.parse_multipart(self.rfile, pdict)
                messageContent = fields.get('newRestaurantName')

            r_id = self.path.split('/')[2]
            # if I remove .one() from the instruction bellow, the error goes away.
            # 'session' is an SQLAlchemy DBSession defined above.
            restaurant = session.query(Restaurant).get(r_id).one()

            restaurant.name = messageContent[0]
            session.add(restaurant)
            session.commit()

            self.send_response(301)
            self.send_header('Content-type', 'text/html')
            self.send_header('Location', '/restaurants')
            self.end_headers()
            return
    except:
        (....)

And this is the server output when trying to perform the POST method.
Server running at port 8080
10.0.2.2 - - [25/Oct/2018 23:17:27] "GET /restaurants HTTP/1.1" 200 -
10.0.2.2 - - [25/Oct/2018 23:17:30] "GET /restaurants/1/edit HTTP/1.1" 200 -
inside post /restaurants/1/edit
inside post /restaurants/1/edit
inside post /restaurants/1/edit

After removing the .one() from the query expression, the operation executes without issues.
What I'm trying to understand is why I'm having the debugging message printed three times ! whereas I only performed one (unsuccessful) POST request ? Even if there was an exception, shouldn't the do_POST function only execute once ?
(the server is running from inside a Vagrant VM)
Thank you !


text:
Q: Проверка изображения при загрузке В общем, на сервер загружается изображение следующим образом:
Юзер выбирает изображение на локальном ПК -> файл грузится в tmp, там проверяется размер, тип файла и тд.
Единственное, тчо нужно добавить  - определение размера изображение, и если оно больше, чем  90х90 - обрезать его до этого значения, либо ужать.
Какие примеры реализации есть для этого?
A: в PHP есть встроенная вещь, называется getimagesize, она вернет тебе массив, где [0] - ширина, [1] - высота. А для уменьшения размеров, лучше загуглите библиотеку для работы с картинками (их полным полно) и так проще будет.


text:
Q: convert custom string to json How to convert a string to JSON,
This string to
x:100%,y:20%,radius:50%

Json
{"x":"100%","y":"20%","radius":"50%"}

A: You don't need jQuery for that.
var s = "x:100%,y:20%,radius:50%";
var json = JSON.stringify(
    s.split(',').reduce(function(m,v) {
       var t = v.split(':');
       m[t[0]] = t[1];
       return m;
    }, {})
);

Demonstration
If you want to be compatible with IE8, add a shim for reduce.

A: Its not a good idea, but you can do this:
var j = 'x:100%,y:20%,radius:50%'
j = '{"' + j.replace(/:/g,'":"').replace(/,/g,'","') + '"}'
console.log(j)

{"x":"100%","y":"20%","radius":"50%"}

Then you can parse produced string using JSON
JSON.parse(j)

Object {x: "100%", y: "20%", radius: "50%"}


text:
Q: How to really print EURO sign in c++ application console in Windows My target is to print euro sign - € in c++ application in Windows. Methods that already tried and did not working are:
#include <windows.h>
SetConsoleOutputCP(1252);
cout << "\u20a0";

also  "\u20a0" did not working and without SetConsoleOutputCP(). No working solution by far. So much forums and questions, and no straight answer....

A: This worked for me
SetConsoleOutputCP(1252);
cout << (char)(128);


text:
Q: Examples when wavefunction is changing but probability density is constant? What are examples of wavefunction that changes with time but the square of wavefunction is constant?

A: Energy eigenstates have this property. If a state is an energy eigenstate, then the time-dependent Schrödinger equation is
$$i \hbar \frac{\partial \psi}{\partial t} = H \psi $$
$$= E \psi$$
which is solved by
$$\psi(x,t) = \psi(x)e^{-itE/\hbar}$$
where $\psi(x)$ solves the time-independent Schrödinger equation,
$$H \psi = E \psi$$


text:
Q: Django Error 500: Internal Server Error The website was running without any problem. I recently updated **wcgi.py** and **production.py**, and now I get a 500 error. Here's the detailed response:

********************************************************************************
>Error 500: Internal Server Error

>The server encountered an internal error and was unable to complete your request.

>Error message: (none)

Some possible causes of this could be:

1. The script/program that was executed contains errors or the permissions for the script are not properly set.

2. The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script.
********************************************************************************

**wsgi.py:**
********************************************************************************
import os
from os.path import abspath, dirname
from sys import path

SITE_ROOT = dirname(dirname(abspath(__file__)))
path.append(SITE_ROOT)

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxx.settings.production")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
********************************************************************************

base.py
    ********************************************************************************
    """Common settings and globals. .... base.py"""
from os.path import abspath, basename, dirname, join, normpath
from sys import path

########## PATH CONFIGURATION
DJANGO_ROOT = dirname(dirname(abspath(__file__)))

SITE_ROOT = dirname(DJANGO_ROOT)

SITE_NAME = basename(DJANGO_ROOT)

path.append(DJANGO_ROOT)
########## END PATH CONFIGURATION

########## DEBUG CONFIGURATION
DEBUG = False

TEMPLATE_DEBUG = DEBUG
########## END DEBUG CONFIGURATION

########## MANAGER CONFIGURATION
ADMINS = (
    ('xxx xxx', 'xxx@xxx'),
)

MANAGERS = ADMINS
########## END MANAGER CONFIGURATION

########## DATABASE CONFIGURATION
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}
########## END DATABASE CONFIGURATION

########## GENERAL CONFIGURATION
TIME_ZONE = 'America/Los_Angeles'

LANGUAGE_CODE = 'en-us'

SITE_ID = 1

USE_I18N = True

USE_L10N = True

USE_TZ = True
########## END GENERAL CONFIGURATION

########## MEDIA CONFIGURATION
MEDIA_ROOT = normpath(join(SITE_ROOT, 'media'))

MEDIA_URL = '/media/'
########## END MEDIA CONFIGURATION

########## STATIC FILE CONFIGURATION
STATIC_ROOT = normpath(join(SITE_ROOT, 'assets'))

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    normpath(join(SITE_ROOT, 'static')),
)

STATICFILES_FINDERS = (`enter code here`
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
########## END STATIC FILE CONFIGURATION

########## SECRET CONFIGURATION
SECRET_KEY = r"-40hhv97se0m46r@bv!6&b!l76a#-%(26=z^hcjra!2-z$q#sr"
########## END SECRET CONFIGURATION

########## SITE CONFIGURATION
ALLOWED_HOSTS = []
########## END SITE CONFIGURATION

########## FIXTURE CONFIGURATION
FIXTURE_DIRS = (
    normpath(join(SITE_ROOT, 'fixtures')),
)
########## END FIXTURE CONFIGURATION

########## TEMPLATE CONFIGURATION
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.tz',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.request',
)

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

TEMPLATE_DIRS = (
    normpath(join(SITE_ROOT, 'templates')),
)
########## END TEMPLATE CONFIGURATION

########## MIDDLEWARE CONFIGURATION
MIDDLEWARE_CLASSES = (
    # Default Django middleware.
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'tools.UserBasedExceptionMiddleware',
)
########## END MIDDLEWARE CONFIGURATION

########## URL CONFIGURATION
ROOT_URLCONF = '%s.urls' % SITE_NAME
########## END URL CONFIGURATION

########## APP CONFIGURATION
DJANGO_APPS = (
    # Default Django apps:
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Useful template tags:
    # 'django.contrib.humanize',

    # Admin panel and documentation:
    'django.contrib.admin',
    # 'django.contrib.admindocs',
)

LOCAL_APPS = (
)

INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS
########## END APP CONFIGURATION

########## LOGGING CONFIGURATION
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'applogfile': {
            'level':'ERROR',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': join(DJANGO_ROOT, 'APPNAME.log'),
            'maxBytes': 1024*1024*15, # 15MB
            'backupCount': 10,
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'APPNAME': {
            'handlers': ['applogfile',],
            'level': 'ERROR',
        },
    }
}
########## END LOGGING CONFIGURATION

########## WSGI CONFIGURATION
WSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME
########## END WSGI CONFIGURATION

########## SOUTH CONFIGURATION
INSTALLED_APPS += (
    # Database migration helpers:
    'south',
)
SOUTH_TESTS_MIGRATE = False
########## END SOUTH CONFIGURATION
********************************************************************************

production.py
    ********************************************************************************
    """Production settings and globals."""
from __future__ import absolute_import

from os import environ

from .base import *

from django.core.exceptions import ImproperlyConfigured

def get_env_setting(setting):
    """ Get the environment setting or return exception """
    try:
        return environ[setting]
    except KeyError:
        error_msg = "Set the %s env variable" % setting
        raise ImproperlyConfigured(error_msg)

########## HOST CONFIGURATION
ALLOWED_HOSTS = [xxx.xxx.xxx]
########## END HOST CONFIGURATION

########## EMAIL CONFIGURATION
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST = environ.get('EMAIL_HOST', 'xxx@xxx')

EMAIL_HOST_PASSWORD = environ.get('EMAIL_HOST_PASSWORD', '')

EMAIL_HOST_USER = environ.get('EMAIL_HOST_USER', '')

EMAIL_PORT = environ.get('EMAIL_PORT', 25)

EMAIL_SUBJECT_PREFIX = '[%s] ' % SITE_NAME

EMAIL_USE_TLS = True

SERVER_EMAIL = EMAIL_HOST_USER
########## END EMAIL CONFIGURATION

########## DATABASE CONFIGURATION
DATABASES = {}
########## END DATABASE CONFIGURATION

########## CACHE CONFIGURATION
CACHES = {}
########## END CACHE CONFIGURATION

########## SECRET CONFIGURATION
SECRET_KEY = get_env_setting('SECRET_KEY')
########## END SECRET CONFIGURATION
********************************************************************************

How could I fix this problem?


text:
Q: All possible combinations of elements in vector with repetitions in MATLAB I have 6 numbers with repetition: 1,2,2,3,3,4. I want all possible combinations using any 4 of the numbers. How will I get that in MATLAB?
Generally I use 'nchoosek' function if there is no repetition.
Example: A = 1:6; combinations = nchoosek(A,4);

A: nchoosek is sufficient for this task, and includes repetitions.
A = [1 2 2 3 3 4];
combinations = nchoosek(A, 4);

If you would have wanted not to include any repetitions, you would have done:
combinations = nchoosek(unique(A), 4);


text:
Q: Any more concise way to set default values?
Since PHP 5.3, it is possible to leave out the middle part of the
  ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1
  evaluates to TRUE, and expr3 otherwise.

Is there any better or more concise way than following code to set default value of variables?
$v = isset($v) ? $v : "default value";

A: TL;DR - No, that expression can't be made any shorter.
What you want is for the shortened ternary expression to perform an implicit isset(). This has been discussed on the mailing list and an ifsetor RFC has been created that covers the concept as well.
Since the shortened ternary operator already existed at the time of the above discussion, something like this was proposed using a non-existent operator ??:
// PROPOSAL ONLY, DOES NOT WORK
$v = $v ?? 'default value';

Assign 'default value' if $v is undefined.
However, nothing like this has been implemented in the main language to date. Until then, what you have written can't be made any shorter.
This horrible construct is shorter, but note that it's not the same because it assigns the default value if the variable exists but evaluates to false:
// DO NOT USE
$v = @$v ?: 'default value';

A: Just asked this and was pointed here. So in case you use a key of an array, this might be an improvement
function isset_get($array, $key, $default = null) {
    return isset($array[$key]) ? $array[$key] : $default;
}

A: Here is a shorter syntax:
isset($v) || $v="default value";

A: Nope. That's the right way if you don't really know whether $v is set.

A: No way.If you use ternary operator.


text:
Q: how to sum up number in front of string How do I sum up numbers in front of strings? For example, I have input:
15 humpbacks
3 killer whales
2 sperm whales
19 belugas
2 humpbacks
2 sperm whales
7 killer whales
4 pygmy right whales
7 humpbacks

Then I want to sum up the numbers and be like this:
24 humpbacks
10 killer whales
4 sperm whales
19 belugas
4 pygmy right whales

A: You need to implement a data structure that allows you to map a string with an integer variable. In a loop, you will read a line, parse it, and populate your map. When you parse a line, you would take the string and look it up in your map. If the entry does not exist, create it and initialize the integer variable to 0. If it does exist obtain the variable. In either case, add the number found in the line to the variable. Continue this until you have no more input. At the end of the program, iterate over your map and print out the string and the associated value.


text:
Q: Capture "replies=all" for a User Stream und Phirehose in PHP This a simple question, but I wasn't able to find an answer thus far.
I use the Phirehose library (lib/UserstreamPhirehose.php) to capture the user stream in real time (class MyUserConsumer extends UserstreamPhirehose and I process the enqueueStatus() function).
It all works very well, however by default the stream does not return all replies (as per Twitter documentation: By default @replies are only sent from mutual followings. All @replies by followings can be enabled with the replies=all parameter.)
How do I enable the "replies=all" parameter in the Phirehose library?
Thanks a lot,
Filip

A: I have seen this issue in a number of places but https://groups.google.com/forum/#!topic/phirehose-users/rHARDfPPyiU shows how it may be possible so I've amended the code and it now works.
To achieve this:
1) Add public $params = null; in Phirehose.php
2) In the connect() function replace $requestParams = array() with $requestParams = is_array($this->params) ? $this->params : array();
3) Before you call consume() put $CLASS->params = array('replies'=>'all','with'=>'user'); in your code. (where class is your class name)
This works for me and I hope it works for you.
Thanks.


text:
Q: Binary addition carrying from left to right How would you efficiently implement 64 bit binary addition carrying from left to right? Like flipping the bits then adding:
0101 + 1110 = BitReverse(1010 + 0111)
            = BitReverse(10001)
            = 10001

My current solution is to reverse the bit order of the inputs using delta swaps (and possibly a byteswap intrinsic), use normal addition, then reverse again, which is not particularly fast, but probably better than looping for 64-bit integers. (I haven't tested it but it would still be too slow.)
uint64_t addreverse(uint64_t a, uint64_t b) {
    return BitReverse(BitReverse(a) + BitReverse(b));
}

This is quite slow, as the bits need to be reversed three times, requiring over 40 operations when using byteswap.
EDIT: I cannot store them reversed as I require regular addition as well.

A: Emulating a Kogge-Stone adder, with the shift direction reversed, gives a nice algorithm,
uint64_t p = x ^ y;
uint64_t g = x & y;

g |= p & (g >> 1);
p &= p >> 1;

g |= p & (g >> 2);
p &= p >> 2;

g |= p & (g >> 4);
p &= p >> 4;

g |= p & (g >> 8);
p &= p >> 8;

g |= p & (g >> 16);
p &= p >> 16;

g |= p & (g >> 32);

uint64_t result = x ^ y ^ (g >> 1);

A: I would use LUT tables. Here small C++ 32bit (DOWRD = unsigned __int32_t) example:
//---------------------------------------------------------------------------
// select fastest operation
#define BitReverse BitReverse1
#define AddReverse AddReverseKS
//---------------------------------------------------------------------------
DWORD BitReverseSlow(DWORD x)   // Slow 1bit reversing
    {
    DWORD m0,m1,y;
    for (y=0,m0=1,m1=0x80000000;m0<m1;m0<<=1,m1>>=1)
        {
        if (DWORD(m0&x)) y|=m1;
        if (DWORD(m1&x)) y|=m0;
        }
    return y;
    }
//---------------------------------------------------------------------------
DWORD BitReverse1(DWORD x)
    {
    x=((x<<16)&0xFFFF0000)|((x>>16)&0x0000FFFF);
    x=((x<< 8)&0xFF00FF00)|((x>> 8)&0x00FF00FF);
    x=((x<< 4)&0xF0F0F0F0)|((x>> 4)&0x0F0F0F0F);
    x=((x<< 2)&0xCCCCCCCC)|((x>> 2)&0x33333333);
    x=((x<< 1)&0xAAAAAAAA)|((x>> 1)&0x55555555);
    return x;
    }
//---------------------------------------------------------------------------
DWORD BitReverse8(DWORD x)      // fast 8bit LUT reversing
    {
    DWORD y;
    BYTE *px=(BYTE*)&x;
    BYTE *py=(BYTE*)&y;
    static const BYTE BitReverse8_LUT[256]= // BitReverse8_LUT[x]=BitReverse(x) in 8bits
        {
        0x00,0x80,0x40,0xC0,0x20,0xA0,0x60,0xE0,0x10,0x90,0x50,0xD0,0x30,0xB0,0x70,0xF0,
        0x08,0x88,0x48,0xC8,0x28,0xA8,0x68,0xE8,0x18,0x98,0x58,0xD8,0x38,0xB8,0x78,0xF8,
        0x04,0x84,0x44,0xC4,0x24,0xA4,0x64,0xE4,0x14,0x94,0x54,0xD4,0x34,0xB4,0x74,0xF4,
        0x0C,0x8C,0x4C,0xCC,0x2C,0xAC,0x6C,0xEC,0x1C,0x9C,0x5C,0xDC,0x3C,0xBC,0x7C,0xFC,
        0x02,0x82,0x42,0xC2,0x22,0xA2,0x62,0xE2,0x12,0x92,0x52,0xD2,0x32,0xB2,0x72,0xF2,
        0x0A,0x8A,0x4A,0xCA,0x2A,0xAA,0x6A,0xEA,0x1A,0x9A,0x5A,0xDA,0x3A,0xBA,0x7A,0xFA,
        0x06,0x86,0x46,0xC6,0x26,0xA6,0x66,0xE6,0x16,0x96,0x56,0xD6,0x36,0xB6,0x76,0xF6,
        0x0E,0x8E,0x4E,0xCE,0x2E,0xAE,0x6E,0xEE,0x1E,0x9E,0x5E,0xDE,0x3E,0xBE,0x7E,0xFE,
        0x01,0x81,0x41,0xC1,0x21,0xA1,0x61,0xE1,0x11,0x91,0x51,0xD1,0x31,0xB1,0x71,0xF1,
        0x09,0x89,0x49,0xC9,0x29,0xA9,0x69,0xE9,0x19,0x99,0x59,0xD9,0x39,0xB9,0x79,0xF9,
        0x05,0x85,0x45,0xC5,0x25,0xA5,0x65,0xE5,0x15,0x95,0x55,0xD5,0x35,0xB5,0x75,0xF5,
        0x0D,0x8D,0x4D,0xCD,0x2D,0xAD,0x6D,0xED,0x1D,0x9D,0x5D,0xDD,0x3D,0xBD,0x7D,0xFD,
        0x03,0x83,0x43,0xC3,0x23,0xA3,0x63,0xE3,0x13,0x93,0x53,0xD3,0x33,0xB3,0x73,0xF3,
        0x0B,0x8B,0x4B,0xCB,0x2B,0xAB,0x6B,0xEB,0x1B,0x9B,0x5B,0xDB,0x3B,0xBB,0x7B,0xFB,
        0x07,0x87,0x47,0xC7,0x27,0xA7,0x67,0xE7,0x17,0x97,0x57,0xD7,0x37,0xB7,0x77,0xF7,
        0x0F,0x8F,0x4F,0xCF,0x2F,0xAF,0x6F,0xEF,0x1F,0x9F,0x5F,0xDF,0x3F,0xBF,0x7F,0xFF
        };
    py[0]=BitReverse8_LUT[px[3]];
    py[1]=BitReverse8_LUT[px[2]];
    py[2]=BitReverse8_LUT[px[1]];
    py[3]=BitReverse8_LUT[px[0]];
    return y;
    }
//---------------------------------------------------------------------------
DWORD AddReverseSlow(DWORD x,DWORD y)
    {
    return BitReverse(BitReverse(x)+BitReverse(y));
    }
//---------------------------------------------------------------------------
DWORD AddReverse4(DWORD x,DWORD y)
    {
    int i;
    DWORD z,cy0,cy,a;
    static const BYTE AddReverse4_LUT[16][16]=  // AddReverse4_LUT[x][y]=BitReverse(BitReverse(x<<1)+BitReverse(y<<1)) in 4bits
        {
        { 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 },
        { 2, 1, 6, 5, 10, 9, 14, 13, 18, 17, 22, 21, 26, 25, 30, 29 },
        { 4, 6, 2, 1, 12, 14, 10, 9, 20, 22, 18, 17, 28, 30, 26, 25 },
        { 6, 5, 1, 3, 14, 13, 9, 11, 22, 21, 17, 19, 30, 29, 25, 27 },
        { 8, 10, 12, 14, 4, 6, 2, 1, 24, 26, 28, 30, 20, 22, 18, 17 },
        { 10, 9, 14, 13, 6, 5, 1, 3, 26, 25, 30, 29, 22, 21, 17, 19 },
        { 12, 14, 10, 9, 2, 1, 6, 5, 28, 30, 26, 25, 18, 17, 22, 21 },
        { 14, 13, 9, 11, 1, 3, 5, 7, 30, 29, 25, 27, 17, 19, 21, 23 },
        { 16, 18, 20, 22, 24, 26, 28, 30, 8, 10, 12, 14, 4, 6, 2, 1 },
        { 18, 17, 22, 21, 26, 25, 30, 29, 10, 9, 14, 13, 6, 5, 1, 3 },
        { 20, 22, 18, 17, 28, 30, 26, 25, 12, 14, 10, 9, 2, 1, 6, 5 },
        { 22, 21, 17, 19, 30, 29, 25, 27, 14, 13, 9, 11, 1, 3, 5, 7 },
        { 24, 26, 28, 30, 20, 22, 18, 17, 4, 6, 2, 1, 12, 14, 10, 9 },
        { 26, 25, 30, 29, 22, 21, 17, 19, 6, 5, 1, 3, 14, 13, 9, 11 },
        { 28, 30, 26, 25, 18, 17, 22, 21, 2, 1, 6, 5, 10, 9, 14, 13 },
        { 30, 29, 25, 27, 17, 19, 21, 23, 1, 3, 5, 7, 9, 11, 13, 15 }
        };
    for (cy0=0,z=0,i=28;i>=0;i-=4,cy0=cy)
        {
        a=AddReverse4_LUT[(x>>i)&15][(y>>i)&15]; cy=a&1; a>>=1; // add
        if (cy0){ a=AddReverse4_LUT[8][a]; cy|=a&1; a>>=1; }    // adc
        z|=a<<i;
        }
    return z;
    }
//---------------------------------------------------------------------------
WORD AddReverese8_LUT[256][256];    // LUT[x][y]=BitReverse(BitReverse(x<<1)+BitReverse(y<<1)) in 8bits
DWORD AddReverse8(DWORD x,DWORD y)
    {
    int i;
    DWORD z,cy0,cy,a;
    BYTE *px=(BYTE*)&x;
    BYTE *py=(BYTE*)&y;
    BYTE *pz=(BYTE*)&z;
    for (cy0=0,z=0,i=3;i>=0;i--,cy0=cy)
        {
        a=AddReverese8_LUT[px[i]][py[i]]; cy=a&1; a>>=1;            // add
        if (cy0){ a=AddReverese8_LUT[128][a]; cy|=a&1; a>>=1; }     // adc
        pz[i]=a;
        }
    return z;
    }
//---------------------------------------------------------------------------
DWORD AddReverseKS(DWORD x,DWORD y) // https://en.wikipedia.org/wiki/Kogge–Stone_adder
    {                               // Adder from harold's answer ported to 32bit
    DWORD p=x^y;
    DWORD g=x&y;

    g|=p&(g>> 1); p&=p>> 1;
    g|=p&(g>> 2); p&=p>> 2;
    g|=p&(g>> 4); p&=p>> 4;
    g|=p&(g>> 8); p&=p>> 8;
    g|=p&(g>>16);

    return x^y^(g>>1);
    }
//---------------------------------------------------------------------------

The AddReverse8_LUT is initialized like this:
for (DWORD x=0;x<256;x++)
 for (DWORD y=0;y<256;y++)
  AddReverse8_LUT[x][y]=BitReverse(BitReverse(x<<1)+BitReverse(y<<1));

Here measured times on mine setup:
 8M x BitReverseSlow [ 506.585 ms]
 8M x BitReverse1    [  59.769 ms]
 8M x BitReverse8    [  72.355 ms]
16M x AddReverseSlow [ 611.677 ms]
16M x AddReverse4    [ 491.546 ms]
16M x AddReverse8    [ 347.293 ms]
16M x AddReverseKS   [ 142.149 ms]

As you can see the bigger LUT the better speed at the cost of space. On top of that if the resolution is 8/16/32bit you can use BYTE access by pointer instead of slow bit shift/mask speeding up even more.
Just to be sure the Addition LUT[][] table is encoded such that the addition is shifted to left by 1 bit and the empty space is occupied by Carry flag for the next nibble ...
In the additions when I am doing the adc (incrementing by carry flag) the operand for LUT is 1 bit reversed in LUT bit resolution so
    1000bin =   8dec // 4 bits
10000000bin = 128dec // 8 bits

To port this to 64 bit just change DWORD to your datatype and change the bit masks and iterations count to match 64 bit ...
Anyway this reminds me at my old answer to:

*

*Cant make value propagate through carry
However it looks like non LUT versions of BitReverse are faster
After some digging it looks like LUT usage with temp variables force my compiler to compile my functions differently with great speed decrease (more tan twice). Once all functions are enforced to such calling api the LUT versions are sligthly faster:
 8M x BitReverseSlow [ 537.534 ms]
 8M x BitReverse1    [  99.804 ms] <- this is slowed down due to changing call style to the same as the BitReverse8
 8M x BitReverse8    [  80.725 ms]

so I suspect that for reasonably simple functions my compiler uses Assembly call style (not using heap/stack for operands and returning value).
So the result is that:
using BitReverse1 is faster. Also harolds answer beats mine by far for the same reasons + it has less operations needed ...
However if you would hardwire this (FPGA or on die or using gates) I suspect the LUT versions of BitReverse will be faster (Although you can Hardwire bitreversal directly which is unbeatbale).

A: You want to do it bit-wise and keep track of carry.  Something like:
uint64_t addreverse(uint64_t a, uint64_t b) {
    uint64_t current_bit = 0x8000000000000000ull;
    unsigned int shift = 63;
    unsigned int carry = 0;
    uint64_t sum = 0;
    while (current_bit) {
        uint64_t bit_sum = ((a & current_bit) >> shift) +
                                 ((b & current_bit) >> shift);
        sum += (((bit_sum & 1) + carry) << shift);
        carry = (bit_sum & 2) >> 1;
        current_bit >>= 1;
        --shift;
    }
    return sum;
}