text:
Q: How do you trigger an event across classes? I am writing a Class Library that will be used by other applications. I am writing it in C#.NET. I am having a problem with triggering events across classes. Here is what I need to do...
public class ClassLibrary
{
    public event EventHandler DeviceAttached;

    public ClassLibrary()
    {
        // do some stuff
        OtherClass.Start();
    }
}

public class OtherClass : Form
{
    public Start()
    {
        // do things here to initialize receiving messages
    }

    protected override void WndProc (ref message m)
    {
       if (....)
       {
          // THIS IS WHERE I WANT TO TRIGGER THE DEVICE ATTACHED EVENT IN ClassLibrary
          // I can't seem to access the eventhandler here to trigger it.
          // How do I do it?

       }
       base.WndProc(ref m);
    }

}

Then in the application that is using the class library I will do this...
public class ClientApplication
{
    void main()
    {
       ClassLibrary myCL = new ClassLibrary();
       myCL.DeviceAttached += new EventHandler(myCl_deviceAttached);
    }

    void myCl_deviceAttached(object sender, EventArgs e)
    {
         //do stuff...
    }
}

A: Probably the easiest option is to add a method to ClassLibrary which raises the event...i.e.
internal void RaiseDeviceAttached(object sender, EventArgs e)
{
  if (DeviceAttached != null) DeviceAttached(sender, e);
}

Then, in OtherClass, simply call that method of ClassLibrary.
Another option is to go down the reflection route to trigger the event.


text:
Q: how do I link a form to a button on react I created a page with a register button that is supposed to take you to a form once you click on it. I did this using React. I have not been able to link the form to the button. kindly explain how I can do this
let navigate = useNavigate();
  function handleClick() {
    navigate('/Form')
    return (
      <>
        <FormComp />
        <button className='btn' onClick={handleClick}>
          <b>Register Now</b>
        </button>
      </>

I wrote this code within the button component but it didnt work

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can I not upgrade pip? I have been trying to upgrade the Pip version that is installed on a VM hosted on Azure (current version is 8.1.2) and cannot get it to upgrade.
I have also already tried to upgrade both supertools and setuptools but they all generate the same error.

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-x/pip, setuptools, supertools

Error message + script
Any clues on how to get around this issue and/or how to resolve it?
Happy to provide any additional information as necessary.


text:
Q: Facebook Group Graph API endpoint for Fetching Groups I have this endpoint for fetching groups an authenticated user is an admin of:
        let groupsDataURL = `https://graph.facebook.com/${userId}/groups?access_token=${accessToken}&fields=administrator,member_count,id,name,icon,cover,permissions,privacy`;

But for some weird reason, some users of my app have been complaining bitterly that they are admin to some groups but the groups are not showing up in the results.
That begs the question, is there another undocumented parameter that I need to use to ensure the Endpoint works well for me. I want all groups the user is an admin of to be returned correctly 100% of the time.
Please help me as my users are super upset already!!!
Thank you.


text:
Q: Message when running apt upgrade "No original module was found for this module on this kernel" When I update ubuntu, apt upgrade, this appears,
rtl8723be.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
I'm using
Kernel 4.4.0-66-generic
Ubuntu 16.04.2 LTS
there is something wrong?
The same goes for:
rtl_pci.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
rtl_usb.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
rtlwifi.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
btcoexist.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
rtl8188ee.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
rtl8192c-common.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
rtl8192ce.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
rtl8192cu.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
rtl8192de.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
rtl8192ee.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
rtl8192se.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
rtl8723ae.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
rtl8821ae.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.4.0-63-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall anyMessage when running apt upgrade "No original module was found for this module on this kernel"
With the new update, does not appear "no original module was found for this module on this kernel".
Current kenel 4.4.0-67-generic
Ubuntu 16.04.2 LTS
64-bit


text:
Q: How to send email from a java web app I have a java web application sitting on Tomcat/Apache.
I have a form which has to send email. What is the best way to get this working.

A: I suppose these threads did appear when you posted your question:
Sending mail from java
How do I send an e-mail in Java?
How can I send an email by Java application using GMail, Yahoo, or Hotmail?

A: You should look at JavaMail API
Additionally, you may want to look at Fancymail, a small library to simplify usage of JavaMail API.

A: Short and dirty copy-and-paste for sending a simple plain text  mail message using javamail here
Tiny example of sending a plain text msg, using custom smtp host:
        Properties props = new Properties();
    props.put("mail.smtp.host", "your.mailhost.com");
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(true);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress("mail@from.com"));
    msg.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("mail@to.com")});
    msg.setSubject("Subject Line");
    msg.setText("Text Body");
    Transport.send(msg);


text:
Q: how to reduce noise or filter out noise with k-means clustering algorithm? DBSCAN? I have 7 known centroids shape=(7,4) and a numpy array of shape=(160000, 4).
If I remove one data set from the numpy array and just use 6 centroids then the kmeans cluster algorithm works quite well. If I include the dataset that has noisy data, then the kmeans clustering algorithm runs into issues.
What are some recommended ways of reducing noise or filtering it out with scikit-learn kmeans clustering?
As an alternative, I have considered using the dbscan algorithm http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html
I did also try to use init=initial_centroids but that did not seem to make a difference
    #numpy array containing noise
    data_with_noise.shape=(160000,4)
    centroids= sk.KMeans(n_clusters=7, init='k-means++', max_iter=1000)
    #this data set gives errors
    centroids.fit_transform(data_with_noise)

    #works well but only for 6 clusters
    no_noise_centroids= sk.KMeans(n_clusters=6, init='k-means++', max_iter=1000)
    no_noise_centroids.fit(data_no_noise)


text:
Q: wvdial, pppd and default route metric I have this in wvdial.conf:
[Dialer Defaults]
Init1 = ATZ
Init2 = ATQ0 V1 E1 S0=0
Modem Type = USB Modem
Phone = *99#
New PPD = yes
ISDN = 0
Username = foo
Init1 = ATZ
Password = foo
Modem = /dev/ttyUSB1
Baud = 9600
Stupid Mode = 0
#Init2 = ATQ0 V1 E1 S0=0 &C1 &D2 +FCLASS=0
Init3 = AT+CFUN=1
Init4 = AT+CGDCONT=1,"ip","internet"
Auto Reconnect = on

(PIN disabled)
This is working for 4G USB Dongle Huawei E3131 @ T-mobile.pl.
And now I have 2 questions:
1 How to translate this config to /etc/conf.d/net for connect as net.ppp1 (Gentoo) (I would connecting without wvdial)
2 After connecting I get default route with metric 0, How to change metric to say 100? (I'm interested in setting metric for both wvdial & pppd way)


text:
Q: ASP compare validator cannot take current date after publish I made an asp.net 4.5 web form application. In my app, one webform has a compare validatior control. Here is my aspx code:

Here's my aspx.cs code for that validator:
        protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            string currentDate = DateTime.Now.ToString("dd/MM/yyyy");
            ComparevalidatorDOB.ValueToCompare = currentDate;
        }
    }

It works fine on my PC. But when I published the web form application in smarterasp; I get this error whenever I go the page using compare validator:

How can I solve this error?   Please note that I'm getting this error after publishing the application. The app works fine in my visual studio 2017. And I can't use javascript for some particular reason.

A: Found a solution to my problem. Here it is...
I added the appropriate culture for date on the top of the page where the problem was occurring.
<%@ Page Title="" Culture="bn-BD" %>

Now my page works fine.
P.S: I found this link very useful to determine which culture to use for different types of format.


text:
Q: How to find three dates are consecutive in an array of dates in javascript? I want a function from which I can identify the dates are consecutive or not.
const userArr1 = [
  { userid: "abc@email.com", doj: "2023-02-15T00:00:00.000Z" },
  { userid: "def@email.com", doj: "2023-02-16T00:00:00.000Z" },
  { userid: "pqr@email.com", doj: "2023-02-17T00:00:00.000Z" },
];

On passing this array in that function it should show dates are consecutive.
const userArr2 = [
  { userid: "abc@email.com", doj: "2023-02-10T00:00:00.000Z" },
  { userid: "def@email.com", doj: "2023-02-5T00:00:00.000Z" },
  { userid: "pqr@email.com", doj: "2023-02-12T00:00:00.000Z" },
];

On passing this array in that function it should show dates are not consecutive.
const userArr3 = [
  { userid: "abc@email.com", doj: "2023-01-31T00:00:00.000Z" },
  { userid: "def@email.com", doj: "2023-02-01T00:00:00.000Z" },
  { userid: "pqr@email.com", doj: "2023-02-02T00:00:00.000Z" },
];

On passing this array in that function it should show dates are consecutive.
I am unable to find the solution my expected solution is I want to find that the dates are consecutive or not.

A: I modified the above answer and its working fine. I also added a new feature as it was required in my case. In that we can find no. of consecutive days you want to check.
const areDatesConsecutive = (userArr, noOfDays) => {
  if (userArr.length >= noOfDays) {
    for (let i = 1; i < userArr[noOfDays]; i++) {
      const diffInDays =
        (new Date(userArr[i].doj) - new Date(userArr[i - 1].doj)) / 86400000;

      if (diffInDays !== 1) return false;
    }
    return true;
  } else return false;
};

A: function areDatesConsecutive(dates) {
  for (let i = 1; i < dates.length; i++) {
    const currentDate = new Date(dates[i].doj.split('T')[0]+"T00:00:00.000Z");
    const previousDate = new Date(dates[i - 1].doj.split('T')[0]+"T00:00:00.000Z");
    const differenceInDays = (currentDate - previousDate) / (1000 * 60 * 60 * 24);
    if (differenceInDays !== 1) {
      return false;
    }
  }
  return true;
}

The function takes an array of objects with doj properties representing dates. It then loops through each date and compares it to the previous date to see if they are one day apart. If any two dates are not consecutive, the function returns false. If all the dates are consecutive, the function returns true.


text:
Q: How to select a column from a table and another column from another table Trying to make a database that has one table for a question and a table for answers to that question.
How to select a question (from poll_question) and the answers (from poll_answer) to that question?
CREATE TABLE poll_question(Id_question int primary key not null, question varchar(60));

CREATE TABLE poll_answer(Id_answer int primary key not null, answer varchar(100));

INSERT INTO poll_question(Id_questao, questao)
VALUES(1,"What kind of paper is allowed in tommorows exam?");

INSERT INTO poll_answer(Id_answer,answer)
VALUES(1,"A4 squared sheet");

INSERT INTO poll_answer(Id_answer,answer)
VALUES(2,"A4 lined sheet");

A: Your poll_answer table is incomplete. It needs another column which indicates which question each answer belongs to e.g.
CREATE TABLE poll_answer(Id_answer int primary key not null, Id_question int, answer varchar(100));
INSERT INTO poll_answer(Id_answer,Id_question,answer)
VALUES(1,1,"A4 squared sheet"),
(2,1,"A4 lined sheet");

Then you can find the answers to a given question with a JOIN:
SELECT q.question, a.answer
FROM poll_question q
JOIN poll_answer a ON a.Id_question = q.Id_question

Output:
question                                            answer
What kind of paper is allowed in tommorows exam?    A4 squared sheet
What kind of paper is allowed in tommorows exam?    A4 lined sheet

Demo on dbfiddle


text:
Q: Regarding Days and Week in Calendar How to find the Particular day for 27 -1-1932, can anyone solve the Problem, how to study the Day for particular calendar events

A: There is a method deduced from congruencies and having into account some facts concerning Leap-years.
The day is given by
$$A+B+C+D+E \equiv x\pmod 7$$ where the digit $x$ gives the required day according to the correspondence $1,2,3,4,5,6,0$ to Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, respectively. This is very easy to remember (why?).
In this formula, $A,B,C,D,E$ are as follows.
$A$ is the century affected by the following procedure:
Giving to the century $2000-2099$ the value $0$, future centuries are valued successively increasing by the terms of an arithmetic progression of common difference and first term equal to $-2$ and past centuries, successively decreasing, the term of an arithmetic progression of common difference equal to 2 and  first term equal to $1$; so one has, for example:
$$1700—1799\to 5\\1800—1899\to 3\\1900—1999\to 1\\2000—2099\to 0\\2100—2199\to -2\\2200—2299\to -4\\2300-2399\to -6$$
$B=$ {last two digits, say $ab$, of the year plus the floor function of $\frac{ab}{4}$}, in other words if $abcd$ is the year then $$B=ab+ \left[\frac{ab}{4}\right]$$
$C$ is the month. You have the following table assigning to each month a fixed number:
$$\begin{cases}6\text{ to January  }  \\2\text{ to February  } \\2\text{ to March   } \\ 5\text{ to April   }  \\ 0 \text{ to May  }  \\3\text{ to June   } \\5\text{ to July   } \\ 1\text{ to August   }  \\ 4\text{ to September   } \\ 6\text{ to October   }  \\2\text{ to November   }  \\ 4 \text{ to December  }\end{cases}  $$
 $D$ is the day- number of the date.
$E$ concerns the Leap-years and its value is $-1$ or $0$.
►►Leap-years are those whose last two digits are multiples of $4$ (say your 1932) and when the number of the year is multiple of $400$. To these special years you assign the variable $E$ with two possible values, $$\begin{cases}E=-1 \text{ when the month is January or February }\\E=0 \text { otherwise }◄◄ \end{cases}$$
Example: For your $1-27-1932$ you have
$$A=1$$ $$B= 32+8=40$$ $$C=6\text{ according to the given table for the variable } C$$  $$D=27$$ $$E=-1$$ hence $$1+40+6+27-1=73\equiv3\pmod7$$ and this $3$ corresponds to the third day of the week (see the beginning).
Your day is $\color{red}{ Wednesday }$.


text:
Q: Move mail runtime error I have set up a macro in Outlook and it was working however in the last few days it has stopped filing received emails to specific folders and comes up with a Run Time Error 438 Object doesn't support this property or method error
First the code:
Dim ns As Outlook.NameSpace
Dim objItem As Object
Dim FolderInbox As Folder
Dim MyItem As Outlook.MailItem

'// Added - A collection to hold the IDs of message to be deleted
Dim cMAILS As Collection

Set ns = Application.GetNamespace("MAPI")
Set FolderInbox = ns.GetDefaultFolder(olFolderInbox)
Set cMAILS = New Collection

For Each objItem In FolderInbox.Items

    ' here is the error
    If objItem.ReceivedTime < Now - 50 And objItem.FlagStatus = 1 Then

        ' Here is a series of code in place
        '  to move copies of messages to different folder

    Next

    On Error Resume Next

    Do While cMAILS.Count > 0

        Set MyItem = ns.GetItemFromID(cMAILS(1))

        If Not MyItem Is Nothing Then
            MyItem.Delete
        End If

        cMAILS.Remove (1)
    Loop

The line with the error is:
If objItem.ReceivedTime < Now - 50 And objItem.FlagStatus = 1 Then

A: Test that each object is a mailitem, because if not they might not have ReceivedTime or Flagstatus. Try something like:
If TypeOf objItem Is MailItem Then
   If objItem.ReceivedTime < Now - 50 And objItem.FlagStatus = 1 Then

...


text:
Q: How to recover only the second instance of a string in a text file? I have a large number of text files (>1000) with the same format for all.
The part of the file I'm interested in looks something like:
# event 9
num:     1
length:      0.000000
otherstuff: 19.9 18.8 17.7
length: 0.000000 176.123456

# event 10
num:     1
length:      0.000000
otherstuff: 1.1 2.2 3.3
length: 0.000000 1201.123456

I need only the second index value of the second instance of the defined variable, in this case length. Is there a pythonic way of doing this (i.e. not sed)?
My code looks like:
with open(wave_cat,'r') as catID:
        for i, cat_line in enumerate(catID):
            if not len(cat_line.strip()) == 0:
                line    = cat_line.split()
                #replen = re.sub('length:','length0:','length:')
                if line[0] == '#' and line[1] == 'event':
                    num = long(line[2])
                elif line[0] == 'length:':
                    Length = float(line[2])

A: If you can read the entire file into memory, just do a regex against the file contents:
for fn in [list of your files, maybe from a glob]:
    with open(fn) as f:
        try:
            nm=pat.findall(f.read())[1]
        except IndexError:
            nm=''
        print nm

If larger files, use mmap:
import re, mmap

nth=1
pat=re.compile(r'^# event.*?^length:.*?^length:\s[\d.]+\s(\d+\.\d+)', re.S | re.M)
for fn in [list of your files, maybe from a glob]:
    with open(fn, 'r+b') as f:
        mm = mmap.mmap(f.fileno(), 0)
        for i, m in enumerate(pat.finditer(mm)):
            if i==nth:
                print m.group(1)
                break

A: Use a counter:
with open(wave_cat,'r') as catID:
    ct = 0
    for i, cat_line in enumerate(catID):
        if not len(cat_line.strip()) == 0:
            line    = cat_line.split()
            #replen = re.sub('length:','length0:','length:')
            if line[0] == '#' and line[1] == 'event':
                num = long(line[2])
            elif line[0] == 'length:':
                ct += 1
                if ct == 2:
                    Length = float(line[2])
                    ct = 0

A: You're on the right track. It'll probably be a bit faster deferring the splitting unless you actually need it. Also, if you're scanning lots of files and only want the second length entry, it will save a lot of time to break out of the loop once you've seen it.
length_seen = 0
elements = []
with open(wave_cat,'r') as catID:
    for line in catID:
        line = line.strip()
        if not line:
            continue
        if line.startswith('# event'):
            element = {'num': int(line.split()[2])}
            elements.append(element)
            length_seen = 0
        elif line.startswith('length:'):
            length_seen += 1
            if length_seen == 2:
                element['length'] = float(line.split()[2])


text:
Q: Application crashes while doing unit testing from framework project I have created a framework project to include all the business logic of my application. So that, the core data model also moved to the framework project. Now I have a few XCTestCase classes to do unit testing for the manager and module classes in the framework. These classes have core data operation. So, during the unit testing, those classes refers to DBManager class. I am getting crash in this case, occurring at the creation of persistent model. At the same time when I used the same unit test cases in the main project, everything is working fine.One thing I mainly noted is that, the storeURL creating at the time of persistent creation is different while running main project and unit test cases in the framework. Following are the storeURL created. file:///Users/Gowtham/Library/Developer/CoreSimulator/Devices/F7DB4F9B-D323-4978-A816-B5363F26BE32/data/Containers/Data/Application/92F08534-F5AD-4B4B-B1A3-D3CEF17758C0/Documents/IHA.sqlite [Main project]
file:///Users/Gowtham/Library/Developer/CoreSimulator/Devices/F7DB4F9B-D323-4978-A816-B5363F26BE32/data/Documents/IHA.sqlite [Unit test cases in the framework project]
Following is the exception showing in the console.

Unresolved error Error Domain=YOUR_ERROR_DOMAIN Code=9999 "Failed to initialize the application's saved data"
  UserInfo={NSLocalizedDescription=Failed to initialize the
  application's saved data, NSUnderlyingError=0x7be93420 {Error
  Domain=NSCocoaErrorDomain Code=134100 "(null)" UserInfo={metadata={
      NSPersistenceFrameworkVersion = 641;
      NSStoreModelVersionHashes =     {
          UserDictionaryEntry = ;
      };
      NSStoreModelVersionHashesVersion = 3;
      NSStoreModelVersionIdentifiers =     (
          ""
      );
      NSStoreType = SQLite;
      NSStoreUUID = "6C70A93B-39DD-4357-A0C2-0BDA5DF51E32";
      "_NSAutoVacuumLevel" = 2; }, reason=The model used to open the store is incompatible with the one used to create the store}},
  NSLocalizedFailureReason=There was an error creating or loading the
  application's saved data.}, {
      NSLocalizedDescription = "Failed to initialize the application's saved data";
      NSLocalizedFailureReason = "There was an error creating or loading the application's saved data.";
      NSUnderlyingError = "Error Domain=NSCocoaErrorDomain Code=134100 \"(null)\" UserInfo={metadata={\n    NSPersistenceFrameworkVersion =
  641;\n    NSStoreModelVersionHashes =     {\n
  UserDictionaryEntry = ;\n    };\n
  NSStoreModelVersionHashesVersion = 3;\n
  NSStoreModelVersionIdentifiers =     (\n        \"\"\n    );\n
  NSStoreType = SQLite;\n    NSStoreUUID =
  \"6C70A93B-39DD-4357-A0C2-0BDA5DF51E32\";\n    \"_NSAutoVacuumLevel\"
  = 2;\n}, reason=The model used to open the store is incompatible with the one used to create the store}"; }

Can anyone give me suggestion for the proper way of writing unit test cases which communicate with core data in a Framework project?
The crash is happening in the following method of DatabaseManager class:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
    return _persistentStoreCoordinator;
}

// Create the coordinator and store

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"IHA.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
    // Report any error we got.
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
    dict[NSLocalizedFailureReasonErrorKey] = failureReason;
    dict[NSUnderlyingErrorKey] = error;
    error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
    // Replace this with code to handle the error appropriately.
    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return _persistentStoreCoordinator;

}
When the app communicate with Framework project for DB operation, it's working fine. At the same time, when the XCTest Target in Framework project invokes DB operation, the crash is happening. Kindly request anyone to give a helpful answer.

A: - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil)
    {
        return _persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"IHA.sqlite"];

    NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
    [options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
    [options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
    {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

A: Thanks for the suggestions given. Finally I found out the reason which is very simple. Even though, I have deleted the app from simulator, references of sqlite file created before in the following path was not cleared. Then I manually went to that path and deleted the old sqlite files generated. Then everything works fine. If anyone face the similar kind of issue, check the older sqlite file generated from the following path. There was a mismatch in the structure defined in older sqlite and xcdatamodel.
/Users/...username.../Library/Developer/CoreSimulator/Devices/F7DB4F9B-D323-4978-A816-B5363F26BE32/data/Documents/appname.sqlite
F7DB4F9B-D323-4978-A816-B5363F26BE32 is the folder which holds all the data related to the app.


text:
Q: javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase I am trying to write a regular expression to validate a password which must meet the following criteria:

*

*Contain at least 8 characters

*contain at least 1 number

*contain at least 1 lowercase character (a-z)

*contain at least 1 uppercase character (A-Z)

*contains only 0-9a-zA-Z

I tried the following but it doesn't seem to work.
http://jsfiddle.net/many_tentacles/Hzuc9/
<input type='button' value='click' class='buttonClick' />
<input type='text' />

and...
$(".buttonClick").click(function () {

    if ($("input[type=text]").filter(function () {
        return this.value.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8})$/);
    })) {
        $("div").text("pass");
    } else {
        $("div").text("fail");
    }

});

Any ideas?

A: Your regular expression should look like:
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/

Here is an explanation:
/^
  (?=.*\d)          // should contain at least one digit
  (?=.*[a-z])       // should contain at least one lower case
  (?=.*[A-Z])       // should contain at least one upper case
  [a-zA-Z0-9]{8,}   // should contain at least 8 from the mentioned characters
$/

A: Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.
Note, also, that your usage of .filter() was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each() loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:
$(".buttonClick").click(function () {

    $("input[type=text]").each(function () {
        var validated =  true;
        if(this.value.length < 8)
            validated = false;
        if(!/\d/.test(this.value))
            validated = false;
        if(!/[a-z]/.test(this.value))
            validated = false;
        if(!/[A-Z]/.test(this.value))
            validated = false;
        if(/[^0-9a-zA-Z]/.test(this.value))
            validated = false;
        $('div').text(validated ? "pass" : "fail");
        // use DOM traversal to select the correct div for this input above
    });
});

Working demo

A: Your regex only allows exactly 8 characters. Use {8,} to specify eight or more instead of {8}.
But why would you limit the allowed character range for your passwords? 8-character alphanumeric passwords can be bruteforced by my phone  within minutes.

A: At least 8 = {8,}:
str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)


text:
Q: Error mod_wsgi django Saludos estoy intentando colocar django en apache tengo la configuracion de la siguiente manera:
<VirtualHost *:80>
    ServerName test.org
    ServerAlias www.test.org
        ServerAdmin pocholo199037@gmail.com

    DocumentRoot /var/www/html/healthsys
    WSGIScriptAlias /var/www/html/healthsys/healthsys/wsgi.py
    <Directory /var/www/html/healthsys/>
            <Files wsgi.py>
                Require all granted
            </Files>
        </Directory>
    ErrorLog /var/www/html/logs/error.log
    CustomLog /var/www/html/logs/custom.log combined
</VirtualHost>

el error que me genera es el siguiente:
ene 07 00:47:18 diego-19 systemd[1]: Starting The Apache HTTP Server...
ene 07 00:47:18 diego-19 apachectl[24419]: AH00526: Syntax error on line 7 of /etc/apache2/sites-enabled/000-default.conf:
ene 07 00:47:18 diego-19 apachectl[24419]: WSGIScriptAlias requires at least two arguments, Map location to target WSGI script file.
ene 07 00:47:18 diego-19 apachectl[24419]: Action 'start' failed.
ene 07 00:47:18 diego-19 apachectl[24419]: The Apache error log may have more information.
ene 07 00:47:18 diego-19 systemd[1]: apache2.service: Control process exited, code=exited status=1
ene 07 00:47:18 diego-19 systemd[1]: apache2.service: Failed with result 'exit-code'.
ene 07 00:47:18 diego-19 systemd[1]: Failed to start The Apache HTTP Server.

Es la primera vez que intento publicar un proyecto de django con apache en ubuntu quiza alguna sugerencia o que estoy haciendo mal, nota no uso entorno virtual uso django instalado de manera global, me pase en el siguiente tutorial:
Publicar Django con apache2
Gracias de antemano

A: Yo siempre uso entorno virtual, pero supongo que utilizando en entorno global funcione igualmente.
De momento creo que tienes un error en la línea WSGIScriptAlias
El formato sería así:
WSGIScriptAlias / /var/www/html/healthsys/healthsys/wsgi.py

En este enlace puedes ver más detalles link
Te recomendaría configurarlo usando el daemon mode con las directivas WSGIDaemonProcess y WSGIProcessGroup


text:
Q: Stuck on trivial proof show $(I - A)$ is non singular if $\|A\| < 1$ Assume $A$ is square, $\|A\| < 1$
Attempt: (by contradiction)
Suppose $I - A$ is singular, then there exists $x$ such that $x \neq 0$, $\|x\| > 0$, $(I - A)x = 0$
Then $\|(I - A)x\| = 0$ and $\|Ix - Ax\| \geq | \|x\| - \|Ax\|$|
But here we do not know $\|Ax\|$, so we cannot claim
$| \|x\| - \|Ax\| > 0$ to obtain a contradiction...
Does anyone know how to carry on from this point?

A: Suppose to the contrary that there exists an $x\neq 0$ such that $(I-A)x = 0$. Assume without loss of generality that $\|x\| = 1$. Then $\|Ax\| = \|x\| = 1$. Hence, $\|A\| = \max_{\|x\|=1} \|Ax\| \geq 1$, which is a contradiction.

A: Hint:
$$\| (I-A)x \| = \| x - Ax \| \geq \| x \| - \| A x \| \geq \| x \| - \| A \| \| x \|$$
The first inequality is the "reverse triangle inequality". It follows from the standard triangle inequality, because
$$x=(x-Ax)+Ax \Rightarrow \| x \| \leq \| x - Ax \| + \| Ax \|.$$

A: Hint: $(I - A)(\sum_n A^n)=(\sum_n A^n) (I - A)=I$ Note that $\|A\| < 1$ implies $\sum_n A^n$ converges


text:
Q: MYSQL UPDATE ERROR - UNABLE TO FIND ISSUE I am getting the following error:

Update Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ContactOfficeNo='20045878' WHERE ClientCode='MARI'' at line 2

Now I notice after ClientCode='Mari', there is another '?
But my code is as below. I can't seem to find the issue. I've got opening & closing "" with the update query inside as it should be:
include("../dbinfo.inc.php");
$comm=@mysql_connect(localhost,$username,$password);
$rs=@mysql_select_db($database) or die( "Unable to select database");

$id = $_POST["clientcode"];
$cli = $_POST["clientname"];
$em1 = $_POST["email1"];
$em2 = $_POST["email2"];
$em3 = $_POST["email3"];
$cry = $_POST["currency"];
$occ = $_POST["othercc"];
$mob = $_POST["mobile"];
$dty = $_POST["dtymobile"];
$off = $_POST["office"];

$sql = "UPDATE tbl_client SET ClientName='$cli', ContactEmail#1='$em1', ContactEmail#2='$em2', ContactEmail#3='$em3', Currency='$cry', OtherCCinfo='$occ', ContactMobileNo='$mob', DutyMobileNo='$dty',
ContactOfficeNo='$off' WHERE ClientCode='$id'";

A: what is the value of $dty ? It is useful in these moments to remember two tips:

*

*) The error (almost) always occurs before the "near" point in the SQL error output notice, so the few characters BEFORE ContactOfficeNo='20045878 is whatever is causing your issue.

*) It is good practive to error log out your complete SQL before you run it to see exactly what's going on when the error occurs.
error_log("My SQL: Line ".__LINE__." :". $sql );

Additionals:
1) As others comments have said you really, REALLY should be looking at using MySQLi or PDO Parameterised queries.

Little Bobby says your script is at risk for SQL Injection Attacks.. Even escaping the string is not safe!

-- Jay Blanchard

If you use parameterized queries, you won't have this problem.

-- Gordon Linoff
2) Stop using @ to suppress errors. You're causing yourself more problems than you're solving.
3) MySQL is DEPRECATED and should not be used. Use MySQLi (or PDO). NOW.
4) Please read and take heed of the comments by Gordon and Jay underneath your question, this is (probably) the cause of your issue, you're not escaping your $_POST input. This is extremely dangerous and will (is) causing you all sorts of issues and bumps.
5) Having non alphabetic characters (so not a-z) in your MySQL column name is risky at best, and may be causing you additional issues. Highly recommended to move away from having any non-a-z characters in your column names.
Please read the docs refrence by Mark Baker about suitable column names.

ContactEmail#1?!? You really have a # in your column names? Permitted characters in unquoted identifiers: ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore) Extended: U+0080 .. U+FFFF If you have other characters, then you need to wrap the column name in backticks (`)

-- Mark Baker


text:
Q: Showing max y-axis with CorePlot CPTAxisLabelingPolicyAutomatic setting I want to plot a figure which have the max y axis value label showing on the label tick with CPTAxisLabelingPolicyAutomatic setting. However I haven't found any public function allow me to do that.
After checking CorePlot source code (autoGenerateMajorTickLocations method) I think I can do some workaround by using CPTDecimalDivide and CPTNiceNum. I implemented my code by increasing my plotRange in Y axis with the calculated "nice number" interval
var majorInterval = CPTDecimalDivide( Decimal(yAxisLength),
CPTDecimalFromUnsignedInteger(5-1))
majorInterval = CPTNiceNum(majorInterval)

let interval = Int(truncating: majorInterval as NSNumber)
let number = Int(yAxisLength/interval) + 1
yAxisLength = Int(Double(number * interval))

However the CPTNiceNum is not a public method so I am wondering are there any better way to do that?

A: Call -layoutIfNeeded on the graph to make sure the axis labels are updated and then read the majorTickLocations set from the y-axis. You can find the max location value in the set easily.


text:
Q: what is lazy allocation? What does lazy allocation of objects mean and how is it useful?

A: Lazy allocation simply means not allocating a resource until it is actually needed.  This is common with singleton objects, but strictly speaking, any time a resource is allocated as late as possible, you have an example of lazy allocation.
By delaying allocation of a resource until you actually need it, you can decrease startup time, and even eliminate the allocation entirely if you never actually use the object.  In contrast, you could pre-allocate a resource you expect to need later, which can make later execution more efficient at the expense of startup time, and also avoids the possibility of the allocation failing later in program execution.
The following code provides an example of a lazily-allocated singleton:
public class Widget {
    private Widget singleton;

    public static Widget get() {
        if (singleton == null) {
            singleton = new Widget();
        }
        return singleton;
    }

    private Widget() {
        // ...
    }

    // ...
}

Do note that this code isn't threadsafe.  In most cases, access to the get() method should be synchronized in some fashion.
A similar (and perhaps more general) concept is lazy initialization.


text:
Q: Tkinter Frame Grids does not work and places them incorrectly Good day, I am currently restructuring my code in which I create several classes as frames and instantiate them at the end in the AllView. The problem is that several things are packed into the same frame and I don't understand that, since I have to create all the frames in the AllView.
For reasons of clarity, I have left out the code in some classes, because it does not play a role in the placement of the frame classes.
The button and plot frame will be instantiated later using a method

   class GUI(Tk):
    def __init__(self):
        super().__init__()
        self.title("GUI")
        self.mainTab = ttk.Notebook(self)
        self.create_tabs()
        self.style = ThemedStyle()
        self.style.set_theme("breeze") #yaru #adapta #breeze

    def create_tabs(self):
        self.mainTab.grid(row=0, column=0)

        device = AllView(self.mainTab)
        self.mainTab.add(device, text="Device")

        # Random new Device
        random = ttk.Notebook(self.mainTab)
        self.mainTab.add(random, text="random")
        self.mainTab.grid(row=0, column=1)

    class MethodFrame(ttk.Frame):
    def __init__(self,master):
        super().__init__(master)
        pass

    class ParameterFrame(ttk.Frame):
        def __init__(self,master):
            super().__init__(master)
            pass

    class PortFrame(ttk.Frame):
        def __init__(self,master):
            super().__init__(master)
            pass

    class ButtonFrame(ttk.Frame):
        def __init__(self,master):
            super().__init__(master)
            pass

    class AllView(tk.Frame):
        def __init__(self, master, *args, **kwargs):
            tk.Frame.__init__(self, master, *args, **kwargs)
            self.methodframe = MethodFrame(self)
            self.portframe = PortFrame(self)
            self.paramframe = ParameterFrame(self)
            self.buttonframe = ttk.Frame(self)
            self.plotframe = PlotView(self,None)
            self.methodframe.grid(row=0, column=0, columnspan=3, sticky=tk.W, padx=5, pady=5)
            self.portframe.grid(row=1, column=0, columnspan=3, sticky=tk.S, padx=5, pady=5)
            self.paramframe.grid(row=2, column=0, columnspan=3, sticky=tk.N + tk.S + tk.W + tk.E)

A: I've never used classes when making my tkinter GUI but it looks like you may be wanting to use the toplevel() function to create new windows for yours, the below link offers a very good guide for getting started. When you make a toplevel frame, you will be able to grid/pack your elements into each newly created frame at the time it called.
https://www.geeksforgeeks.org/python-tkinter-toplevel-widget/


text:
Q: How to get the k smallest elements? Assume I have the vector c(3,7,1,9,7,6,4) and I need to get its three least elements c(3,1,4). How can I do it with R?

A: One possible solution:
sort( c(3,7,1,9,7,6,4) )[1:3]

A: Another possible solution:
sort(x = c(3,7,1,9,7,6,4), partial = 3)[1:3]

Which performs a partial sort.


text:
Q: Bullet spawn speed or generation speed phaser Hi all I have a function that generates bullets every time the player touches the screen.
Is there a way that I can limit the amount of bullets generated? Basically if I press the screen very quickly lots of bullets get generated but I would like to limit it to at least i per second instead of 2 or 3 per second.
Below you can find my firing function and my bullet creation function:
createBullets: function(){
    //Bullets
    this.bullets = this.add.group();
    this.bullets.enableBody = true;
    this.bullets.physicsBodyType = Phaser.Physics.P2JS;
    this.bullets.createMultiple(500, 'bullet', 0, false);
    this.bullets.setAll('anchor.x', 0.5);
    this.bullets.setAll('anchor.y', 0.5);
    this.bullets.setAll('outOfBoundsKill', true);
    this.bullets.setAll('checkWorldBounds', true);

},

fireBullet: function(){
    this.bullet = this.bullets.getFirstExists(false);
    if (this.bullet) {
        this.bullet.reset(this.tanque.x, this.tanque.y - 20);
        this.bullet.body.velocity.y = -500;
    }
},

and my update function:
if(this.input.activePointer.isDown){
    if (!this.mouseTouchDown) {
        this.touchDown();
    }
}else {
    if (this.mouseTouchDown) {
        this.touchUp();
    }
}

Any help I would really appreciate.

A: One option is to store two values:

*

*nextShotTime: next time a shot can be fired

*shotDelay: delay between shots (can be set like Phaser.Timer.SECOND * 2)

I don't see where you're calling fireBullet() in your example code above, but either before you make the call, or within the function, you could then check to see if the nextShotTime is in the past. If it is, fire another bullet and then update the nextShotTime with the current time plus the shotDelay.
For example:
if (this.nextShotTime < this.time.now) {
    this.nextShotTime = this.time.now + this.shotDelay;
    // add your code that will fire a bullet.
}

A: I have had similar problems in games before. The solution I used is the same as the one posted above. I found it in this
Phaser tutorial.
The fire function used in the tutorial is:
fire: function() {
if (this.nextShotAt > this.time.now) {
  return;
}

this.nextShotAt = this.time.now + this.shotDelay;

You can modify it to suit your purposes.
This is part of a fire function I used in a game I made:
    fire: function() {
    //Make sure the player can't shoot when dead and that they are able to shoot another bullet
        if(!this.player.alive || this.time.now < this.nextFireTime) {
            return;
        }

        this.nextFireTime = this.time.now + this.fireRate;

        var bullet;
            //If weaponlvl = 0, shoot a normal bullet
            if(this.weaponlvl === 0) {
                if(this.bullet1.countDead() === 0) {
                    return;
                }
                //Properties for the basic weapon
                this.fireRate = 500;
                bullet = this.bullet1.getFirstExists(false);
                bullet.reset(this.player.x, this.player.y-22);
                bullet.body.velocity.y = -300;
            }

Hope this helps you in some way.


text:
Q: Can't configure Qt on windows I have source code folder of Qt 5.1.0 and also 4.8.4. The thing is that when I put command:
configure -static -release -no-exeptions the text of help screen only flashes and nothing else happens. What's the problem?
Please, help me ASAP.

A: Qt 5.1 is released as an SDK.  Additionally, you can install and use the 4.8.4 library -  which I currently use.  Is there a reason you need to build from source?


text:
Q: jQuery ASP.NET MVC - $.post() to a different URL path in different environments Consider the need to  $.post() to a slightly different URL structure in the Visual Studio Dev environment vs. deployed IIS Production or Test environment.
When deployed to the Test server, the app is running under a Virtual Directory in IIS. The URL will be something like:
Deployed
URL: http://myServer/myApplication/Area/Controller/Action
Using jQuery's .post(), I need to supply the string:
 $.post( "/myApplication/myArea/myController/myMethod"

Development
When in the Visual Studio environment
Cassini URL is: http://localhost:123/Area/Controller/Action
Using jQuery's .post(), I need to supply the string:
 $.post( "/myArea/myController/myMethod"

Question:
How can I make both these use the same line of code, regardless of their deployed environment?

A: The way I've done this is by generating the url from the RouteUrl method like so:
var url = "<%= Url.RouteUrl(new { area="myArea", controller = "controller", action = "actionmethod" }) %>";
$.post(url ...

As long as your routes are set up correctly, this will generate the appropriate Url.
Edit: Now works with areas without modification.

A: Another (simpler?) implementation would be to setup a js variable of your application root:
<script type="text/javascript" >
    var globalAppPath = '<%= Request.ApplicationPath %>';
</script>

Then you can just append it to the beginning of any url request.
$.post( globalAppPath + "/myArea/myController/myMethod"

It'll work no matter where you put your web app.


text:
Q: Azure Front Door with SSL - how to set this up for HTTPS traffic to App Service? Azure Font Door nicely gives us free SSL certificates (well - included in the price). These are auto-generated and no management is needed.
How can we then achieve SSL communciation to our App service from the Front Door (the Front Door is essentially a reverse proxy)?
The issue is that (as per my understanding) - in order for cookies to work correctly - we must set the Host Header correctly for the traffic going Front Door -> App service - which means that the App Service itself must have the certificate in order to do HTTPS for that host name.... but how can we get the App Service to use the certificate that's in the Front Door?
step by step:

*

*in browser: https://www.mycompany.com

*this resolves to the Azure Front Door which does the SSL validation.

*Azure Front Door routes this to the App Service hosted on mycompany.azurewebsites.net

*for cookies to work the Front Door must set the Host Header to 'www.mycompany.com'

*in order for this traffic to be HTTPS the App service must have the certificate for 'www.mycompany.com' - but how can I get/use this certificate bearing in mind it's managed by the Front Door?

I can see no way of getting the certificate out of the Front Door.
What am I missing or mis-understanding here please?
thanks-


text:
Q: How to disable RecyclerView items in Android? Textviews and Checkboxes are in a Recyclerview. Initially all Checkboxes are selected. I want to prevent user changing Checkboxes state but I do not want to prevent Recyclerview scroll. I would like to do this in my fragment class not in adapter class.
How can I prevent user changing Checkboxes state?
Below is the sample code written in onBindViewHolder in adapter class.
holder.cbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            //set your object's last status
            tblFilm.setSelected(isChecked);
        }
    });

The above code used for first mode which allows user clicks on
  checkbox.
After that I have second mode where I do not want to get clicked on
  checkbox at all.

For that I have done is below.
optionsoff(recyclerView);
private static void optionsOff(ViewGroup layout) {
        layout.setEnabled(false);
        layout.setClickable(false);
        for (int i = 0; i < layout.getChildCount(); i++) {
            View child = layout.getChildAt(i);
            if (child instanceof ViewGroup) {
                optionsOff((ViewGroup) child);
            } else {
                child.setEnabled(false);
                child.setClickable(false);
            }
        }

I guess this optionsoff() is not working. Because it is not disabling the checkbox. I can still click on checkbox. I need help on this second method which is disabling the Recyclerview items.

A: Every CheckBox has method setEnabled.
In onBindViewHolder you can get the reference to the checkBox you want and disable it.
Something like this:
public void onBindViewHolder(ViewHolder holder, final int position) {
    holder.checkBox.setEnabled(data.get(position).isEnabled());
}

Also an answer below is working solution through the xml.

A: Mayby try something like this?
<CheckBox
        android:id="@+id/server_is_online"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:checked="true"
        android:clickable="false"
        android:text="@string/server_is_online"
        android:textSize="23sp" />

programmatically in your adapter (which extends BaseAdapter) you can add
public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.rowbuttonlayout, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
        } else {
            view = convertView;
            ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.checkbox.setChecked(true);
        holder.checkbox.setEnabled(false);
}

Good example of class extends BaseAdapter here.


text:
Q: Parse Xml using dom **In this xml only image tag which is in user tag is parsed , rest are not working how to resolve this error.

        1
        Post found

    <url>http://industryvegas.com/pokerspyapp/central//f06d5d94b40d7af9dbba1bd601e5ae33</url>
    <title>test</title>
    <text>testimage</text>
    <image>http://industryvegas.com/pokerspyapp/uploads/posts/a5771bce93e200c36f7cd9dfd0e5deaa.jpg</image>
    <gcomments>
    <gcomment id="38" createdOn="1354269393" likes="1" user_like="false" comments="1">
    <user id="40" username="bhanusharma" user_level="2">
    <image>http://industryvegas.com/pokerspyapp/uploads/users/d645920e395fedad7bbbed0eca3fe2e0.jpg</image>
    </user>
    <text>test image</text>
    <image>http://industryvegas.com/pokerspyapp/uploads/comments/a5771bce93e200c36f7cd9dfd0e5deaa.jpg</image>
    <greplies></gcomment>
    <gcomment id="37" createdOn="1354268379" likes="1" user_like="false" comments="1">
    <user id="40" username="bhanusharma" user_level="2">
    <text>test image comment</text>
    <image>http://industryvegas.com/pokerspyapp/uploads/comments/a5bfc9e07964f8dddeb95fc584cd965d.jpg</image>
    <greplies></gcomment>
    </gcomments>
    </gpost>
    </response>**


text:
Q: PowerShell: Using Out-File to write specific part of Dir listing to a text file So I know how to use Out-File to write a full directory listing to a text file, but my issue is that I want to write only certain parts of the directory to the file, i.e., I only want to write the directory name, the file name, the length of the file, and the last write time.
Here is what I have tried:
I use the "~" as a delimeter.
cls

$Path = "C:\Testpath"
$OutFile = "C:\Testpath\Output.txt"

gci -Path $Path -Recurse | % { $_.Directory + "~" + $_.Name + "~" + $_.Length + "~" + $_.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss") } | Out-File $Outfile

It seems to create the file and write a few lines, then I get this error multiple times until the script finishes. The only few lines that were written seem to be the subfolders within the parent folder.
Error:
+ : Method invocation failed because [System.IO.DirectoryInfo] doesn't contain a method named 'op_Addition'.

At C:\SomeDirectory.ps1:4 char:46
+ gci -Path $Path -Recurse | % { $_.Directory + <<<<  "~" + $_.Name + "~" + $_.Length + "~" + $_.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss") } | Out-File $Outfile
+ CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound

Note: I replaced my actual location with C:\SomeDirectory in the error for obvious reasons.

A: Try to convert Directory to string:
$_.Directory.ToString()

A: Run
$Path = "C:\Testpath"
gci -Path $Path | Get-Member -MemberType Properties | ft -AutoSize

You can see that there are different sets of properties for

*

*TypeName: System.IO.DirectoryInfo:

*

*no .Directory property: use .PSParentPath.Remove(0,38) or  .PSParentPath.Replace('Microsoft.PowerShell.Core\FileSystem::', '') instead (not found smarter substitution);

*no .Length property: use "-0" or whatever else;

*TypeName: System.IO.FileInfo:

*

*use .DirectoryName property (type string) rather than .Directory one (type System.IO.DirectoryInfo).

Here is my dummy solution:
$Path = "C:\Testpath"
$OutFile = "C:\Testpath\Output.txt"

gci -Path $Path -Recurse | % {
    if ($_.Attributes -match "Directory") {
        $_.PSParentPath.Remove(0,38) + "~" + $_.Name + "~" + "-0" + "~" + $_.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
    } else {
        $_.DirectoryName + "~" + $_.Name + "~" + $_.Length + "~" + $_.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
    }
} | Out-File $Outfile


text:
Q: Solving an inequality in 2 similar ways gives opposite solution I have the following inequality: $x+\sqrt{2x^2-4x+4} \ge 0$
Here are the 2 ways how I tried to solve it:
No. 1:
$x+\sqrt{2x^2-4x+4} \ge 0$
$x \ge -\sqrt{2x^2-4x+4}$
$x^2 \ge 2x^2-4x+4$
$0 \ge x^2-4x+4$
$(x-2)^2 \le 0$
The last inequality doesn't make sense, so I tried the other way.
No. 2:
$x+\sqrt{2x^2-4x+4} \ge 0$
$\sqrt{2x^2-4x+4} \ge -x$
$2x^2-4x+4 \ge x^2$
$x^2-4x+4 \ge 0$
$(x-2)^2 \ge 0$
I cannot figure out where did I make the mistake in the first try.

A: Hint:
Note that $$x\geq y\not\Rightarrow x^2\geq y^2$$
For instance:
$$1>-2\Rightarrow1<4$$
Also, note that $$\sqrt{x}\geq0,\ \forall\ x\geq0$$
Can you figure out your mistake?

A:
No. 2:
$x+\sqrt{2x^2-4x+4} \ge 0$
$\sqrt{2x^2-4x+4} \ge -x$
$2x^2-4x+4 \ge x^2$
$x^2-4x+4 \ge 0$
$(x-2)^2 \ge 0$

Here, $\sqrt{2x^2-4x+4} \ge -x$, since LHS is positive, and RHS can be negative or positive.  Hence out final solution would be $(x-2)^2 \ge 0$.  This means
  x
  ∈

    R

.

A: First of all, you must determine for which $x$ an inequality makes sense. Here the condition is
$$2x^2-4x+4=2\bigl((x-1)^2+1\bigr)\ge 0,$$
so it makes sense for all $x$.
You can rewrite  it as
$$\sqrt{2x^2-4x+4}\ge -x.$$
Now remember that, if $A\ge 0$,
$$\sqrt A\ge B\iff A\ge B^2\quad\text{OR}\quad B\le 0$$
so here it is equivalent to
$$2x^2-4x+4\ge x^2\quad\text{OR}\quad x\ge 0\iff x^2-4x+4=(x-2)^2\ge0\quad  \text{OR}\quad x\ge 0. $$
As the first term of this disjunction is always true, the given inequality is always true.

A: Alternative way: $\;\sqrt{2x^2-4x+4} = \sqrt{x^2+(x-2)^2} \ge \sqrt{x^2} = |x| \ge -x\,$ for all $\,\forall x \in \mathbb{R}\,$.


text:
Q: Display data on html page load I'm having some difficulty getting some data to be shown the first time a page is loaded on an ionic app.
What I want to happen is for a user to click a link of the menu, the page to load and data to instantly be displayed. But whats happening is nothing is shown the first time the page is loaded, but if you re-click the link from menu data will be displayed.
My code is -
export class ViewSessions {

lastScans = [];

ionViewWillEnter(){
this.barcodeTracker.lastScans = this.barcodeTracker.getScans();
}

constructor(private barcodeScanner: BarcodeScanner, private
nativeStorage: NativeStorage, private barcodeTracker: BarcodeTracker,
private storage: Storage) {

this.lastScans = this.barcodeTracker.getScans();

}

}

I think what is happening is the array is only being created the first time the page is loaded. Then populated the second time its loaded. So I tried to create the array on the home-page which is loaded with the app, then adding data to this array when this page is loaded and showing the array from home-page in the html, but this was unsuccessful.
Edit -
This is the getScans function that is being called -
public getScans(){
console.log(this.data);
return this.data;
 }


text:
Q: Mule 4.1.2 custom connector error I have created custom connector project using below command,                  "mvn org.mule.extensions:mule-extensions-archetype-maven-plugin:generate" in Mule 4. But when i open this project in anypoint studio 7.1.2 it gives below error ('The import org.mule.runtime cannot be resolved') in all of defaultly created java.class files. I have updated the pom file dependencies also, but still issue persists.
Help me to resolve this error, thanks in advance
Thanks,
Videesh.

A: Studio 7 (including the at this time last release 7.2.2) doesn't support Mule SDK projects. You can use any other IDE that supports generic Maven projects.


text:
Q: How to use AutoMapper to map OData enum string in json request dto to entity enum property I am working on a new ASP.NET Core 3.1.1 API with Microsoft.AspNetCore.OData v 7.3.0, AutoMapper v9.0.0 and Microsoft.AspNetCore.Mvc.NewtonsoftJson v3.1.1
I am getting the following error when I make a POST to the Accounts endpoint using Postman v7.18.0;
AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.

I have reviewed the similar questions list when creating this question but was unable to find a solution.
In reviewing google searches for AutoMapper OData Enums all I could find were the recommendation to decorate my dto class with...
[AutoMap(typeof(Account))]

... and to decorate my dto enum properties with ...
[JsonConverter(typeof(StringEnumConverter))]

However, I still get the error. I found references to using an AutoMapperProfile class with a mapper defined as
CreateMap<Account, AccountModel>().ReverseMap();

But it appears that AutoMapper v9.0.0 no longer has a CreateMap method. My understanding was that adding the [AutoMap(typeof(Account))] to the dto class had the same effect as creating the map in the profile class.
I feel like I am going in circles at this point here so I though I would reach out to the SO community. I am sure it is something simple, I  am just not seeing it.
Here is my POST request body from Postman;
{
  "@odata.context": "https://localhost:44367/v1/$metadata#Accounts",
  "AccountName": "Test Provider",
  "AccountType": "Provider",
  "IsTaxExempt": false,
  "Status": "Active"
}

Here is my AccountsController Post method;
[ODataRoute]
[Produces("application/json;odata.metadata=minimal")]
[ProducesResponseType(typeof(AccountModel), Status201Created)]
[ProducesResponseType(Status400BadRequest)]
public async Task<IActionResult> Post([FromBody] AccountModel record)
{

    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    record.Id = new Guid();
    var entity = _mapper.Map<Account>(record);
    _context.Add(entity);
    await _context.SaveChangesAsync();
    var createdRecord = _mapper.Map<AccountModel>(entity);
    return Created(createdRecord);

}

Here is my Account entity class;
public class Account : EntityBase
{
    [Required]
    [Column(TypeName = "nvarchar(50)")]
    [MaxLength(50)]
    public string AccountName { get; set; }

    public AccountTypes AccountType { get; set; }

    public bool IsTaxExempt { get; set; }

}

Here is the EntityBase class;
public class EntityBase
{
    [Required]
    public Guid Id { get; set; }

    public DateTimeOffset? DateTimeCreated { get; set; } = DateTime.UtcNow;

    public DateTimeOffset? DateTimeLastModified { get; set; }

    [JsonConverter(typeof(StringEnumConverter))]
    public StatusTypes Status { get; set; }

    public bool DeleteFlag { get; set; }
}

Here is my Account DTO class;
[Filter, Count, Expand, OrderBy, Page, Select]
[AutoMap(typeof(Account))]
public class AccountModel : BaseModel
{
    [Required]
    [MaxLength(50)]
    public string AccountName { get; set; }

    [JsonConverter(typeof(StringEnumConverter))]
    public AccountTypes AccountType { get; set; }

    public bool IsTaxExempt { get; set; }
}

Here is my BaseModel class;
[Select, Filter]
public class BaseModel
{
    public Guid Id { get; set; }
    public DateTimeOffset DateTimeCreated { get; set; } = DateTime.UtcNow;
    public DateTimeOffset DateTimeLastModified { get; set; }

    [JsonConverter(typeof(StringEnumConverter))]
    public StatusTypes Status { get; set; }

    public bool DeleteFlag { get; set; }
}

And here are my Enums for AccountTypes and StatusTypes
public enum AccountTypes
{
    Customer = 0,
    Reseller = 1,
    Provider = 2,
}

public enum StatusTypes
{
    Active = 0,
    Inactive = 1,
}

Any ideas?

A: It turns out that I needed to create an instance of an AutoMapper MapperConfiguration and assign it to the mapper.
I ended up putting in in the constructor of the Controller, for example;
    public AccountsController(CdContext context, IMapper mapper)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
        _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        var config = new MapperConfiguration(cfg => cfg.CreateMap<Account, AccountModel>().ReverseMap());
        _mapper = new Mapper(config);
    }

After I did this, everything worked as expected.
Here is a link to AutoMappers docs on the subject.


text:
Q: Passing structure as argument through files/functions I can't get to pass structure as argument through subs/functions in different files of single vbnet project like I use to in earlier MS basic versions.
Here is short example of situation:
Module1.vb
Imports System.IO

Structure mymultitry
     Dim index As Integer
    <VBFixedString(6)> Dim name As String
    Dim weight As Double
End Structure

Module Module1
Public mysetupfile = "mysetup.dat"

Public Sub rwfile(ByVal rw As Integer, ByVal myrecord As Integer, ByVal mmt As mymultitry)

'EDIT: Thanks to SteveDog - proper line should be:
'Public Sub rwfile(ByVal rw As Integer, ByVal myrecord As Integer, ByRef mmt As mymultitry)

    Dim fnum As Integer
    fnum = FreeFile()
    FileOpen(fnum, mysetupfile, OpenMode.Random, OpenAccess.ReadWrite, OpenShare.Shared, Len(mmt))
    If rw Then
        FilePut(fnum, mmt, myrecord)
    Else
        FileGet(fnum, mmt, myrecord)
    End If
    FileClose(fnum)
End Sub

End Module

Form1.vb
Public Class Form1
Dim mmt As mymultitry
Dim mmt1 As mymultitry

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    With mmt
        .index = 4
        .name = "Helga"
        .weight = 128.1445
    End With
    rwfile(1, 1, mmt)  'write

    rwfile(0, 1, mmt1) 'read

    'all zero here !?!
    Debug.Print(mmt1.index)
    Debug.Print(mmt1.name)
    Debug.Print(mmt1.weight)

End Sub
End Class

File "mysetup.dat" is reachable and data is saved correctly what I can see with HxD.
But read part seem's to not work as expected.
Please any help on reliable passing structure as argument without too much public elements based on upper example.

A: I strongly suggest you rewrite your code to use the new .NET IO methods in the System.IO.File class, but, that aside, I think your problem with your existing code is that you need to change your mmt argument from ByVal to ByRef.


text:
Q: How to change mouse wheel scroll speed per application Is it possible to have different mouse wheel scroll speed based on application running on top (focused).
Like slower scroll speed for guake for easy reading and higher for web browser to scroll faster.

A: Introduction
The following script dynamic_mouse_speed.py  allows specifying what mouse pointer and/or scroll speed should be when user-defined window has focus.
Important: the script requires imwheel program to increase scrolling speed. Please install it via sudo apt-get install imwheel
Usage
As shown by -h flag:
usage: dynamic_mouse_speed.py [-h] [-q] [-p POINTER] [-s SCROLL] [-v]

Sets mouse pointer and scroll speed per window

optional arguments:
  -h, --help            show this help message and exit
  -q, --quiet           Blocks GUI dialogs.
  -p POINTER, --pointer POINTER
                        mouse pointer speed,floating point number from -1 to 1
  -s SCROLL, --scroll SCROLL
                        mouse scroll speed,integer value , -10 to 10
                        recommended
  -v, --verbose         prints debugging information on command line

The script allows user to select the window they want to track with mouse click. The mouse pointer will turn into cross and user can select a window they want.
Running python3 dynamic_mouse_speed.py alone only shows popup dialog and does nothing by itself.
Running python3 dynamic_mouse_speed.py  -s 5 increases scroll speed, while python3 dynamic_mouse_speed.py  -s -5 slows scroll speed down. python3 dynamic_mouse_speed.py  -p -0.9 decreases pointer speed, while python3 dynamic_mouse_speed.py  -p 0.9 increases pointer speed. -s and -p options can be mixed. -v produces debugging information on command line.
Source
Also available as GitHub gist
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Sergiy Kolodyazhnyy
Date:  August 2nd, 2016
Written for: https://askubuntu.com/q/806212/295286
Tested on Ubuntu 16.04 LTS

usage: dynamic_mouse_speed.py [-h] [-q] [-p POINTER] [-s SCROLL] [-v]

Sets mouse pointer and scroll speed per window

optional arguments:
  -h, --help            show this help message and exit
  -q, --quiet           Blocks GUI dialogs.
  -p POINTER, --pointer POINTER
                        mouse pointer speed,floating point number from -1 to 1
  -s SCROLL, --scroll SCROLL
                        mouse scroll speed,integer value , -10 to 10
                        recommended
  -v, --verbose         prints debugging information on command line

"""
from __future__ import print_function
import gi
gi.require_version('Gdk', '3.0')
gi.require_version('Gtk', '3.0')
from gi.repository import Gdk, Gtk,Gio
import time
import subprocess
import sys
import os
import argparse

def run_cmd(cmdlist):
    """ Reusable function for running shell commands"""
    try:
        stdout = subprocess.check_output(cmdlist)
    except subprocess.CalledProcessError:
        print(">>> subprocess:",cmdlist)
        sys.exit(1)
    else:
        if stdout:
            return stdout

def get_user_window():
    """Select two windows via mouse.
       Returns integer value of window's id"""
    window_id = None
    while not window_id:
        for line in run_cmd(['xwininfo', '-int']).decode().split('\n'):
            if 'Window id:' in line:
                window_id = line.split()[3]
    return int(window_id)

def gsettings_get(schema,path,key):
    """Get value of gsettings schema"""
    if path is None:
        gsettings = Gio.Settings.new(schema)
    else:
        gsettings = Gio.Settings.new_with_path(schema,path)
    return gsettings.get_value(key)

def gsettings_set(schema,path,key,value):
    """Set value of gsettings schema"""
    if path is None:
        gsettings = Gio.Settings.new(schema)
    else:
        gsettings = Gio.Settings.new_with_path(schema,path)
    return gsettings.set_double(key,value)

def parse_args():
    """ Parse command line arguments"""
    arg_parser = argparse.ArgumentParser(
                 description="""Sets mouse pointer and scroll """ +
                             """speed per window """)
    arg_parser.add_argument(
                '-q','--quiet', action='store_true',
                help='Blocks GUI dialogs.',
                required=False)

    arg_parser.add_argument(
                '-p','--pointer',action='store',
                type=float, help=' mouse pointer speed,' +
                'floating point number from -1 to 1', required=False)

    arg_parser.add_argument(
                '-s','--scroll',action='store',
                type=int, help=' mouse scroll speed,' +
                'integer value , -10 to 10 recommended', required=False)

    arg_parser.add_argument(
                '-v','--verbose', action='store_true',
                help=' prints debugging information on command line',
                required=False)
    return arg_parser.parse_args()

def get_mouse_id():
    """ returns id of the mouse as understood by
        xinput command. This works only with one
        mouse attatched to the system"""
    devs = run_cmd( ['xinput','list','--id-only']   ).decode().strip()
    for dev_id in devs.split('\n'):
        props = run_cmd( [ 'xinput','list-props', dev_id  ]   ).decode()
        if "Evdev Scrolling Distance" in props:
            return dev_id

def write_rcfile(scroll_speed):
    """ Writes out user-defined scroll speed
        to ~/.imwheelrc file. Necessary for
        speed increase"""

    number = str(scroll_speed)
    user_home = os.path.expanduser('~')
    with open( os.path.join(user_home,".imwheelrc") ,'w'  ) as rcfile:
        rcfile.write( '".*"\n' )
        rcfile.write("None, Up, Button4, " + number + "\n"   )
        rcfile.write("None, Down, Button5, " + number + "\n")
        rcfile.write("Control_L, Up,   Control_L|Button4 \n" +
                     "Control_L, Down, Control_L|Button5 \n" +
                     "Shift_L,   Up,   Shift_L|Button4 \n" +
                     "Shift_L,   Down, Shift_L|Button5 \n" )

def set_configs(mouse_speed,scroll_speed,mouse_id):
    """ sets user-defined values
        when the desired window is in focus"""
    if mouse_speed:
        gsettings_set('org.gnome.desktop.peripherals.mouse',None, 'speed', mouse_speed)

    if scroll_speed:
       if scroll_speed > 0:
           subprocess.call(['killall','imwheel'])
           # Is it better to write config here
           # or in main ?
           write_rcfile(scroll_speed)
           subprocess.call(['imwheel'])
       else:
           prop="Evdev Scrolling Distance"
           scroll_speed = str(abs(scroll_speed))
           run_cmd(['xinput','set-prop',mouse_id,prop,scroll_speed,'1','1'])

def set_defaults(mouse_speed,scroll_speed,mouse_id):
    """ restore values , when user-defined window
        looses focus"""
    if mouse_speed:
        gsettings_set('org.gnome.desktop.peripherals.mouse', None,
                      'speed', mouse_speed)

    if scroll_speed:
        if scroll_speed > 0:
           subprocess.call(['killall','imwheel'])
        if scroll_speed < 0:
           prop="Evdev Scrolling Distance"
           run_cmd(['xinput','set-prop',mouse_id,prop,'1','1','1'])

def main():
    """Entry point for when program is executed directly"""
    args = parse_args()

    # Get a default configs
    # gsettings returns GVariant, but
    # setting same schema and key requires
    # floating point number
    screen = Gdk.Screen.get_default()
    default_pointer_speed = gsettings_get('org.gnome.desktop.peripherals.mouse',
                                          None,
                                          'speed')
    default_pointer_speed = float(str(default_pointer_speed))

    # Ask user for values , or check if those are provided via command line
    if not args.quiet:
       text='--text="Select window to track"'
       mouse_speed = run_cmd(['zenity','--info',text])

    user_window = get_user_window()

    scroll_speed = args.scroll
    pointer_speed = args.pointer
    mouse_id = get_mouse_id()

    if pointer_speed:
        if pointer_speed > 1 or pointer_speed < -1:

           run_cmd(['zenity','--error',
                    '--text="Value out of range:' +
                    str(pointer_speed) + '"'])
           sys.exit(1)

    # ensure that we will raise the user selected window
    # and activate all the preferences
    flag = True
    for window in screen.get_window_stack():
        if user_window == window.get_xid():
            window.focus(time.time())
            window.get_update_area()
    try:
        while True:
            time.sleep(0.25) # Necessary for script to catch active window
            if  screen.get_active_window().get_xid() == user_window:
                if flag:
                    set_configs(pointer_speed,scroll_speed,mouse_id)
                    flag=False

            else:
               if not flag:
                  set_defaults(default_pointer_speed, scroll_speed,mouse_id)
                  flag = True

            if args.verbose:
                print('ACTIVE WINDOW:',str(screen.get_active_window().get_xid()))
                print('MOUSE_SPEED:', str(gsettings_get(
                                          'org.gnome.desktop.peripherals.mouse',
                                           None, 'speed')))
                print('Mouse ID:',str(mouse_id))
                print("----------------------")
    except:
        print(">>> Exiting main, resetting values")
        set_defaults(default_pointer_speed,scroll_speed,mouse_id)

if __name__ == "__main__":
    main()

Notes

*

*multiple instances of script allow for setting speed per each separate window.

*When running from command line, popup dialogs produce the following message: Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged. These can be ignored.

*Consult How can I edit/create new launcher items in Unity by hand? for creating a launcher or desktop shortcut for this script , if you desire to launch it with double-click

*In order to link this script to a keyboard shortcut for easy access, consult  How to add keyboard shortcuts?

*It is recommended to use only one mouse when script is running, since it operates on the first device that is found to have Evdev Scrolling Distance property

*Multiple instances can be started to control multiple windows, but it is not recommended for the sake of performance


text:
Q: Unable to find reason for Crash on -[UIScrollView(UIScrollViewInternal) _scrollViewAnimationEnded:finished:] In my app many crashes with the following log are reported very often, but even with several test devices and iOS versions I am not able to reproduce it. So there's no way to find the reason on Xcode. Because there's no step in the trace, that leads to my code, I cannot imagine any way to find the origin of it. The App itself is very complex and of course many Scroll Views, also embedded, are used.
Has anyone an idea where to start looking? Or has anyone had a similar problem before?
I'm very thankful for any help!
Best regards,
Florian
OS Version:      iPhone OS 6.0.1 (10A523)
Report Version:  104

Exception Type:  SIGSEGV
Exception Codes: SEGV_ACCERR at 0xd1d28fbc
Crashed Thread:  0

Thread 0 Crashed:
0   libobjc.A.dylib                     0x392e65b0 objc_msgSend + 16
1   UIKit                               0x35a839f7 -[UIScrollView(UIScrollViewInternal)  _scrollViewAnimationEnded:finished:] + 135
2   UIKit                               0x35a838e9 -[UIAnimator stopAnimation:] + 469
3   UIKit                               0x35b1e257 -[UIAnimator(Static) _advanceAnimationsOfType:withTimestamp:] + 295
4   UIKit                               0x35a83381 -[UIAnimator(Static) _LCDHeartbeatCallback:] + 53
5   QuartzCore                          0x323d3071 CA::Display::DisplayLink::dispatch(unsigned long long, unsigned long long) + 161
6   QuartzCore                          0x323d2fc9 CA::Display::IOMFBDisplayLink::callback(__IOMobileFramebuffer*, unsigned long long, unsigned long long, unsigned long long, void*) + 65
7   IOMobileFramebuffer                 0x340befd7 IOMobileFramebufferVsyncNotifyFunc + 155
8   IOKit                               0x35ee8449 IODispatchCalloutFromCFMessage + 193
9   CoreFoundation                      0x339605db __CFMachPortPerform + 119
10  CoreFoundation                      0x3396b173 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 35
11  CoreFoundation                      0x3396b117 __CFRunLoopDoSource1 + 139
12  CoreFoundation                      0x33969f99 __CFRunLoopRun + 1385
13  CoreFoundation                      0x338dcebd CFRunLoopRunSpecific + 357
14  CoreFoundation                      0x338dcd49 CFRunLoopRunInMode + 105
15  GraphicsServices                    0x33f222eb GSEventRunModal + 75
16  UIKit                               0x3596a2f9 UIApplicationMain + 1121
17                                 0x00005233 main (main.m:14)

A: The SIGSEGV signal is sent to a process when it makes an invalid virtual memory reference, or segmentation fault. (see Wikipedia)
So you are accessing an object that likely has been released. As this is an during an animation, maybe you defined a selector to be invoked after the animation finished or something like that? That would be were I would starting looking.

A: You might want to take a look at this thread: Is there a way to cancel an animated UITableView/UIScrollView setContentOffset:animated:?
That discussion suggests it might be a delegate that is dealloc'd before the scrollview sends the animation ended message.

A: I had the same crash. It turned out to be because we were animating a controller with [controller setContentOffset:newPt animated:YES], and we implemented the scrollViewDidScroll delegate method on the controller. Clicking a button on the screen let you advance to another controller, so if a user managed to click the button while the animation was in progress, we would hit the original poster's crash. The solution is simply to set the delegate to nil in dealloc.


text:
Q: Php: updating database with values from dynamically generated form fields How do I save the following form?
<form name="myform">
<input type="text" name="title" value="title" />

$result = mysql_query("SELECT id, text from details where parent='$parent'
order by id asc") or die('Error');
while(list($id,$ftext) = mysql_fetch_row($result)) {
?>
<textarea name="formfield<?php echo $id;?>" id="<?php echo $id;?>">
<?php echo $ftext;?>
</textarea>
<?php
}
</form>

As you can see above, the MySQL query will load data and dynamically create textareas:
<textarea name="formfield34" id="34">text</textarea>
<textarea name="formfield56" id="56">more text</textarea>
<textarea name="formfield78" id="78">anothet text</textarea>

I need to update database like this:
$result = mysql_query("UPDATE details SET text='$formfield34' WHERE id ='34'") or die('Error');
$result = mysql_query("UPDATE details SET text='$formfield56' WHERE id ='56'") or die('Error');
$result = mysql_query("UPDATE details SET text='$formfield78' WHERE id ='78'") or die('Error');

The problem is that each form will have a different number of textareas loaded dynamically and different $ids. I can not imagine hot to save this form.
Thanks.

A: What you probably need to do is to look at using array notation in your form field names like this:
<textarea name="formfield[34]" id="34">text</textarea>
<textarea name="formfield[56]" id="56">more text</textarea>
<textarea name="formfield[78]" id="78">anothet text</textarea>

PHP will automatically build an array in $_POST['formfield']. that you can access with all this data.  This make it easy to loop through this array and generate SQL for your updates.
foreach($_POST['formfield'] as $key => $value) {
    // write SQL here
}

Now, rather than a bunch of individual SQL queries, you might want to consider using REPLACE syntax so that you can insert/update your data with a single query.

A: in the "while" while creating the textarea save an array with the id of these textarea.
Then retrace the array to use ids when you need it


text:
Q: How can I play a file audio (.mp3) when a button is clicked from a gui? I'm a beginner in Java and so far I learnt to do this:
import javax.swing.JFrame; // Importing JFrame
import javax.swing.JButton; // Importing JButton

public class GUI
{
    public static void main(String[] args) {
        JFrame frame = new JFrame("[JYT]"); // Naming a JFrame to frame + title [JYT]
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit on close
        frame.setSize(500,500); // Size of the frame
        frame.setVisible(true); // Setting to visible
        frame.getContentPane().setBackground(new java.awt.Color(218, 165, 32)); // Goldenrod color
        // Frame is set, time to add a button
        JButton button = new JButton();
        frame.add(button);
    }
}

Thing is I don't know how to display a button on the gui and how to make it play an mp3 when the button is clicked?
Are there any tutorials that will assist me?


text:
Q: fragment won't hide I have a navbar which is supposed to be hidden when a button is pressed, but nothing happens.
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
private TextView mavisTxt;
private Button testBtn;
private Fragment navigationBar;

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

}

private void initVariables() {
    navigationBar = new HeaderNav();
    mavisTxt = (TextView)findViewById(R.id.mavisTxt);
    testBtn = (Button)findViewById(R.id.testBtn);

    testBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                FragmentManager fm = getSupportFragmentManager();
                fm.beginTransaction()
                        .hide(navigationBar)
                        .commit();
                mavisTxt.setText("navbar is hidden");
        }
    });

}
}

Here is the java file for the fragment
public class HeaderNav extends Fragment {
    private static Button homeBtn, optionsBtn, connectionBtn, micBtn, aboutBtn;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.navbar, container, false);

        homeBtn = (Button)view.findViewById(R.id.homeBtn);
        optionsBtn = (Button)view.findViewById(R.id.optionsBtn);
        connectionBtn = (Button)view.findViewById(R.id.micBtn);
        micBtn = (Button)view.findViewById(R.id.homeBtn);
        aboutBtn = (Button)view.findViewById(R.id.aboutBtn);

        return view;
    }
}

and the fragment tag in the main_activity xml :
<fragment
        android:id="@+id/navigationBar"
        android:name="com.example.egi.mavisme.HeaderNav"
        android:layout_width="fill_parent"
        android:layout_height="60dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout="@layout/navbar" />

what am I doing wrong? none of the solutions here in SO works for me. Someone help me.
EDIT:
I have edited my code and now it hides. I have another issue when adding a custom animation, I am getting a
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.ViewGroup.startViewTransition(android.view.View)' on a null object reference

Here is my code now :
public class MainActivity extends AppCompatActivity {
    private TextView mavisTxt;
    private Button testBtn;
    private HeaderNav navigationBar;

    private FragmentManager fm;
    private FragmentTransaction ft;

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

    }

    private void initVariables() {
        fm = getSupportFragmentManager();
        ft = fm.beginTransaction();
        navigationBar = (HeaderNav)fm.findFragmentById(R.id.navigationBar);

        mavisTxt = (TextView)findViewById(R.id.mavisTxt);
        testBtn = (Button)findViewById(R.id.testBtn);

        testBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
                    ft.hide(navigationBar)
                    .commit();
                    if(navigationBar.isHidden()) {mavisTxt.setText("navbar is hidden");}
            }
        });

    }
}

A: Here are some things to note-

*

*Use the ActionBar/ToolBar, this isn't iOS

*You have to add a fragment first

*You are using the show call instead of hiding it
testBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                FragmentManager fm = getSupportFragmentManager();
                fm.beginTransaction()
                        .**show**(navigationBar)
                        .commit();
                mavisTxt.setText("navbar is hidden");
        }
    });


text:
Q: My R plot is displaying its axes completely incorrectly, can someone tell me why? I have used the following dataframe:
dataframe1 = data.frame(x1 = numeric(), x2 = character(), x3 = character(),
                        stringsAsFactors = FALSE)
dataframe1
dataframe1[1,] = c(8.10136702697, "Uncleared", "Before")
dataframe1[3,] = list(0.24816604371, "Uncleared", "After")
dataframe1[2,] = list(4.47101137777, "Cleared", "Before")
dataframe1[4,] = list(12.32421000000, "Cleared", "After")

and used the following code to plot:
plot =  ggplot(dataframe1) +
  geom_bar(aes(x = x3, y = x1, fill = factor(x2)),
           stat="identity", position = "stack", width = 0.7) +
  coord_cartesian(ylim = c(0, 10)) +
  scale_fill_manual('',  values = c("red", "blue"), labels = c("Uncleared", "Cleared")) +
  labs(x="CCP",y="Nominal") +
  theme_bw(base_size = 14)

However, for some reason my axes are completely messed up. They are misaligned and more importantly, the two blocks stacked together should be the same length on a normal axis but instead I have something completely different. Can someone understand where its going wrong, I cannot figure it out

A: Your x1 is character. Transform it to numeric with as.numeric:
ggplot(dataframe1) +
  geom_bar(aes(x = x3, y = as.numeric(x1), fill = factor(x2)),
           stat="identity", position = "stack", width = 0.7) +
  coord_cartesian(ylim = c(0, 10)) +
  scale_fill_manual('',  values = c("red", "blue"), labels = c("Uncleared", "Cleared")) +
  labs(x="CCP",y="Nominal") +
  theme_bw(base_size = 14)


text:
Q: Could you give me an example of how to attach an object in Deleted state – I keep getting an exception From MSDN :

An object in the Deleted state can only be attached when the
  ObjectStateManager is already tracking the relationship instance.

Could you give me an example of how to attach an object in the Deleted state. I tried the following and got "System.InvalidOperationException: The object being attached is in an added or deleted state. Relationships cannot be created for objects in this state".
        var contact = context.Contacts.First();
        Console.WriteLine(contact.Addresses.Count()); // 2

        var address = contact.Addresses.First();

        context.Addresses.DeleteObject(address);
        contact.Addresses.Attach(address); // InvalidOperationException

thank you

A: The exception occurs because the object is already attached once you call DeleteObject. If you want to commit the delete, you should then call
context.SubmitChanges();


text:
Q: Better code reuse I am making a program in VB.Net that connects to a database and allows users to add, edit, and delete records etc. I however want to be able to use a module to create Sub Routines and Functions and referencing them in my forms. I have found a way to get the field names of the table in the dataset so that i can use a loop to get the field and write data to it. My problem however is that the controls used to write to these fields have to be explicitly named  (e.g. txtFirst_Name or cboSubjects). That makes it difficult for me to achieve my tasks as I wont be able to use a loop to add to the fields and i would have to write a line for every input field on a form instead of looping through 10 times for example. Below are copies of my code including use of subs.
Adding to database
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
    query = "Select * from Supplier"
    getTable()
    Try
        Dim cb As New OleDbCommandBuilder(da)
        Dim dSet_NewRow As DataRow
        dSet_NewRow = dSet.Tables("Table").NewRow
        dSet_NewRow.Item("Name") = TextBox1.Text
        dSet_NewRow.Item("Address1") = TextBox2.Text
        dSet_NewRow.Item("Address2") = TextBox3.Text
        dSet_NewRow.Item("Town") = TextBox4.Text
        dSet_NewRow.Item("County") = TextBox5.Text
        dSet_NewRow.Item("Country") = TextBox6.Text
        dSet_NewRow.Item("PostCode") = TextBox7.Text
        dSet.Tables("Table").Rows.Add(dSet_NewRow)
        da.Update(dSet, "Table")
        dSet.Tables.Clear()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

End Sub

Connecting to database
Sub Connect()
    Try
        conn.ConnectionString = connString
        conn.Open()
        'If conn.State = ConnectionState.Open Then
        'MsgBox("open")
        'End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Putting information in a dataset
Sub getTable()
    Try
        da = New OleDbDataAdapter(query, conn)
        da.Fill(dSet, "Table")
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

does anyone know how to use a loop to dynamically assign input using the controls without having to name the textbox1, textbox2......

A: Your methods for reuse would have the variables supplied to them.
Public Shared Sub LoadSomeData(name As String, addr1 As String, addr2 As String, town As String, county As String, country As String, pc As String)
 Try
    Dim cb As New OleDbCommandBuilder(da)
    Dim dSet_NewRow As DataRow
    dSet_NewRow = dSet.Tables("Table").NewRow
    dSet_NewRow.Item("Name") = name
    dSet_NewRow.Item("Address1") = addr1
    dSet_NewRow.Item("Address2") = addr2
    dSet_NewRow.Item("Town") = town
    dSet_NewRow.Item("County") = county
    dSet_NewRow.Item("Country") = country
    dSet_NewRow.Item("PostCode") = pc
    dSet.Tables("Table").Rows.Add(dSet_NewRow)
    da.Update(dSet, "Table")
 Catch ex As Exception
    MsgBox(ex.Message)
 End Try
End Sub

Usage:
LoadSomeData(textbox1.Text, textbox2.Text, textbox3.Text, textbox4.Text, textbox5.Text, textbox6.Text, textbox7.Text)

Though I hope you get around to naming the Textboxes with a name that has some meaning - tbName, tbAddress, etc...


text:
Q: Bitwise operators for filtering? I am struggling a little bit to find a nice data representation for a fairly typical scheduling app. The requirements which mess things up a bit is that there are two parties each who have an arbitrary availability daily and there are courses which are offered more or less at fixed times (though exceptions can occur here as well) independent of whether there are two parties available at that timing or not.
As one of the challenges later will be to find available providers for the scheduled courses, I was wondering whether a quick and elegant way could be to simply store a weekly availability pattern for these in a 64-bit integer with a kind of bit-mask.
My rationale is that essentially, every day has 24 hours (< 2^5) and splitting the day into 10 minute intervals there are 144 slots per day (much less than 2^8). Therefore, every person could get a weekly schedule with every day being an 8 bit availability mask for that day (7 x 8bit = 56 bit, less than a 64 bit int).
Filtering and identifying of potential users can very quickly and simply be done by converting any potential appointments into the same kind of mask and then just doing a bitwise operation to only select candidates which are available there without bothering about further rules etc.
What I am wondering is what the reasons are why I don't see much more filtering happening on bit-level as it seems to be fairly straight forward and I'm guessing will hopefully actually even end up being more elegant than a more verbose and explicit logic, any thoughts/ideas?

A: Typical case of premature optimization. Get your program running first, and only if it is slow, you should start thinking about optimizing it with bitwise operations. You should really start with implementing it in the cleanest way possible, for example by using a vector or list of booleans, which are not limited to some arbitrary length of 64.
You could use for example a numpy array with dtype=bool. This might be slightly less compact than a hand-coded bit-vector, but you get all logical operations for free (you can also use operators like |, ^, & and ~), and on top you can have virtually unlimited size, allow for slicing, indexing, etc.


text:
Q: Example of a SOAP payload for IDEONE Has anyone got a sample SOAP payload for the ideone.com service?
I've tried several clients including the Firefox SOA client ( which returns an error from the service), the 360Works java soap client which crashes on reading the wsdl, and the online soapclient.com which returns nothing.

A: I tried two of the SOAP clients you mentioned, soapclient.com and Firefox SOA, and successfully accessed the service at ideone.com.
First, make sure you are using the API password when trying the service and not the site password.
With soapclient.com, make sure that you're viewing the results as XML. You won't see anything if you choose HTML (one of their options).
With both clients, make sure you don't interpret the status with a key name of "error" as meaning that an error has been returned, if the value of this field is "OK". This indicates success.


text:
Q: Updating create-react-app app, but cannot find react-scripts in package.json The title says it all.
To update my app, which was made with create-react-app, I have to update react-scripts. But, I cannot find this in my package.json. I've even tried installing it manually even though it was not there in the first place and should have been. No luck. Any ideas?

A: can you upload s screenshot what is the message they show you once you run it ?