text:
Q: Processing save table with AM or PM in file name I have a project where I have data come in via the serial port every 15 minutes. I am using processing to read this data and save it as a CSV.
I would like for a new file to be created every 12 hours. However, when the file switches from AM to PM the entire row gets saved in the PM file (all the previous AM values)
How can I reset the table and start saving to a new file?
      saveTable(dataTable, fileName());
      dataTable.clearRows();

I tried this but it just clears the CSV file.
String fileName() {
  String fileName = "";
  String month = "";
  String day = "";
  int m = month();
  int d = day();

  if (d < 10) {
    day = str(d);
    day = "-0" + day;
  } else {
    day = "-" + str(d);
  }

  switch(m) {
  case 1:
    month = "-JAN";
    break;
  case 2:
    month = "-FEB";
    break;
  case 3:
    month = "-MAR";
    break;
  case 4:
    month = "-APR";
    break;
  case 5:
    month = "-MAY";
    break;
  case 6:
    month = "-JUN";
    break;
  case 7:
    month = "-JUL";
    break;
  case 8:
    month = "-AUG";
    break;
  case 9:
    month = "-SEP";
    break;
  case 10:
    month = "-OCT";
    break;
  case 11:
    month = "-NOV";
    break;
  case 12:
    month = "-DEC";
    break;
  }

  if (hour() >= 12) {
    hour = "-PM";
  } else {
    hour = "-AM";
  }

  fileName = "SensorData_" + str(year()) + month + day  + hour + ".csv";
  return fileName;
}

Update: Code for collecting and saving data
void serialEvent(Serial myPort) {
  if (myPort.available() > 0) {
    String serialDataString = myPort.readString();
    if (serialDataString != null) {
      serialDataString = trim(serialDataString);
      float[] sensorData = float(split(serialDataString, ','));
      TableRow newRow = dataTable.addRow();
      if (sensorData.length == 4) {
        temperature = sensorData[0];
        humidity    = sensorData[1];
        moisture    = sensorData[2];
        int packet = int(sensorData[3]);

        if (packet < 10) {
          packets = "00" + str(packet);
        } else if (packet < 100) {
          packets = "0" + str(packet);
        }

        String time = str(hour()) + ":" + str(minute()) + ":" + str(second());
        String date = str(month()) + "/" + str(day());
        newRow.setFloat("Temperature", temperature);
        newRow.setFloat("Humidity", humidity);
        newRow.setFloat("Moisture", moisture);
        newRow.setString("Time", time);
        newRow.setString("Date", date);
      }
      saveTable(dataTable, fileName());
    }
  }
}

A: In comments you've mentioned

Clearing after a save does not work as expected,
To clarify, what I meant is, if you call clearRows(), previous data will be erased. Saving before clearRows() should save previous data only, saving after clearRows() should only save current data.

I wrote a basic sketch and to me it looks that this works as expected:
void setup() {
  // make new table, add 3 cols
  Table dataTable = new Table();
  dataTable.addColumn();
  dataTable.addColumn();
  dataTable.addColumn();
  // add 1, 2, 3
  TableRow newRow = dataTable.addRow();
  newRow.setInt(0, 1);
  newRow.setInt(1, 2);
  newRow.setInt(2, 3);
  // save to disk  (expecting 1, 2, 3)
  saveTable(dataTable,"test1.csv");

  // print (expecting 1, 2, 3)
  dataTable.print();
  // completely clear table
  dataTable.clearRows();

  // add 4, 5, 6
  newRow = dataTable.addRow();
  newRow.setInt(0, 4);
  newRow.setInt(1, 5);
  newRow.setInt(2, 6);
  // save again (expecting 4, 5, 6)
  saveTable(dataTable,"test2.csv");
  // print (expecting, 4, 5, 6)
  dataTable.print();

}

(It's also nice that saveTable() appends data (and doesn't overwrite data) in this case.)
This is how I understand how/when data flows in your setup:

*

*Arduino sends data over serial every 15 minutes. You haven't specified if the Arduino has a real time clock (RTC) and the code there uses it to only output data every 15 minutes on the clock (e.g. at :00, :15, :30, :45 past the hour, every hour). The assumption is there is no realtime clock and you're either using delay() or millis() so the actual time data gets sent out is relative to when the Arduino was powered.

*When Processing sketch starts, it reads this serial data (meaning any prior data is loest). The assumption is there is no time sync between Arduino and Processing. The first row of data from Arduino comes at Arduino's next 15 minute (not Processing's) after the sketch was started.

The issue you might be experiencing based on your short snippet,
saveTable(dataTable, fileName());
dataTable.clearRows();

if it gets called in serialEvent() is that you'll loose data.
(Confusingly, it doesn't like you're calling clearRows() from serialEvent() ?)
One idea I can think is having some sort of event when the switch from AM/PM to then (first save any accumated data with the previous filename), then clear the the table and update the filename, otherwise (in serial event, save the data with the same filename).
A hacky approach is, once the AM/PM suffixed timestamp is generated to check if this suffix changes and only update filename/clear rows when this change occurs (e.g. manually "debouncing").
Here's a rough sketch to illustrate the idea:
Serial myPort;
float temperature, humidity, moisture;

Table dataTable = new Table();

String packets;
int packet;

boolean isAM,wasAM;
String tableFileName;

public void setup() {

  textSize(14);

  try{
    myPort = new Serial(this, "COM4", 9600);
    myPort.bufferUntil('\n');
  }catch(Exception e){
    println("Error opening Serial port!\nDouble check the Serial port is connected via USB, the port name is correct and the port istn't already open in Serial Monitor");
    e.printStackTrace();
  }

  tableFileName = "SensorData_" + getDateStampString() + ".csv";
}

public void draw() {

  background(255);

  String sensorText = String.format("Temperature: %.2f Humidity: %.2f  Moisture: %.2f", temperature, humidity, moisture);
  float textWidth = textWidth(sensorText);
  float textX = (width - textWidth) / 2;
  fill(255);
  rect(textX - 10, 14, textWidth + 20, 21);
  fill(0);
  text(sensorText, textX, 30);
  // get an update date string
  String dateStamp = getDateStampString();
  // check AM/PM switch and update
  isAM = dateStamp.endsWith("AM");
  if(!wasAM && isAM){
    println("changed PM to AM");
    updateTableAMPM(dateStamp);
    // update previous state for debouncing
    wasAM = true;
  }

  if(wasAM && !isAM){
    println("changed AM to PM");
    updateTableAMPM(dateStamp);
    wasAM = true;
  }

}

public void updateTableAMPM(String dateStamp){
  // saves current table (old filename): we're vaing data before the AM/PM switch
  saveDataTable();
  // clear rows so next 12 cycle starts fresh
  dataTable.clearRows();
  // update filename (for next save (serialEvent) to use)
  tableFileName = "SensorData_" + dateStamp + ".csv";
}

public String getDateStampString(){
  return new SimpleDateFormat("yyyy-MMM-dd-aa").format(new Date());
}

public void saveDataTable(){
  saveTable(dataTable, tableFileName);
  println("saved",tableFileName);
}

public void serialEvent(Serial myPort) {
  if (myPort.available() > 0) {
    String serialDataString = myPort.readString();
    if (serialDataString != null) {
      serialDataString = trim(serialDataString);
      float[] sensorData = PApplet.parseFloat(split(serialDataString, ','));
      TableRow newRow = dataTable.addRow();
      if (sensorData.length == 4) {
        temperature = sensorData[0];
        humidity    = sensorData[1];
        moisture    = sensorData[2];
        int packet = PApplet.parseInt(sensorData[3]);

        if (packet < 10) {
          packets = "00" + str(packet);
        } else if (packet < 100) {
          packets = "0" + str(packet);
        }

        String time = str(hour()) + ":" + str(minute()) + ":" + str(second());
        String date = str(month()) + "/" + str(day());
        newRow.setFloat("Temperature", temperature);
        newRow.setFloat("Humidity", humidity);
        newRow.setFloat("Moisture", moisture);
        newRow.setString("Time", time);
        newRow.setString("Date", date);
      }
      // save data, but don't change the filename
      saveDataTable();
    }
  }
}

Note the above isn't tested (so might contain errors), but hopefully it illustrates the ideas aforementioned.
(One minor note on packets (which I'm unsure where it's used): you can use nf() to easily pad a number with zeros (There are similar functions like nfc(), nfp(), nfs())).
Another option (similar to what I've mentioned in comments) is to use java utilities to call a function after a set time (e.g. the difference in time since the start of the sketch until either noon or midnight, whichever comes first), to then repeat at 12 hour intervals. You can check out TimerTask, or if your familiar with setTimeout in JS you can try this Thread based WIP setTimeout Processing workaround.


text:
Q: MediaPlayer mOnPreparedListener is null I've a problem with MediaPlayer.OnPreparedListener(). The Logcat keep saying that mOnPreparedListener is null. Failed to send MEDIA_PREPARED message. According to the MediaPlayer reference this code should work, but it's not:
MediaPlayer mp = MediaPlayer.create(Settings.this, R.raw.play_samle);
    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        // onPrepared() is never called
        public void onPrepared(MediaPlayer mp) {
           mp.start();
        }

    });

A: To begin with, you should have :
MediaPlayer mp = MediaPlayer.create(Settings.this, R.raw.play_samle);

your mp doesn't do anything, as it contains nothing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: having spacing issues in using "\n" in a separate file e.write("y.write('\n+d')")

I was trying to write this line of code into a separate python program
y.write('\n'+d)

and when it wrote it, it went like this
str.write('

'+d)

but the '+d) was up one space above this text
any suggestions to keep it in the same line?

A: e.write("y.write('\\n'+d)")

(escape the backslash to make it a literal character), or:
e.write(r"y.write('\n'+d)")

(use a raw string to make backslashes not special).


text:
Q: uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex Im new to objective C and I was wondering if someone can help me figure out why my app keeps crashing.  I believe it has something to do with my Array but I'm not sure how to fix it..  Can someone help please???..
Here's the Log output when it crashes:
2014-11-26 10:37:42.172 SamplePhotoReDo[89697:109203550] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 2 beyond bounds [0 .. 0]'
    *** First throw call stack:
     (
0   CoreFoundation                      0x000000010c75af35 __exceptionPreprocess + 165
1   libobjc.A.dylib                     0x000000010c09cbb7 objc_exception_throw + 45
2   CoreFoundation                      0x000000010c65301e -[__NSArrayI objectAtIndex:] + 190
3   UIKit                               0x000000010d67474a -[UITableViewDataSource tableView:heightForHeaderInSection:] + 39
4   UIKit                               0x000000010d221f4e -[UITableView _delegateWantsHeaderForSection:] + 261
5   UIKit                               0x000000010d3a6983 -[UISectionRowData refreshWithSection:tableView:tableViewRowData:] + 162
6   UIKit                               0x000000010d3ace45 -[UITableViewRowData rectForFooterInSection:heightCanBeGuessed:] + 320
7   UIKit                               0x000000010d3acf3a -[UITableViewRowData heightForTable] + 56
8   UIKit                               0x000000010d1ffaf0 -[UITableView _updateContentSize] + 381
9   UIKit                               0x000000010d21cecd -[UITableView didMoveToWindow] + 65
10  UIKit                               0x000000010d1a39a0 -[UIView(Internal) _didMoveFromWindow:toWindow:] + 1482
11  UIKit                               0x000000010d1b4333 -[UIScrollView _didMoveFromWindow:toWindow:] + 55
12  UIKit                               0x000000010d1a368e -[UIView(Internal) _didMoveFromWindow:toWindow:] + 696
13  UIKit                               0x000000010d19c112 __45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke + 125
14  UIKit                               0x000000010d19c086 -[UIView(Hierarchy) _postMovedFromSuperview:] + 437
15  UIKit                               0x000000010d1a5f4b -[UIView(Internal) _addSubview:positioned:relativeTo:] + 1604
16  UIKit                               0x000000010d486534 -[UINavigationTransitionView transition:fromView:toView:] + 479
17  UIKit                               0x000000010d2841ef -[UINavigationController _startTransition:fromViewController:toViewController:] + 2967
18  UIKit                               0x000000010d284487 -[UINavigationController _startDeferredTransitionIfNeeded:] + 523
19  UIKit                               0x000000010d284f47 -[UINavigationController __viewWillLayoutSubviews] + 43
20  UIKit                               0x000000010d3ca509 -[UILayoutContainerView layoutSubviews] + 202
21  UIKit                               0x000000010d1a8973 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 521
22  QuartzCore                          0x000000011052bde8 -[CALayer layoutSublayers] + 150
23  QuartzCore                          0x0000000110520a0e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
24  QuartzCore                          0x000000011052087e _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
25  QuartzCore                          0x000000011048e63e _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
26  QuartzCore                          0x000000011048f74a _ZN2CA11Transaction6commitEv + 390
27  UIKit                               0x000000010d12d54d -[UIApplication _reportMainSceneUpdateFinished:] + 44
28  UIKit                               0x000000010d12e238 -[UIApplication _runWithMainScene:transitionContext:completion:] + 2642
29  UIKit                               0x000000010d12cbf2 -[UIApplication workspaceDidEndTransaction:] + 179
30  FrontBoardServices                  0x0000000112f002a3 __31-[FBSSerialQueue performAsync:]_block_invoke + 16
31  CoreFoundation                      0x000000010c69053c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
32  CoreFoundation                      0x000000010c686285 __CFRunLoopDoBlocks + 341
33  CoreFoundation                      0x000000010c686045 __CFRunLoopRun + 2389
34  CoreFoundation                      0x000000010c685486 CFRunLoopRunSpecific + 470
35  UIKit                               0x000000010d12c669 -[UIApplication _run] + 413
36  UIKit                               0x000000010d12f420 UIApplicationMain + 1282
37  SamplePhotoReDo                     0x000000010bb60453 main + 115
38  libdyld.dylib                       0x000000010f2d2145 start + 1
 )
  libc++abi.dylib: terminating with uncaught exception of type NSException
   (lldb)'

Here's the code that might be causing the crash:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1 + self.collectionsFetchResults.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger numberOfRows = 0;
    if (section == 0) {
        numberOfRows = 1; // "All Photos" section
    } else {
        PHFetchResult *fetchResult = self.collectionsFetchResults[section - 1];
        numberOfRows = fetchResult.count;
    }
    return numberOfRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    NSString *localizedTitle = nil;

    if (indexPath.section == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:AllPhotosReuseIdentifier forIndexPath:indexPath];
        localizedTitle = NSLocalizedString(@"All Photos", @"");
     } else {
        cell = [tableView dequeueReusableCellWithIdentifier:CollectionCellReuseIdentifier forIndexPath:indexPath];
        PHFetchResult *fetchResult = self.collectionsFetchResults[indexPath.section - 1];
        PHCollection *collection = fetchResult[indexPath.row];
        localizedTitle = collection.localizedTitle;
    }
    cell.textLabel.text = localizedTitle;

    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *title = nil;
    if (section > 0) {
        title = self.collectionsLocalizedTitles[section - 1];
    }
    return title;
}

#pragma mark - PHPhotoLibraryChangeObserver

- (void)photoLibraryDidChange:(PHChange *)changeInstance
{
    // Call might come on any background queue. Re-dispatch to the main queue to handle it.
    dispatch_async(dispatch_get_main_queue(), ^{
        NSMutableArray *updatedCollectionsFetchResults = nil;
        for (PHFetchResult *collectionsFetchResult in self.collectionsFetchResults) {
            PHFetchResultChangeDetails *changeDetails = [changeInstance changeDetailsForFetchResult:collectionsFetchResult];
            if (changeDetails) {
                if (!updatedCollectionsFetchResults) {
                    updatedCollectionsFetchResults = [self.collectionsFetchResults mutableCopy];
                }
            [updatedCollectionsFetchResults replaceObjectAtIndex:[self.collectionsFetchResults indexOfObject:collectionsFetchResult] withObject:[changeDetails fetchResultAfterChanges]];
        }
    }
    if (updatedCollectionsFetchResults) {
        self.collectionsFetchResults = updatedCollectionsFetchResults;
        [self.tableView reloadData];
    }
    });
}

A:  reason: '*** -[__NSArrayI objectAtIndex:]: index 2 beyond bounds [0 .. 0]'

Quite clear, your array doesn't have as many elements as you think it has. Put a break point at the places where your array is populated and double check it's as expected.


text:
Q: Detecting already installed programs on a secondary HDD in Windows 8 I recently bought a new computer and installed Windows 8 on to a 150Gb hdd, with a 2Tb hdd for most programs and files.
After a week of using the computer and installing a fair few programs, I have been given a bigger faster hard drive to use as my primary, with the 2Tb remaining as my data/programs.
Now that I have installed Windows on this again, none of my programs installed to the large disk are available through the start menu, and I can't seem to find a solution through google.
A friend suggested adding shortcuts to my desktop but that just looks cluttered and becomes ridiculous with a large number of programs.
Is there a way I can get Windows to find these programs, which are still intact on the second disk, without having to re-install them all?
Any help would be much appreciated!

A: The best way to go is usually to re-install your programs. That will ensure proper operation since many program installers also put information in the windows registry, put some files in your Users folder, and/or install any additional libraries they require (eg. Java, DirectX, .NET, etc.) -- those were lost by reinstalling windows.
That said, as you probably noticed, many programs will still work anyway. In such case, to place icons to your Start Screen instead of the Desktop, do this:

*

*Open File Explorer

*Enable Hidden Files in the View ribbon (since C:\ProgramData is hidden)

*Go to C:\ProgramData\Microsoft\Windows\Start Menu\Programs\ - this is where Start Screen shortcuts are stored. Any shortcut you add there will automatically appear in the Start Screen.

However, by default, you don't have permission to create shortcuts there. To remedy this,

*

*Right-click on the Programs folder and select Properties

*Go to the Security tab and click the Edit button

*Select `Users

*Check the Modify checkbox (which will also check the Write checkbox)

*Click OK, and OK again

Now you can create shortcuts to your programs, or move your existing Desktop shortcuts. You don't have to create subfolders, but if you do they will also be grouped accordingly in the "All Apps" screen.


text:
Q: VueBootstrap and New VeeValidate can't make custom modal Hello I have in my component this modal:

       <ValidationObserver v-slot="{ invalid }">

             <ValidationProvider rules="minVal:0.1" v-slot="{ errors, valid }" name="quantità">

                   {{errors[0]}}

             </ValidationProvider>

         <template v-slot:modal-footer>
            close
            save
         </template>
      </ValidationObserver>

But I can't compile with this error:

To avoid scope ambiguity, the default slot should also use
  syntax when there are other named slots.

My problem is that :
I would like disable "submit" button in realtime with validation and also I would like override footer modal template of vue-bootstrap modal.
If I put   outisde  I can compile, but I can't disabled button with ValidationObserver valid slot.
I have create also a codeSandBox.
https://codesandbox.io/embed/vue-template-o4vkk?fontsize=14
What I'm wrong?

A: Wrap the entire modal in the ValidationObserver - see working sandbox. This way you have access to the scoped props offered by the ValidationObserver in the footer slot of the b-modal.
<ValidationObserver v-slot="{ invalid }">

             <ValidationProvider rules="minVal:0.1" v-slot="{ errors, valid }" name="quantità">

                   {{errors[0]}}

             </ValidationProvider>

         <template v-slot:modal-footer>
            close
            save
         </template>

</ValidationObserver>


text:
Q: OpenCL global vs __global and kernel vs __kernel This is more a question of semantics.
In XCode, __global and global are syntax highlighted the same.
__kernel and kernel are syntax highlighted the same.
What is the difference between __global vs global and __kernel vs kernel? Are they the same?

A: There is no difference.
By manual for __global:

The address space names without the __ prefix i.e. global, local, constant and private may be substituted for the corresponding address space names with the __ prefix.


text:
Q: how to add color, background-color value through variable in PyQt5? Its my code. How to assign the values for CSS through variable and the use same in PyQt5 stylesheet ?
    self.label = QLabel("sample")
    self.label.setObjectName("label_1")
    self.label.setStyleSheet(my_stylesheet())

def my_stylesheet():
    return """
    QLabel#label_1{color:red;background-color:blue;}
    """

Instead of direct values (like red, blue), assign it in a  variable and how to use it.
For ex :
color_1 =red
color_2 = blue
QLabel#label_1{"color:color_1; background-color:color_2;}

A: A possible solution is to use property where the Qt stylesheet change is applied in the setter:
import sys

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor, QFont
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow

class Label(QLabel):
    def __init__(
        self, background=QColor("white"), foreground=QColor("black"), parent=None
    ):
        super().__init__(parent)
        self._background = background
        self._foreground = foreground

        self._change_stylesheet()

    @property
    def background(self):
        return self._background

    @background.setter
    def background(self, color):
        if self._background == color:
            return
        self._background = color
        self._change_stylesheet()

    @property
    def foreground(self):
        return self._foreground

    @foreground.setter
    def foreground(self, color):
        if self._foreground == color:
            return
        self._foreground = color
        self._change_stylesheet()

    def _change_stylesheet(self):
        qss = "QLabel{color:%s;background-color:%s}" % (
            self.background.name(),
            self.foreground.name(),
        )
        self.setStyleSheet(qss)

if __name__ == "__main__":
    app = QApplication(sys.argv)

    label = Label()
    label.setText("Qt is awesome!!!")
    label.setAlignment(Qt.AlignCenter)
    label.setFont(QFont("Arial", 40))

    label.background = QColor("red")
    label.foreground = QColor("blue")

    w = QMainWindow()
    w.setCentralWidget(label)
    w.resize(640, 480)
    w.show()

    sys.exit(app.exec_())

A: This code doesn't give a direct solution to your problem. But it solves your problem, somehow.
import sys
from PyQt5 import QtWidgets

color_red = "color_red"
color_blue = "color_blue"

backcolor_skyblue = "bcolor_skyblue"
backcolor_lightgreen = "bcolor_lightgreen"

class CssSample(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Css Stylesheet")

        self.label_1 = QtWidgets.QLabel("Sample 1 Label")
        self.label_1.setFixedSize(200,50)
        self.label_1.setProperty("color",color_red )
        self.label_1.setProperty("backcolor",backcolor_skyblue)
        self.label_1.setStyleSheet(my_stylesheet())

        self.label_2 = QtWidgets.QLabel("Sample 2 Label")
        self.label_2.setFixedSize(200, 50)
        self.label_2.setProperty("color", color_blue)
        self.label_2.setProperty("backcolor",backcolor_lightgreen)
        self.label_2.setStyleSheet(my_stylesheet())

        self.vbox = QtWidgets.QVBoxLayout()
        self.vbox.addWidget(self.label_1)
        self.vbox.addWidget(self.label_2)
        self.setLayout(self.vbox)

def my_stylesheet():

    return """
    QLabel[color = "color_red"]
    { color : red;font-family: Trebuchet MS; font-style: normal; font-size:12pt; font-weight:700; }

    QLabel[color = "color_blue"]
    { color : blue;font-family: Trebuchet MS; font-style: normal; font-size:12pt; font-weight:700;}

    QLabel[backcolor = "bcolor_skyblue"]
    { background-color : skyblue}

    QLabel[backcolor = "bcolor_lightgreen"]
    { background-color : lightgreen}

    QLabel{ background-color: @mycolor;}

"""

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    mainwindow = CssSample()
    mainwindow.show()
    sys.exit(app.exec_())


text:
Q: User-defined command line arguments in python Encountered a couple of problems with my python program. Basically, I want to be able to send the path files of multiple images to the command prompt (the user defines how many images, so just putting the direct file paths as args, as below, doesn't do what I want). My code currently looks like this:
os.system("java -jar C:\\Inetpub\\ftproot\\JPivSource\\jpivc.jar image_00000001.jpg image_00000002.jpg image_00000003.jpg")

There are many more images, so of course, writing out image_00000004, 5, 6, etc, is hardly efficient and depends entirely on there being the same number of images each time, which there isn't. (jpivc.jar is the program that opens upon execution of this code, and imports the images and does stuff - that bit works fine). Ideally, the code would be something like:
for i in range(1, NumberOfImages):
    os.system("java -jar C:\\Inetpub\\ftproot\\JPivSource\\jpivc.jar image_0000000" + i + ".jpg")

Except, you know, without opening jpivc.jar each time i is incremented, I'm just using the above to show the kind of thing I want. Unfortunately this doesn't work, as it only sends the first part in " " to the command line, if it doesn't give an error message - my first question is, is there any way of making this do what I want it to do? I'm relatively inexperienced at python, so please be as gentle as possible with the technical details.
My second question is - is there a way of then closing either the command prompt or jpivc.jar? I've tried all the predefined functions I can think of - os.system("tskill cmd.exe") and variatons thereupon,  os.kill() (although I'm using 2.5, so I'm not surprised this doesn't work), Popen.kill() and Popen.terminate(), and even tried writing my own kill function using ctypes. Nothing works - until either cmd.exe or jpivc.jar are closed manually, then everything in the rest of my code works perfectly. I think Python halts until the command line is closed - which isn't helpful when I want to then close the command line from Python! To sum up; why does it halt like that, and how can I fix it?
More extracts from my code can be provided if needed - I'm using Python 2.5.4 on Windows XP Professional. Don't ask me to provide anything from jpivc.jar - I won't even pretend to understand the slightest bit of Java.
Thanks in advance,
Dave

A: I believe you are looking for something like this
fileNames=""
for i in range(1, NumberOfImages):
    fileNames += "image_0000000%d.jpg "%i

os.system( "java -jar C:\\Inetpub\\ftproot\\JPivSource\\jpivc.jar %s"%fileNames )

Rename your file from script.py to script.pyw to avoid the opening of command prompt.
jpivc.jar will remain open until you close it manually or programmer changes its code to quit after it completes processing all files.
[EDIT]
I found this for starting and killing a process
pidId = os.spawnl(os.P_NOWAIT, "\\windows\\notepad.exe")
import win32api
win32api.TerminateProcess(pidId ,0)


text:
Q: JQuery draggable and droppable append issue I want to drag a div to a droppable div and have the droppable div 'contain it' while the initial draggable div is still draggable within the droppable.
However,
When I drag the draggable div to the droppable div the draggable div is appended in a manner that is visually offset.
To cut through the above nursery rhyme and see what I actually mean see the fiddle below and drag thing1 or thing2 to the gray palette.
It offsets to the right.
http://jsfiddle.net/mnmyS/
I want to know how to fix that.
$(".card").draggable();

$('.box').draggable().resizable();

$(".pallette").droppable({
    tolerance: "intersect",
    accept: ".card",
    activeClass: "ui-state-default",
    hoverClass: "ui-state-hover",
    drop: function(event, ui) {
        $(this).append($(ui.draggable));
        $(".card").draggable({containment: $(this)});
    }
});

A: I was facing this issue before some day. After a lot of effort I found a solution for me. I simply removed the draggable element when it dropped and again created a same element inside the droppable element. I know its not your solution. But may be this can help you.
http://jsfiddle.net/D3cxz/
var div = document.createElement("div");
div.style.width = "30%";
div.style.height = "10%";
div.className = "card";
div.id = "draggable";
div.innerHTML = "thing1";
div.style.fontSize="small";

    document.body.appendChild(div);
    $('.card').draggable();

    var box = document.createElement("div");
    box.className = "box";

    document.body.appendChild(box);
    $('.box').draggable();

    var pallette = document.createElement("div");
    pallette.className = "pallette";

    box.appendChild(pallette);

    $('.pallette').droppable({
         drop: function (event, ui) {
        div.parentElement.removeChild(div);

           var div1 = document.createElement("div");
        div1.style.width = "30%";
        div1.style.height = "10%";
        div1.className = "card";
        div1.id = "draggable";
        div1.innerHTML = "thing1";
        div1.style.fontSize="small";
              pallette.appendChild(div1);

             $('.card').draggable(
                 {
                     containment: '.pallette'
                 });
         }});


text:
Q: Histogram Comparison Using Pyramid Match Kernel Distance I am following spatial pyramid representation for images (both Sketch and Photo), i.e. dividing image into 2L levels and each level l = 0, 1, ..., L-1 has 22l grids.
It means level 0 has 1 grid (single image), level 1 has 4 grids and so on.
I have considered the 4 levels here. I am dividing image up to 4 levels i.e. 64 blocks. Then divided image at each level has that many numbers of histograms (e.g. level 1 has 4 blocks so 4 histograms and so on) then obtained final histogram by merging these histograms (keeping this example final histogram is obtained by merging 4 histograms and so on).
Then this final histogram of sketch image is matched with the final histogram of photo image at each level.
I want to compare the histograms of two images i.e. sketch image histogram (input from user) and photo image (database of colour image though I haven't created database yet but I need to create. Please also help me with that as well) using Pyramid Match Kernel (PMK) Distance. This distance is given as below: I want Source code for implenting this distance.
d(Hp, L, Hs, L) = chi-Square(Hp, 0, Hs, 0) / 2L + l = 1L ∑chi-Square(Hp, l, Hs, l) / 2L - l -1

where:

*

*L - number of levels = 4 (That is I am considering)

*l - individual levels, i.e. 0, 1, 2, 3 (Since I am considering 4 levels)

*Hs - Sketch Histogram

*Hp - Photo Histogram

Currently I am statically computing these histograms but I need to store four histograms for one photo image in .mat database of matlab (four histograms since first for level one, second for level two, third for level three and fourth for level four), so that I can run loop for comparing the input image histogram with the histograms of images in database.
I need your help for both implementing this PMK distance and creating database to store 4 histograms for single photo image. Currently I have 100 images with me so I need to store histograms corresponding to each photo image in .mat file, tell me how do I do that?


text:
Q: Intellisense shows 'typeof import "/path"' - how to get intellisense of imported variables? When I import some data and hover over the variable, it shows 'typeof import "/some/path"' instead of a list of the variables.
I would like it to show the list to enable autocomplete and such things.
I made an example project.
If you hover over theme1 in index.ts of that project, it shows vars: typeof import("some/path");
The way it happens is:
A folder has files with named exports. There is an index.ts file which exports everything from that folder:
//stuff/variables/index.ts
export * from '.';

.
//stuff/variables/vars1.ts
const stuff1 = 'stuff1';
const stuff2 = 'stuff2';
const stuff3 = 'stuff3';

export { stuff1, stuff2, stuff3 };

A file in the parent folder imports all from that index.ts file, and exports it as a variable:
//stuff/index.ts
import * as variablesData from './variables/index';

export const vars = variablesData;

Another file imports that variable and includes it in an exported object:
//stuff/theme.ts
import { vars } from './index';

const obj = {
  blue: 'blue',
};

export const theme1 = {
 ...obj,
 vars,
};

And lastly, the top index.ts imports that named export.
//index.ts
import { theme1 } from './stuff/theme';
console.log(theme1);

If I hover over that imported variable, it doesn't list the variables, but instead it shows  typeof import("some/path");
So the export * from '.' is not resolved by intellisense. Can't I use `"export *" ?
Can this be helped by adding some type or writing it in a different way?

A: I believe that what you are describing is a bug/missing feature in Typescript itself. Though I did not find it among github issues upon doing an ultra quick search there.
What you can do is define the vars variable directly in vars1.ts file.
//stuff/variables/vars1.ts
const stuff1 = 'stuff1';
const stuff2 = 'stuff2';
const stuff3 = 'stuff3';

const vars = { stuff1, stuff2, stuff3 };

export { stuff1, stuff2, stuff3, vars };

Then adjust your index file
//stuff/index.ts
export { vars } from './variables/index';

and your intellisense will work beautifully.
Yes this approach is a little bit more work than you did, but at least the types work now :).


text:
Q: Can you extract energy from "hot" things without a temperature differential? I've been reading about extracting energy from heat, particularly Sterling engines. There's always a temperature gradient. Heat flows from the hot side to the cold side through the working fluid. As the temperature differential approaches zero the engine stops.
My question is that why do we even need a temperature differential? Even more broadly why do we use energy to cool things? Let's take a gallon of water at 50 deg C. Water has a specific heat of 4.18JdegC/g. Ignoring the heat of fusion and following Q = CMdT, just by virtue of it being "warm" (323 deg C above absolute zero) wouldn't the water "contain" 3780 * 4.18 * 323 = 5104 kJ of energy (3780 grams per gallon of water). Why couldn't you extract any of this energy as work and as a result of extracting the energy the water cools itself (it gives up energy, for every 3780*4.18 J extracted it should lower by 1 deg C). I'm invisioning the heated water (or anything heated above abs zero) as an energy sink or battery. Theoretically you should be able to extract 5104 kJ of energy from this 50 deg C gallon of water.
In the Sterling engine we could lower the cold side with liquid nitrogen but it takes energy to make this. In an AC system we spend energy to lower the temperature in the room. Since "cold" is the absence of "heat" or energy, shouldn't cooling things actually create energy for us (the hot things that earlier had energy imparted into them give up their energy to make work). It seems wasteful to just waste the heat on warming up something at a lower temperature differential such as the cool side of the Sterling engine or the ambient air by the condenser.

A: The Ideal
The main problem is that all current technologies seem to waste a certain amount of energy on actually displacing some of the heat energy from A to B. If there were no such inefficiency, then we would in a sense obtain "free" energy as we could displace and focus an arbitrarily large amount of energy from a material into a finite space, and then use the laws of thermodynamics to power (e.g.) a stirling engine. If only there exists a structure that can naturally, without energy input, make one side cold and another warm. However, this gives us a contradiction.
The Contradiction
Due to the second law of thermodynamics and the conservation of energy, this becomes impossible. As having a perfect "structure" that can transfer heat from A to B would violate these laws. It is required that energy be put into the system to actually perform the displacement. Therefore, even if said system is 100% efficient, energy is still put into the system such that no "free" energy is ever gained.
For reference (2nd Law of Th.) (wikipedia)

When two initially isolated systems in separate but nearby regions of
  space, each in thermodynamic equilibrium with itself but not
  necessarily with each other, are then allowed to interact, they will
  eventually reach a mutual thermodynamic equilibrium. The sum of the
  entropies of the initially isolated systems is less than or equal to
  the total entropy of the final combination. Equality occurs just when
  the two original systems have all their respective intensive variables
  (temperature, pressure) equal; then the final system also has the same
  values.

A Law
Unfortunately, the question is hard to answer:

My question is that why do we even need a temperature differential?

The reason is that the contrary is made impossible by a law. A law in physics and mathematics doesn't necessarily equate a theorem or theory. It only states "such is so." whilst a theory would actually explain "why such is so".

A: A)
Without a temperature differential, there's no "hot". To say something is hot would mean it has a higher temperature than what you're comparing it with. eg. coconut oil, chocolate or gallium will melt in your hand because you are too hot for it to stay solid, but phosphorus or soap will stay solid because you're too cold for it.
Since 'hotness' is a measure of temperature differential, extracting energy from a point will change the temperature at that point. Also to extract (heat) energy, would mean to move it from a higher temperature to lower temperature (potential), just like any other form of energy, whether electricity or fluid dynamics.
In your case of "5104 kJ of energy", 100% of it could be extracted for work if the environment was at absolute zero and your extractor efficiency was at 100%.
B)
Re: "shouldn't cooling things actually create energy for us"
To cool anything, means to do some work, in this case 'cool'. Doing work, needs energy. So to cool anything will need energy, not create energy. As in A) above (the 1st part of your question), extracting (heat) energy from a point will cool it (reduce temperature), which requires work. So the energy potential you would create at that point by this extraction would be equal to the work you've done to extract the energy from that point, with 100% efficiency.
Further reading keywords: entropy, thermal equilibrium, conservation of momentum, conservation of energy, theory of relativity

A: It may be possible using cold fraction from a vortex tube. Use heat source to boil water; use vortex tube to separate the steam into hotter steam and cooler steam; use hotter steam to replace original heat source. So the original body of water produces some kinetic energy and loses a lot of thermal energy. You would need a temporary external heat source but would gain that energy back and then some if the chain reaction consumed enough water.


text:
Q: Penwidth in my graphviz installation doesn't work. Which package did I miss? It has cairo, and I installed on cent os 5 linux and below is the dot-file and command I used to test it.
1.dot :
digraph {
    a [
    color ="#AA00AA"
        style="filled"
        fontcolor="cyan"
        pos = "0,0!"
      ]
    b [label = "yyy",pos = "10,10!"]
    a -> b[penwidth="6", color="red"]
    b -> c
}

command:
neato -Tps 1.dot -o 1.ps

dot -Tps 1.dot -o 1.ps

A: As the asker said in a comment:

found answer: dot-V gives graphviz version 2.12. too old to have
  penwidth. graphviz.996277.n3.nabble.com/… –  asker ask Sep 6 '13 at
  16:09

and in the source:

penwidth was added in January 2008

Here's the source for that information:
http://graphviz.org/doc/info/attrs.html#d:penwidth
Based on this repository: http://www.graphviz.org/pub/graphviz/ARCHIVE/
It's unlikely to be available in Graphviz until 2.20 (maybe 2.18) on.


text:
Q: Run tests inside Docker container with Jenkins We want to give it a try to setup CI/CD with Jenkins for our project. The project itself has Elasticsearch and PostgreSQL as runtime dependencies and Webdriver for acceptance testing.
In dev environment, everything is set up within one docker-compose.yml file and we have acceptance.sh script to run acceptance tests.
After digging documentation I found that it's potentially possible to build CI with following steps:

*

*dockerize project

*pull project from git repo

*somehow pull docker-compose.yml and project Dockerfile - either:

*

*put it in the project repo

*put it in separate repo (this is how it's done now)

*put somewhere on a  server and jut copy it over

*execute docker-compose up

*project's Dockerfile will have ONBUILT section to run tests. Unit tests are run through mix tests and acceptance through scripts/acceptance.sh. It'll be cool to run them in parallel.

*shutdown docker-compose, clean up containers

Because this is my first experience with Jenkins a series of questions arise:

*

*Is this a viable strategy?

*How to connect tests output with Jenkins?

*How to run and shut down docker-compose?

*Do we need/want to write a pipeline for that? Will we need/want pipeline when we will get to the CD on the next stage?

Thanks

A:
Is this a viable strategy?

Yes it is. I think it would be better to include the docker-compose.yml and Dockerfile in the project repo. That way any changes are tied to the version of code that uses the changes. If it's in an external repo it becomes a lot harder to change (unless you pin the git sha somehow , like using a submodule).

project's Dockerfile will have ONBUILD section to run tests

I would avoid this. Just set a different command to run the tests in a container, not at build time.

How to connect tests output with Jenkins?

Jenkins just uses the exit status from the build steps, so as long as the test script exits with a non-zero code on failure and a zero code on success that's all you need. Test output that is printed to stdout/stderr will be visible from jenkins console.

How to run and shut down docker-compose?

I would recommend this to run Compose:
docker-compose pull # if you use images from the hub, pull the latest version
docker-compose up --build -d

In a post-build step to shutdown:
docker-compose down --volumes

Do we need/want to write a pipeline for that?

No, I think just a single job is fine. Get it working with a simple setup first, and then you can figure out what you need to split into different jobs.


text:
Q: Highcharts Overflowing the parent container So my issue is pretty weird, I have multiple high charts on my bootstrap page, they were working fine. Recently i observed that the size of the high chart is overflowing the size of its parent container.
But when I open console (Or when I resize browser window), the high charts again fits in.
What can cause this behaviour? Did high charts made any size changes in the production?
Rest everything on the page is as good as it was.

A: Its general issue asked many times and I also had same issue in starting.
make your div's position relative and put following css for highcharts container
.highcharts-container
{
 position: absolute;
  width: 100% !important;
 }


text:
Q: Unity3d render texture based on position I'm currently trying to create a container in Unity with multiple quads inside, and am looking for a way to stop parts of the quad that fall outside of the containers bounds from being rendered?
I just spent twenty minutes trying to fiqure out how to explain the problem properly (and failed) so created this pretty picture instead. The red line represents the bounds with the black squares representing my textured quads.

A: Try this:
private Rect ClipRectToScreen (Rect input)
                    {
                            // Special handling for screen reading of render texture so it always stay in visible area.
                            // Will throw error withoud this fix.
                            Rect r;
                            r = new Rect (input.x, (Screen.height - input.y - input.height) , input.width, input.height);
                            if (r.x < 0f) {
                                    r.width = r.width - UnityEngine.Mathf.Abs (r.x);
                                    r.x = 0f;
    //                              Debug.Log ("x < 0");
                            }
                            if (r.y < 0f) {
                                    r.height = r.height - UnityEngine.Mathf.Abs (r.y);
                                    r.y = 0f;
    //                              Debug.Log ("y < 0");
                            }
                            if (r.x > Screen.width) {
                                    r.width = r.width - UnityEngine.Mathf.Abs (r.x);
                                    r.x = 0f;
    //                              Debug.Log ("x > Screen.width");
                            }
                            if (r.y > Screen.height) {
                                    r.height = r.height - UnityEngine.Mathf.Abs (r.y);
                                    r.y = 0f;
    //                              Debug.Log ("y > Screen.height");
                            }
                            if ((r.x + r.width) > Screen.width) {
                                    r.width = Screen.width - r.x;
    //                              Debug.Log ("r.x + r.width > Screen.width");
                            }
                            if ((r.y + r.height) > Screen.height) {
                                    r.height = Screen.height - r.y;
    //                              Debug.Log ("r.y + r.height > Screen.height");
                            }

                            return r;
                    }


text:
Q: RTL support for LinearLayout in versions earlier 4.2 of android I have the following LinearLayout:
Which shows on LTR orientation: Image + Text + arrow
I want to reverse the order for RTL. On Android versions 4.2 works out of the box, for earlier versions it does not. I have added the paddingEnd and paddingStart following link Any idea?
(I have enabled rtl support on the manifest also)
  <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:minHeight="48dp"
    android:paddingLeft="@dimen/category_list_row_padding_left_right"
    android:paddingStart="@dimen/category_list_row_padding_left_right"
    android:paddingRight="@dimen/category_list_row_padding_left_right"
    android:paddingEnd="@dimen/category_list_row_padding_left_right"
    android:paddingTop="@dimen/category_list_row_padding"
    android:paddingBottom="@dimen/category_list_row_padding"
    android:layoutDirection="locale">
    <ImageView
        android:id="@+id/icon"
        android:layout_weight="0"
        android:layout_width="48dp"
        android:layout_height="32dp"
        android:layout_gravity="center_vertical"
        />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:color="@color/category_name"
            android:text=""
            android:id="@+id/name"
            android:textSize="17dp"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/category_label"
            android:text=""
            android:id="@+id/counter"
            android:textAppearance="@android:style/TextAppearance.Small"
            android:textSize="11dp"/>
    </LinearLayout>
    <ImageView
        android:id="@+id/next"
        android:src="@drawable/ic_chevron_right_black_24dp"
        android:layout_weight="0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" />
</LinearLayout>


text:
Q: Swift Initialization - Why are multiple init functions being called? Here's is my class with override inits
class BottomView: UIView {

    // MARK: - initilization

   override init() {
        println("init")
        super.init()
        setup()
    }

    override init(frame: CGRect) {
        println("init frame")
        super.init(frame: frame)
        setup()
    }

    required init(coder aDecoder: NSCoder) {
        println("init decoder")
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {
        println("setup")
    }
}

I then initialize in my ViewController with the following code
class ViewController: UIViewController {

    let bottomView = BottomView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        bottomView.frame = CGRectMake(0.0, self.view.frame.height/2.0, self.view.frame.width, self.view.frame.height/2.0)
        bottomView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleTopMargin
        self.view.addSubview(bottomView)

    }
}

And my output is
init
init frame
setup
setup

So my question is, why is init(frame:) being called?

A: super.init() calls self.init(frame:...). Essentially, it's just their way of saying that frame is optional; if you don't pass it, they assign a frame of (0,0,0,0).
func init() {
  self.init(frame:CGRectMake(0,0,0,0));
}


text:
Q: Border on three sides Is there way to create a border that is only on the top, left, and right sides?

A: And just for fun, to do so in code:
var b = new Border();
b.BorderThickness = new Thickness{Top=1, Bottom=0, Left=1, Right=1};

A: Yes:
<Border BorderThickness="1 1 1 0" BorderBrush="Black"/>

Same as goes for Margin, Padding etc.


text:
Q: Kafka Number of messages in a topic I need the number of messages in a kafka topic stored.
This is not concerned with whether any consumer has consumed the messages or not.
kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list localhost:9092,localhost:9093,localhost:9094 --topic test-topic

The above gives the offset number for the topic?
Is the above equal to the number of messages currently stored in the kafka topic?

A: Not exactly. The numbers you got only refers to the current max offsets of all the topic partitions. Message count also depends on the partitions' beginning offsets for that topic.
You could run
kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list localhost:9092,localhost:9093,localhost:9094 --topic test-topic --time -1
and
kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list localhost:9092,localhost:9093,localhost:9094 --topic test-topic --time -2
respectively, and calculate the message count for each partition by subtracting beginningOffsets from endOffsets, then sum them up to get the total record count for that topic.

A: Yes,this is equal to number of messages if earliest offset is equal to zero.If earliest offset is not equal to zero ,you need to calculate the difference and then sum per partition.

A: The above gives the offset number for the topic?
Yes it gives the current max offset
Is the above equal to the number of messages currently stored in the kafka topic?
No, it's not the number of messages in the kafka as after retention period messages will be deleted from topic so offset != count of messages
To get number of messages in kafka
    brokers="<broker1:port>"
topic=<topic-name>
sum_1=$(/usr/hdp/current/kafka-broker/bin/kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list $brokers --topic $topic --time -1 | grep -e ':[[:digit:]]*:' | awk -F  ":" '{sum += $3} END {print sum}')
sum_2=$(/usr/hdp/current/kafka-broker/bin/kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list $brokers --topic $topic --time -2 | grep -e ':[[:digit:]]*:' | awk -F  ":" '{sum += $3} END {print sum}')
echo "Number of records in topic ${topic}: "$((sum_1 - sum_2))

where option --time -1 => current max offset & --time -2 is current min offset


text:
Q: Best practice for using assert?
*

*Is there a performance or code maintenance issue with using assert as part of the standard code instead of using it just for debugging purposes?
Is
assert x >= 0, 'x is less than zero'

better or worse than
if x < 0:
    raise Exception('x is less than zero')

*Also, is there any way to set a business rule like if x < 0 raise error that is always checked without the try/except/finally so, if at anytime throughout the code x is less than 0 an error is raised, like if you set assert x < 0 at the start of a function, anywhere within the function where x becomes less then 0 an exception is raised?

A: Asserts should be used to test conditions that should never happen.  The purpose is to crash early in the case of a corrupt program state.
Exceptions should be used for errors that can conceivably happen, and you should almost always create your own Exception classes.

For example, if you're writing a function to read from a configuration file into a dict, improper formatting in the file should raise a ConfigurationSyntaxError, while you can assert that you're not about to return None.

In your example, if x is a value set via a user interface or from an external source, an exception is best.
If x is only set by your own code in the same program, go with an assertion.

A: For what it's worth, if you're dealing with code which relies on assert to function properly, then adding the following code will ensure that asserts are enabled:
try:
    assert False
    raise Exception('Python assertions are not working. This tool relies on Python assertions to do its job. Possible causes are running with the "-O" flag or running a precompiled (".pyo" or ".pyc") module.')
except AssertionError:
    pass

A: Well, this is an open question, and I have two aspects that I want to touch on: when to add assertions and how to write the error messages.
Purpose
To explain it to a beginner - assertions are statements which can raise errors, but you won't be catching them. And they normally should not be raised, but in real life they sometimes do get raised anyway. And this is a serious situation, which the code cannot recover from, what we call a 'fatal error'.
Next, it's for 'debugging purposes', which, while correct, sounds very dismissive. I like the 'declaring invariants, which should never be violated' formulation better, although it works differently on different beginners... Some 'just get it', and others either don't find any use for it, or replace normal exceptions, or even control flow with it.
Style
In Python, assert is a statement, not a function! (remember assert(False, 'is true') will not raise. But, having that out of the way:
When, and how, to write the optional 'error message'?
This acually applies to unit testing frameworks, which often have many dedicated methods to do assertions (assertTrue(condition), assertFalse(condition), assertEqual(actual, expected) etc.). They often also provide a way to comment on the assertion.
In throw-away code you could do without the error messages.
In some cases, there is nothing to add to the assertion:
def dump(something):
       assert isinstance(something, Dumpable)
       # ...
But apart from that, a message is useful for communication with other programmers (which are sometimes interactive users of your code, e.g. in Ipython/Jupyter etc.).
Give them information, not just leak internal implementation details.
instead of:
assert meaningless_identifier <= MAGIC_NUMBER_XXX, 'meaningless_identifier is greater than MAGIC_NUMBER_XXX!!!'

write:
assert meaningless_identifier > MAGIC_NUMBER_XXX, 'reactor temperature above critical threshold'

or maybe even:
assert meaningless_identifier > MAGIC_NUMBER_XXX, f'reactor temperature({meaningless_identifier }) above critical threshold ({MAGIC_NUMBER_XXX})'

I know, I know - this is not a case for a static assertion, but I want to point to the informational value of the message.
Negative or positive message?
This may be conroversial, but it hurts me to read things like:
assert a == b, 'a is not equal to b'

*

*these are two contradictory things written next to eachother. So whenever I have an influence on the codebase, I push for specifying what we want, by using extra verbs like 'must' and 'should', and not to say what we don't want.
assert a == b, 'a must be equal to b'
Then, getting AssertionError: a must be equal to b is also readable, and the statement looks logical in code. Also, you can get something out of it without reading the traceback (which can sometimes not even be available).

A: Is there a performance issue?

*

*Please remember to "make it work first before you make it work fast".
Very few percent of any program are usually relevant for its speed.
You can always kick out or simplify an assert if it ever proves to
be a performance problem -- and most of them never will.

*Be pragmatic:
Assume you have a method that processes a non-empty list of tuples and the program logic will break if those tuples are not immutable. You should write:
def mymethod(listOfTuples):
    assert(all(type(tp)==tuple for tp in listOfTuples))

This is probably fine if your lists tend to be ten entries long, but
it can become a problem if they have a million entries.
But rather than discarding this valuable check entirely you could
simply downgrade it to
def mymethod(listOfTuples):
    assert(type(listOfTuples[0])==tuple)  # in fact _all_ must be tuples!

which is cheap but will likely catch most of the actual program errors anyway.

A: "assert" statements are removed when the compilation is optimized.  So, yes, there are both performance and functional differences.

The current code generator emits no code for an assert statement when optimization is requested at compile time. - Python 2 Docs Python 3 Docs

If you use assert to implement application functionality, then optimize the deployment to production, you will be plagued by "but-it-works-in-dev" defects.
See PYTHONOPTIMIZE and -O -OO

A: An Assert is to check -
1. the valid condition,
2. the valid statement,
3. true logic;
of  source code. Instead of failing the whole project it gives an alarm that something is not appropriate in your source file.
In example 1, since variable 'str' is not null. So no any assert or exception get raised.
Example 1:
#!/usr/bin/python

str = 'hello Python!'
strNull = 'string is Null'

if __debug__:
    if not str: raise AssertionError(strNull)
print str

if __debug__:
    print 'FileName '.ljust(30,'.'),(__name__)
    print 'FilePath '.ljust(30,'.'),(__file__)

------------------------------------------------------

Output:
hello Python!
FileName ..................... hello
FilePath ..................... C:/Python\hello.py

In example 2, var 'str' is null. So we are saving the user from going ahead of faulty program by assert statement.
Example 2:
#!/usr/bin/python

str = ''
strNull = 'NULL String'

if __debug__:
    if not str: raise AssertionError(strNull)
print str

if __debug__:
    print 'FileName '.ljust(30,'.'),(__name__)
    print 'FilePath '.ljust(30,'.'),(__file__)

------------------------------------------------------

Output:
AssertionError: NULL String

The moment we don't want debug and realized the assertion issue in the source code. Disable the optimization flag
python -O assertStatement.py
nothing will get print

A: In addition to the other answers, asserts themselves throw exceptions, but only AssertionErrors. From a utilitarian standpoint, assertions aren't suitable for when you need fine grain control over which exceptions you catch.

A: Both the use of assert and the raising of exceptions are about communication.

*

*Assertions are statements about the correctness of code addressed at developers: An assertion in the code informs readers of the code about conditions that have to be fulfilled for the code being correct.  An assertion that fails at run-time informs developers that there is a defect in the code that needs fixing.

*Exceptions are indications about non-typical situations that can occur at run-time but can not be resolved by the code at hand, addressed at the calling code to be handled there.  The occurence of an exception does not indicate that there is a bug in the code.

Best practice

Therefore, if you consider the occurence of a specific situation at run-time as a bug that you would like to inform the developers about ("Hi developer, this condition indicates that there is a bug somewhere, please fix the code.") then go for an assertion.  If the assertion checks input arguments of your code, you should typically add to the documentation that your code has "undefined behaviour" when the input arguments violate that conditions.
If instead the occurrence of that very situation is not an indication of a bug in your eyes, but instead a (maybe rare but) possible situation that you think should rather be handled by the client code, raise an exception.  The situations when which exception is raised should be part of the documentation of the respective code.

Is there a performance [...] issue with using assert

The evaluation of assertions takes some time.  They can be eliminated at compile time, though.  This has some consequences, however, see below.

Is there a [...] code maintenance issue with using assert

Normally assertions improve the maintainability of the code, since they improve readability by making assumptions explicit and during run-time regularly verifying these assumptions.  This will also help catching regressions.  There is one issue, however, that needs to be kept in mind: Expressions used in assertions should have no side-effects.  As mentioned above, assertions can be eliminated at compile time - which means that also the potential side-effects would disappear.  This can - unintendedly - change the behaviour of the code.

A: The only thing that's really wrong with this approach is that it's hard to make a very descriptive exception using assert statements.  If you're looking for the simpler syntax, remember you can also do something like this:
class XLessThanZeroException(Exception):
    pass

def CheckX(x):
    if x < 0:
        raise XLessThanZeroException()

def foo(x):
    CheckX(x)
    #do stuff here

Another problem is that using assert for normal condition-checking is that it makes it difficult to disable the debugging asserts using the -O flag.

A: To be able to automatically throw an error when x become less than zero throughout the function. You can use class descriptors. Here is an example:
class LessThanZeroException(Exception):
    pass

class variable(object):
    def __init__(self, value=0):
        self.__x = value

    def __set__(self, obj, value):
        if value < 0:
            raise LessThanZeroException('x is less than zero')

        self.__x  = value

    def __get__(self, obj, objType):
        return self.__x

class MyClass(object):
    x = variable()

>>> m = MyClass()
>>> m.x = 10
>>> m.x -= 20
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "my.py", line 7, in __set__
    raise LessThanZeroException('x is less than zero')
LessThanZeroException: x is less than zero

A: The four purposes of assert
Assume you work on 200,000 lines of code with four colleagues Alice, Bernd, Carl, and Daphne.
They call your code, you call their code.
Then assert has four roles:

*

*Inform Alice, Bernd, Carl, and Daphne what your code expects.
Assume you have a method that processes a list of tuples and the program logic can break if those tuples are not immutable:
def mymethod(listOfTuples):
    assert(all(type(tp)==tuple for tp in listOfTuples))

This is more trustworthy than equivalent information in the documentation
and much easier to maintain.

*Inform the computer what your code expects.
assert enforces proper behavior from the callers of your code.
If your code calls Alices's and Bernd's code calls yours,
then without the assert, if the program crashes in Alices code,
Bernd might assume it was Alice's fault,
Alice investigates and might assume it was your fault,
you investigate and tell Bernd it was in fact his.
Lots of work lost.
With asserts, whoever gets a call wrong, they will quickly be able to see it was
their fault, not yours. Alice, Bernd, and you all benefit.
Saves immense amounts of time.

*Inform the readers of your code (including yourself) what your code has achieved at some point.
Assume you have a list of entries and each of them can be clean (which is good)
or it can be smorsh, trale, gullup, or twinkled (which are all not acceptable).
If it's smorsh it must be unsmorshed; if it's trale it must be baludoed;
if it's gullup it must be trotted (and then possibly paced, too);
if it's twinkled it must be twinkled again except on Thursdays.
You get the idea: It's complicated stuff.
But the end result is (or ought to be) that all entries are clean.
The Right Thing(TM) to do is to summarize the effect of your
cleaning loop as
assert(all(entry.isClean() for entry in mylist))

This statements saves a headache for everybody trying to understand
what exactly it is that the wonderful loop is achieving.
And the most frequent of these people will likely be yourself.

*Inform the computer what your code has achieved at some point.
Should you ever forget to pace an entry needing it after trotting,
the assert will save your day and avoid that your code
breaks dear Daphne's much later.
In my mind, assert's two purposes of documentation (1 and 3) and
safeguard (2 and 4) are equally valuable.
Informing the people may even be more valuable than informing the computer
because it can prevent the very mistakes the assert aims to catch (in case 1)
and plenty of subsequent mistakes in any case.

A: The English language word assert here is used in the sense of swear, affirm, avow. It doesn't mean "check" or "should be". It means that you as a coder are making a sworn statement here:
# I solemnly swear that here I will tell the truth, the whole truth,
# and nothing but the truth, under pains and penalties of perjury, so help me FSM
assert answer == 42

If the code is correct, barring Single-event upsets, hardware failures and such, no assert will ever fail. That is why the behaviour of the program to an end user must not be affected. Especially, an assert cannot fail even under exceptional programmatic conditions. It just doesn't ever happen. If it happens, the programmer should be zapped for it.

A: As has been said previously, assertions should be used when your code SHOULD NOT ever reach a point, meaning there is a bug there. Probably the most useful reason I can see to use an assertion is an invariant/pre/postcondition. These are something that must be true at the start or end of each iteration of a loop or a function.
For example, a recursive function (2 seperate functions so 1 handles bad input and the other handles bad code, cause it's hard to distinguish with recursion). This would make it obvious if I forgot to write the if statement, what had gone wrong.
def SumToN(n):
    if n <= 0:
        raise ValueError, "N must be greater than or equal to 0"
    else:
        return RecursiveSum(n)

def RecursiveSum(n):
    #precondition: n >= 0
    assert(n >= 0)
    if n == 0:
        return 0
    return RecursiveSum(n - 1) + n
    #postcondition: returned sum of 1 to n

These loop invariants often can be represented with an assertion.

A: In IDE's such as PTVS, PyCharm, Wing assert isinstance() statements can be used to enable code completion for some unclear objects.

A: I'd add I often use assert to specify properties such as loop invariants or logical properties my code should have, much like I'd specify them in formally-verified software.
They serve both the purpose of informing readers, helping me reason, and checking I am not making a mistake in my reasoning. For example :
k = 0
for i in range(n):
    assert k == i * (i + 1) // 2
    k += i
    #do some things

or in more complicated situations:
def sorted(l):
   return all(l1 <= l2 for l1, l2 in zip(l, l[1:]))

def mergesort(l):
   if len(l) < 2: #python 3.10 will have match - case for this instead of checking length
      return l
   k = len(l // 2)
   l1 = mergesort(l[:k])
   l2 = mergesort(l[k:])
   assert sorted(l1) # here the asserts allow me to explicit what properties my code should have
   assert sorted(l2) # I expect them to be disabled in a production build
   return merge(l1, l2)

Since asserts are disabled when python is run in optimized mode, do not hesitate to write costly conditions in them, especially if it makes your code clearer and less bug-prone


text:
Q: Disable text file previews/thumbnails in nautilus Nautilus in 14.04 generates "thumbnails" of all text files in that it shows them all as the same, blank text icon. If I turn off thumbnails altogether, then it displays correct icons, but I need thumbnails of image files. So I tried enabling thumbnails, and then in Dconf disabling them specifically for 'text/css', and so on. This does not work. Can this be achieved without disabling all thumbnails?
I should note I searched this site and there's a few posts here addressing this issue, but those posts are without answers, or referred to other posts - that are also without answers.
A bit of a vicious circle.
I'd appreciate any suggestions.Thanks.


text:
Q: Match ip against list with CIDR notations and comment I'm trying to match an ip address (ie 192.168.192.168) against a list:
192.168.192.0/24 TESTCOMMENT
...
I know ipset supports comments so I tried the following:
$ ipset create foo hash:net comment
$ ipset add foo 192.168.192.0/24 comment TESTCOMMENT
$ sudo ipset test foo 192.168.192.168
192.168.192.168 is in set foo.

As you can see I the comment is not shown. My next try was making use of grepcidr
$ cat foo.txt
192.168.192.0/24 TESTCOMMENT
$ grepcidr -f foo.txt <(echo 192.168.192.168)
192.168.192.168
$ grepcidr -f foo.txt <(echo 192.168.0.168)
$

This matches but does not show the comment.
Does someone know an alternative to try out?

A: With the help of someone else we've tackled the problem. We used rgxg to change the subnet in the file to a regex.
$awk -v ip=192.168.192.168 '{ "rgxg cidr " $1 | getline regex; if (ip ~ regex) print $2 }' foo.txt
TESTCOMMENT

The solution I use is to save the regex to the file:
192.168.192.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9]) TESTCOMMENT
and use the following line to test the IP address:
$ ip=192.168.192.168; while read line; do [[ $ip =~ ${line%% *} ]] && echo ${line##* }; done < foo.txt
TESTCOMMENT


text:
Q: Many to Many relationship Entity Framework creating new rows I'm building a feedback functionality. The feedback is supposed to have multiple categories and it should be possible to find feedback based on a category so there is a many to many relationship.
I've set up the following code for this, its designed as code first.
The feeback item:
public class FeedbackItem
{
    public FeedbackItem()
    {

    }
    [Key]
    public long Id { get; set; }

    public virtual ICollection<FeedbackCategory> Categorys { get; set; }
    //public
    public string Content { get; set; }
    public bool Notify { get; set; }
    public string SubscriptionUserName { get; set; }
    public string SubscriptionUserEmail { get; set; }
    public long SubscriptionId { get; set; }
}

The feedback category:
public class FeedbackCategory
{

   [Key]
   public int Id { get; set; }
   public string Value { get; set; }

   public virtual ICollection<FeedbackItem> Feedbacks { get; set; }
}

The Database Context:
public class FeedbackContext : DbContext, IFeedbackContext
{
    public FeedbackContext() : base("DefaultConnection")
    {
        //Database.SetInitializer<FeedbackContext>(new FeedbackContextDbInitializer());
    }
    public DbSet<FeedbackItem> FeedbackItems { get; set; }
    public DbSet<FeedbackCategory> Categories { get; set; }
}

And the Initializer
class FeedbackContextDbInitializer : DropCreateDatabaseAlways<FeedbackContext>
{
    protected override void Seed(FeedbackContext context)
    {
        IList<FeedbackCategory> categories = new List<FeedbackCategory>()
            {
                new FeedbackCategory() { Value = "Android" },
                new FeedbackCategory() { Value = "API" }
            };

        foreach (var feedbackCategory in categories)
        {
            context.Categories.Add(feedbackCategory);
        }

        base.Seed(context);
    }
}

The code above generates three tables when ran. These being FeedbackCategories, FeedbackCategoryFeedbackItems and FeedbackItems
The table FeedbackCategories is seeded with some already existing categories. The trouble comes when I try to create a new FeedbackItem that has one or more categories.
The Json i provide is the following:
{
"categorys": [
    {
        "$id": "1",
        "Feedbacks": [],
        "Id": 1,
        "Value": "Android"
    }
],
"subscriptionUserName": "name",
"subscriptionUserEmail": "my@email.com",
"content": "this is a feedback item",
"notify": false,
"subscriptionId": 2
}

This is converted into a FeedbackItem and handled by the following code
public class FeedbackSqlRepository : IFeedbackSqlRepository
{

    public int Create(FeedbackItem feedback)
    {
        if (feedback == null)
        {
            throw new ArgumentNullException("feedback", "FeedbackItem cannot be empty.");
        }
        using (var context = new FeedbackContext())
        {
            context.FeedbackItems.Add(feedback);
            return context.SaveChanges();
        }
    }
}

The thing that happens here is that EF creates a new FeedbackItem, a new FeedbackCategory an maps the created feedback item to the newly created feedback category in the FeedbackCategoryFeedbackItems table.
this is not the working i want
I want the following:
Create a new FeedbackItem and reverence an existing FeedbackCategory in the FeedbackCategoryFeedbackItems table. My knowledge of EF is too little to understand what's going wrong here and what to do to get the preferred working.
========
Fixed the issue with the following code inside the Create method from the FeedbackSqlRepository:
 foreach (FeedbackCategory feedbackCategory in feedback.Categories)
            {
                context.Entry(feedbackCategory).State = EntityState.Unchanged;
            }
            context.FeedbackItems.Add(feedback);

            return context.SaveChanges();

A: Entity Framework will not examine entity contents and determine for you if they are new or added.
DbSet.Add() causes ALL entities in an object graph to be marked as added and to generate inserts when you call SaveChanges().
DbSet.Attach() leaves all entities marked as Unmodified.
If some of your entities are new, some are modified and some are just references then you should use either Add() or Attach() and then manually set entity states where necessary before calling SaveChanges().
DbContext.Entry(entity).State = EntityState.Unmodified


text:
Q: How to make sub menu in Material's Popover Component I'd like to create submenu with items (utilizing Popover and MenuItem components). Can't figure out how to position the submenu so that it will be placed on the left from its parent item.
I tried to make parent  position: relative however wrapper prevents the submenu from displaying outside of the Popover flow.
<Popover
  id="simple-popper"
  open={open}
  anchorEl={anchorEl}
  onClose={this.handleClose}
  anchorOrigin={{
    vertical: "bottom",
    horizontal: "center"
  }}
  transformOrigin={{
    vertical: "top",
    horizontal: "center"
  }}
>
  <MenuItem>
    Link 1
    <Paper
      style={{
        position: "absolute"
      }}
    >
      <MenuItem>SubLink 1</MenuItem>
      <MenuItem>SubLink 2</MenuItem>
      <MenuItem>SubLink 3</MenuItem>
    </Paper>
  </MenuItem>
  <MenuItem>Link 2</MenuItem>
  <MenuItem>Link 3</MenuItem>
  <MenuItem>Link 4</MenuItem>
</Popover>;

I'd like to implement classical two-level material design menu


text:
Q: JQuery datatables showing plain HTML page while loading Can someone please help me with this code? I'm facing problem i.e plain html page showing up  in the beginning. I noticed that with smaller query like 100 records, it works fine but with larger queries like 8000. It shows entire table as plain html table while loading in the beginning and then works normally.
        $(document).ready( function () {
            var oTable = $('#datatables').dataTable( {
                "bJQueryUI": true,
                "sScrollY": "300px",
                "sScrollX": "100%",
                "sScrollXInner": "150%",
                "bScrollCollapse": true,
                "bPaginate": true,
                "aaSorting":[[0, "asc"]],
                "sPaginationType":"full_numbers",
            });
            new FixedColumns( oTable );
        });

A: First of all, set your table to hidden by default:
<table id="#datatables" hidden>

Then include the initComplete callback in the $().DataTable() constructor. This will run only after all of the data has been loaded, so you can then set your table to $().show():
$('#datatables').dataTable( {
  "initComplete": function(settings, json) {
     $('#datatables').show();
     }
} );

A: Remove any data in your HTML file and leave it empty.  This way your page loads right away.  The Ajax source will display a nice loading graphic while the data is being loaded into the page.
Below is the configuration for the plugin to use the Ajax source option.
$(document).ready(function() {
    $('#datatables').dataTable( {
        "bProcessing": true,
        "sAjaxSource": 'arrays.txt'
    } );
} );

Below is served from the arrays.txt where your data is served as a static file or perhaps you have server logic to create your data:
arrays.txt
{
  "aaData": [
    [
      "Trident",
      "Internet Explorer 4.0",
      "Win 95+",
      "4",
      "X"
    ],
    [
      "Trident",
      "Internet Explorer 5.0",
      "Win 95+",
      "5",
      "C"
    ],
    [
      "Trident",
      "Internet Explorer 5.5",
      "Win 95+",
      "5.5",
      "A"
    ]
}


text:
Q: How to read and write Data in Airtable with Flutter? dependencies:
airtable: ^0.0.2
import 'package:airtable/airtable.dart'; ??
import 'package:dart_airtable/dart_airtable.dart'; ??
void main() async {
  final apiKey = 'my-airtable-api-key'
  final projectBase = 'my-airtable-project-base';
  final recordName = 'Tasks';

  var airtable = Airtable(apiKey: apiKey, projectBase: projectBase);
  var records = await airtable.getAllRecords(recordName);

  print(records);
}

If anyone knows how to solve it, I will be very grateful.

A: First of all, it seems like you mix two things together. Currently there are two packages that provide a library for the communication with airtable: airtable 0.0.2 and dart_airtable 0.1.1.
In your example code you use the import statement for the first package but the code from the second one. As the first one doesn't provide a valid link to a repository I'll have a look at the second one.
To retrieve records for a project from the API you can use this code:
var records = await airtable.getAllRecords(recordName);

Unfortunately the package has some bugs. As I wanted to create a record I used the method createRecord like this:
var test = await airtable.createRecord(
  recordName,
  AirtableRecord(
    fields: [
      AirtableRecordField(
        fieldName: 'Short Description',
        value: 'Test Description',
      ),
    ],
  ),
);

print(test);

But the only response I got was null. So I cloned the project and debugged the method. The result was this:
{"error":{"type":"INVALID_REQUEST_UNKNOWN","message":"Invalid request: parameter validation failed. Check your request data."}}

After a little bit of searching I found out that the package sends wrong data to the airtable API. In a toJson method of the AirtableRecord model, the author added the unnecessary fields id and createdTime. After deleting them, the method works.
Response:
AirtableRecord(id: rec9bqN78Le1dbC1g, createdTime: 2020-10-20 19:10:21.000Z, fields: {Short Description: Test Description})

I didn't look for the remaining methods, but my advice is to write your own connection to the airtime API or use the existing package and change the things that aren't working. Hopefully this helps you.
Edit:
I'll checked the repository again, and it seems that the author is inactive. As it only contains a few methods and models to work with the airtable API, I'll guess it's not a bad idea to just wrote your own implementation.
Here an simple example of how to do this (with Dio for the network connection):
try {
  final response = await Dio().post(
    'https://api.airtable.com/v0/$projectBase/$recordName',
    options: Options(
      contentType: 'Application/json',
      headers: {
        'Authorization': 'Bearer $yourApiKey',
        'Accept': 'Application/json',
      },
    ),
    data: {
      'records': [
        {
          'fields': {
            'Short Description': 'Cactus',
            'Total': 11.5,
          }
        },
      ],
    },
  );

  // TODO: Whatever you want to do with the response. A good practice is to transform it into models and than work with them
  print(response);
} on DioError catch (e) {
  // TODO: Error handling
  if (e.response != null) {
    print(e.response.data);
  } else {
    print(e.request);
    print(e.message);
  }
}

Response:
{"records":[{"id":"recrvxH93gJgAGo7j","fields":{"Short Description":"Cactus","Total":11.5},"createdTime":"2020-10-21T20:41:19.000Z"}]}

You could now extend this, maybe as a service with the GetIt package and add your required funtions. I definetly recommend to also use models for your response (have a look at this).
I used one of their example workspaces. The projectBase was an ID. You can just look at their API documentation to see how to build the requests.
Edit 2:
Read could be simple done by this:
final response = await Dio().get(
    'https://api.airtable.com/v0/$projectBase/$recordName',
    options: Options(
      contentType: 'Application/json',
      headers: {
        'Authorization': 'Bearer $yourApiKey',
        'Accept': 'Application/json',
      },
    ),
  );

Update:
final response = await Dio().patch(
    'https://api.airtable.com/v0/$projectBase/$recordName',
    options: Options(
      contentType: 'Application/json',
      headers: {
        'Authorization': 'Bearer $yourApiKey',
        'Accept': 'Application/json',
      },
    ),
    data: {
      'records': [
        {
          'id': 'rechYkD0pDW1NjFAF',
          'fields': {
            'Short Description': 'Cactus II',
            'Total': 11.5,
          }
        },
      ],
    },
  );

And delete:
final response = await Dio().delete(
    'https://api.airtable.com/v0/$projectBase/$recordName/rec0bMv507juqS7pv',
    options: Options(
      headers: {
        'Authorization': 'Bearer $yourApiKey',
        'Accept': 'Application/json',
      },
    ),
  );

These are only examples, I advice you to also read the API documentation to get a overview of what is possible. And your own implementation with proper error handling.
Edit 3:
You can use the filterByFormula parameter to retrieve all the data that matches your condition (Reference).
E.g.:
final response = await Dio().get(
    'https://api.airtable.com/v0/$projectBase/$recordName',
    queryParameters: {
      'filterByFormula': 'SEARCH("Cactus",{Short Description})' // Searches the value 'Cactus' in the 'Short description' field.
    },
    options: Options(
      headers: {
        'Authorization': 'Bearer $yourApiKey',
        'Accept': 'Application/json',
      },
    ),
  );


text:
Q: How to unpickle the files in python? I have some pickle files which have trained machine learning models.
I want to unpickle them and want to see the code. I tried by writing these code lines.
import pickle
with open('cv.pickle','rb') as f:
    data_1 = pickle.load(f)

This code is giving the following error:
AttributeError                            Traceback (most recent call last)

<ipython-input-5-25ea81eeb394> in <module>()
      2
      3 with open('cv.pickle','rb') as f:
----> 4     data_1 = pickle.load(f)

AttributeError: Can't get attribute 'dummy_fn' on <module '__main__'>

A: Pickle doesn't store the code only the variables, class names, import paths, etc. This is why it's easy to create problems with pickle if the supporting code changes.
The code that opens the pickle needs to be able to reach the classes/functions that are referenced in the pickle file. The problem here is that your pickle file references dummy_fn but that function does not exist in the main module you are unpickling in.
It looks like you're reading this in an ipython environment. Define the functions and classes in the same way that you did when you created the pickle file, then open the file.
To mitigate problems, you could define these classes/functions in a module and then just import the module when saving the file and when loading the file.


text:
Q: Is there a theme that reprises the old Sun Sparc style interface? Something like the following:

or

A: You want the CDE desktop environment featuring the Motif toolkit.
As an old-timer, I believe you will have no trouble installing these, even if you have to use the command line ;-).
CDE Solaris theme

GTK2-notif2, a Motif GTK+ 2 theme

Metacity Motif

A: The second image you showed is of OpenWindows. A similar appearance can be obtained by using OLWM or OLVWM, but you won't necessarily have the same applications. (though, the applications actually pictured are XV, Netscape, both of which aren't actually part of openwin, and shelltool, which is a fairly boring terminal emulator.)
I don't think there are any GTK/QT themes that emulate Open Look, though.
Beyond that, some applications with the same look can be found at http://step.polymtl.ca/~coyote/xview_main.html - I don't think any of them are packaged.

A: Try FVWM
http://www.fvwm.org/screenshots/desktops/


text:
Q: Update a row with the position mysql I'm am currently writing a little ranking system in a database. The main problem in the site is that the SQL querys are limited, that's why I try to write the smaller amount of querys, even if that's mean more complicated querys. At the moment my table ranking contain 3 field, user_id, score and rank. Obviously a better score mean a highter rank, here is a little SQL fiddle of my data.
CREATE TABLE ranking(user_id INT, score INT, rank INT);
INSERT INTO ranking(user_id, score, rank) VALUES
    (1, 150, 1),
    (2, 120, 3),
    (3, 130, 2),
    (4, 100, 5),
    (5, 110, 4);

My aim is to write a query that change the score (from here no problem), then set the ranking to the new position, in my fiddle, if I want to add 15 to the score of the user 4, his score will be 115, so he will have a better score that user 5, and his ranking should now be 4 and user five ranking's should be 5, is it possible to do such thing using pure SQL and in only one (maybe two) querys?  I have no idea of how to build such complex query
Edit: After some research, I found some querys With SET @rn=0;
SELECT @rn:=@rn+1 AS rankid, But how use this in a subquery to update the ranking of every user affected by the score change?

A: UPDATE ranking AS r1
JOIN (SELECT score AS old_score, score+15 AS new_score FROM ranking WHERE user_id = 4) AS r2
JOIN (SELECT COUNT(*) AS new_rank FROM ranking
      WHERE user_id != 4
      AND score > (SELECT score+15 FROM ranking WHERE user_id = 4)) r3
SET r1.score = IF(r1.user_id = 4, r2.new_score, r1.score),
    r1.rank = CASE WHEN r1.user_id = 4 THEN r3.new_rank
                   WHEN (r1.score > r2.old_score) = (r1.score > r2.new_score) THEN r1.rank
                   WHEN r1.score > r2.old_score AND r1.score <= r2.new_score THEN r1.rank + 1
              END

DEMO


text:
Q: Radius over WAN I have a couple of small-business routers (Cisco RV120W) that I use at some of our smaller offices configured with a site-to-site VPN to allow connectivity for devices & such between my main office and the remote endpoints.  The RV120W does a fine job of this... and I really can't complain too much.  Users have now been asking about setting up WIFI... and having played with the RV120W quite a bit... I know it supports "enterprise authentication" with wpa2.  After setting it up and trying to make it work... I quickly discovered that the router isn't sending the RADIUS packets through the VPN tunnel...  (packets go out the WAN interface for some dumb reason.)
My last 3 major issues I brought up with Cisco... ended up with a "Won't Fix" ... (even though they admitted it was a bug)... so I don't really feel like battling this problem with them.  So, now I'm reconsidering how to approach this problem to make it work despite limitations of the device.  As a last ditch effort... I may end up putting a dedicated AP on site behind the router... but I would rather not have yet-another device to maintain at each site.
TL;DR:
How safe is it to throw RADIUS packets over the public internet?  Potentially, could the data be intercepted and decrypted?  Is there a potential for a replay attack of sorts?  Are there other concerns I should be aware of?

A: Here is the way I see it then.  You've called their support and they state there's nothing they can do.  IMO this is a routing issue of some sort.  I don't know how much you can configure on your device (I presume it doesn't have the cisco IOS running on it).  Anyway, let's leave that aside and assume you can't.  The option I see are as follows.

*

*Upgrade your routers to a Cisco 881w.  This supports RADIUS over a VPN for sure (that's what we do).

*Live with the extra AP's.  Not actually a bad plan, now your wireless isn't tied into your router.  Meaning if a new wifi standard comes out, you can upgrade independently of the router.

*You can do RAIDUS over the internet, but since its PAP, I would strongly reccomend you NOT do that.

A: Are you using PAP? using CHAP would lower some risk.
Also what type of WAN are we talking?
If the WAN is to your ISP or a shared network? On a closed network meaning a transport that segregates traffic via VLAN or subnet, or directly to public internet with VLAN or subneting, its not as risky. Going across a more open network using PAP is more risky. Also using PPTP vs XAUTH would be an added level of risky.
Radius servers, should be able, manage spoofed Radius Authe/Autho packets over any network from a malicious nas.
Configuring something like nas shared key, duplicate login, client(nas) id, nas type, packet formating. These combined with the encryption will make it very difficult, but not impossible, to used maliciously.


text:
Q: access vba replace vblf's with vbcrlf's Lets say for example my table name is    "thistablelf"  and the column where I want to replace all the vblf occurances is  called   "vblftovbcrlf".
How do I replace all occurances of vblf's to vbcrlf's?

A: IIRC the vb* constants dont work in Access SQL so how about;
UPDATE thistablelf
  SET vblftovbcrlf = replace([vblftovbcrlf],Chr(13),Chr(13) & Chr(10));


text:
Q: $ \sum_{m=1}^{n} \sum_{k=1}^{m} (-1)^{k+1} H_k ~ ^{n}C_{k} = H_n $ How to show that $$\sum_{m=1}^{n}\sum_{k=1}^{m} (-1)^{k+1} H_k  ~ {m \choose k} = H_n.$$
 I substituted $ H_k $ with $ \int_{0}^{1} \frac{1-x^{(k-1)}}{1-x} dx$ in the summation, but I got stuck in integration of the summation.

A: Let $$S_n=\sum_{m=1}^{n}\sum_{k=1}^{m} (-1)^{k+1} H_k  ~ {m \choose k}$$
 Using the representation of the harmonic numbers $$  H_k = \int_{0}^{1} \frac{x^{k}-1}{x-1} dx. ~~~(1) $$ Notice  the power of $x$ is $k$ and not $k-1$ in (1),  we get, $$ S_n = \sum_{m=1}^{n} \int_{0}^{1} \sum_{k=1}^{m} (-1)^{k+1} ~ \frac{x^{k}-1}{x-1} ~ {m \choose k} ~ dx = \sum_{m=1}^{n} \int_{0}^{1} \frac{1}{x-1} \sum_{k=1}^{m} \left[- (-x)^k {m \choose k}+(-1)^{k} {m \choose k} \right]dx
$$ $$ \Rightarrow S_n = \sum_{m=1}^{n} \int_{0}^{1} \frac{1}{x-1} [1 -(1-x)^m -  1 ] ~dx = \sum_{m=1}^{n} \int_{0}^{1} (1-x)^{m-1} dx = \sum_{m=1}^{n}  \frac{1}{m}  = H_n $$

A: We can also use binomial inversion.
We have (defining $H_0=0$) $$H_n = \sum\limits_{m=0}^{n} a_m\binom{n}{m},$$ where $a_0=0$ and $a_m = \frac{(-1)^{m-1}}{m}$ for all positive integers $m$. Hence by binomial inversion, we have
$$a_m = \sum\limits_{k=0}^{m} (-1)^{m+k}H_k\binom{m}{k}$$
for all non-negative integers $m$.
That is,
$$\frac{(-1)^{m-1}}{m} = \sum\limits_{k=0}^{m} (-1)^{m+k}H_k \binom{m}{k}$$
for all positive integers $m$ (by the definition of $a_m$).
This implies that
$$\frac{1}{m} = \sum\limits_{k=1}^{m} (-1)^{k-1}H_k \binom{m}{k}$$
(rememberring we defined $H_0=0$). Summing both sides over $m$ now gives the result.