text:
Q: How to override cartcontroller in magento 2? I want to override cartcontroller(checkout/controller/cart.php) by my module controller. Can anyone help me please? Any help will be appreciated.
I just tried, But it is not working. My files are,
\code \StwBuyXGetY \BuyXGetY \etc\di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <preference for="Magento\Checkout\Controller\Cart"
             type="StwBuyXGetY\BuyXGetY\Controller\Checkout\Cart" />
</config>

\code \StwBuyXGetY \BuyXGetY \Controller\Checkout\Cart.php
<?php
namespace StwBuyXGetY\BuyXGetY\Controller\Checkout;
class Cart extends \Magento\Checkout\Controller\Cart
{
    public function execute(){
        echo 'Hello World'; exit;}
}

Please help. (Note:- I just put the dummy content in cart.php, this is not the actual function.)

A: First of all...I advice against rewriting controllers.
Actually I advice against rewriting anything if you can do it an other way.
Second:  The class Magento\Checkout\Controller\Cart is an abstract class. It is never instantiated so you cannot rewrite it.
I assume you want to replace the behavior of the execute method from one of the classes that extend Magento\Checkout\Controller\Cart.
If so, you can do it with an around plugin for your execute method in the original controller.
Let's take for example Magento\Checkout\Controller\Cart\Add controller action
For this you will need to add this to the di.xml of your module:
 <type name="Magento\Checkout\Controller\Cart\Add">
    <plugin name="buy-x-get-y" type="StwBuyXGetY\BuyXGetY\Plugin\Controller\Checkout\Cart\Add" sortOrder="1" />
</type>

Then create the file StwBuyXGetY/BuyXGetY/Plugin/Controller/Checkout/Cart/Add.php with this content:
namespace StwBuyXGetY\BuyXGetY\Plugin\Controller\Checkout\Cart;
class Add
{
    public function aroundExecute(\Magento\Checkout\Controller\Cart\Add $add, \callable $proceed)
    {
        //your code goes here
        //if you don't want the original method to be called ignore what'e below.
        $returnValue = $proceed();
        return $returnValue;
    }
}

I haven't tested the code, so look out for typos.


text:
Q: Ultraweak convergence on matrix over a von Neumann algebra Let $N$ be a von Neumann algebra and $n\geq1$be an integer. Let $x_\lambda=[x_{i, j}^\lambda]_{i,j} $ be a net in $M_n(N)$. Is it true that $(x_\lambda)_\lambda$ converges ultraweakly to zero in $M_n(N)$ if and only if each entry-net $(x_{i,j}^\lambda)_\lambda$ converges to 0 in the ultraweak topology of $N$?
I was trying to prove that the maps $N\to M_n(N)$ sending an element of $N$ to the matrix with 0 everywhere except the $i, j$ position and the element in the $i, j$ position are ultraweakly continuous and the same for the maps $M_n(N) \to N$ sending a matrix to one of its entries, but I could not do it. Any hint would be appreciated.

A: I believe the simplest answer goes as follows.
First of all, note that this is easily deduced when $N=\mathcal{B(H)}$ because we have a nice description of the predual of $\mathcal{B(H)}$: the trace-class operators, or, if you prefer,
$$\mathcal{B(H)}_*=\overline{\{\phi\in(\mathcal{B(H)},\|\cdot\|)^*:\phi\text{ is WOT continuous}\}}^{\|\cdot\|_{\mathcal{B(H)}^*}}$$
I actually think that this description is more practical here than the trace class operators. Now the $*$-isomorphism $M_n(\mathcal{B(H)})\cong\mathcal{B(H^{(n)})})$ can be used to obtain the result.
Now let $N$ be an arbitrary von Neumann algebra. Then choose a concrete representation of $N$, i.e. find a faithful representation $\pi:N\to\mathcal{B(H)}$ so that $\pi(N)$ is SOT-closed in $\mathcal{B(H)}$. Then $\pi(N)$ is ultraweakly closed: Indeed, if $(\pi(x_\lambda))\subset\pi(N)$ is a net such that $\pi(x_\lambda)\to y$ ultraweakly, then $\pi(x_\lambda)\to y$ in (WOT) because the ultraweak topology is stronger than the weak topology. But $\pi(N)$ is a convex set and (SOT) closed, thus it is also (WOT) closed, so $y\in\pi(N)$. My point is, $\pi(N)\subset\mathcal{B(H)}$ is an inclusion of von Neumann algebras. Since $N\cong\pi(N)$ and $*$-isomorphisms are topological homeomorphisms with respect to the ultraweak topologies, we may simplify this to $N\subset\mathcal{B(H)}$ as von Neumann algebras. But now $M_n(N)\subset M_n(\mathcal{B(H)})$ as von Neumann algebras and the result follows from the one we proved in the special case of $\mathcal{B(H)}$.
This was hinted to me on MO by Nik Weaver, I deleted my post there because on second thought it was way too elementary for math overflow.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Specify which column not to load in numpy.loadtxt() I'm using numpy.loadtxt() to open a csv file. My file has 33 columns and I don't want to load columns 16, 28, 23, and 25. I read that numpy.loadtxt has a parameter usecols where you can specify which column to load.
I think it is not neat to input numpy.loadtxt(usecols=0,1,2,3,4,5.... 15,17,... 33) in the code. Is there a way to handle my problem using numpy.loadtxt or there's another way to open a csv file so I can omit to open some columns in my file?

A: You could do a little set wrangling to produce the desired list of columns:
np.load(..., usecols=sorted(set(range(34))-{16,28,23,25}))


text:
Q: No sound using sdl2_mixer from Homebrew My friend has asked me to test a program for them which uses sdl2_mixer for sound. I am using OS X 10.11.
I installed sdl2_mixer from Homebrew, but when I run the program, there is no sound.
We have tried .mp3, and .ogg files, but to no avail.
This warning is displayed, but I don't know if it is connected to the issue:
This application, or a library it uses, is using the deprecated Carbon
Component Manager for hosting Audio Units. Support for this will be
removed in a future release. Also, this makes the host incompatible with
version 3 audio units. Please transition to the API's in AudioComponent.h.

A: Edit:
Apparently this doesn't work anymore. See Mike's comment below.

After much searching, I tried reinstalling sdl2_mixer with optional compile options enabled in Homebrew.
First, I removed the original install of sdl2_mixer with
brew remove sdl2_mixer

Then I ran
brew --info sdl2_mixer

to find out what compile options I could enable.
Finally, I reinstalled sdl2_mixer with
brew install sdl2_mixer --with-flac --with-fluid-synth --with-libmikmod \
--with-libmodplug --with-libvorbis --with-smpeg2

Not all of these compile options will be necessary in every case. You could experiment by enabling just one at a time until you find the one that works in your case.
(I'm pretty sure the depreciation warning mentioned in the question is not relevant to the successful or unsuccessful playback of sound, because the warning still displays even when sound playback is working.)


text:
Q: Connect ZingCharts to MySQL (build a line chart) Thank you. I can now see the second graph but the second graph I'm having does not have any data in it so it is just a blank chart. This is my php code. What am I doing wrong?
My code:
    <?php
    /* Open connection to "zing_db" MySQL database. */
    $mysqli = new mysqli("localhost", "root", "database123", "productno");

    /* Check the connection. */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
?>

    <script>
/* First line chart */

var myData=[<?php
$data=mysqli_query($mysqli,"SELECT * FROM records");
while($info=mysqli_fetch_array($data))
    echo '["'.$info['Date'].'",'.$info['Alibaba'].'],'; /* Data is formatted here, using the . concatenation operator */
    echo '[]'; /* We'll end up with a trailing comma, so we add an empty element here to pop off later*/
?>];

//--------- Second Line Chart ---------------

var myData1=[<?php
$data1=mysqli_query($mysqli,"SELECT * FROM records");
while($info1=mysqli_fetch_array($data1))
    echo '["'.$info1['Date'].'",'.$info1['Lelong'].'],'; /* Data is formatted here, using the . concatenation operator */
    echo '[]'; /* We'll end up with a trailing comma, so we add an empty element here to pop off later*/
?>];

<?php
/* Close the connection */
$mysqli->close();
?>
myData.pop(); /* Pop off the final, empty element from the myData array */

//Display first line chart

    window.onload=function(){
    zingchart.render({
        id:"AlibabaChart",
        width:"100%",
        height:300,
        data:{
        "type":"line",
        "title":{
            "text":"Alibaba"
        },
        "series":[
            {
                "values":myData
            }
    ]
    }
    });

//Display second line chart

zingchart.render({
        id:"LelongChart",
        width:"100%",
        height:300,
        data:{
        "type":"line",
        "title":{
            "text":"Lelong"
        },
        "series":[
            {
                "values":myData1
            }
    ]
    }
    });

    };

</script>

FYI, the data are from the same table, x value and database but different columns(y value). Thanks!

A: I'm on the team here at ZingChart, and I'll be happy to help you out.
I've replicated your MySQL database setup using your specified structure to better assist you, and I've filled it up with some dummy data that looks like this:
Date,Alibaba
1/13/11,70
2/13/11,42
3/13/11,33
4/13/11,3
5/13/11,28
...

First, we need to open a connection to the database:
<?php
/* Open connection to database */
$mysqli = new mysqli("localhost", "root", "pass", "productno");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
?>

Once we have opened a connection successfully, the next step is to format the data into a format readable by ZingChart. Assuming that you want to use your date values along the x-axis, perhaps it would be best to format your data as ordered pairs like this:
"values":[
    [Date(string),value(int)],
    [Date2(string),value2(int)],
    [Date3(string),value3(int)]
    ...
    ]

In the next step, we will query the database, and use concatenation to wrap quotation marks around each date, and to wrap each Date,Alibaba ordered pair in square brackets.
<script>
/* Create myData variable in js that will be filled with db data */
var myData=[<?php
$data=mysqli_query($mysqli,"SELECT * FROM records");
while($info=mysqli_fetch_array($data))
    echo '["'.$info['Date'].'",'.$info['Alibaba'].'],'; /* Data is formatted here, using the . concatenation operator */
    echo '[]'; /* We'll end up with a trailing comma, so we add an empty element here to pop off later*/
?>];
<?php
/* Close the connection */
$mysqli->close();
?>
myData.pop(); /* Pop off the final, empty element from the myData array */

At this point, if you were to view the page source, variable myData would look like this:
var myData = [
    ["2011-01-13", 70],
    ["2011-02-13", 42],
    ["2011-03-13", 33],
    ...
];

...which means that it's ready to be put into our chart!
    window.onload = function() {
        zingchart.render({
            id: "myChart",
            width: "50%",
            height: 400,
            data: {
                "type": "line",
                "title": {
                    "text": "Data Pulled from MySQL Database"
                },
                "series": [{
                    "values": myData
                }]
            }
        });
    };
</script>

Here's our final result:

I hope that helps you out! Let me know if you have any questions.
Edit 10/20/14:
I see you're having trouble generating two line charts in the same page. In order to render multiple charts in a page, you must include multiple <div> elements with unique ids, with a call to the zingchart.render method for each chart that you want to generate.
Please take a look at this demo.
Notice that there are two <div> elements, one with id="myChartDiv" and another with id="myChartDiv2". We also included two calls to the zingchart.render method in the window.onload function. The first call tells ZingChart to render the chart at the location of the <div> element with id="myChartDiv" and the second call tells ZingChart to render the chart at the location of the <div> element with id="myChartDiv2".
It is possible to use the same array of data in both charts on the page, as seen with the myData variable in the demo provided.
Edit 10/21/14:
Hi again, Cael. I've used your code in my test environment, and it looks like the data isn't loading because you didn't pop off the empty element from the end of your myData1 array.
Simply add:
myData1.pop();

after the line:
myData.pop();

and you should be good to go!


text:
Q: Deletion control button on UITableview edit mode is not working I have implemented UITableview edit mode when a button is clicked but every time it goes to edit mode and I click on the deletion button, nothing happens. I have a view controller with a UITableview on it. I have set my delegate and tableview source as well as all of my editing callbacks. Everything is working (like reordering cells) but whenever I try to delete by pressing the delete control button, the delete button doesn't show up.
I am desperate since it seems like a really simple problem but no matter what I try it doesn't seem to work.
This is how I am implementing edit mode
- (UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:

(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [favoriteCurrencyValueList removeObjectForKey:[favoriteCurrencyList objectAtIndex:indexPath.row]];
    [favoriteCurrencyList removeObjectAtIndex:indexPath.row];
    NSUserDefaults *defaultSettings = [NSUserDefaults standardUserDefaults];
    [defaultSettings setObject:favoriteCurrencyList forKey:@"FavoriteCurrencies"];
    [defaultSettings setObject:favoriteCurrencyValueList forKey:@"PastValues"];
    [defaultSettings synchronize];
    [self.favoriteCurrencyTable beginUpdates];
    [self.favoriteCurrencyTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:(UITableViewRowAnimation)UITableViewRowAnimationLeft];
    [self.favoriteCurrencyTable endUpdates];
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    indexPathSelected = indexPath;
    //[self.view endEditing:YES];
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    [self.favoriteCurrencyList exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];

    [[NSUserDefaults standardUserDefaults] setObject:self.favoriteCurrencyList forKey:@"FavoriteCurrencies"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

This is what sets the edit mode
- (IBAction)editButtonPressed:(UIBarButtonItem *)sender {
    if (self.editing && self.favoriteCurrencyTable.editing) {
        self.editing = NO;
        [self.favoriteCurrencyTable setEditing:NO animated:YES];
        [self.editButton setTitle:@"Edit"];
    }
    else {
        self.editing = YES;
        [self.favoriteCurrencyTable setEditing:YES animated:YES];
        [self.editButton setTitle:@"Done"];
    }
}

A: You need to implement the following method:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

A: - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if (([touch.view isKindOfClass:[UIButton class]] && touch.view.tag==<Button_TAG>)) {
        // prevent recognizing touches on the slider
        return NO;
    }
    return YES;
}

For tap gestures add the delegate and write the above code.

A: If delete does not work then it is a problem of your table view delegate or datasource methods called.Check these methods should definitely be called
1.tableView:editingStyleForRowAtIndexPath:
2.tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:
3.tableView:shouldIndentWhileEditingRowAtIndexPath:
You try to check if titleforDeleteConfirmationbutton is called at every time you click edit and check how many times it calls and also check if you are giving indent return value as yes in shouldIndentwhileediting method.
check your gesture recognizers.


text:
Q: Orthogonal vector such that outer product condition is true I'm having a hard time with a analytic geometry problem. It says: Given the vectors $\vec u = (0,1,-2)$, $\vec v = (3,-6,-3)$ and $\vec w = (0,-1,3)$, determine the vector $\vec a$, orthogonal to $\vec w$, such that $\vec a \times \vec u = \vec v$. I already found the outer product of $\vec a \times \vec u$ using determinants, but I'm not sure how to go on and figure out the variables such that $\vec a \bullet \vec w = 0$.
Thanks in advance.

A: I would start with the fact that $a \cdot w =0$, this says that $a$ is of the form $(x,3z,z)$. Then take a cross product of a vector of this form with $u$, solving for $x$ and$ z$, to make the result $v$.


text:
Q: Android Studio - Daily Notification crashes application I'm new to writing applications, but I had this interesting idea and I have managed to complete it with only one thing left to do. A daily notification. I would like to have one particularly at 21:37 every day, as a reminder to the user. I have tried copying various solutions from tutorials on youtube, unfortunately none of them worked for me. Each time after implementing the code from tutorials and emulating the application in Android Studio the app crashes.
This is the example code I tried to use:
public class MainActivity extends AppCompatActivity
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.working_drawable_main);

        CreateNotificationChannel();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 21);
        calendar.set(Calendar.MINUTE, 37);
        calendar.set(Calendar.SECOND, 0);

        if(Calendar.getInstance().after(calendar)) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        Intent intent = new Intent(MainActivity.this, Notification_recever.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 159, intent, 0);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }

CreateNotificationChannel():

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            CharSequence name = "ReminderChannel";
            String description = "Channel For Alarm Manager";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel("random", name, importance);
            channel.setDescription(description);

            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }

BroadcastReceiver:

public class Notification_recever extends BroadcastReceiver

    @Override
    public void onReceive(Context context, Intent intent) {

        Intent repeating_intent = new Intent(context, RepetingActivity.class);
        repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 159, repeating_intent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "random")
                .setContentIntent(pendingIntent)
                .setSmallIcon(android.R.drawable.arrow_up_float)
                .setContentTitle("Random Game")
                .setContentText("The game you all been waiting for")
                .setAutoCancel(true)
                .setDefaults(NotificationCompat.DEFAULT_ALL)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
        notificationManagerCompat.notify(159, builder.build());
    }

RepeatingActivity:

public class RepetingActivity extends AppCompatActivity

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

    }

AndroidManifest:

    <uses-permission android:name="android.permission.SET_ALARM"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Random_Application.NoActionBar"
        tools:targetApi="31">
        <activity
            android:name=".menu_activity"
            android:exported="false"
            android:label="@string/title_activity_menu" />
        <activity android:name=".RepetingActivity"></activity>
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".Notification_recever"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

    </application>

</manifest>

Logcat of the crash:
2022-09-04 13:08:13.346 25976-25976/com.example.random_app D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2022-09-04 13:08:13.376 25976-26027/com.example.random_app D/libEGL: loaded /vendor/lib64/egl/libEGL_emulation.so
2022-09-04 13:08:13.377 25976-26027/com.example.random_app D/libEGL: loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
2022-09-04 13:08:13.379 25976-26027/com.example.random_app D/libEGL: loaded /vendor/lib64/egl/libGLESv2_emulation.so
2022-09-04 13:08:13.436 25976-25976/com.example.random_app D/CompatibilityChangeReporter: Compat change id reported: 160794467; UID 10146; state: ENABLED
2022-09-04 13:08:13.437 25976-25976/com.example.random_app D/AndroidRuntime: Shutting down VM
2022-09-04 13:08:13.440 25976-25976/com.example.random_app E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.random_app, PID: 25976
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.random_app/com.example.random_app.MainActivity}: java.lang.IllegalArgumentException: com.example.random_app: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
    Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3635)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.IllegalArgumentException: com.example.random_app: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
    Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
        at android.app.PendingIntent.checkFlags(PendingIntent.java:375)
        at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:645)
        at android.app.PendingIntent.getBroadcast(PendingIntent.java:632)
        at com.example.random_app.MainActivity.onCreate(MainActivity.java:128)
        at android.app.Activity.performCreate(Activity.java:8051)
        at android.app.Activity.performCreate(Activity.java:8031)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
            ... 12 more
2022-09-04 13:08:13.468 25976-25976/? I/Process: Sending signal. PID: 25976 SIG: 9

I would be more than happy, if someone replied with the solution or linked an explanation. It's probably something small that I just don't know about. Hope I provided all the important information about the problem
PS: Don't know If that's relevant, but the application has this drawer layout implemented. The type that slides with the menu after you swipe left to right


text:
Q: Bootstrap3 row getting pushed to two lines This is not exactly how my code is but for the sake of an example, I have a 3 column layout, first column being a col-md-3, and inside that I have 3 more columns, one which is col-md-1.  However, because col-md-1 has a width of less than the padding (30px), the column to its right is now pushed to the second line.
to see my example, pull the divider until you are in desktop mode, and notice how the blue column is now on a separate line:
http://plnkr.co/edit/pQyjbrd7v4dWN4Ffkq9b?p=preview
Does this mean I can't have a column that small?  I am coming from Bootstrap 2.x where the span1 had a width with a margin-left, so it used to work fine.

A: The short answer to your question is "Correct, can't have a column that small."  You can't have a "1" sized column within a "3" side column for your purpose. The math is that the tiny column you're trying to display is only 2% (i.e., 8.3% of 25%) of the available page layout. On top of the Bootstrap 3 cols have a 15px left and right padding, which effectively wipes out that 2%.  This is why you're seeing it wrap funny at anything less than about 1410 pixels, by my testing with your code. I don't know what you're trying to do, but the grid probably isn't the right way to do it for a so small a slice of the page.


text:
Q: How can I tell Firefox to access intranet At my job, we have a lot of sites on our intranet. How can I tell Firefox to access the intranet sites?
I keep getting this:

The requested item could not be loaded by the proxy.
Proxy server is unable to locate the
  server: myintranet. The server does
  not have a DNS entry. Check the server
  name in the Location (URL) and try
  again.

A: In the network setting dialog box, where you define the proxy that firefox will you, you can specify which websites will bypass the proxy server.  In here you will need to specify all of the intranet sites that you want to use.

A: You can try
Tools -> Options
then
icon Advanced -> tab Network -> Settings...
and write in textbox No Proxy for:  10.4.* (for example) depending on IP range of your intranet

A: Seems like you need to disable proxy for intranet domain. You can do this near the proxy settings, by mentioning "No Proxy for" your intranet domain.


text:
Q: jQuery font picker in add block form dialog submits form instead of selecting font I want to use the Google Font Picker ( https://www.npmjs.com/package/font-picker ) in the Add Block form dialog (part of Concrete5 CMS). But when I click on the font picker select, it submits the form instead of simply selecting the font. Seems like a JS conflict between the font picker select event and the form dialog submit.
Anyone know how to fix that?
Thank you.
Code (part of Add Block form dialog which pops up with JS):

    <?php
    echo $form->label('font', t('Select text font family'));
    ?>

Image text preview

[SOLVED]
Thanks to Terry:
$('#ccm-block-form').on("click", ":submit", function(e) {
    if (e.target.id !== 'ccm-form-submit-button')
    {
        e.preventDefault();
    }
});

A: e.target actually references a DOM node, not a jQuery object. You should compare it to the DOM node returned from the jQuery object by appending a [0] to it:
if (e.target !== $('#ccm-form-submit-button')[0]) { ... }

Alternatively, a simpler way is simply to check the target's ID:
if (e.target.id !== 'ccm-form-submit-button') { ... }


text:
Q: The role of the 'main.cpp' in a Qt project In a Qt project we generally find a project.pro file, the main.cpp and several header, source and *.ui files, containing all the resources to breathe life and function into the application/project.
If there is more to it than "press the button to show 'Hello, world!'", there might be directories for storing data and configuration files, etc.
My question is (in spite of the fact that an exact answer depends on the specific situation):
What is the general role of the main.cpp in a Qt project (Qt Widgets Application)?

To make clear what I mean:

*

*Is the main.cpp's only purpose to kick off the application?

*If not, what are typical tasks to be performed by the main.cpp?

*Speaking of config files - consider the application has a main form which has (and maybe other classes/dialogs instantiated by the main form as well) to know about some configuration data retrieved from a file. Would the initialization happen in the main.cpp or in the MainForm. In short: "Setting things up..." should be placed where (in the light of the current question)?

*Whatever you feel like saying...

A: (Note: A complete answer should incorporate @thokra's comment, which is to say that main.cpp is a filename and the appearance of the program entry point in a file with that name is only convention.  But it's a fairly well-adhered to convention in Qt programs and C++ in general to try and put the program's entry point in a file with that name.)
One category would be registration of global hooks and settings.  Think about things like qInstallMessageHandler, or QTextCodec::setCodecForCStrings.
Initialization of any non-Qt libraries that your app wants to take for granted would be another area.
If your program has a main window object that's only created and destroyed one time, it might seem equally suitable to put the "run once" code in its constructor/destructor.  But ask yourself exactly what is it about your app that only lets it have one main window.  Why wouldn't it be able to have two in the same process?  Even if that's not part of the requirement today, it can suggest an architectural boundary.
I'll mention from personal experience that if you try making a class derived from QApplication, and then put your global run-once-code in the constructor and destructor of that derived class, that is trickier than it sounds (especially if you spawn threads and make widgets in that constructor).  So I don't think in most scenarios you should derive from QApplication.  I stuck with it because I was making an application framework...but avoid that and your run-once code goes in the main.cpp.

A:
"1. Is the main.cpp's only purpose to kick off the application?"

As from the c++ [standards definition]1 the 1st section says:

3.6 Start and termination [basic.start]
3.6.1 Main function [basic.start.main]
1 A program shall contain a global function called main, which is the designated start of the program. It
  is implementation-defined whether a program in a freestanding environment is required to define a main
  function.
  [ Note: In a freestanding environment, start-up and termination is implementation-defined; startup
  contains the execution of constructors for objects of namespace scope with static storage duration;
  termination contains the execution of destructors for objects with static storage duration. —end note ]

A qt application is still using C++, thus this constraint needs to be satisfied for any executable application.
So presumably: Yes, the main()'s only purpose is to kick off the application.
MainForm and main() aren't really strongly related, other than your configuration will generate a main() function instantiating and calling it. You can also have Qt projects, that don't have any MainForm instance at all (e.g. a just command line app).


text:
Q: The single word for "without any constraints" What is the single word for "without any constraints"?
Or the words in the similar context.
For example,

They express their thoughts _________.

A:
They express their thoughts...

There are many answers:
Openly,
Freely,
Overtly
...
Cambridge dictionary defines them as:
openly:

without hiding any of your thoughts or feelings

freely

without being controlled or limited

overtly

done or shown publicly or in an obvious way and not secret

A: I have seen unrestrained used in such contexts. It means the same as unconstrained.

They express their thoughts unrestrained.

Cambridge Dictionary:

unrestrained
adjective  not limited or controlled:
unrestrained joy/anger/criticism


text:
Q: Overloaded unary operator ++ takes one parameter I want to overload an operator '++' in C#, but when I wrote following code, the VS 2012 give me an error message.
    public LogItem operator ++()
    {
        ++ visitTimes;
    }

The error is Overloaded unary operator ++ takes one parameter
And I here's the definition of class LogItem:
     public class LogItem
     {
        /**
         * Constructor
         */
        public LogItem(string ip)
        {
            ipAddress = ip;
            visitTimes = 0;
        }

        /**
         * Operator Overload Function
         */
        public LogItem operator ++()
        {
            ++ visitTimes;
        }

        public string ipAddress { get; private set; }
        public string location { get; set; }
        public int visitTimes { get; private set; }
     }

What should I do to overload the operator '++'?

A: Operator need to be static member of its defining class and in case of ++ takes an argument of that type:
public class LogItem
{
    ....
    public static LogItem operator ++(LogItem item)
    {
       item.visitTimes ++;
       return item;
    }
}

See Operator overloading tutorial on MSDN for more samples.

A: Overloading the unary operator ++ in C# overloads both the postfix and prefix versions of the operator.
See: http://devhawk.net/2003/07/09/operator-overloading-in-c/ http://www.programmingvideotutorials.com/csharp/csharp-operator-overloading


text:
Q: problem about sqlite database, no such table:  I open a sqlite database and use rawquery to get data.
But the log.e show the information:

android.database.sqlite.SQLiteException: no such table: types:

But, I really have this table.
And i also try to use the other sql ,But also get the error message such as

android.database.sqlite.SQLiteException: no such table: malls:

I am sure there are this two tables.
So why get the error message?

A: If you have multiple contents providers, you might think that your table exists while it does not. In which case the error you are getting is legitimate.
Take a look here for details and solution:
http://devserghini.blogspot.com/2010/11/android-sqliteopenhelper-and-multiple.html

A: I think this error occurs when you change the table structure. To solve this, clean the data
(Settings -> Manage application -> Clear data) before installing the new application.
Regards.

A: If this is on the emulator, use DDMS File Explorer or adb pull to download a copy of the database file and confirm its contents.

And i crate a custom SQLiteOpenHelper
  to copy this file to path :
  /data/data/com.SGMalls/databases/mallMapv2.sqlite

If you are attempting to copy the file in SQLiteOpenHelper's onCreate(), you are too late. I would do it before then.

So the copy file code may be can not
  copy the complete file.

It is more likely you would get an error about a corrupt file in that case.

A: SQLiteDatabase.execSQL() interpretation takes a single string sql, ending with ";". Two lines have not interpreted.
Creating tables in a few lines sql just not executed.


text:
Q: Make submit work by pressing enter on PHP and Javascript login page I'm pretty new to Javascript and I'm sure this is an easy fix, but I can't figure it out.
I'm using a slightly modified version of the code from this page and I want to make the form work by entering the information and pressing enter rather than having to click the button.
FYI I've read this thread and can't work out my own answer from there. I tried changing the type to "submit" from "button" but then the login didn't work. I've also tried changing "onlick" to "onsubmit" and had the same problem.

A: Use a type of "submit" but change the onclick to onclick="loginFunction(); return false;"
The return false stops the submit button from actually doing the submit.

A: If you want to submit a form  on click of button instead of enter then no need to use input type="submit" instead of this you can use input type='button' and set a onclick function in this like input type="button" onclick="my_func()" and in the definiton of this function my_func you can use document.formname.submit() for submitting the form.
  hope it will work for you.

A: Set the "tab index" property of your html elements with your button having the highest index (or one up after the last html element)


text:
Q: Generating the next heatmap in a sequence of labelled heatmaps without assuming continuity I have a sequence of labelled heatmaps and I want to generate a new heatmap that is the 'best guess' at what the next heatmap in the sequence will look like, without assuming that the next heatmap should have any 'continuity' with the previous heatmap (i.e. so not like frames of a video of someone walking, where there is generally continuity between one frame and the next).
As an example, these heatmaps could represent the areas of a 2D space where people spent most of their time in a given time interval.
My question is: what machine learning model would be best suited to predict the next heatmap in the sequence, knowing that 1) continuity with the previous heatmap should not be assumed (which potentially rules out those models that predict the next frame in a video), and 2) we want a 'best guess' at the next heatmap, not multiple different guesses in the same way that a conditional GAN designed to output handwritten digits would output different 1s or 5s each time?

A: A conditional GAN would likely work. Many practical implementations of cGAN leave out the noise, on the basis that there is so much training data, it's unlikely the discriminator will notice that the generator only produces one output per conditional input. (Or, if you don't want to use this trick, you could query the GAN with multiple noise vectors and average all the outputs to get the "conditional mean").


text:
Q: delphi service application stop after 15 second, timer not executing I want to make service application in Delphi that run and copy some files everyday at 02:00 PM. So i have used timer. but control not going to timer event and Service terminate within 15 second. I have wrote a code on Timer Event. How can i use timer with service? Please Help. Thanks in Advance.
My Code is Here:
unit untMain;

interface

uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs, Vcl.ExtCtrls, DateUtils, Vcl.Forms,
untCommon;

type
TsrvBackupService = class(TService)
tmrCopy: TTimer;
procedure tmrCopyTimer(Sender: TObject);

private
strlstFiles : TStringList;
{ Private declarations }
public
{ Public declarations }
end;

var
srvBackupService: TsrvBackupService;

implementation

{$R *.DFM}

procedure ServiceController(CtrlCode: DWord); stdcall;
begin
srvBackupService.Controller(CtrlCode);
end;

procedure TsrvBackupService.tmrCopyTimer(Sender: TObject);
var
strCurTime   : string;
strBKPpath   : string;
strBKPTime   : string;
NowDay       : word;
NowMonth     : word;
NowYear      : word;
NowHour      : word;
NowMin       : word;
NowSec       : word;
NowMilli     : Word;
begin
  DecodeTime(now,NowHour,NowMin,NowSec,NowMilli);
  strCurTime := IntToStr(NowHour)+':'+IntToStr(NowMin);
  strBKPTime := '14:00'
  strBKPpath := ExtractFilePath(Application.ExeName);
  if strCurTime = strBKPTime then begin
     Try
           CopyFile(PChar('c:\datafile.doc'),PChar(strBKPpath + 'datafile.doc'),true);
     except
        on l_e: exception do begin
           MessageDlg(l_E.Message,mtError,[mbOk],0);
        end;
     end;
  end;
end;

end.

A: Instead of a timer, use a simple thread launched in OnStart event.
A tutorial is here:
http://www.tolderlund.eu/delphi/service/service.htm
TTimer is better suited for GUI applications. They need a message pump (see here):

TTimer requires a running message queue in order to receive the
  WM_TIMER message that allows the OS to pass the message to the HWND,
  or to trigger the specified callback

A: As others have explained, you cannot simply use a TTimer component inside a Windows Service Application, as it relies on a message pump which does not come by default in a Service. I see four main options:

*

*Implement a message pump to be able to use the TTimer,

*Use a Thread to continuously check for the date/time

*Just like #2, use the Service's OnExecute event to check for date/time

*Utilize Windows' Scheduled Tasks
I would recommend #2 above, and here's why.
#1 might be a bit much for your scenario, I'm sure you don't want to go that far.
#3 might be easier, but the service's thread needs a little special treatment which I'm also sure you don't need to care about.
#4 might be the ideal solution, but I won't try to change your decision on a service.
Creating a thread is the way to go because it's rather simple and expandable. All my service applications work on a multi-threaded basis, and nothing ever goes inside the actual service's thread, other than handling the actual service.
I was working on a sample for you, but I over-complicated it and it would be a lot of pollution to include it here. I hope at least I got you moving in the right direction.

A: When you say "service terminates after 15 seconds" it makes me think you are debugging the code.
If you don't have any option and can't use what others suggested, with the code above the timer event is triggered properly when you install and start the service via services.msc. However, if you are debugging the service, the timer event will not be triggered and the aplication will terminate (as you said). I would create a procedure to be called inside timer event, and call it once in ServiceExecute event, so you could debug like this:
procedure TSomeService.ServiceExecute(Sender: TService);
begin
  ExecuteSomeProcess(); // Put breakpoint here to debug
  while not self.Terminated do
    ServiceThread.ProcessRequests(true);
end;

procedure TSomeService.TimerTimer(Sender: TObject);
begin
  timer.Enabled := false;
  ExecuteSomeProcess(); // This can't throw any exception!
  timer.Enabled := true;
end;


text:
Q: ViewPagerIndicator Compile Errors 'dividerPadding cannot be resolved' I for the life of me cannot get ViewPagerIndicator to compile for use in my project!
Website: http://viewpagerindicator.com/
Github: https://github.com/JakeWharton/Android-ViewPagerIndicator
Here are the steps I have taken:

*

*Download Version 2.4.1 — 2012-09-11 from http://viewpagerindicator.com/.
(I have also tried cloning from the git repo)

*In Eclipse File->Import->Existing Projects into Workspace.

*In the Import dialog, I browse to the Android-ViewPagerIndicator directory and import the example and library projects.

*Eclipse then imports the projects and displays the following compile errors:

*

*The container 'Android Dependencies' references non existing library 'C:\Users\Jonathan\workspace\Android-ViewPagerIndicator\library\bin\library.jar'

*error: Error: No resource found that matches the given name: attr 'android:dividerPadding'.

*dividerPadding cannot be resolved or is not a field

*SHOW_DIVIDER_NONE cannot be resolved to a variable

*error: Error: No resource found that matches the given name: attr 'android:showDividers'.

*SHOW_DIVIDER_MIDDLE cannot be resolved to a variable

*The project cannot be built until build path errors are resolved

*showDividers cannot be resolved or is not a field
My environment:

*

*Windows 7 SP 1

*Eclipse Platform 4.2.0.I20120608-1400 - org.eclipse.platform.ide

*Android 2.3.3 (API 10) Installed

*Android Support Library Installed

*Java v7.0.70.11

These errors seem stupid, why would basic constants and attributes be missing?
I've been Googling this damn thing for hours and can't find anything, your help is MUCH appreciated!

A: The ViewPagerIndicator library requires being compiled with Android 4.0 or newer.
VPI uses constants which are only available on API 14 and newer which end up getting compiled into the class files directly. This is why despite using things from a new API you can still utilize the library back through Android 1.6.


text:
Q: Split Row by Condition in R I have a dataframe with coefficients and standard errors (in parenthesis) of a regression model that looks like this:
data =  data.frame(Variable = c('x1', 'x2', 'x3'),
           Coefficients_se1 = c('0.04 (0.03)', '', ''),
           Coefficients_se2 = c('', '0.08*** (0.01)', ''),
           Coefficients_se3 = c('', '', '0.02* (0.01)'))

print(data)

  Variable Coefficients_se1 Coefficients_se2 Coefficients_se3
1       x1      0.04 (0.03)
2       x2                    0.08*** (0.01)
3       x3                                       0.02* (0.01)

I would like to know if there is a way to move the values in the parenthesis to the line above in the same dataset. This way, I would like to produce an output like above:
  Variable Coefficients_se1 Coefficients_se2 Coefficients_se3
1       x1             0.04
2                    (0.03)
3       x2                           0.08***
4                                     (0.01)
5       x3                                              0.02*
6                                                      (0.01)

Is it possible to do this using R ?

A: I can't think of an 'easy' way to achieve your expected output, but you can manipulate your data using tidyverse functions, e.g.
library(tidyverse)

data = data.frame(Variable = c('x1', 'x2', 'x3'),
                   Coefficients_se1 = c('0.04 (0.03)', '', ''),
                   Coefficients_se2 = c('', '0.08*** (0.01)', ''),
                   Coefficients_se3 = c('', '', '0.02* (0.01)'))

data %>%
  pivot_longer(-Variable) %>%
  filter(value != "") %>%
  separate(col = value, into = c("coef", "stderr"),
           sep = " ") %>%
  pivot_longer(-c(name, Variable),
               names_to = "stat") %>%
  pivot_wider(names_from = name,
              values_from = value)
#> # A tibble: 6 × 5
#>   Variable stat   Coefficients_se1 Coefficients_se2 Coefficients_se3
#>   <chr>    <chr>  <chr>            <chr>            <chr>
#> 1 x1       coef   0.04             <NA>             <NA>
#> 2 x1       stderr (0.03)           <NA>             <NA>
#> 3 x2       coef   <NA>             0.08***          <NA>
#> 4 x2       stderr <NA>             (0.01)           <NA>
#> 5 x3       coef   <NA>             <NA>             0.02*
#> 6 x3       stderr <NA>             <NA>             (0.01)

Created on 2023-01-10 with reprex v2.0.2


text:
Q: Neo4j: possible to create an alternative to node ids based on integer increments? Neo4j's nodes tend to be set on the basis of integer increments. I can see this having issues in an application that needs to merge multiple two databases. Is it possible to configure the database to use another format, such as UUIDs to identify each node?

A: What I have done before is set a property on each node to store a GUID and created an index using the IndexService that creates a GUID index. I have then worked with that index to retrieve nodes based on GUID rather than the internal Neo4J generated ids.

A: No, it's not.
[Stack Overflow requires 30 chars]

A: Here is a neo4j extension that adds uuid properties to each node.
https://github.com/sarmbruster/neo4j-uuid
Quote from the author why you should use uuid if you are dealing with multiple database:

... node.getId() is a bad choice since after deletion of a node its id might be recycled.


text:
Q: Running SQLite inside an Azure Kubernetes Cluster I am evaluating if it makes sense and is even possible to use an SQLite database inside a Kubernetes cluster that runs on Azure.
I have little to no experience with Kubernetes and Azure. I have some experience with Docker and I imagine running an SQLite database would be as simple as defining a volume that contains the database and has other services on the cluster using it.
Is that considered bad practice since I mostly see Postgres being used in such environments, or am I overthinking it?
I imagine an SQLite database would be useful since users wouldn't have to pay for another Postgres instance and the data being stored is not critical (mostly logs). I just don't know if this is right in a cloud environment.

A: It sounds to me wrong design. You will have many issues with sqlite, also how will it scale?  The main idea of kubernetes is ability to scale with sqlite you could do it but you will spend lots of time on making it work..
I would recommend you to use Application Insights service. When it comes to logs its not only storing it also how do you query that. And using app insight for years i think it worth paying for it. If cost is a big deal you can have a look into sampling


text:
Q: Two different methods for sharing data between Android activities I noticed that sharing data between activities can be performed with 2 methods !
1st Method :
 Intent myIntent = new Intent (view.getApplication,myActivity.class);
 myIntent.putExtra("data","value");

2nd Method :
Intent myIntent = new Intent (view.getApplication,myActivity.class);
Bundle myBundle = new Bundle();
myBundle.putString("data","data");
myIntent.putExtra(myBundle);

My question here is what's actually the difference between those 2 methods ?

A: As you can see from Intent.java source code, data passed to Intent always serialized into Bundle object. So difference is "how your data will be serialized/deserialized"
public Intent putExtra(String name, String value) {
    if (mExtras == null) {
        mExtras = new Bundle();
    }
    mExtras.putString(name, value);
    return this;
}

public Intent putExtra(String name, Bundle value) {
    if (mExtras == null) {
        mExtras = new Bundle();
    }
    mExtras.putBundle(name, value);
    return this;
}


text:
Q: How to parse marked up text in C# I am trying to make a simple text formatter using MigraDoc for actually typesetting the text.
I'd like to specify formatting by marking up the text. For example, the input might look something like this:
"The \i{quick} brown fox jumps over the lazy dog^{note}"

which would denote "quick" being italicized and "note" being superscript.
To make the splits I have made a dictionary in my TextFormatter:
internal static TextFormatter()
    {
        FormatDictionary = new Dictionary<string, TextFormats>()
        {
            {@"^", TextFormats.supersript},
            {@"_",TextFormats.subscript},
            {@"\i", TextFormats.italic}
        };
    }

I'm then hoping to split using some regexes that looks for the modifier strings and matches what is enclosed in braces.
But as multiple formats can exist in a string, I need to also keep track of which regex was matched. E.g. getting a List<string, TextFormats>, (where string is the enclosed string, TextFormats is the TextFormats value corresponding to the appropriate special sequence and the items are sorted in order of appearance), which I could then iterate over applying formatting based on the TextFormats.
Thank you for any suggestions.

A: Consider the following Code...
string inputMessage = @"The \i{quick} brown fox jumps over the lazy dog^{note}";
MatchCollection matches = Regex.Matches(inputMessage, @"(?<=(\\i|_|\^)\{)\w*(?=\})");

foreach (Match match in matches)
{
    string textformat = match.Groups[1].Value;
    string enclosedstring = match.Value;
    // Add to Dictionary<string, TextFormats>
}

Good Luck!

A: I'm not sure if callbacks are available in Dot-Net, but
If you have strings like "The \i{quick} brown fox jumps over the lazy dog^{note}"  and
you want to just do the substitution as you find them.
Could use regex replace using a callback
 #  @"(\\i|_|\^){([^}]*)}"

 ( \\i | _ | \^ )         # (1)
 {
 ( [^}]* )                # (2)
 }

then in callback examine capture buffer 1 for format, replace with {fmtCodeStart}\2{fmtCodeEnd}

or you could use
 #  @"(?:(\\i)|(_)|(\^)){([^}]*)}"

 (?:
      ( \\i )             # (1)
   |  ( _ )               # (2)
   |  ( \^ )              # (3)
 )
 {
 ( [^}]* )                # (4)
 }

then in callback
 if (match.Groups[1].sucess)
   // return "{fmtCode1Start}\4{fmtCode1End}"
 else if (match.Groups[2].sucess)
   // return "{fmtCode2Start}\4{fmtCode2End}"
 else if (match.Groups[3].sucess)
   // return "{fmtCode3Start}\4{fmtCode3End}"


text:
Q: $x^{4}+y^{2}+z^{2}=1$ diffeomorphic to 2-sphere $\mathbb{S}^{2}$ This is homework so no answers please
The problem is: $A=\{(x,y,z)\in \mathbb{R}^{3}: x^{4}+y^{2}+z^{2}=1\}$ is diffeomorphic to 2-sphere $\mathbb{S}^{2}$.
Any mistakes:
Consider $f:\mathbb{R}^{3}\setminus \{0\}\to \mathbb{R}^{3}$ defined as $f(x,y,z)=(\sqrt{x},y,z)$. This is a smooth map so its restriction to $f':A\to \mathbb{S}^{2}$ is also smooth with smooth inverse $f(x,y,z)=(x^{2},y,z)$. Bijectivity follows easily.
Yeah so the problem is A will not be contained in $\mathbb{R}^{3}\setminus \{0\}$.  I want to avoid going through the coordinate representations. Let alone that I will have to show A is a submanifold.
Any hints?
Thanks


text:
Q: Synchronize model in MySQL Workbench After reading the documentation for MySQL Workbench I got the impression that it's possible to alter a database in the server (e.g. add a new column) and later incorporate the DDL changes into your EER diagram. At least, it has a Synchronize Model option in the Database menu. I found it a nice feature because I could use a graphic modelling tool without becoming its prisoner.
In practice, when I run such tool I'm offered these options:
Model             Update  Source
================  ======  ======
my_database_name  -->     ! N/A
   my_table_name  -->     ! N/A
N/A               -->     ! my_database_name
   N/A            -->     ! my_table_name

I can't really understand it, but leaving it as is I basically get:
DROP SCHEMA my_database_name
CREATE SCHEMA my_database_name
CREATE TABLE my_table_name

This is a dump of the model that overwrites all remote changes in my_table_name.
Am I misunderstanding the feature?

A: Here is the real bug that you can follow. http://bugs.mysql.com/bug.php?id=61211 And there is a workaround from one of the mysql QA people:
A workaround is to open the Scripting Shell, inspect the name of the schema and make
sure that the oldName field contains the same name as what you're trying to synchronize
against.
Commands for that are:
# print current oldName value
print grt.root.wb.doc.physicalModels[0].catalog.schemata[0].oldName
# change the oldName field value
grt.root.wb.doc.physicalModels[0].catalog.schemata[0].oldName = "newname"

A: Honestly? I think it's a bug.  I've run into the same problem on several occasions and I'm not sure what the issue is.
I suggest checking the bug repository and, if you don't find anything, reporting this as a new one.

A: I always use the synchronization successful several times! But today I have the same problem - and wonder way?
So I study the BUG-Report by MySQL and find the problem...
Don't use caps or underscore in the name of the database
So I am:

*

*rename my database,

*change the name of the model in the "Model Overview"

*and  change the name of the Default Schema, use in the "Connection Options".

And it works! ... now I have to change the name of the database in the applicationconfig ...


text:
Q: python - Cannot detect links of other language with os.walk I am trying to get a list of files and directories present in a specified URL. The URL I'm using is of an online Dictionary : www.shabdkosh.com/kn/browse/. My code is as follows:
html_files = []

for root, dirs, files in os.walk("www.shabdkosh.com/kn/browse"):
    for file in files:
        #Files in shabdkosh have a digit as name to represent page number
        if file.isdigit():
            html_files.append(os.path.join(root, file))

when I print the contents of files, I get:
www.shabdkosh.com/kn/browse/3/1
www.shabdkosh.com/kn/browse/a/1
www.shabdkosh.com/kn/browse/a/10
www.shabdkosh.com/kn/browse/a/2
...

This is cool. But other URLs should have also been retrieved. The URLs containing Kannada alphabets are not displayed (Kannada is an Indian Language) even though they exist.
For example,
www.shabdkosh.com/kn/browse/ಅ/

Like so are not displayed even though they lie in the path "www.shabdkosh.com/kn/browse" specified as the parameter for os.walk. So, how do I get os.walk to get the list of URLs with the Kannada letters ?
I even tried including the following code at the top of my python file:
#!/usr/bin/env python
# -*- coding: ascii -*-

But no luck. Any help is appreciated.
P.S Sorry if it bothers you that I'm using Old python 2.7.

A: Couple things to try:

*

*If you're using any coding at all, it should be utf-8, not ascii. Clearly those are not ascii characters.

*Make sure your path is unicode, e.g. os.walk(u"www.shabdkosh.com/kn/browse"). See Ciro's comment on Using os.walk() to recursively traverse directories in Python


text:
Q: How to determine the properties of a Scala class at runtime? I would like to programmatically determine all properties of a Scala class at runtime.  For instance, for the following Scala class I would like to determine that the methods name1, name3, name4, and name5 are getters for properties of A:
class A(val name1: String, private val name2: String) {
  val name3 = ""
  var name4 = ""
  def name5 = ""
  def name6() = ""
}

Most of the work can be done with Java's reflection API.  Unfortunately I was not able to detect the difference between name5 and name6().  Therefore I started a next trial using the ScalaSigParser, but ScalaSig's flags for name5 and name6() are unfortunately also the same.  Here is my code:
def gettersOf(clazz: Class[_]) = {
  for (ssig <- ScalaSigParser.parse(clazz))
  yield {
    ssig.symbols.toList.collect{
      case m: MethodSymbol => m
    }.filter(m => (m.symbolInfo.flags & 0xFFFFF) == 0x200)
  }
}

gettersOf(classOf[A]).get.foreach{m =>
  println(m.name + ": " + m)
}

As you can see in the following output both methods differ only in the info value:
name1: MethodSymbol(name1, owner=0, flags=28400200, info=22 ,None)
<init>: MethodSymbol(<init>, owner=0, flags=200, info=38 ,None)
name3: MethodSymbol(name3, owner=0, flags=8400200, info=45 ,None)
name4: MethodSymbol(name4, owner=0, flags=8000200, info=45 ,None)
name4_$eq: MethodSymbol(name4_$eq, owner=0, flags=8000200, info=54 ,None)
name5: MethodSymbol(name5, owner=0, flags=200, info=45 ,None)
name6: MethodSymbol(name6, owner=0, flags=200, info=66 ,None)

However, info does not seem to return static constants.  If you add another method to the class the info value of name6 will change while there seems to be some stability:

*

*name3, name4, and name5 have always the same info value

*name6 and name5 have always different info values

Does someone know the meaning of info and how one can use it to surely determine which kind of method it is?
Related questions:

*

*How does Scala know the difference between "def foo" and "def foo()"?

A: Your best bet is to use a reflection API of the coming Scala 2.10.
Here's how to get the properties of a type in 2.10.0-M6:
scala> import reflect.runtime.universe._
import reflect.runtime.universe._

scala> typeOf[A].members.view.filter{_.isValue}.filter{!_.isMethod}.toList
res0: List[reflect.runtime.universe.Symbol] = List(variable name4, value name3, value name2, value name1)

Unfortunately there's not much reading material on it yet. There are some answered questions on SO though. For instance, this question might be of interest to you. Also please check out this blogpost by Daniel Sobral.

A: import reflect.runtime.universe._
typeOf[A].members map (m => m -> m.typeSignature) collect {
  case (m, nm: NullaryMethodType) => m
}

A: I finally found a solution.  Instead of using the primitive info value one can use the more informative infoType which seems to return a NullaryMethodType for all methods not having parenthesis:
def gettersOf(clazz: Class[_]) = {
  for (ssig <- ScalaSigParser.parse(clazz))
  yield {
    ssig.symbols.toList.collect {
      case m: MethodSymbol => m
    }.filter(m => (m.symbolInfo.flags & 0xFFFFF) == 0x200 && m.infoType.isInstanceOf[NullaryMethodType])
  }
}

In the end we get the desired result without name6 and without the hidden <init> method:
name1: MethodSymbol(name1, owner=0, flags=28400200, info=22 ,None)
name3: MethodSymbol(name3, owner=0, flags=8400200, info=45 ,None)
name4: MethodSymbol(name4, owner=0, flags=8000200, info=45 ,None)
name5: MethodSymbol(name5, owner=0, flags=200, info=45 ,None)


text:
Q: phpunit not generating coverage-xml file The following:

phpunit "C:\xampp\htdocs\LaravelTest\tests\ExampleTest.php" --coverage-xml "C:\Users\James\Documents\Test Logs"

is not creating an xml file for me.
I have also tried:

phpunit "C:\xampp\htdocs\LaravelTest\tests\ExampleTest.php" --coverage-xml "C:\Users\James\Documents\Test Logs\test.xml"

Any ideas where i'm going wrong? It simply runs the tests
source of syntax: https://phpunit.de/manual/current/en/textui.html

A: *

*I had placed the option in the wrong place. It needs to go after phpunit as described in the documentation (doh)

*The --coverage-xml does not seem to work. however --log-junit does

The following command works:

phpunit --log-junit "C:\xampp\htdocs\LaravelTest\tests\ExampleTest.php" "C:\Users\James\Documents\Test Logs\log.xml"


text:
Q: Security - The view and edit id is visible in the address bar CakePHP Version 3.5.5
The id is visible in the address bar for view and edit which for my application creates a security risk. Any logged in user at the same company can change the id in the address bar and view or edit the details
of users they are not allowed to.
IE: https://localhost/crm/users/edit/1378 can be manually changed in the address bar to https://localhost/crm/users/edit/1215 and entered. This would display the details of user 1215 which is not allowed.
To overcome this I am selecting the ids which the user is allowed to edit and checking that the id from the url is one of these ids with the following code:
public function view($id = null)
{
    if ($this->request->is('get')) {

        // Select the permitted ids.
       if (superuser) { // example to explain only
            $query = $this->Users->find()
                ->where(['companyid' => $cid])
                ->andWhere(['status' => 1])
                ->toArray();
       }
       elseif (manager) { // example to explain only
           $query = $this->Users->find()
                ->where(['areaid' => $areaid])
                ->andWhere(['status' => 1])
                ->toArray();
       }
       elseif (team leader) { // example to explain only
           $query = $this->Users->find()
                ->where(['teamid' => $teamid])
                ->andWhere(['status' => 1])
                ->toArray();
       }

        // Check if the edit id is in the array of permitted ids.
        $ids = array_column($query, 'id');
        $foundKey = array_search($id, $ids);

        // If the edit id is not in the array of permitted ids redirect to blank.
        if (empty($foundKey)) {
            // Handle error.
        }

        $user = $this->Users->get($id);
        $this->set('user', $user);
        $this->set('_serialize', ['user']);
    }
    else {
        // Handle error.
    }
}

My question: Is the above code the best cake way of achieving this or is there a better way to do it?
This code does work but because it's to do with security I'd appreciate any input which would improve it or point out it's weakness/es.
/////////////////////////////////////////////////////////////////////////////
As requested by cgTag please see below.
My app has superusers, managers, team leaders and users.
Managers manage one area which can contain many teams.
Team Leaders lead one team and must belong to an area.
Users are assigned to an area or a team.
For example:
Area is UK
Team is England
Team is Scotland
Team is Wales
Area is USA
Team is Florida
Team is California
Team is Texas
On index - superusers see all the superusers, managers, team leaders and users in the company.
On index - managers see themself and users in their area, team leaders in their area and users in the teams.
On index - team leaders see themself and users in their team
My problem is say the manager of area UK clicks edit on one of the records and that record is displayed with a url of https://localhost/crm/users/edit/1378
Then say this disgruntled manager makes a guess and changes the url to https://localhost/crm/users/edit/1215 and submits it then this record is displayed. (This record could be anyone, a superuser, another manager, a team leader who is not in their area or a user not in their area.
This manager could then change say the email address and submit this and it's this type of situation that I need to protect against.
My fix is to reiterate the find for the superuser, manager and team leader I've done on index in the view and edit class. This ensures that say a manager can only view or edit someone in their area.
Hopefully I've explained it well enough but if not just let me know and I'll have another go.
Thanks. Z.
/////////////////////////////////////////////////////////////////////////////
Thanks cgTag, I feel a lot more confident with this approach but I cannot use this code because you have correctly assumed that I am using an id to select all the companies results but I'm using a 40 char string. I do this so I can make my sql queries more robust.
It's impossible for you to help me unless you have all the info required so I have posted an accurate representation below:
public function view($id = null)
{
    if(!$this->request->is('get') || !$id) {
        //throw new ForbiddenException();
        echo 'in request is NOT get or id NOT set ' . '
';
    }

    $user_id = $this->Auth->user('id');

    // regular users can never view other users.
    if($user_id !== $id) {
        //throw new ForbiddenException();
        echo 'in $user_id !== $id ' . '
';
    }

    // Declare client id 1.
    if ($this->cid1() === false) {
        echo 'in throw exception ' . '
';
    }
    else {
        $c1 = null;
        $c1 = $this->cid1();
    }

    $company_ids = $this->getCompanyIds($c1);
    $area_ids = $this->getAreaIds($user_id, $c1);
    $team_ids = $this->getTeamIds($user_id, $c1);

    // company_id does not exist which will cause an unknown column error.
    // The column I select by is cid_1 so I have changed this column to cid_1 as shown below.
    $user = $this->Users->find()
    ->where([
        'id' => $id,
        'cid_1 IN' => $company_ids,
        'area_id IN' => $area_ids,
        'team_id IN' => $team_ids,
        'status' => 1
    ])
    ->firstOrFail();

    $this->set(compact('user'));
}

The functions:
public function cid1()
{
    $session = $this->request->session();
    if ($session->check('Cid.one')) {
        $c1 = null;
        $c1 = $session->read('Cid.one');
        if (!is_string($c1) || is_numeric($c1) || (strlen($c1) !== 40)) {
            return false;
        }
        return $c1;
    }
    return false;
}

public function getCompanyIds($c1 = null)
{
    $query = $this->Users->find()
        ->where(['status' => 1])
        ->andWhere(['cid_1' => $c1]);
    return $query;
}

public function getAreaIds($c1 = null, $user_id = null)
{
    $query = $this->Users->find()
        ->where(['status' => 1])
        ->andWhere(['cid_1' => $c1])
        ->andWhere(['area_id' => $user_id]);
    return $query;
}

public function getTeamIds($c1 = null, $user_id = null)
{
    $query = $this->Users->find()
        ->where(['status' => 1])
        ->andWhere(['cid_1' => $c1])
        ->andWhere(['team_id' => $user_id]);
    return $query;
}

With this code I get the following error:
Error: SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s)
I don't know if your example will work with this new information but at least you have all the information now.
If it can be ammended great but if not I really don't mind. And I do appreciate the time you've put aside to try to help.
Thanks Z
/////////////////////////////////////////////////////////////////////////////
@tarikul05 - Thanks for the input.
Your suggestion is very similar to my first effort at addressing this security issue but I went for security through obscurity and hid the id in a 80 char string, example below.
// In a cell
public function display($id = null)
{
    // Encrypt the id to pass with view and edit links.
    $idArray = str_split($id);
    foreach($idArray as $arrkey => $arrVal) {
        $id0 = "$idArray[0]";
        $id1 = "$idArray[1]";
        $id2 = "$idArray[2]";
        $id3 = "$idArray[3]";
    }

    // Generate string for the id to be obscured in.
    $enc1 = null;
    $enc1 = sha1(uniqid(mt_rand(), true));
    $enc2 = null;
    $enc2 = sha1(uniqid(mt_rand(), true));
    $encIdStr = $enc1 . $enc2;

    // Split the string.
    $encIdArray = null;
    $encIdArray = str_split($encIdStr);

    // Generate the coded sequence.
    $codedSequence = null;
    $codedSequence = array(9 => "$id0", 23 => "$id1", 54 => "$id2", 76 => "$id3");

    // Replace the id in the random string.
    $idTemp = null;
    $idTemp = array_replace($encIdArray, $codedSequence);

    // Implode the array.
    $encryptedId = null;
    $encryptedId = implode("",$idTemp);

    // Send the encrypted id to the view.
    $this->set('encryptedId', $encryptedId);
}

And then decrypted with
// In function in the app controller
public function decryptTheId($encryptedId = null)
{
    $idArray = str_split($encryptedId);
    foreach($idArray as $arrkey => $arrVal) {
        $id0 = "$idArray[9]";
        $id1 = "$idArray[23]";
        $id2 = "$idArray[54]";
        $id3 = "$idArray[76]";
    }
    $id = null;
    $id = $id0.$id1.$id2.$id3;
    return $id;
}

The problem with this was that when testing I managed to get the script to error which revealed the array positions which would of undermined the security by obscurity principle and made it a lot easier for a hacker.
Your suggestion is neater than my obscurity method but I believe md5 has been cracked therefore it should not be used.
I'm no security expert but in my opinion checking the view and edit id against an array of permitted ids is the most secure way to address this.
Maybe I'm wrong but if I do it this way there's is no way a hacker no matter what they try in the address bar can see or edit data they are not meant to and it keeps the url cleaner.
What I was originally looking/hoping for was a Cake method/function which addressed this but I couldn't find anything in the cookbook.
Thanks anyway. Z.

A: I would simplify your code so that the SQL that fetches the user record only finds that record if the current user has permissions. When you're dependent upon associated data for those conditions. Follow this approach even if you have to use joins.
You create the SQL conditions and then call firstOrFail() on the query. This throws a NotFoundException if there is no match for the record.
public function view($id = null) {
     if(!$this->request->is('get') || !$id) {
           throw new ForbiddenException();
     }

     $user_id = $this->Auth->user('id');

     // regular users can never view other users.
     if($user_id !== $id) {
            throw new ForbiddenException();
     }

     $company_ids = $this->getCompanyIds($user_id);
     $area_ids = $this->getAreaIds($user_id);
     $team_ids = $this->getTeamIds($user_id);

     $user = $this->Users->find()
        ->where([
           'id' => $id
           'company_id IN' => $company_ids,
           'area_id IN' => $area_ids,
           'team_id IN' => $team_ids,
           'status' => 1
        ])
        ->firstOrFail();

     $this->set(compact('user'));
}

The above logic should be sound when a user belongsTo a hierarchical structure of data. Where by, they can view many users but only if those users belong to one of the upper associations they have access too.
It works because of the IN clause of the where conditions.

Note: The IN operator throws an error if the array is empty. When you have users who can see all "teams" just exclude that where condition instead of using an empty array.

The key here is to have functions which return an array of allowed parent associations such as; getCompanyIds($user_id) would return just the company IDs the current user is allowed access too.
I think if you implement it this way then the logic is easy to understand, the security is solid and a simple firstOrFail() prevents access.


text:
Q: How to check if button clicked, IF form is actually submitted Selenium / TestNG I am new to java/selenium/testNG, I have an issue were I run 4 sets of data using the dataprovider, however, One set of data is incorrect just for the purpose of testing that the test works. I first check the button is displayed then clicked. I want to be able to check that the button was clicked and then check if the form was submitted IF the form was not submitted then print error. I am unsure on how to do this my code is below:
WebElement  login = driver.findElement(By.id("dijit_form_Button_1_label"));

      //If statement - will check if element is Displayed before clicking on login button.
      if(login.isDisplayed()){
          login.click();
          //Main Event is logged If Passed
          Reporter.log("Login Form Submitted  | ");
          logger1.info("Submit Button Clicked");
      }else{

          Reporter.log("Login Failed  | ");
          Assert.fail("Login Failed - Check Data | ");
          //Main Event Log Fail
         }

    WebElement logout = driver.findElement(By.id("dijit_form_Button_0_label"));

    if(logout.isDisplayed()){
        logout.click();
    Reporter.log("Logout Successful  | ");
    }else {
        Reporter.log("Logout Failed");
        Assert.fail("Logout Failed - Check Data | ");
    }

The test displays a error message as "logout Failed" but it should display the first message "Login Failed" How do I get it to check if login and form was submitted successfully?
The reason it prints the second message is the code runs passed that point and selenium cant see the logout button displayed.
Any thoughts on were I am going wrong?

A: Try this:
private static By outButton = By.id("dijit_form_Button_0_label");
if(driver.findElements(outButton).size() > 0)
{
    logout.click();
    Reporter.log("Logout Successful  | ");
}

A: after submitting the form, you should make the webdriver wait for some condition to be true.
something like that
int timeout = 30
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(new Function <WebDriver, Boolean>(){
    //@Override
    public Boolean apply(WebDriver driver) {
            //if the login has been successful return true
            //if not, return false
        }
    });


text:
Q: Get category of post inside save_post hook I don't have much experience with hooks in WordPress so i have found a problem who don't look too difficult, but i can't find the answer.
In my project i have a metabox who will get the content after i make a category check inside my save_post hook.
But now i can't get the category selected and i don't know how can i know that info.
I'm using get_the_category($post_id) inside my hook, but this don't return my category.
My function is this below (and i got this from other question here):
function updatePost( $post_id, $post, $update ) {

    // Stop anything from happening if revision
    if ( wp_is_post_revision( $post_id ) ) {
        return;
    }

    // unhook this function so it doesn't loop infinitely
    remove_action( 'save_post', 'updatePost' );

    // get post type
    $post_type = get_post_type( $post_id );

    // run codes based on post status
    $post_status = get_post_status();
    if ( $post_status != 'draft' )  {
        if ( isset( $_POST['img-destacada'] ) ) {
            get_the_category($post_id);
            // here i will put some logic to set the $img value based on my category
            $img = '';
            update_post_meta($post_id, "img-destacada", $img);
        }
    }

    // re-hook this function
    add_action( 'save_post', 'updatePost', 100, 3 );
}

How can i get the category info to then set the $img value?

A: Your code calls get_the_category() but it doesn't use the value returned.
// ...
if ( isset( $_POST['img-destacada'] ) ) {
    $categories = get_the_category($post_id);
    $img = '';
    // $categories should contain either an array of WP_Term objects,
    // or an empty array.
    if ( ! empty( $categories ) ) {
        // Here I've used the slug of the first item in the array to set the $img.
        // You may have other logic you want to use.
        $img = $categories[0]->slug . '.jpg';
    }
    if ( ! empty( $img ) ) {
        // Checks to make sure there's an $img set.
        update_post_meta($post_id, "img-destacada", $img);
    }
}
// ...

References

*

*get_the_category()

*WP_Term


text:
Q: Why when I add my animation with Core Animation does it immediately snap back to what it was at the end? I'm trying to build a simple pie-chart style progress indicator. It animates well, but after the animation concludes, it snaps right back to the previous value before the animation.
My code is as follows:
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    // Create a white ring that fills the entire frame and is 2 points wide.
    // Its frame is inset 1 point to fit for the 2 point stroke width
    CGFloat radius = CGRectGetWidth(self.frame) / 2;
    CGFloat inset  = 1;
    CAShapeLayer *ring = [CAShapeLayer layer];
    ring.path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(self.bounds, inset, inset)
                                           cornerRadius:radius-inset].CGPath;

    ring.fillColor   = [UIColor clearColor].CGColor;
    ring.strokeColor = [UIColor whiteColor].CGColor;
    ring.lineWidth   = 2;

    // Create a white pie-chart-like shape inside the white ring (above).
    // The outside of the shape should be inside the ring, therefore the
    // frame needs to be inset radius/2 (for its outside to be on
    // the outside of the ring) + 2 (to be 2 points in).
    self.innerPie = [CAShapeLayer layer];
    inset = radius/2; // The inset is updated here
    self.innerPie.path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(self.bounds, inset, inset)
                                               cornerRadius:radius-inset].CGPath;
    self.innerPie.fillColor   = [UIColor clearColor].CGColor;
    self.innerPie.strokeColor = [UIColor whiteColor].CGColor;
    self.innerPie.lineWidth   = (radius-inset)*2;

    [self.layer addSublayer:ring];
    [self.layer addSublayer:self.innerPie];

    self.progress = 0.0;
    self.innerPie.hidden = YES;
}

- (void)setProgress:(CGFloat)progress animated:(BOOL)animated {
    self.innerPie.hidden = NO;

    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    pathAnimation.duration = 3.0;
    pathAnimation.fromValue = [NSNumber numberWithFloat:_progress];
    pathAnimation.toValue = [NSNumber numberWithFloat:progress];
    [self.innerPie addAnimation:pathAnimation forKey:@"strokeEndAnimation"];

    if (_progress != progress) {
        _progress = progress;
    }
}

I simply set it up in drawRect then have a method to set the progress with an animation. What am I doing wrong here?

A: That's how core Animation works. What you want to do is to set the property to it's final value just before adding the animation to the layer. Then the animation hides the fact that you changed the property, and when the animation is removed after it's finished, the property is at it's end value.


text:
Q: WPF TabControl - IDictionary missing key attribute error I have a TabControl on my grid and everything works fine, but the system complains that a key attribute is missing. The code compiles and works though. I have tried to add an x:Key property to the style but then it didn't work anymore. Any ideas?
<TabControl x:Name="mainTabControl" BorderBrush="White">
        <TabControl.Resources>
            <Style TargetType="{x:Type TabPanel}">
                <Setter Property="HorizontalAlignment" Value="Center" />
            </Style>
            <Style TargetType="TabItem">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="TabItem">
                            <Grid Name="Panel">
                                <ContentPresenter x:Name="ContentSite"
                                    VerticalAlignment="Center"
                                    HorizontalAlignment="Center"
                                    ContentSource="Header"
                                    Margin="30,20"/>
                            </Grid>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsSelected" Value="True">
                                    <Setter TargetName="Panel" Property="Background" Value="LightSkyBlue" />
                                </Trigger>
                                <Trigger Property="IsSelected" Value="False">
                                    <Setter TargetName="Panel" Property="Background" Value="White" />
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TabControl.Resources>
        <TabItem Header="Production">
            <Grid/>
        </TabItem>
    </TabControl>

A: Its just a warning. You can make it go away by adding
x:Key="{x:Type TabPanel}"

Or you can suppress the warning if you don't want to add a Key attribute
In Solution Explorer, choose the project in which you want to suppress warnings.
On the menu bar, choose View, Property Pages.
Choose the Build page.
In the Suppress warnings box, specify the error codes of the warnings that you want to suppress, separated by semicolons, and then rebuild the solution.


text:
Q: XML from URL - Data at the root level is invalid. Line 1, position 1 Why it works with one URL and not the other? As far as I can tell, these two end points are both valid XML output. However when I use the same code on the second end point I get the error:

Data at the root level is invalid. Line 1, position 1

Here is my code:
        //Works
        XmlDocument testDocument = new XmlDocument();
        testDocument.Load("https://www.w3schools.com/xml/note.xml");

        //Fails
        XmlDocument testDocumentTwo = new XmlDocument();
        testDocumentTwo.Load("https://www.domainNameHere.com/direct/umbraco/api/productsearch/NameSearch?countryCode=en-gb");

A: I opened Fiddler and watched the request and its response, and lo and behold your endpoint is returning JSON, not XML:

If I use HttpClient to set an explicit Accept header, then I get XML back and everything works:
using var client = new HttpClient();
var requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://www.clinigengroup.com/direct/umbraco/api/productsearch/NameSearch?countryCode=en-gb");
requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
var response = await client.SendAsync(requestMessage);
var xml = await response.Content.ReadAsStringAsync();

XmlDocument testDocumentTwo = new XmlDocument();
testDocumentTwo.LoadXml(xml);


text:
Q: How to make my crawler (made in R) automatic? I've been working on a RStudio to crawl some websites. I wanted to be able to run my code automatically at a particular instances during the day. I've been using Rcrawler and Rvest to crawl.
The point is to do news aggregation from several sites using different keywords at different times during the day. I'm trying to automate the process of running the particular script.
Is there a way to do so in R or should I move to Python for the same?
I'm using Rstudio on Windows.

A: There is an easy way to do this, though I'm not sure it's the right way. Use a loop and run the script in the background.
while(1){
  tnow<-format(Sys.time(),'%H:%M')
  tschedule<-'18:00'
  while(tnow<tschedule){
    Sys.sleep(60)
  }
  # Your code here
}

The start condition can be modified as needed, but you can see the idea

A: You haven't mentioned your OS, but if you are on Linux / Unix then look into Cron. There is an r Package called CronR that allows you to schedule the running of a script at specific times or intervals (hourly, daily etc.) There is also an Rcommander plugin for a CronR GUI.
You need to install and start the cron service in Linux (i.e. using apt-get)
You can then write an R script to schedule a job;
library(cronR)
cmd <- cron_rscript("/home/job.R") #, log_append = TRUE)
cmd
cron_add(command = cmd, frequency = 'hourly', id = 'Scrape', description = 'Webscrape')
cron_njobs()

The best way to keep adding to an output is then using something like write table with append = TRUE
write.table(df, "Scrape.csv", sep = ",", col.names = F, append = T)

The job will run until you choose to end it, all it's doing is executing an entire r script, so all your writing to .csv etc needs to be in that script.


text:
Q: Which is better? mask_compress + store or mask_compressstoreu I am using sde (intel's emulator) to run avx512 code and do not have actual hardware to benchmark.
For some reason there is no information that I could find on comparative performance between compress + store and compressstore.
compress + store would store the whole register and not just the selected elements but I am fine with that. While compressstore has to mask the not selected elements.
What is better? There is no latency information on the intel's website as far as I can see.

A: UPD: AMD - ZEN4. According to this: https://www.mersenneforum.org/showthread.php?p=614191 ZEN4 perf of compressstoreu is very poor, so if the code might be running on AMD -compressstoreu should be avoided.
I looked in a slightly wrong place: the compress instructions are only avaliable for epi32 and those have latencies:
_mm256_mask_compress_epi32 has latency 6
_mm256_mask_compressstoreu_epi32 has latency 11
and the others seem to require VBMI2, which are not available on my target.
So seems like compress + store should be better.


text: Q: table разъезжается Есть огромная таблица на 3-5 тыс строк. После загрузки в некоторых браузерах она разъезжается более ширины экрана. Стоит width=1000, max-width:100 и ничего не помогает. В Safari отображается отлично, в chrome разъезжается примерно до 3000 пикселей в ширину. Возможно реализовать строгую ширину?


text:
Q: Binding gridview with arraylist asp.net/c# I have created a grid view, can I bind that grid view columns with a array list ?
If it is possible can you please write a sample code.
Thank you in anticipation

A: Yes,it is possible. You have to specify columns in you grid view, bind them to some expression, depending on your needs and contents of the ArrayList (what kind of objects do you sotre in it?) and then just type in your code behind:
myGrid.DataSource = myArrayList;
myGrid.Databind();

A: After creating an ArrayList, you just add the arraylist into a datatable and bind the datatable to the Gridview. Then in the design page you mention AutoGenerateColumns property as "true".
Like the following code:
In design page:
<asp:GridView ID="gvarray" runat="server" Width="328px">
     <Columns>
          <asp:TemplateField HeaderText="Select One">
              <ItemTemplate>
                  <asp:Label ID = "rdoday" runat = "server" text = '<%# DataBinder.Eval (Container.DataItem, "Item") %>' />

              </ItemTemplate>
          </asp:TemplateField>
     </Columns>

In code-behind:
ArrayList Array_L = new ArrayList();
        Array_L.Add("One");
        Array_L.Add("two");
        Array_L.Add(2);
DataTable dt = new DataTable();
dt.Columns.Add("Name");
for (int i = 0; i < Array_L .Count();i++)
{
    dt.Rows.Add();
    dt.Rows[i]["Name"] = Array_L [i].ToString();
}
gvarray.DataSource = dt;
gvarray.DataBind();

A: You can create a new ArrayList to get all the data from SqlDataSource. Then, you can use data table to insert data from ArrayList into specified columns and rows of grid view.
The following is the code behind file:
ArrayList myList = sampleController.getDataFromTable();
        DataTable dataTable = new DataTable();
        DataColumn dataColumn;
        dataColumn = new DataColumn("UserID");
        dataTable.Columns.Add(dataColumn);
        dataColumn = new DataColumn("Username");
        dataTable.Columns.Add(dataColumn);
        dataColumn = new DataColumn("MobileNo");
        dataTable.Columns.Add(dataColumn);
        dataColumn = new DataColumn("Address");
        dataTable.Columns.Add(dataColumn);

        foreach (object str in myList)
        {
            Customer customer= new Customer();
            customer= (Customer)str;
            DataRow dataRow = dataTable.NewRow();
            dataRow[0] = customer.DailyRunNo;
            dataRow[1] = customer.Area.Name;
            dataRow[2] = customer.Employee.EmployeeName;
            dataRow[3] = customer.SalStatus;

            dataTable.Rows.Add(dataRow);
        }
        gvCustomer.DataSource = dataTable;
        gvCustomer.DataBind();//Bind datatable

The following is in ASPX design page:
<asp:TemplateField HeaderText="User ID">
                        <ItemTemplate>
                            <asp:Label ID="lblDailyRunNo" runat="server" Text='<%# Eval("UserID") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="UserName">
                        <ItemTemplate>
                            <asp:Label ID="lblAreaNo" runat="server" Text='<%# Eval("Username") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Mobile Number">
                        <ItemTemplate>
                            <asp:Label ID="lblSalespersonName" runat="server" Text='<%# Eval("MobileNo") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Address">
                        <ItemTemplate>
                            <asp:Label ID="lblStatus" runat="server" Text='<%# Eval("Address") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>

A: It is not logical to use ArrayList when data to be bind is in tabular structure. You  use ArrayList at that moment when data need to bind with Dropdown or ListView Controls.
If you want to bind data to gridview / datalist / DataList controls then better option you should use DataTable/Dataset or you can use LIST ex: LIST.
Here i have one Example for Datatable with gridview.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Data.OleDb;
using System.Collections;

namespace TestApp
{
     public partial class MyWebPage: System.Web.UI.Page
     {
         static string GetConnectionString()
         {
             return ConfigurationManager.ConnectionStrings["myConnString"].ConnectionString;
         }
         protected void Page_Load(object sender, EventArgs e)
         {
             if (!IsPostBack)
             {
                BindData();
             }
         }

         private void BindData()
         {
            string connstring = GetConnectionString();
            using(SqlConnection cn = new SqlConnection())
            {
                string query = "your sql query";
                SqlDataAdapter da = new SqlDataAdapter(query,cn);
                cn.Open();
                DataTable dtMyTable = new DataTable();
                da.Fill(dtMyTable);
                GridView1.DataSource = dtMyTable;
                GridView1.DataBind();
              }
            }
      }
  }


text:
Q: Exchange event of onclick and ondblclick event I am trying to exchange the event of onclick and ondblclick event in Javascript. This is my HTML page:

<input type="button" value="Click Me" onclick="clickFunction()" ondblclick="doubleClick()">
<input type="button" value="Switch Event" onclick="switchEvent()">

I want a script for switchEvent() function which exchange the onclick and ondblclick events. It means after clicking "switch Event" button onclick should work as ondblclick and vice versa.
I did it like this:
var booleanFlag = true;

    function clickFunction(){
        if(booleanFlag)
            document.getElementById("displayStatus").innerHTML="Single Click";
        else
            document.getElementById("displayStatus").innerHTML="Double Click";
    }
    function doubleClick(){
        if(booleanFlag)
            document.getElementById("displayStatus").innerHTML="Double Click";
        else
            document.getElementById("displayStatus").innerHTML="Single Click";
    }

    function switchEvent(){
        if (booleanFlag) {
            booleanFlag=false;
        }
    }

but this causes code repetition. Please share any better options for doing this.

A: One function is enough. Just get the button with document.getElementById and change it's onclick attribute depending on the booleanFlag state.
With every click on switchEvent you will see in the console that the onclick attribute of the button changes from clickFunction() to doubleClick() and ondblclick changes from doubleClick() to clickFunction() and so on.

var booleanFlag = true;
var btn = document.getElementById('btn');

function switchEvent() {
  if (booleanFlag) {
    btn.setAttribute('onclick', 'doubleClick()');
    btn.setAttribute('ondblclick', 'clickFunction()');
    booleanFlag = false;
  }
  else {
    btn.setAttribute('onclick', 'clickFunction()');
    btn.setAttribute('ondblclick', 'doubleClick()');
    booleanFlag = true;
  }
  console.log(btn);
}

function clickFunction(){
  console.log('onclick');
}

function doubleClick(){
  console.log('doubleClick');
}

<input type="button" id='btn' value="Click Me" onclick="clickFunction()" ondblclick="doubleClick()">
<input type="button" value="Switch Event" onclick="switchEvent()">

A: No code repetition option:

    <input type="button" value="Click Me" onclick="handler(false)" ondblclick="handler(true)">
    <input type="button" value="Switch Event" onclick="switchEvent()">


text:
Q: Child Page where the Parent Page is the same Permalink as a Post_Type I am in need of building child pages with the same URL as a post_type.
ie; my post_type is work

*

*I can publish a Page at /work and it works.

*My posts under /work/thing-1 work

*A Page under /work/page does not work, as it's looking for a post_type of page there.

How can I have the child pages work while the post_type exists with the same slug? If I change the slug to works everything works. But the client wants the post_type to have the same slug structure as the pages.
My post_type is:
        "name" => __( "Portfolios", "clients-child" ),
        "singular_name" => __( "Portfolio", "clients-child" ),
    ];

    $args = [
        "label" => __( "Portfolios", "clients-child" ),
        "labels" => $labels,
        "description" => "",
        "public" => true,
        "publicly_queryable" => true,
        "show_ui" => true,
        "show_in_rest" => true,
        "rest_base" => "",
        "rest_controller_class" => "WP_REST_Posts_Controller",
        "has_archive" => false,
        "show_in_menu" => true,
        "show_in_nav_menus" => true,
        "delete_with_user" => false,
        "exclude_from_search" => false,
        "capability_type" => "post",
        "map_meta_cap" => true,
        "hierarchical" => false,
        "rewrite" => [ "slug" => "work", "with_front" => false, "with_archive" => false ],
        "query_var" => true,
        "supports" => [ "title", "editor", "thumbnail" ],
    ];

    register_post_type( "portfolio", $args );
}

add_action( 'init', 'cptui_register_my_cpts_portfolio' );