text:
Q: Difference between Rotate[] and Translate[] I don't understand why Rotate[] and Translate[] behave differently. For example,
ga and gb below look as I expected:
ga = Graphics[Line[{{0, 0}, {1, 0}}]];
Print[ga];
gb = Rotate[ga, \[Pi]/4, {0, 0}];
Print[gb];
gc = Translate[gb, {1, 1}];
Print[gc];

But gc results in this:

A: Your problem here is that you are calling Graphics too early. You want to Rotate and Translate the Line, not the Graphics.
ga = Line[{{0, 0}, {1, 0}}];
Graphics[ga]
gb = Rotate[ga, \[Pi]/4, {0, 0}];
Graphics[gb]
gc = Translate[gb, {1, 1}];
Graphics[gc]

Will do what you want.
Graphics[{Red, ga, Blue, gb, Green, gc}]


text:
Q: Not getting the JSON data in PHP I am creating an android application and submit the user details from Android application to php at server side by JSON. But at server side I am not getting the JSON data. At server side php the JSON comes from android application is seems null. I am using POST method for this. I know that my POST method code is wrong in PHP at server side. But I have no idea to solve this.
Here is my PHP code for getting JSON. Every time I get same message:

Required fields missing

Code:
<?php

/*
* Following code will create a new user row
* All user details are read from HTTP Post Request
*/

// array for JSON response
$response = array();
print_r($_POST);
// check for required fields
if (isset($_POST['Firstname']) && isset($_POST['Lastname']) && isset($_POST['Username'])     && isset($_POST['Email']) && isset($_POST['Password']) && isset($_POST['Country']) &&     isset($_POST['Mobile'])) {
echo('bhargavi');
$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Username = $_POST['Username'];
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$Country = $_POST['Country'];
$Mobile = $_POST['Mobile'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO     users(Firstname,Lastname,Username,Email,Password,Country,Mobile)     VALUES('$Firstname','$Lastname','$Username','$Email','$Password','$Country','$Mobile')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "User successfully Registered.";

    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>

A: Probably you should decode the json string before checking $_POST['Firstname'] etc...
Let's say you send from the app a string called data. On php you should do something like that:
$data = json_decode($_POST['data']);
and then check if $data contains the data you neeed by doing:
if (isset($data->Firstname) && isset($data->Lastname) etc...){
...
...
}

If I can give you an advice it would be better if you check data integrity directly from your app instead of doing it on your server, it would give the chance to spare some server resources...
As Jay Blanchard already mentioned don't use mysql like that or you'll be exposed to mysql injection...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reading a numpy array of strings in memmap mode I created this numpy array and stored it in disk as follows:
s = (b'foo', b'bar', b'baz', b'buzz')
def build_numpy_array():
  return np.fromiter((s for _ in range(200)), dtype=[('foo','S40'),
  ('bar', 'S40'), ('baz', 'S40'),
  ('buzz', 'S40')
  ])

np.save('data.dat', {'data': build_numpy_array()})

This works fine
np.load('data.dat.npy')
But, I want to use it in memmap mode. So this fails
np.load('data.dat.npy',mmap_mode='r')

ValueError: Array can't be memory-mapped: Python objects in dtype.
And this gives weird encoding
np.memmap('data.dat.npy',  mode='r',dtype=[('foo','S40'),
  ('bar', 'S40'), ('baz', 'S40'),
  ('buzz', 'S40')
  ])

 (b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00bar', b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00baz', b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00buz', b'z\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00foo')

A: data = build_numpy_array()

is a (200,) structured array.
to load:
In [152]: np.save('data.dat', {'data': data})

I have to use allow_pickle:
In [157]: x=np.load('data.dat.npy',allow_pickle=True)

x is () shaped object array.  That is x.item() is a dictionary, containing the array as an element value.
The problem lies with the save - it's saving a dictionary.

In [161]: np.save('data.dat', data)
In [162]: x=np.load('data.dat.npy')
In [163]: x.shape
Out[163]: (200,)

now
In [165]: r = np.load('data.dat.npy',mmap_mode='r')
In [166]: r
Out[166]:
memmap([(b'foo', b'bar', b'baz', b'buzz'),
        (b'foo', b'bar', b'baz', b'buzz'),
        (b'foo', b'bar', b'baz', b'buzz'),
    ...


text:
Q: Efficiently search for NSString in a set Consider a set of thousands of NSString objects, in memory.
What is the most efficient way to search for a particular NSString in the set? Would using NSDictionary suffice? Or is it guaranteed that NSSet's search is O(1) (couldn't find any documentation that says so)?
And would the same strategy apply to NSData objects?

A: This page shows the following note about sets:

Note: If the objects in the set have a good hash function, accessing an element, setting an element, and removing an element all take constant time. With a poor hash function (one that causes frequent hash collisions), these operations take up to linear time. Classes such as NSString that are part of Foundation have a good hash function.

So for NSString you could expect constant time based on the above.

A: NSSet uses hash table in its implementation and tests for equality between all elements that are in hash collision. So performance is directly tied to the hash efficiency of its elements.


text:
Q: How to create an Azure Kusto query to group by client OS name only (OS version removed) on App insights? What I want
The number of page views grouped by client OS (no OS version = only OS name) and week.
What I have - Kusto query:
pageViews
|where timestamp > ago(90d)
|summarize Browser_hits = count() by Date = startofweek(timestamp), client_Browser
|sort by Date
|render timechart

The problem with this query is that the client OS name is coming with the version in it and that ends up in different versions grouping separately (see picture below).

Update
This is close to what I need but it won't work for any names, I'm just posting this as an example that helps to understand the actual question.
pageViews
|where timestamp > ago(90d)
|summarize Browser_hits = count() by Date = startofweek(timestamp), BrowserNameTrimed = substring(client_Browser,0,5)
| sort by Date
| render timechart

With the previous query I get this (kind of cheating):

A: would this work? (parsing the browser name out of the "browser name + browser version" combination using the parse operator):
pageViews
| where timestamp > ago(90d)
| summarize Browser_hits = count() by Date = startofweek(timestamp), client_Browser
| parse kind=regex client_Browser with client_Browser @" \d+" *
| render timechart


text:
Q: how to config JsonSerializable `.g` to return jsonEncode? I am using json_annotation: ^4.5.0 package that generate login.g.dart file.
@JsonSerializable()
class LoginRequestModel {
  LoginRequestModel({
    required this.username,
    required this.password,
  });
  String username;
  String password;

  Map<String, dynamic> toJson() => _$LoginRequestModelToJson(this);
}

in the above code We have toJson().  And as we are calling toJson while making API call... below is code
class LoginProvider {
  Future<Map<String, dynamic>?> login(LoginRequestModel request) async {
    final response = await post(
      Uri.parse(UrlPath.baseAPI),
      body: jsonEncode(request.toJson()),
      headers: {
        'Content-Type': 'application/json',
      },
    );
    return response.asMap();
  }
}

It doesn't return encoded json so, evey-time We have to do jsonEncode(request.toJson()),
So, is it possible to config the JsonSerializable  so, that We don't have to do jsonEncode When we call api but, instead toJson() already do it's own?


text:
Q: Serialize XML with XML string I have to produce the following XML
<object>
    <stuff>
        <body>
            <random>This could be any rondom piece of unknown xml</random>
        </body>
    </stuff>
</object>

I have mapped this to a class, with a body property of type string.
If I set the body to the string value: "<random>This could be any rondom piece of unknown xml</random>"
The string gets encoded during serialization. How can I not encode the string so that it gets written as raw XML?
I will also want to be able to deserialize this.

A: XmlSerializer will simply not trust you to produce valid xml from a string. If you want a member to be ad-hoc xml, it must be something like XmlElement. For example:
[XmlElement("body")]
public XmlElement Body {get;set;}

with Body an XmlElement named random with InnerText of "This could be any rondom piece of unknown xml" would work.

[XmlRoot("object")]
public class Outer
{
    [XmlElement("stuff")]
    public Inner Inner { get; set; }
}
public class Inner
{
    [XmlElement("body")]
    public XmlElement Body { get; set; }
}

static class Program
{
    static void Main()
    {
        var doc = new XmlDocument();
        doc.LoadXml(
           "<random>This could be any rondom piece of unknown xml</random>");
        var obj = new Outer {Inner = new Inner { Body = doc.DocumentElement }};

        new XmlSerializer(obj.GetType()).Serialize(Console.Out, obj);
    }
}


text:
Q: Publish page by invoking submit via jQuery I'm looking for a solution to a bug that occured in an answer to an earlier question.
The general idea is that I want to invoke submit on the post form and have the page published. What happens now is that the page reloads and the message "Page updated" appears, however the page is not published and not even drafted. I've created a small demo to drop into your functions.php to test it out. In the demo I've created a secondary publish button that you can use to experience the problem, this is merely for illustration purposes, in the real case submit is invoked via ajax.
add_action('add_meta_boxes', 'add_metaboxes_pages', 10, 2);
function add_metaboxes_pages($post_type, $post)
{
    add_meta_box('pagesubmitdiv', 'WPSE_DEMO_META_BOX', 'page_submit_meta_box', 'page', 'advanced', 'low');
}

function page_submit_meta_box($post)
{?>
    Secondary Publish<?php
}

add_action( 'admin_head-post.php', 'wpse_publish_admin_hook' );
add_action( 'admin_head-post-new.php', 'wpse_publish_admin_hook' );
function wpse_publish_admin_hook()
{
    global $current_screen;
    if( 'page' != $current_screen->post_type )
        return;

    ?>

    <?php
}

A: Trigger the click event of the publish button instead, and let WP do the work.

Don't use language (it was deprecated in HTML 4.01!) - you can drop type too (WP now has an HTML5 doctype).


text:
Q: FullCalendar eventRender problem = Unknown option 'eventRender'? I am unable to get eventRender to work.
anyway I add it, I get "Unknown option 'eventRender'.
What am I doing wrong?
Here a short code that already show the error:
<body>
<script>
                document.addEventListener('DOMContentLoaded', function() {
                    var date = new Date();
                    var calendarEl = document.getElementById('calendar');
                    var calendar = new FullCalendar.Calendar(calendarEl, {
                    initialView: 'dayGridMonth',
                    eventRender: function(info){
                        console.log("1");
                    },
                    events: [
                        {
                            title: "hello",
                            start: date,
                            allDay: true,
                        }
                    ],
                  });
                  calendar.render();
                });

                </script>

    <div id = "calendar">

    </div>
</body>

A: if you are using new version, use eventDidMount like this:
eventDidMount: function(info) {console.log(1);}

look this example from documentation: event tootip example


text:
Q: Show navigation loader spinner with delay in angular 2+ I'm new to angular 2+ and RxJS, trying to get used to RxJS.
I show load spinner on route transitions, but only if it takes more then certain amount time, lats say 160ms
I have a load spinner as a separate component, with subscription to ngrx store, so I show/hide load spinner based on value in the sore (showSpinner)
In my app root component, I subscribe to router change events, and dispatch actions (SHOW_SPINNER/HIDE_SPINNER)
So the question is, Is there a simpler way to achieve it?
Here are parts of my code
....

export const navigationStreamForSpinnerStatuses = {
  NAVIGATION_STARTED: 'NAVIGATION_STARTED',
  NAVIGATION_IN_PROGRESS: 'NAVIGATION_IN_PROGRESS',
  NAVIGATION_ENDED: 'NAVIGATION_ENDED'
};

....
private navigationStartStream;
private navigationStartStreamWithDelay;
private navigationFinishStream;

constructor(private store: Store<IAppState>, private router: Router) {
  this.navigationStartStream = router.events
    .filter(event => {
      return event instanceof NavigationStart;
    })
    .map(() => navigationStreamForSpinnerStatuses.NAVIGATION_STARTED);

  this.navigationStartStreamWithDelay = this.navigationStartStream
    .delay(160)
    .map(() => navigationStreamForSpinnerStatuses.NAVIGATION_IN_PROGRESS);

  this.navigationFinishStream = router.events
    .filter(event => {
      return event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError;
    })
    .map(() => navigationStreamForSpinnerStatuses.NAVIGATION_ENDED);

  this.navigationStartStream
    .merge(this.navigationFinishStream)
    .merge(this.navigationStartStreamWithDelay)
    .pairwise()
    .subscribe([previousStatus, currentStatus] => {
      if (previousStatus !== navigationStreamForSpinnerStatuses.NAVIGATION_ENDED && currentStatus === navigationStreamForSpinnerStatuses.NAVIGATION_IN_PROGRESS) {
        this.store.dispatch({ type: StateLoaderSpinnerActionsTypes.SHOW_SPINNER });
      } else if (previousStatus === navigationStreamForSpinnerStatuses.NAVIGATION_IN_PROGRESS && currentStatus === navigationStreamForSpinnerStatuses.NAVIGATION_ENDED) {
        this.store.dispatch({ type: StateLoaderSpinnerActionsTypes.HIDE_SPINNER });
      }
    });
}

A: My approach is based on Http requests, which may not work in every case since some apps will only use WebSockets or no external requests at all. But for a large set of apps, they are getting all their data via HttpClient (angular 4.3+). I wrote an HttpInterceptor that does just this.
import { HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http'
import { Inject, Injectable, RendererFactory2 } from '@angular/core'
import { Observable, timer } from 'rxjs'
import { filter, takeUntil, tap } from 'rxjs/operators'
import { DOCUMENT } from '@angular/common'

const reqIsSpinnable = (req: HttpRequest<any>) => {
  return req.url.includes('api/')
}

@Injectable()
export class HttpSpinnerInterceptor implements HttpInterceptor {
  constructor(@Inject(DOCUMENT) private doc: HTMLDocument, private rdf:
    RendererFactory2) { }

  // tslint:disable-next-line:no-null-keyword
  readonly rdr = this.rdf.createRenderer(null, null)

  get spinnerElement() {
    return this.doc.querySelector('#core-spin')
  }

  startSpin() {
    this.rdr.setStyle(this.spinnerElement, 'display', 'block')
  }

  closeSpin() {
    this.rdr.setStyle(this.spinnerElement, 'display', 'none')
  }

  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<any> {
    const responseTimer$ = next.handle(req).pipe(filter(e => e instanceof HttpResponse))
    timer(120).pipe(takeUntil(responseTimer$)).subscribe(() => this.startSpin())

    return next.handle(req).pipe(tap(evt => {
      if (reqIsSpinnable(req) && evt instanceof HttpResponse) {
        this.closeSpin()
      }
    }))

}
}

A: Utilize the takeUntil operator to cancel your spinner timer if it returns before the time. Additionally, create a hot observable using timer to trigger an action after a certain time has passed.

takeUntil Returns the values from the source observable sequence until the other observable sequence or Promise produces a value.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/takeuntil.md

timer Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/timer.md
You can simplify your logic here by handling the dispatch directly on each stream.
this.navigationEnd$ = router.events
  .filter(event => event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError);

this.navigationStart$ = router.events
  .filter(event => event instanceof NavigationStart)
  .subscribe(_ => {
    Observable.timer(160)
      .takeUntil(this.navigationEnd$)
      .subscribe(_ => this.store.dispatch({ type: StateLoaderSpinnerActionsTypes.SHOW_SPINNER });
  });

this.navigationEnd$.subscribe(_ => this.store.dispatch({ type: StateLoaderSpinnerActionsTypes.HIDE_SPINNER });

So what we've done is listen to the start of the navigation and start a timer for 160ms.  If the navigation end event happens before the timer, no spinner will show (takeUntil). Otherwise, the store action will be dispatched and the spinner will show.  Regardless of whether or not the spinner is showing, after the navigation finishes we dispatch the hide spinner action.


text:
Q: Call a PHP function in Twig with context variable as an argument if the function has another argument In PHP I have:
protected function registerTwigFunctions()
{
    return [
        'count_VKcomments' => 'countVKCommentsFunction'
    ];
}

public function countVKCommentsFunction($context, $pdo) {
    $url = $context['url'];
    $sql = "SELECT id, COUNT(*) FROM level_1 WHERE url = ?";
    $count = $pdo->prepare($sql)->execute([$url])->fetchColumn();
    return $count;
}

In Twig I have:
{% set url = global.request.uri %}
{{ count_VKcomments({ 'url': url }) }

But it only works if I remove the $pdo argument from countVKCommentsFunction, otherwise some temporary file complains about too few arguments being passed from Twig. But I need to include that $pdo argument just to avoid duplicating connection to the database, which is already defined as $pdo in another function. At the same time, I don't understand how to properly call countVKCommentsFunction provided that it needs $pdo as an argument.

A: From perspective of Twig your function should only accept/care about what template practically needs to pass to it.
From perspective of PHP implementation your function needs access to state of your application (your database connection in this case).
The solution here is to decouple the two tasks:

*

*Make and instantiate object that has access to the necessary state.

*Use the object's method as callback for Twig function.

That way template data comes through arguments and state data comes through implementation.

A: I ended up creating a separate function that defines $pdo:
private function pdo() {
    $core = Core::getInstance();
    $pdo = $core->dbh;
    return $pdo;
}

Then in every function that needs to use this variable I added $pdo = $this->pdo();
Another approach would be to declare the variable as a class member, but I ended up doing it like I described.


text:
Q: Photos do not show up in iTunes When my iPhone 5c is connected via lightning cable the photos are showing up on one of my macs - which has El Capitan.  The photos do  not show up on another one that has High Sierra (and it did not show up earlier when that computer was on Sierra either).
Here is what is available:

What configuration is needed to get the photos tab?

A: You have to disable icloud streaming photo on settings, otherwise you cannot see the photo menu below others. After disabling it you will be able to see all folders of photo


text:
Q: Why mysql return one row? When I use count() function MySQL return one row. I need to use count function for pagination system, I don't have a better idea.
My SQL is:
SELECT *, count(id_question) AS num FROM `questions` LIMIT 0, 10

A: when you use any aggregate function, without the group by clause you see only one result.

A: The COUNT() is an aggregate function and so will group all the rows together. If you need the count of all rows just count the number of rows returned in whatever language you're using.

A: SQL does not allow to aggregate over the whole table and return all rows at the same time.
You have to use two queries, one for the total number of rows (count) and one for the rows themselves.

A: Have you tried ...
SELECT *, count(*) AS num FROM `questions` LIMIT 0, 10

or simply using mysql_num_rows() to get the count?

A: Since count is an aggregate function, it will by design only return one row. You would have two use two queries, one for the select and one for the count.
Alternatively you could do a nested select:
SELECT *, (SELECT count(id_question) from 'questions') AS num FROM `questions` LIMIT 0, 10

A: You can use mysql_num_rows($queryHandle) on your normal results query. An example:
$query = 'SELECT * FROM `questions` LIMIT 0, 10';
$queryHandle = mysql_query($query);
$count = mysql_num_rows($queryHandle);
$firstRow = mysql_fetch_assoc($queryHandle);

A: Try:
SELECT * FROM `questions` a
INNER JOIN (
  SELECT count(`id_question`) as `num`
  FROM `questions`
) b
LIMIT 0, 10;

Each row will now have the total row count of the table as a column called num.


text:
Q: Cannot Resolve Fargo HDP5000 Badge Printer "Check Ribbon" Error 97 I am having issues resolving a ribbon error on a Fargo badge printer. When we try to print a badge  once it starts printing black it throws an error and then the badge that ran through the printer gets spit out blank. The ribbons look good, no damage or anything. We ran a color print test and a calibration test and the badge printed just fine with no issues at all.
What I've done:

*

*changed some settings in the driver and made sure there was write privileges

*updated drivers and printer firmware

Let me know what you guys think!

A: A quick search gave a number of websites with instructions for clearing your error.
Apart from the things you have already done, one of the main suggestions is calibrating the ribbon sensor. Go to Printing Preferences > Toolbox button > Calibrate Ribbon tab.
If that fails as well, the last suggestion is to call for service.


text:
Q: how to disable parent window in asp.net using javascript i hv an asp.net form in which i have used master page, in this by clicking on one link button a popup window will be opened, my problem is i want to close a popup child window when parent form is closed.. or i should make parent form disable when child popup is active...
i got some code but its working only for IE,, please help me to work this in Google chrome
 this is my code which is working For IE
 in parent window i wrote like this
function topWindow() {
    var popup = window.open('BranchSearch.aspx', 'mywindow', 'location=1,width=450,height=100,toolbar=0,menubar=no,resizable=no,scrollbars=no,status=no,left=340,top=340');
    popup.focus();
        }

and in body tag of child pop window i wrote like dis

please help me as soon as possible
thank u

A: You can use window.showModalDialog This will disable parent window until you close the child window.


text:
Q: How would I make custom notification sound in Android Studio? I want to add an mp3 that I have stored in firebase as my custom notification sound using the URL in firebase.
Here is code to add it if the media file was in the resource folder:
NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    String title = context.getString(R.string.app_name);

    Intent notificationIntent = new Intent(context,
            SlidingMenuActivity.class);
    notificationIntent.putExtra("isInbox", true);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.FILE_NAME);  //Here is FILE_NAME is the name of file that you want to play

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            NotificationChannel mChannel = new NotificationChannel("YOUR_CHANNEL_ID",
                "YOUR CHANNEL NAME",
                NotificationManager.IMPORTANCE_DEFAULT)

            AudioAttributes attributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();

            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID,
                    context.getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_HIGH);

            // Configure the notification channel.
            mChannel.setDescription(msg);
            mChannel.enableLights(true);
            mChannel.enableVibration(true);
            mChannel.setSound(sound, attributes); // This is IMPORTANT

            if (mNotificationManager != null)
                mNotificationManager.createNotificationChannel(mChannel);
        }

How would I do it using the Firebase storage URL given to my MP3 file in firebase?
Source code: Code


text:
Q: How to configure pip to look for modules in a local directory first I have a local pip server in my company that hosts a lot of modules, some of those are outdated.
Since I don't have the ability to add/modify modules in the server, I have created a local directory and downloaded the latest versions for some modules I need.
Now I want to modify my local pip configuration pip.conf so that pip would firstly look for modules in my directory, and if it doesn't find any, then look up them up in the local server.
How can I achieve that? Is it possible to do so without hosting a server locally?

A: You should be able to cache files locally.  Useful if you would be offline.  See https://pip.pypa.io/en/latest/user_guide/#installing-from-local-packages


text:
Q: Fortran on VS Code I have started learning Fortran recently using MSDEV compiler. I mean I'm at beginner level.
My question:
Can I use VS Code as a compiler for Fortran ?

A: No. VS Code is not a compiler for any programming language. VS Code is a text editor.
You can use VS Code as an editor together with many Fortran compilers. But you surely have to install some Fortran compiler. There are many free and commercial options and some of them have plugins that integrate them into VS Code.


text:
Q: How to add an application to startup using installer? I am making an installer using "setup" project in VS2005. I want the project output - application.exe to be added to startup by modifying this registry HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run.
How can I do in the setup project.Thanks

A: Right click setup project in Solution Explorer, choose View/Registry and in the new window that will popup set all the registry keys you need. You can do similar things to the file system and choose where each file from your application will be placed and so on.


text:
Q: c++ porque no puedo crear un objeto con new de una escructura
este es el codigo completo
es compilador de visual studio 2022 me da este error

lo unico que quiero hacer es crear el objeto en el heap!!!

A: El tipo referencia (variables declaradas como tipo&) en c++ necesita apuntar a algo; en otras palabras, no puede existir una referencia que no referencie nada:
int i = 0;
int &r = i; // 'r' es una referencia a 'i'.
int &error; // 'error' no referencia a nada, esto no es posible en C++.

En tu código tienes un objeto que tiene un miembro referencia:
struct _idolz {
    int edad;
    std::string& name; // 'name' es una referencia a cadena.
    _idolz* _idol_next;
};

Cuando instancias _idolz DEBES indicar la cadena a la que hará referencia _idolz::name:
std::string cadena;
_idolz a{0, cadena, nullptr}; // Correcto, 'a::nombre' apunta a 'cadena'.
_idolz b; // Error, 'b::nombre' no apunta a nada.

Dado que es IMPOSIBLE instanciar un _idolz sin argumentos de construcción (necesitas al menos indicar dónde debe apuntar _idolz::name) el compilador elimina el constructor predeterminado (el constructor que no recibe argumentos), de ahí tu error:

no se puede hacer referencia al constructor predeterminado de "_idolz": es una función eliminada

Muy probablemente lo que en realidad querías es esto:
struct _idolz {
    int edad;
    std::string name; // 'name' es una INSTANCIA de cadena.
    _idolz* _idol_next;
};


text:
Q: Domain of a differentiable function contains an interval on which the function is either increasing or decreasing. Let  be differentiable at  in a domain (,) and $f'(b)\neq0$.
Then does (,) contain an interval (,) such that  is either increasing or decreasing on (,)?
For example, = is differentiable at 1 in (0,2) with $f'(1)=1$ and (0,2) contains (0,1) on which = is increasing.
I was wondering this is true in general. Does $f'$ also have to be continuous?


text:
Q: Git LFS doesn't push LFS files unless I specify them with object-id I have a repo hosted on Azure DevOps that uses LFS.
When pushing a commit, the new LFS object isn't pushed with it (if I pull the changes on a separate repository, it yields Smudge Error: Object does not exist on server [404]).
The only way for the LFS object to be pushed is to do it manually by specifying the object id :
git lfs push origin --object-id ae488...
Here is my git config -l:
$ git config -l
http.sslcainfo=C:/Users/200207121/AppData/Local/Programs/Git/mingw64/ssl/certs/ca-bundle.crt
http.sslbackend=openssl
diff.astextplain.textconv=astextplain
core.autocrlf=true
core.fscache=true
core.symlinks=false
core.editor="C:\\Program Files\\Notepad++\\notepad++.exe" -multiInst -notabbar -nosession -noPlugin
credential.helper=manager
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
user.email=<omitted>
user.name=<omitted>
alias.lg=log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
http.sslverify=false
diff.tool=default-difftool
difftool.default-difftool.cmd=code --wait --diff $LOCAL $REMOTE
merge.tool=vscode
mergetool.vscode.cmd=code --wait $MERGED
core.repositoryformatversion=0
core.filemode=false
core.bare=false
core.logallrefupdates=true
core.symlinks=false
core.ignorecase=true
remote.origin.url=https://.../MyRepo/_git/MyRepo
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.master.remote=origin
branch.master.merge=refs/heads/master
lfs.https://dev.azure.com/.../MyRepo.git/info/lfs.access=basic
lfs.https://dev.azure.com/.../MyRepo/info/lfs/objects/.access=basic
branch.7_1_0.remote=origin
branch.7_1_0.merge=refs/heads/7_1_0
branch.7_1_A.remote=origin
branch.7_1_A.merge=refs/heads/7_1_A
branch.atvcm01008318_text_class.remote=origin
branch.atvcm01008318_text_class.merge=refs/heads/text_class
branch.atvcm01008824.remote=origin
branch.atvcm01008824.merge=refs/heads/atvcm01008824
branch.atvcm01000423.remote=origin
branch.atvcm01000423.merge=refs/heads/atvcm01000423
gui.wmstate=normal
gui.geometry=1272x626+-5+0 254 315

To prevent a specific branch from pushing, I have added those lines in pre-pushhook. I'm not currently checked out on this branch, and the LFS I try to push isn't on this branch either (so I don't suspect it can be caused by this hook) :
#!/bin/sh

### Prevent pushing test branch
if [[ `grep 'testing_AA'` ]]; then
  echo "You really don't want to push this branch. Aborting."
  exit 1
fi
### End of edition

command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting .git/hooks/pre-push.\n"; exit 2; }
git lfs pre-push "$@"

Why do I have to specify git lfs push --object-id <oid> for the LFS to be pushed ?

A: The way that a pre-push hook works is to read lines from standard input that indicate which refs are to be pushed and what their old and new values are.  Like your script, git lfs pre-push works as a pre-push hook and expects this data on its standard input.  It then determines what LFS objects need to be pushed based on that and pushes them.
What your pre-push hook does is read all of the standard input with grep.  It then invokes git lfs pre-push with no input.  Since Git LFS thinks there are no refs to push (because none were provided on its standard input), it pushes nothing.
If you want to abort in the case that you're pushing a specific ref, then you need to have your pre-push hook parse the standard input a line at a time, aborting if you match the line, and appending it to the future input to git lfs pre-push if you don't.  So something like the following:
#!/bin/sh

INPUT=""

while read line
do
    if echo $line | grep -qs 'testing_AA'
    then
        echo "You really don't want to push this branch. Aborting." >&2
        exit 1
    fi
    INPUT="$INPUT $line"
done

printf "%s %s %s %s\n" $INPUT | git lfs pre-push "$@"


text:
Q: check the array list size How to check the sizeof array list in java without get error exception from the compiler if the arraylist is not been initialised.
I have tried the following but it does not work. and I got this message:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
ArrayList<String> str = new ArrayList<>();
if (str.size()>0)

A: There is nothing in the code you posted that would throw an IndexOutOfBoundsException. I assume you were calling str.get(0) without the size check before?
Anyway, your code is fine, i.e. you should be able to extend it to do something like the following:
List<String> someStrings = new ArrayList<String>();
...
if (someStrings.size() > 0) {
    System.out.println("First element of list is: " + someStrings.get(0));
} else {
    System.out.println("List is empty");
}

However, for cleanliness I would suggest using if (!someStrings.isEmpty()) instead, which checks the same thing as if (someStrings.size() > 0).

A: By initialised do you mean if an object has been assigned to a reference
With the code
List<String> str;

If you call str.size() it will throw a null pointer exception as you have not assigned an object to this list reference.
To assign a reference then you can do
List<String> str = new Arraylist<String>();

str is now pointing at an array list object.
You can now call
str.isEmpty()

to see if the list has any contents.
Lists are zero based so if you call str.get(0) then you will get a IndexOutOfBounds exception. You cannot get the first element (index 0) as there is nothing in there
If you add an element
str.add("hello")

then you can call
str.get(0)

which will return "hello"
If you call str.get(1) then again you will get an IndexOutOfBound because index 1 is actually the second element in the array list and this does not exist.


text:
Q: How to filter a table based off search parameters or a select value Someone on here kindly helped me with my code to get a table of content to filter based off 2 select drop downs. Its working great but I'm not trying to also get it to filter off a url parameter e.g ?role=CommunicationManager
I'd appreciate the help

<select id="myInput" onchange="searchTable()">
<option disabled="disabled" selected="selected" value="">Job Title</option>
<option value="">All Jobs</option>
<option value="CMO">CMO</option>
<option value="HeadofMarketing">Head of Marketing</option>
<option value="HeadofDigitalMarketing">Head of Digital Marketing</option>
<option value="SeniorMarketingManager">Senior Marketing Manager</option>
<option value="MarketingManager">Marketing Manager</option>
<option value="DigitalMarketingManager">Digital Marketing Manager</option>
<option value="SeniorMarketingExecutive">Senior Marketing Executive</option>
<option value="MarketingExecutive">Marketing Executive</option>
<option value="DigitalMarketingExecutive">Digital Marketing Executive</option>
<option value="MarketingAssistant">Marketing Assistant</option>
<option value="BrandManager">Brand Manager</option>
<option value="CampaignManager">Campaign Manager</option>
<option value="CommunicationManager">Communication Manager</option>
<option value="CRMManager">CRM Manager</option>
<option value="CRMAnalyst">CRM Analyst</option>
<option value="PPCManager">PPC Manager</option>
<option value="PPC Executive">PPC Executive</option>
<option value="SEOManager">SEO Manager</option>
<option value="SEOExecutive">SEO Executive</option>
<option value="EventManager">Event Manager</option>
<option value="EventExecutive">Event Executive</option>
</select>

<select id="myInput2" onchange="searchTable()">
<option selected="selected" value="National Average">National Average</option>
<option value="London">London</option>
<option value="SouthEast">South East</option>
<option value="SouthWest">South West</option>
<option value="EastEast">East</option>
<option value="WestMidlands">West Midlands</option>
<option value="EastMidlands">East Midlands</option>
<option value="Yorkshire">Yorkshire</option>
<option value="NorthEast">North East</option>
<option value="Scotland">Scotland</option>
<option value="Wales">Wales</option>
</select>

Role Category
Title
Region
Lower Quartile
Median
Upper Quartle

CMO
CMO
National Average
£98,129
£119,156
£140,184

CMO
CMO
London
£112,000
£136,000
£160,000

CMO
CMO
SouthEast
£103,704
£125,926
£148,148

CMO
CMO
SouthWest
£96,552
£117,241
£137,931

CMO
CMO
EastEast
£100,000
£121,429
£142,857

CMO
CMO
WestMidlands
£97,391
£118,261
£139,130

CMO
CMO
EastMidlands
£97,391
£118,261
£139,130

CMO
CMO
Yorkshire
£94,118
£114,286
£134,454

CMO
CMO
NorthEast
£93,333
£113,333
£133,333

CMO
CMO
NorthWest
£94,118
£114,286
£134,454

CMO
CMO
Scotland
£98,246
£119,298
£140,351

CMO
CMO
Wales
£92,562
£112,397
£132,231

  HeadofMarketing
Head of Marketing
National Average
£70,092
£78,853
£87,615

  HeadofMarketing
Head of Marketing
London
£80,000
£90,000
£100,000

  HeadofMarketing
Head of Marketing
SouthEast
£74,074
£83,333
£92,593

  HeadofMarketing
Head of Marketing
SouthWest
£68,966
£77,586
£86,207

  HeadofMarketing
Head of Marketing
EastEast
£71,429
£80,357
£89,286

  HeadofMarketing
Head of Marketing
WestMidlands
£69,565
£78,261
£86,957

  HeadofMarketing
Head of Marketing
EastMidlands
£69,565
£78,261
£86,957

  HeadofMarketing
Head of Marketing
Yorkshire
£67,227
£75,630
£84,034

  HeadofMarketing
Head of Marketing
NorthEast
£66,667
£75,000
£83,333

  HeadofMarketing
Head of Marketing
NorthWest
£67,227
£75,630
£84,034

  HeadofMarketing
Head of Marketing
Scotland
£70,175
£78,947
£87,719

  HeadofMarketing
Head of Marketing
Wales
£66,116
£74,380
£82,645

I've tried a few different options but can't quite get it working. Here is my current code. It seems to work from the Search Paramter but stops the 1st drop down working.


text:
Q: Find a solution to $tx''+x'+2x = 0$
Find a nontrivial (no need to be general) solution to $$tx''(t)+x'(t)+2x(t) = 0$$

W/A spells the solution to some Bessel function. I tried to use the series method so I derive
$$
x = \sum_{i=0}^\infty a_nx^n, \quad a_{n+1} = \frac{-2}{(n+1)^2} a_n
$$
well it is not the cleanest solution for this, so I'd like to ask if a explicit solution (non-Bessel function) is available.


text:
Q: How to pass a list element as reference? I am passing a single element of a list to a function. I want to modify that element, and therefore, the list itself.
def ModList(element):
    element = 'TWO'

l = list();
l.append('one')
l.append('two')
l.append('three')
print l
ModList(l[1])
print l

But this method does not modify the list. It's like the element is passed by value. The output is:
['one','two','three']
['one','two','three']

I want that the second element of the list after the function call to be 'TWO':
['one','TWO','three']

Is this possible?

A: The explanations already here are correct.  However, since I have wanted to abuse python in a similar fashion, I will submit this method as a workaround.
Calling a specific element from a list directly returns a copy of the value at that element in the list.  Even copying a sublist of a list returns a new reference to an array containing copies of the values.  Consider this example:
>>> a = [1, 2, 3, 4]
>>> b = a[2]
>>> b
3
>>> c = a[2:3]
>>> c
[3]
>>> b=5
>>> c[0]=6
>>> a
[1, 2, 3, 4]

Neither b, a value only copy, nor c, a sublist copied from a, is able to change values in a.  There is no link, despite their common origin.
However, numpy arrays use a "raw-er" memory allocation and allow views of data to be returned.  A view allows data to be represented in a different way while maintaining the association with the original data.  A working example is therefore
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4])
>>> a
array([1, 2, 3, 4])
>>> b = a[2]
>>> b
3
>>> b=5
>>> a
array([1, 2, 3, 4])
>>> c = a[2:3]
>>> c
array([3])
>>> c[0]=6
>>> a
array([1, 2, 6, 4])
>>>

While extracting a single element still copies by value only, maintaining an array view of element 2 is referenced to the original element 2 of a (although it is now element 0 of c), and the change made to c's value changes a as well.
Numpy ndarrays have many different types, including a generic object type.  This means that you can maintain this "by-reference" behavior for almost any type of data, not only numerical values.

A: Python doesn't do pass by reference. Just do it explicitly:
l[1] = ModList(l[1])

Also, since this only changes one element, I'd suggest that ModList is a confusing name.

A: Python is a pass by value language hence you can't change the value by assignment in the function ModList.  What you could do instead though is pass the list and index into ModList and then modify the element that way
def ModList(theList, theIndex) :
  theList[theIndex] = 'TWO'

ModList(l, 1)

A: In many cases you can also consider to let the function both modify and return the modified list. This makes the caller code more readable:
def ModList(theList, theIndex) :
          theList[theIndex] = 'TWO'
    return theList

l = ModList(l, 1)


text:
Q: How does this code generate the proper sequence of characters? The code in question comes from MathGuard, a PHP anti-spam CAPTCHA script that requires the user to answer a simple math problem. It displays the digits and operator symbols as 3x5 matrices of random characters. I understand how the code works in the sense that I can follow the code and understand what it's doing; I just don't understand how one would come to this solution.
This function takes an integer that describes one line of the 3x5 matrix and converts it into a line of random characters:
function decToBin($dec) {
    $pattern = "123456789ABCDEFGHIJKLMNOPQRTSTUWXYZ";
    $output = "   ";
    $i = 0;
    do {
        if ($dec % 2) {
            $rand = rand() % 34;
            $output { 2 - $i } = $pattern { $rand };
        } else {
            $output { 2 - $i } = " ";
        }
        $dec = (int) ($dec / 2);
        $i++;
    } while ($dec > 0);
    $output = str_replace(" ", " ", $output);
    return $output;
}

Here are the digit descriptors:
$number = array (
    array ( 7, 5, 5, 5, 7 ), // 0
    array ( 2, 6, 2, 2, 7 ), // 1
    array ( 7, 1, 7, 4, 7 ), // 2
    array ( 7, 1, 7, 1, 7 ), // 3
    array ( 4, 5, 7, 1, 1 ), // 4
    array ( 7, 4, 7, 1, 7 ), // 5
    array ( 7, 4, 7, 5, 7 ), // 6
    array ( 7, 1, 1, 1, 1 ), // 7
    array ( 7, 5, 7, 5, 7 ), // 8
    array ( 7, 5, 7, 1, 7 )  // 9
);

My question is: how does one come to this conclusion and method of generation and know that, for example, 7 will generate a full line of random characters, and 5 only the outermost characters?
Is this just a form of code obfuscation? What makes this method better than, say, storing the digits as a string (111101101101111 as 0, for example) and replacing each 1 with a random character?

A: Looks like a simple bitmap to me.
7 = 1 1 1
5 = 1 0 1
5 = 1 0 1
5 = 1 0 1
7 = 1 1 1

2 = 0 1 0
6 = 1 1 0
2 = 0 1 0
2 = 0 1 0
7 = 1 1 1


text:
Q: Phantom file anomaly I see something in my Downloads (fanned from Dock) that I didn't download, named XXkkAgSU
Dragging the icon to Terminal pastes the full path and filename as expected.  But the shell can't see it:
WGroleau@MBP ~ % file /Users/WGroleau/Downloads/XXkkAgSU
/Users/WGroleau/Downloads/XXkkAgSU: cannot open `/Users/WGroleau/Downloads/XXkkAgSU' (No such file or directory)
WGroleau@MBP ~ % rm !$
rm /Users/WGroleau/Downloads/XXkkAgSU
rm: /Users/WGroleau/Downloads/XXkkAgSU: No such file or directory

After those commands, fanning Download from Dock still shows it.  But a regular Finder window navigated to ~/Downloads doesn't show it.  Dragging icon from fan to Trash does nothing—still in fan and not in Trash.
????
Something similar happened ages ago but that time the phantom file was in the Trash, and could be seen by shell commands, but couldn't be be deleted.

A: I would remove the entire Downloads folder from the Dock. (Note: this will not affect the 'real' Downloads folder.)
Right-click on it, and under Options, you'll see "Remove From Dock".
Then drag the actual Downloads folder back to its position next to the Trash.


text:
Q: How can I get coupled data in postgres? I'm new at Postgres and I want to find coupled data.
SELECT id, email, count(*) AS total FROM public."mails" GROUP BY email HAVING total > 1 ORDER BY email ASC

I got SQL code like this but I got an error.

A: Using your statement, I get this error:
ERROR: column "mails.id" must appear in the GROUP BY clause or be used in an aggregate function Position: 8

From https://www.sqlservercentral.com/articles/postgresql-where-order-by-and-group-by-clauses:

The PostgreSQL GROUP BY clause is used with SELECT statements to accumulate identical data into groups. This is used to reduce the redundancy in the result. The GROUP BY clause works with aggregates functions, like SUM(), COUNT() and also without aggregate functions.

All selected columns must be part of the group by statement.
Solution tested on http://sqlfiddle.com/#!17/47beb
create table mails (id integer, email varchar(100));
insert into mails (id, email) values (1, 'albert');
insert into mails (id, email) values (1, 'albert');
insert into mails (id, email) values (2, 'isaac');

SQLs statement (with both id and email column included):
SELECT id, email, count(*)
FROM mails
GROUP BY id, email HAVING count(*) > 1
ORDER BY email ASC


text:
Q: MySQL inner join with 2 columns I have one table users with 2 fields : id , name  and another table friends with 2 fields : userid1 userid2 .
So this means userid1 is friend with userid2 . I want , with one inner or left join to show this :
userid1 name(got from users table) is friend with userid2 name(got from users table)
something
SELECT * FROM friends INNER JOIN users ON friends.userid1 = users.id AND friends.userid2 = users.id but this is not working.
Any good query with good explanation please?
If, for example I have the next details in the users table :
ID : 1    NAME : FinalDestiny
ID : 2    NAME : George
and the next details in the friends table :
ID1 : 1      ID2 : 2
So this means 1 is friend with 2.
I need with one query to get the name of 1 and the name of 2 and to echo that they're friends
FinalDestiny is friend with George

A: You check on a user being a friend of itself. Use OR in your select to match user's friends:
SELECT * FROM friends INNER JOIN users ON friends.userid1 = users.id OR friends.userid2 = users.id

A: I know that you specify that you want this done with one join, but it looks to me like you need two.  I believe this query will give you what you need:
SELECT u1.Name, u2.Name
FROM Users u1, Users u2, Friends f
WHERE u1.id = f.userid1 AND u2.id = f.userid2
I am joining the Users table with the Friends table with on Users.id = Friends.userid1.  Then, I am joining this new table with the Users table on (new table).userid2 = Users.id.  This results in a table with 4 columns.  These columns are the original 2 columns of the Friends table in addition to 2 columns for the names of the friends.  u1, u2, and f and referring to the three tables that were joined.  The users table was joined with the friends table twice.  u1 is the copy of the Users table that was joined on Friends.userid1 = User.id.  u2 is the copy of the Users table that was joined on Friends.userid2 = User.id.
From this table with 4 columns, I am selecting only the names of the friends.
Let me know if more explanation is needed.

A: If, for example I have the next details in the users table :
ID : 1    NAME : FinalDestiny
ID : 2    NAME : George
and the next details in the friends table :
ID1 : 1      ID2 : 2
So this means 1 is friend with 2.
I need with one query to get the name of 1 and the name of 2 and to echo that they're friends
FinalDestiny is friend with George


text:
Q: Number of possibilities to seat $3$ pairs of husbands and wives so that at least one husband and wife sit together Question: There are $6$ people that consist of $3$ sets of husbands and wives. How many possibilities are there to seat all of them on a bench if at least one couple sits next to each other?
Initially, I thought I could just subtract from the total number of possibilities to seat $6$ people which is $6!$, the complement of the question which is "How many possibilities are there to seat those same people where no couple sits next to each other?". To evaluate how many possibilities there are for the complement, I'll have to first seat all three women on the bench. There are ${{6}\choose{3}} \cdot 3!$ ways to do it. Next, I'll have to seat the guys accordingly (so neither of them sits next to their spouse). The number of possibilities to seat each of them is exactly $2$, thus resulting in $2^{3}$ possibilities for the three of them.
So according to my calculation, the total number of possibilities is: $$6! - {{6}\choose{3}} \cdot 2^{3} = 560$$
However, after comparing my answer to what is written in the textbook, the answer should be: $$3 \cdot 2 \cdot 5! - 3 \cdot 2^{2} \cdot 4! + 2^{3} \cdot 3! = 480$$
Looks like the textbook's answer uses inclusion/exclusion. Before comparing my answer to the textbook's one, I was certain that inclusion/exclusion was unnecessary (I still do in fact), because there was only one exclusion to make - the complement (which I've described above). I really don't get why someone would apply this principle here. Clarifications on the matter will greatly appreciated.

A: Finding the complement is not so easy. For example assuming $3$ women is sitting together (by together I mean between them there is no men), for the women in middle, the condition for the complement already satisfied. So your calculation must change in this case and this is not the only case where your calculation must change (For example if one of the women is on the leftmost place and there is a woman in right of her, then the woman on the leftmost side also satisfies the condition for complement and obviously, number of ways are different for these two cases).
Instead, you can use Inclusion-Exclusion Principle by considering the events $A_1, A_2, A_3$ where $A_i$ is the event that $i^{th}$ couple is sitting together. So we have to find
$$|A_1 \cup A_2 \cup A_3| = 3|A_1|-3|A_1 \cap A_2|+|A_1 \cap A_2 \cap A_3|$$
since $|A_1| = |A_2| = |A_3|$ and $|A_1 \cap A_2| = |A_1 \cap A_3| = |A_2 \cap A_3|$ by renumbering.
Now, we have $|A_1| = 2! \cdot 5!$ (because first pair is sticked so we have $5$ things to permute with $5!$ and we can switch the man and woman with $2!$), $|A_1 \cap A_2| = 2^2 \cdot 4!$ and $|A_1 \cap A_2 \cap A_3| = 2^3 \cdot 3!$ by similar arguments. So the result follows.


text:
Q: What abstraction to use for an ASynchronous data collection driver I would like to implement a mechanism in my server application but I'm not sure which OTL abstraction would be best appropriate.
My application collects data about various types of equipements.
Some of them use synchronous communication, thus generating Delphi event in my server application. (push-like)
Some of them use asynchronous communication, requiring my application to periodically request the latest data available. (pull like)
Because I want my server application to stay responsive while requesting as frequently as possible the new available data, I want to put that "pull driver" within a separated thread that will request all the configured data points one by one.
I'd like my main thread to spawn this OTL object and then receive the result as a delphi event in the main thread. This would emulate the "push-like" that my server main code is already made for.
Think of it as a thread you launch that periodically request a data you want to monitor and only send you an event when the value has changed.
Which OTL abstraction (high level? Low level?) do you think would be appropriate to this behavior?
Thank you.

A: I'm not sure OTL gives you much benefit here at all, to be honest.  I write a lot of classes for managing hardware devices and the class model is almost invariably a plain TThread descendent.  OTL is nice for spinning off tasks and work packages, queues, parallel calculations, etc.  In this case, however, you don't want to do any of that.  What you do want is a class that models your device and encapsulates the functions it can perform.
This is going to be a single worker thread dedicated to pumping reads and writes to the device.  It is going to be a long-lived thread that will persist as long as the class that encapsulates the device remains alive - TThread makes sense for this.  Your thread is going to be a simple loop that runs continuously, polling all the required data and flushing any write requests.
The class will also serve as a data cache for the device parameters and you will need some sort of synchronization devices (mutex, critical section, etc) to protect reads and writes to those fields through properties so again it makes sense that these sync objects also exist as class fields and that your thread and class model live together in a single entity.  If you want event notifications, these too conveniently wrap into the same model.  One device, one thread, one class.  It's a perfect job for a TThread descendent.


text:
Q: showing buddy-press messages inside my custom page template I am new to WordPress and Buddy-Press but would like to know how to use messaging inside my own template as per my client requirement ? I have been through Buddy Press forums and could not get enough help as well. Her is the code I am currently using from buddy-press message>single page.
<?php
/**
 * BuddyPress - Users Messages
 *
 * @package BuddyPress
 * @subpackage bp-legacy
 */
?>

    <?php bp_get_options_nav(); ?>

<?php if ( bp_is_messages_inbox() || bp_is_messages_sentbox() ) : ?>

<?php bp_message_search_form(); ?>

<?php endif; ?>

<?php
switch ( bp_current_action() ) :

    // Inbox/Sentbox
    case 'inbox'   :
    case 'sentbox' :

        /**
         * Fires before the member messages content for inbox and sentbox.
         *
         * @since 1.2.0
         */
        do_action( 'bp_before_member_messages_content' ); ?>

        <?php bp_get_template_part( 'members/single/messages/messages-loop' ); ?>

    <?php

    /**
     * Fires after the member messages content for inbox and sentbox.
     *
     * @since 1.2.0
     */
    do_action( 'bp_after_member_messages_content' );
    break;

// Single Message View
case 'view' :
    bp_get_template_part('members/single/messages/single' );
    break;

// Compose
case 'compose' :
    bp_get_template_part( 'members/single/messages/compose' );
    break;

// Sitewide Notices
case 'notices' :

    /**
     * Fires before the member messages content for notices.
     *
     * @since 1.2.0
     */
    do_action( 'bp_before_member_messages_content' ); ?>

        <?php bp_get_template_part( 'members/single/messages/notices-loop' ); ?>

    <?php

    /**
     * Fires after the member messages content for inbox and sentbox.
     *
     * @since 1.2.0
     */
    do_action( 'bp_after_member_messages_content' );
    break;

// Any other
default :
    bp_get_template_part( 'members/single/plugins' );
    break;
endswitch; ?>

This is buddy-press's single page message template content. But it does not show anything on my own template?
Can anyone guide me that how can I use buddy press messaging from my own template? So, that my clients can chat with each other from that specific template rather than default buddy press page ... ???
Waiting for any helpfull material, please?


text:
Q: Should these META badge designations be re-evaluated? Here we have 2 Moderation Badges for your consideration; Tag Editor and Research Assistant.  Below is the description of each tag level, and a description of these two badges:

A Bronze badge is supposed to be "easy to get", yet with only 177 Tag Editor badges awarded I'd say it's really not that easy.
A Silver badge is "less common", yet only 4 Research Assistant badges have been awarded.  I'd consider 50 Wiki edits to be an "important contribution", wouldn't you?
The only badge awarded less times than Research Assistant is the Legendary badge, which has only been awarded 3 times.
Is it time to bump these up a notch and make Tag Editor a Silver and Research Assistant a Gold?

A: I don't think their rarity speaks to difficulty - I think you just have less people editing tag wikis. Remember, for Tag Editor the requirement is

First tag wiki edit

And that's not really difficult.
So no, I don't think we need to adjust their rankings.


text:
Q: How to compare two range and set values in a third table with google sheet script I am trying to compare some values in a table (AreaF1) with values in another table (AreaSW). Then, if they match, I set corresponding value of the column in the same column and row of a third sheet (AreaF2) [that is a copy of the first one (AreaF1)]
I tried this code, written using existing examples, but it does not work at all. No errors given. Any idea about how to make it work?
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('Menu')
      .addItem('Calc', 'SWFC')
      .addToUi();
}

function SWFC() {
  var Sheet = SpreadsheetApp.getActive();
  var AreaF1 = Sheet.getSheetByName('Foglio1').getRange(2, 3, 272, 22).getValues();
  var AreaF2 = Sheet.getSheetByName('Foglio2').getRange(2, 3, 372, 22);
  var Dim2 = AreaF2.getValues();
  var AreaSW = Sheet.getSheetByName('Foglio3').getRange(1, 1, 3, 2).getValues();

  for (var i = 0; i<AreaF1.length; i++){
    for (var f = 0; f<Dim2.length; f++){
      for (var k = 0; k<AreaSW.length; k++){
        if(AreaF1[i][f] == AreaSW[k][1]){
            Dim2[i][f] = AreaSW[k][2];
        }
      }
    }
  }
  AreaF2.setValues(Dim2);
}

A: Changing the "for" code section solved the problems. I decided to put fixed length for second and third for due to my personal needs.
  for (var i = 0; i<AreaF1.length; i++)
  {
    for (var j = 0; j<22; j++)
    {
      for (var k = 0; k<AreaSW.length; k++)
      {
        if(AreaF1[i][j] == AreaSW[k][0])
        {
           Dim2[i][j] = AreaSW[k][1];
        }
      }
    }
  }


text:
Q: Find and open all files that match name I have a workspace with a lot of folders. They share a file that I would like to compare. I know I can't compare multiple files at once (wouldn't it be nice) but at least I would like to open the same file from all subfolders and then use Compare Active File with command.
Is this possible? CTRL+P only gives me a possibility to see the results but not to open all of them:


text:
Q: Result from xml2js I'm trying to parse xml after a request.
var fs = require('fs'),
    parseString = require('xml2js').parseString,
    request = require('request');

    request('http://www.stands4.com/services/v2/quotes.php?uid=123&tokenid=123&searchtype=RANDOM', function (error, response, body) {
       if (!error && response.statusCode == 200) {
           parseString(body, function (err, result) {
               console.dir(result);
        });

     }
})

XML
<?xml version="1.0" encoding="UTF-8"?>
<results><result><quote>Some Text</quote><author>Name</author></result></results>

Returns
{ results: { result: [ [Object] ] } }

Why it isn't returning the correct format?

A: { results: { result: [ [Object] ] } }

is the result of console.dir , not the actual value of result.
if you want to know what is the result,try
console.log(JSON.stringify(result));


text:
Q: How to pass generic List to restful web services I have the requirement to create the search operation using restful web services, i.e, using @GET. The method signature takes String and List as input argument and returns List.
public Generic List <Employer> getAllEmployer(String employeeName, Generic List <employeeLocation>);

Kindly request if someone could describe on how to implement the same. Should I use query param or path param or form param. I need to return the List of employer in json format.

A: if the employee locations  are just string, pass them as comma seperated values and spring will take care of converting it to list. I would rather suggest just to have it as a pathparam rather than having it as a query param.

A: This is just my opinion but I think that the "RESTful" way to pass multiple parameters with the same name would be to a MultiValueMap.
Spring and Jersey both have implementations of MultiValueMap however, below is an example of a spring implementation:
@RequestMapping(method = RequestMethod.GET, value = {"/employer/_search"})
public List<Employer> search(@RequestParam MultiValueMap<String,String> params) {
    return someService.search(params);
}

They way that you would call this url would then become:
/employer/_search?employeeName=name&location=1&location=2&location=3

Then behind the scenes spring will create the MultiValueMap for you which is a Map<String,List<String>> where any parameters with the same name are put into the same list.


text:
Q: Determinant of Adjacency Matrix is null Let be $D=(V,E)$ . Prove the determinant of its adjacency matrix , $det(A) = 0$ $\iff$ $\exists S \subseteq V $ (nonempty) such that $|v_{ext} \cap S|$ is an even number , $\forall $ v $\in V$ . $v_{ext}$ denotes the nodes $u$ such that $vu \in E$.
Also , D may have loops (i.e $\exists$ $A_{uu} =1$). All operations are made in $GF(2)$.
I have tried the direct implication in this way : if $det(A) = 0$ , it means that the vectors of $A$ are not linearly independents. But what`s the next step ?
Thanks!

A: Hint: The determinant of $A$ vanishes iff there is a non-zero vector $x$ such that $Ax=0$.

A: Another hint: consider the special case $S=\emptyset$.

A: Some hints:

*

*The determinant is $0$, so there is some vector $\mathbf{x}$ with $A \mathbf{x} = 0$.

*Since all of your calculations are done $\bmod{2}$, your vector $\mathbf{x}$ can be assumed to be a $0/1$ vector.

*Again, since your calculations are done $\bmod{2}$, $A \mathbf{x} = 0$ means that, if you multiply $A$ times this vector using integers (all numbers in the matrix and vector are either $0$ or $1$), you will get an even number.

*Since $\mathbf{x}$ contains $0$ and $1$s, and has the same number of entries as your graph has vertices, you can consider a relation ship between $\mathbf{x}$ and a subset $S \subset V$ by interpreting your $0$s and $1$s in a certain way.

*The entries of $A \mathbf{x}$ are the products of the rows of $A$ with $\mathbf{x}$; the rows of $A$ are each associated with a vertex $v \in V$ in a natural way.


text:
Q: How to prove that covariance equals $ cov[Y'AY, Y'BY]=2 \sigma^{4} tr (AB)$ if $Y_{1},...,Y_{n}$ are independently distributed as $N~(0,\sigma^{2})$ and $A$ and $B$ are any $n \times n$ matrices, how to prove that $ cov[Y'AY, Y'BY]=2 \sigma^{4} tr(AB)$

A: Hint: to prove $\operatorname{cov}(A_{ij}Y_iY_j,\,B_{kl}Y_kY_l)=2\sigma^4A_{ij}B_{ji}$ for symmetric $A,\,B$, show $\operatorname{cov}(Y_iY_jY_kY_l)=\sigma^4(\delta_{ik}\delta_{jl}+\delta_{il}\delta_{jk})$ with this theorem.

A: Use the following fact :
Let  $\textbf{x} \sim N(0,\sigma^2 \textbf{I})$, for a symmetric Matrix $\textbf{T}$,
$Var(\textbf{x}'\textbf{T}\textbf{x}) = 2\sigma^4trace(\textbf{T}^2)$
Now $Cov(\textbf{x}'\textbf{Ax},\textbf{x}'\textbf{Bx}) = \frac{1}{2}*$ $(Var(\textbf{y}'\textbf{(A+B)}\textbf{y}) - Var(\textbf{y}'\textbf{A}\textbf{y}) - Var(\textbf{y}'\textbf{B}\textbf{y}))$
When $\textbf{A}$ and $\textbf{B}$ are symmetric.


text:
Q: ModuleNotFoundError: No module named 'kivy' . How do I fix this error? I have Ubuntu 16.04.4. I installed Kivy from Kivy Official Site.
I followed all the steps correctly. In spite of doing all this, when I try to import kivy in python, it is giving this error: ModuleNotFoundError: No module named 'kivy' I'm getting this error in both the terminal and Anaconda. How can I fix this?

*

*which python
/home/username/anaconda3/bin/python

*echo $PYTHONPATH
This gave no output.

*dpkg -L python-kivy | grep kivy/__init__
/usr/lib/python2.7/dist-packages/kivy/init.py

A: Short answer: Don't use anaconda if you don't know what you're doing.
Long answer: you are using a python installation (anaconda) which exists alongside the system python installation. If you install a system python package, or, in the case of kivy, a package that is made for the system python, it is probably not seen by anaconda.
In order to use it you have to either install the package the way anaconda wants it (beyond the scope of this site), or you have to start the system python interpreter, which is /usr/bin/python.
On the Kivy homepage you find instructions on how to install using virtual environments (https://kivy.org/docs/installation/installation-linux.html#installation-in-a-virtual-environment), I recommend this method if you are not using the standard system python installation.


text:
Q: upgrading spring-data-neo4j from 3.3.0.RELEASE to 4.0.0.RELEASE Not able to import org.springframework.data.neo4j.conversion.Result.
I have code like - Result<Map<String, Object>> result = template.query(matchQuery, null);
Please let me know if api is deprecated/it name got changed in 4.0.0.RELEASE version. If i cant use org.springframework.data.neo4j.conversion.Result then what i have to use instead of this.

A: org.neo4j.ogm.model.Result is the class to use in SDN 4.
BTW, SDN 4.1.1.RELEASE is just out, it would be better to upgrade to that instead,


text:
Q: sscanf not detecting the right numbers I'm having a hard time using sscanf to scan hour and minutes from a list. Below is a small snip of the list.
1704 86 2:30p 5:50p Daily
1711 17 10:40a 2:15p 5
1712 86 3:10p 6:30p 1
1731 48 6:25a 9:30a 156
1732 100 10:15a 1:30p Daily
1733 6 2:15p 3:39p Daily

I've tried this, but it keeps getting me segmentation Fault.(I'm putting this information into structures).
 for(i=0;i<check_enter;i++){
    sscanf(all_flights[i],
    "%d %d %d:%d%c %d:%d%c %s",
    &all_flights_divid[i].flight_number,
    &all_flights_divid[i].route_id,
    &all_flights_divid[i].departure_time_hour,
    &all_flights_divid[i].departure_time_minute,
    &all_flights_divid[i].departure_time_format,
    &all_flights_divid[i].arrival_time_minute,
    &all_flights_divid[i].arrival_time_minute,
    &all_flights_divid[i].arrival_time_format,
    &all_flights_divid[i].frequency);

    printf("%d ",all_flights_divid[i].flight_number);
    printf("%d ",all_flights_divid[i].route_id);
    printf("%d ",all_flights_divid[i].departure_time_hour);
    printf("%d ",all_flights_divid[i].departure_time_minute);
    printf("%c ",all_flights_divid[i].departure_time_format);
    printf("%d ",all_flights_divid[i].arrival_time_hour);
    printf("%d ",all_flights_divid[i].arrival_time_minute);
    printf("%c ",all_flights_divid[i].arrival_time_format);
    printf("%s\n",all_flights_divid[i].frequency);
  }

This is how I declared it.
struct all_flights{
  int flight_number;
  int route_id;
  int departure_time_hour;
  int departure_time_minute;
  char departure_time_format;
  int arrival_time_hour;
  int arrival_time_minute;
  char arrival_time_format;
  char frequency[10];
};
struct all_flights all_flights_divid[3000];

These are the results I get
1704 86 2 30 p 0 50 p Daily
1711 17 10 40 a 0 15 p 5
1712 86 3 10 p 0 30 p 1
1731 48 6 25 a 0 30 a 156
1732 100 10 15 a 0 30 p Daily
1733 6 2 15 p 0 39 p Daily

A: Small mistake, that might be the problem:
this:
&all_flights_divid[1].flight_number,

should be:
&all_flights_divid[i].flight_number,
//                 ^

Edit:
Also, you read arrival_time_minute twice, and not reading arrival_time_hour at all. Fix it and it should be OK.

A: Most of the results seem to be fine, except the first field.
Now if you check your code..
&all_flights_divid[1]

fix it with
&all_flights_divid[i]


text:
Q: Matrix multiplication not working in C++ I made a program that calculates product of all elements in column of a 2D array and stores that value in another 1D array. This is my code:
void product_of_col(int n)
{
    int i, j, product;
    for(i = 0; i < n; i++)
    {
        product = 1;
        for(j = 0; j < n; j++)
            product *= a[j][i];
        b[i] = product;
    }
}

This function works fine, but when I change
for(j = 0; j < n; j++)
    product *= a[j][i];

to
for(j = 0; j < n; j++, product *= a[j][i]);

every product is equal to 0. I runned this code on Ideone and it didn't work. I also made a function that calculates the sum of all elements in the same column and it works fine for both codes.
Can anyone tell me why isn't the second code working?

A: You got the order wrong. Replace for(j = 0; j < n; j++, product *= a[j][i]); with for(j = 0; j < n; product *= a[j][i], j++);

A: Note that in your second snippet the expression j++ gets executed before the expression product *= a[j][i] because of the way the comma operator works.

A: Alright, this is something that you (probably) didn't learn in your C++ class. I know I sure as heck didn't.
the comma operator
You probably know about the term "operator" in c++. You have +-=*/, ect. What you probably DIDN'T know is there is an comma operator (,). What the heck does the comma operator do? Whell basically, it evaluates everything in a statement, but returns only the first value. so i can do
int a = 1,2,3,4;

and a will only equal 1. Additionally, I can do
int x = 5; int y = 10;
int z = (y*=2), (x*=2);
std::cout << x << ',' << y << ',' << z << std::endl;

which will output 10, 20, and 20. What you are ACTUALLY doing in a for loop is calling this comma operator. In your case, we are looking at the statement
j++, product *= a[j][i]
I find it helpful to think of this as the following call:
const int& comma_operator(const int& a,const int& b) {return a;}
   comma_operator(j++,produce*=a[j][i]);
Now that you understand what the comma is actually doing, lets look at the concept of order of evaluation.
order of evaluation
C++ makes NO promises on what order arguments to a function call or operator is called, just that they are all called before the function or operator is run. This may seem counter intuitive: you may be thinking to yourself, why doesn't it just run from left to right?
Well, this would tie the hand of the compiler in a lot of cases where it could optimize the crap out of your code. The common example would be:
int x; int y; int z = x/y+x%y.
In this case, most CPU's can calculate x/y and x%y with the same instruction. Certainly, this doesn't make sense to you, but the first argument to plus and the second argument to plus are calculated at the SAME time rather than sequentially.
C++ only guarantees that the code will behave the same as you wrote it logically, not exactly as you wrote it. And operand evaluation order is not part of that logic.
So just use for(j = 0; j < n; j++) product *= a[j][i]; and you'll be happy.

A: Can anyone tell me why isn't the second code working?
In your second code,
for(j = 0; j < n; j++, product *= a[j][i]);
You are incrementing j before product *= a[j][i]) executes.So,Just change the order like :
for(j = 0; j < n; product *= a[j][i], j++);


text:
Q: Url friendly without losing styles css / js / images I have a website too extensive editing the URLs of styles css and files js, images would cost me too much time.
I'm working at localhost
localhost/project/index.php

The friendly url I want to have:
localhost/project/index/

From this url
localhost/project/online.php

to this
localhost/project/online/video/hd/free/

I have observed this website http://crazycafe.net/demos/seo/ and its source code, the styles css is maintained this way: <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">
without adding an absolute URL to styles css and their files and images.
How do i create a friendly url this way?
If the user modifies the url in this way:
http://crazycafe.net/demos/seo

Redirect to this way:
http://crazycafe.net/demos/seo/

On the other hand like conserving the styles css the files js and images, without having to modify to an absolute route.
My file directory is:
assets/css/style.css
assets/js/app.js
assets/fonts/icons/image.png
assets/fonts/ttf/roboto.ttf
assets/img/system/image.png
assets/img/logo.png

Note:
I found this question in SO, of how conserve CSS styles.
But I do not understand the use of friendly URL - .httaccess

A: You need to switch on mod_rewrite and use it. Example:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^folder1.*$ http://example.com/ [R=301,L]

Folder-based example:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^folder1/(.*)$ http://gs.mt-example.com/folder2/$1 [R=301,L]

Your case:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^online.php$ project/online/video/hd/free/$1 [R=301,L]

See more here.


text:
Q: Have apache run a script before handling request I want to have Apache run a script every time it gets a request. To be clear I want apache to serve the actual file and just have this script called right before Apache handles the request (I have my own script that needs to do some custom logging).
I tried:
 <VirtualHost *:80>
    ServerName voice1.example.org
    DocumentRoot /var/www/html/
    <directory "/">
            Script GET "/test.php"
    </directory>
    ErrorLog /var/log/httpd/dovid.log
    LogLevel info
    CustomLog /var/log/httpd/dovid.access.log combined

as well as
 <VirtualHost *:80>
    ServerName voice1.example.org
    DocumentRoot /var/www/html/
    <directory "/">
             Action pre-script /var/www/html/test.php
            SetHandler pre-script
    </directory>
    ErrorLog /var/log/httpd/dovid.log
    LogLevel info
    CustomLog /var/log/httpd/dovid.access.log combined

Both don't seem to work. What am I doing wrong?


text:
Q: Issue with if statement which should be true comes up as false We recently migrated a very old site to a new server and are running into an odd issue.  There is a simple if statement which should and did on old server read as true but it is not and not sure why.  The statement is below.  When I write out invflag it is equal to 1 which is what I would expect.
'does not trigger as true so iChk remains = ""
iChk = ""
if invflag = True then
    iChk = "checked"
end if

'Works as expected
iChk = ""
if invflag = "1" then
    iChk = "checked"
end if

'works as expected
iChk = ""
if invflag = 1 then
    iChk = "checked"
end if

I know we can simply fix this as you can see but we have these types of statements littered throughout the code and if there is something with the server or database we can set that would be ideal and thought I would check.

A: Simply casting to CBool should do the trick for all cases:
If CBool(invflag) = True Then
    iChk = "checked"
End If

or better
If CBool(invflag) Then
    iChk = "checked"
End If

A: It turned out that during the migration from MSSQL to Mysql it converted the Bit fields to TinyInt.  Once we changed the fields back to Bit the if statements worked as they did before.


text:
Q: Control pressed state of Android Up button I'm trying to control what color the pressed state of the android up/back icon + title text in the action bar will be.
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="android:actionBarStyle">@style/MyActionBar</item>
    <item name="android:homeAsUpIndicator">@drawable/up_button</item>
    <item name="android:actionMenuTextAppearance">@style/H4.Other</item>
    <item name="android:actionMenuTextColor">@color/h4_other</item>
</style>

<style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:background">@color/kf_white</item>
    <item name="android:titleTextStyle">@style/H5.Blue</item>
</style>

As you can see I've defined by own up indicator. I've tried making that a selector but that only deals with the icon I provided, not the combined icon + title text for which Android provides a standard pressed color. The reason I'm asking this is because on some Samsung devices, the standard pressed color is a weird blue which doesn't fit with the style of my app.

A: You could try adding
<item name="android:actionBarItemBackground">@drawable/selector</item>

in your AppTheme. selector.xml will be something like
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:constantSize="false"
android:enterFadeDuration="0"
 android:exitFadeDuration="0" >
<item
    android:state_pressed="true"
    android:drawable="@color/color1" />
<item
    android:state_pressed="false"
    android:drawable="@color/transparent" />
</selector>


text:
Q: pgAgent won't launch after a database restore I've installed pgAgent in our PostgreSQL database for scheduling our jobs, which really works like a charm!
However, after I restored a backup from our database in a test server, pgAgent simply won't launch. Interestingly enough, it seems that pgAgent ignores the current state of the data in this log tables and tries to populate them from zero.
See error message at the log file:
postgres@postgres ERROR:  duplicate key value violates unique constraint "pga_jobsteplog_pkey"
postgres@postgres DETAIL:  Key (jslid)=(1) already exists.
postgres@postgres STATEMENT: INSERT INTO pgagent.pga_jobsteplog(jslid, jsljlgid, jsljstid, jslstatus) SELECT 1, 25, 3, 'r'  FROM pgagent.pga_jobstep WHERE jstid=3

In case you're wondering how the backup is performed:
pg_dumpall --file "/media/jones/Daten/fulldump.sql" --host "address-to-my-server.de" --port "5432" --username "myuser" --no-password --database "mydb" --clean --if-exists --verbose

Environment:
Ubuntu 16.04
PostgreSQL 9.5
pgAgent 3.4.1-2

Any ideas how to make pgAgent come back to life?

A: I'm definitely not happy with the solution, but so far I couldn't find anything better than the following options:

*

*Truncating the log table does the trick, but deletes all job history you had (no big deal in most use cases):

TRUNCATE TABLE pgagent.pga_jobsteplog;

*Alternatively, updating the sequences manually also works, e.g.:

SELECT SETVAL('pgagent.pga_exception_jexid_seq', max(jexid)) FROM pgagent.pga_exception;
SELECT SETVAL('pgagent.pga_job_jobid_seq', max(jobid)) FROM pgagent.pga_job;
SELECT SETVAL('pgagent.pga_jobclass_jclid_seq', max(jclid)) FROM pgagent.pga_jobclass;
SELECT SETVAL('pgagent.pga_joblog_jlgid_seq', max(jlgid)) FROM pgagent.pga_joblog;
SELECT SETVAL('pgagent.pga_jobstep_jstid_seq', max(jstid)) FROM pgagent.pga_jobstep;
SELECT SETVAL('pgagent.pga_jobsteplog_jslid_seq', max(jslid)) FROM pgagent.pga_jobsteplog;
SELECT SETVAL('pgagent.pga_schedule_jscid_seq', max(jscid)) FROM pgagent.pga_schedule;

If anyone has a more elegant solution, please let me know in the comments.

A: In case anybody is still looking, I've found what works in this situation..
Log onto the database, install the pgagent extension
Do the pg_restore of the pgagent schema
Then restore the pgagent.pga_jobsteplog after the rest of the schema has restored.
Then reset the value of the sequences for each table to be 1 above the max value of the column the sequence is based on
Doing this, means you pgagent working, and you also have you job and jobstep logs.


text:
Q: Form won't submit if chosen file is large I have an HTML-form that I use for uploading files (and some other data). The form is as follows:
<form enctype="multipart/form-data" action="register.php" method="post">

        Reason
        <textarea id="reason" class="form-control" name="reason_text" rows="4"></textarea>

        Attachment
        <input type="file" id="reason_file" name="reason_file">

        Score
        <input type="number" id="amount" class="form-control" name="amount">

    <input type="submit" class="btn btn-primary" name="register" value="Register">
</form>

If I use this form with a rather small file, let's say 1 MB, it'll be just fine and my server-side can process it correctly. However, if I use a file that's for example 5.5 MB, the form will only redirect to the action-page (register.php) but it will not send any POST-data whatsoever. Or at least, when checking with PHP, both $_POST and $_FILES are completely empty.
Where is this file-size restriction based and how do I change it?
Thanks in advance for your help!

A: On my server, post_max_size is smaller (quite a lot) then upload_max_filesize. The first is 3M while the latter is 64M. This is why I thought my limit would be at 64M but apparently is much lower. The fix is to change the following rule in php.ini:
post_max_size = 3M


text:
Q: Access is denied error when initializing PostgreSQL DB on Windows I'm on Windows 10. I downloaded the most recent version of Psql.
I was like:
C:\Program Files\PostgreSQL\9.6\bin>initdb.exe "C:\psql_db"

The files belonging to this database system will be owned by user "Sean".
This user must also own the server process.

The database cluster will be initialized with locale "English_United States.1252".
The default database encoding has accordingly been set to "WIN1252".
The default text search configuration will be set to "english".

Data page checksums are disabled.

creating directory C:/psql_db ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting dynamic shared memory implementation ... windows
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

    "pg_ctl" -D "C:\psql_db" -l logfile start

C:\Program Files\PostgreSQL\9.6\bin>"pg_ctl" -D "C:\psql_db" -l logfile start

And it was like:

server starting
Access is denied.

A: I think you are trying to create the logfile inside C:\Program Files\PostgreSQL\9.6\bin, for which you don't have write permission
Specify something like "pg_ctl" -D "C:\psql_db" -l "c:\users\joe\logfile" start

A: This is because of windows file permissions. You can put the data folder on desktop "c:\Users\\Desktop\" instead of "C:\psql_db". Or maybe give your user more permissions.


text:
Q: how to extract word from ps -aux when i execute command  ps -ef | grep yypasswd
I receive this output.
testacc 25124194 2512312620   0 08:00:53  pts/0  0:00 grep yypasswd

how can extract with command from this output word "yypasswd"

A: Since it's not clear what you're trying to do:
If you expect the following output:
yypasswd

then do
ps -ef | grep yypasswd | awk '{print $8}'

if you want the following output:
testacc 25124194 2512312620   0 08:00:53  pts/0  0:00

then do
ps -ef | grep yypasswd |  awk '{print $1, $2, $3, $4, $5, $6 ,$7}'

hope that helps.

A: ps -ef | grep -o yypasswd

From man grep :

-o, --only-matching
                Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

Just note that the ps line you post is the actual process of grep that you ran. To exclude this you could do :
ps -ef | grep -v grep | grep -o yypasswd

Another way to search for a process name is with pgrep :
pgrep -f yypasswd

pgrep wil give you the PID of the matched process

A: Solution
ps -ef | grep yypasswd | awk '/yypasswd/{print $NF;}'

A: use:
ps -ef | grep yypasswd | awk '{print $8}'

or using pgrep
pgrep -l yypasswd | awk '{print $2}'


text:
Q: Maximum duration (or file size) of html5 video I'm trying to use a custom html5 player with a 4-hour long video (2.3 GB!), but I'm getting some problems: playback stops, video seeking doesn't seem to work well and so on.
Using the native player of the browser, I have the same issues.
So I was wondering: are there any recommendations about the maximum duration (or file size) of a video in html5? What about mobile devices?

A: I think that the video had some problems. I did some tests with other videos though:

*

*800MB, 2h and 24m video: everything works ok, tested with a desktop pc and an iPad 3;

*9.7GB, 4h and 3m video: everything works well until I get to 1h 50min (but the video was intentionally big).

But I'd still be glad to find other resources or articles talking about the issue.


text:
Q: How to sum different tibbles in a list? Let's say that I have the following list
My_list<-list(a=structure(list(MTU..UTC. = c("01.01.2016 00:00 - 01.01.2016 01:00",
                                             "01.01.2016 01:00 - 01.01.2016 02:00", "01.01.2016 02:00 - 01.01.2016 03:00",
                                             "01.01.2016 03:00 - 01.01.2016 04:00", "01.01.2016 04:00 - 01.01.2016 05:00",
                                             "01.01.2016 05:00 - 01.01.2016 06:00", "01.01.2016 06:00 - 01.01.2016 07:00",
                                             "01.01.2016 07:00 - 01.01.2016 08:00", "01.01.2016 08:00 - 01.01.2016 09:00",
                                             "01.01.2016 09:00 - 01.01.2016 10:00"), Day.ahead.Price..EUR.MWh. = c(22.39,
                                                                                20.59, 16.81, 17.41, 17.02, 15.86, 18.16, 17.73, 19.77, 23.75
                                             )), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
                                             )),
              b=structure(list(MTU..UTC. = c("01.01.2016 00:00 - 01.01.2016 01:00",
                                             "01.01.2016 01:00 - 01.01.2016 02:00", "01.01.2016 02:00 - 01.01.2016 03:00",
                                             "01.01.2016 03:00 - 01.01.2016 04:00", "01.01.2016 04:00 - 01.01.2016 05:00",
                                             "01.01.2016 05:00 - 01.01.2016 06:00", "01.01.2016 06:00 - 01.01.2016 07:00",
                                             "01.01.2016 07:00 - 01.01.2016 08:00", "01.01.2016 08:00 - 01.01.2016 09:00",
                                             "01.01.2016 09:00 - 01.01.2016 10:00"), Day.ahead.Price..EUR.MWh. = c(22.39,
                                                                                20.59, 16.81, 17.41, 17.02, 15.86, 18.16, 17.73, 19.77, 23.75
                                             )), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
                                             )),
              c=structure(list(MTU..UTC. = c("01.01.2016 00:00 - 01.01.2016 01:00",
                                             "01.01.2016 01:00 - 01.01.2016 02:00", "01.01.2016 02:00 - 01.01.2016 03:00",
                                             "01.01.2016 03:00 - 01.01.2016 04:00", "01.01.2016 04:00 - 01.01.2016 05:00",
                                             "01.01.2016 05:00 - 01.01.2016 06:00", "01.01.2016 06:00 - 01.01.2016 07:00",
                                             "01.01.2016 07:00 - 01.01.2016 08:00", "01.01.2016 08:00 - 01.01.2016 09:00",
                                             "01.01.2016 09:00 - 01.01.2016 10:00"), Day.ahead.Price..EUR.MWh. = c(22.39,
                                                                                20.59, 16.81, 17.41, 17.02, 15.86, 18.16, 17.73, 19.77, 23.75
                                             )), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
                                             )),
              d=structure(list(MTU..UTC. = c("01.01.2015 00:00 - 01.01.2015 01:00",
                                             "01.01.2015 01:00 - 01.01.2015 02:00", "01.01.2015 02:00 - 01.01.2015 03:00",
                                             "01.01.2015 03:00 - 01.01.2015 04:00", "01.01.2015 04:00 - 01.01.2015 05:00",
                                             "01.01.2015 05:00 - 01.01.2015 06:00", "01.01.2015 06:00 - 01.01.2015 07:00",
                                             "01.01.2015 07:00 - 01.01.2015 08:00", "01.01.2015 08:00 - 01.01.2015 09:00",
                                             "01.01.2015 09:00 - 01.01.2015 10:00"), Day.ahead.Price..EUR.MWh. = c(5,
                                                                                NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_)), row.names = c(NA, -10L), class = c("tbl_df",
                                                                                "tbl", "data.frame")))

I want to sum the tibble a with d (contains a lot of NAs) so that I can get the following result
$a
# A tibble: 5 x 2
  MTU..UTC.                           Day.ahead.Price..EUR.MWh.
  <chr>                                                   <dbl>
1 01.01.2016 00:00 - 01.01.2016 01:00                      27.4 #New value
2 01.01.2016 01:00 - 01.01.2016 02:00                      20.6
3 01.01.2016 02:00 - 01.01.2016 03:00                      16.8
4 01.01.2016 03:00 - 01.01.2016 04:00                      17.4
5 01.01.2016 04:00 - 01.01.2016 05:00                      17.0

$b
# A tibble: 5 x 2
  MTU..UTC.                           Day.ahead.Price..EUR.MWh.
  <chr>                                                   <dbl>
1 01.01.2016 00:00 - 01.01.2016 01:00                      22.4
2 01.01.2016 01:00 - 01.01.2016 02:00                      20.6
3 01.01.2016 02:00 - 01.01.2016 03:00                      16.8
4 01.01.2016 03:00 - 01.01.2016 04:00                      17.4
5 01.01.2016 04:00 - 01.01.2016 05:00                      17.0

$c
# A tibble: 5 x 2
  MTU..UTC.                           Day.ahead.Price..EUR.MWh.
  <chr>                                                   <dbl>
1 01.01.2016 00:00 - 01.01.2016 01:00                      22.4
2 01.01.2016 01:00 - 01.01.2016 02:00                      20.6
3 01.01.2016 02:00 - 01.01.2016 03:00                      16.8
4 01.01.2016 03:00 - 01.01.2016 04:00                      17.4
5 01.01.2016 04:00 - 01.01.2016 05:00                      17.0

I tried to get the result using reduce , but the function sum all the elements in the list and i want to sum only this 2 tibbles and keep the others.

A: A bit tedious, but here you go:
I would recommend starting off with converting the list to a tibble using the enframe command - then you can use unnest to get a nice data structure to work with.
Because the dates don't match (d is 2015, all others 2016), we need to either 1) add one year to the date column (potentially using the lubridate package) or 2) we simply add the columns to the new data. This is not ideal as it only works with data.frames that have the same row number, but is what is illustrated below.
We start by filtering out the values of d in a separate data.frame.
Then we add it back to the original one, which we have modified with pivot_wider so that each of a, b, and c are now separate columns.
Then we use a mutate command to sum a and d (Note: here we assume that d is 0 if it's missing to get to the values you use above).
library(tidyverse)
My_list %>%
  enframe %>% # convert list to tibble
  unnest(value) %>% # convert list column to rows
  janitor::clean_names() %>% # clean the names (optional - janitor package)
  filter(name == "d") %>% # get only the values where the group is d
  rename(d = day_ahead_price_eur_m_wh) %>%
  select(d)-> d

My_list %>%
  enframe %>% # convert list to tibble
  unnest(value) %>% # convert list column to rows
  janitor::clean_names() %>% # clean the names (optional - janitor package)
  filter(name != "d") %>% # get all groups apart from d
  pivot_wider(id_cols = mtu_utc, names_from = name, values_from = day_ahead_price_eur_m_wh) %>% # pivot the data so that each group is a column
  bind_cols(.,d) %>% # add the d column to the data
  mutate(d = ifelse(is.na(d),0,d), # convert all missing values in d to a 0
         a = a + d) %>% # sum a and d
  select(-d) %>% # remove d (optional)
  pivot_longer(-mtu_utc) %>% # get back to a longer dataframe (optional)
  arrange(name) -> result # arrange sorts the data not by date but by group

Now result looks like this:
> result
# A tibble: 30 x 3
   mtu_utc                             name  value
   <chr>                               <chr> <dbl>
 1 01.01.2016 00:00 - 01.01.2016 01:00 a      27.4
 2 01.01.2016 01:00 - 01.01.2016 02:00 a      20.6
 3 01.01.2016 02:00 - 01.01.2016 03:00 a      16.8
 4 01.01.2016 03:00 - 01.01.2016 04:00 a      17.4
 5 01.01.2016 04:00 - 01.01.2016 05:00 a      17.0
 6 01.01.2016 05:00 - 01.01.2016 06:00 a      15.9
 7 01.01.2016 06:00 - 01.01.2016 07:00 a      18.2
 8 01.01.2016 07:00 - 01.01.2016 08:00 a      17.7
 9 01.01.2016 08:00 - 01.01.2016 09:00 a      19.8
10 01.01.2016 09:00 - 01.01.2016 10:00 a      23.8
# ... with 20 more rows

If you want to have it back as a list, then you need to do the following:
result %>%
  group_split(name)

A: Base R Solution:
# Clean vector names; store list elements back in a new list:
# cleaned_name_list => list of tibbles:
cleaned_name_list <- lapply(My_list, function(x){
    setNames(
      x,
      tolower(gsub("\\W+", "_", trimws(names(x), whitespace = "\\s+|[[:punct:]]")))
    )
  }
)

# String scalar denoting the name of the tibble to add to the other tibbles:
# to_add => character vector
to_add <- "d"

# Integer vector denoting which list elements are to have to_add element added
# on: to_keep_idx => integer vector
to_keep_idx <- which(names(cleaned_name_list) != to_add)

# Add the element to all other elements in the list:
# cleaned_name_list => list of tibbles:
cleaned_name_list[to_keep_idx] <- lapply(
  cleaned_name_list[to_keep_idx],
  function(x){
    y <- cleaned_name_list[[to_add]]
    data.frame(
      mtu_utc = x$mtuutc,
      dayahead_price_eur_mwh =
      rowSums(
        cbind(
          adjustment = y$dayahead_price_eur_mwh[match(x$mtuutc, y$mtuutc)],
          act_price = x$dayahead_price_eur_mwh
        ),
        na.rm = TRUE
      )
    )
  }
)


text:
Q: How can i fix the error for imports of own package? I learn ML from the book Introduction to Machine Learning with Python.
When I try to import and run mglearn package I have the error:
In:    import mglearn

--------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-35-26a0454c3f6e> in <module>
----> 1 import mglearn

~\Desktop\Introduction to Machine Learning with Python\ml_project\mglearn\__init__.py in <module>
----> 1 from .import plots
      2 from .import tools
      3 from .plots import cm3, cm2
      4 from .tools import discrete_scatter
      5 from .plot_helpers import ReBl

~\Desktop\Introduction to Machine Learning with Python\ml_project\mglearn\plots.py in <module>
      1 from .plot_linear_svc_regularization import plot_linear_svc_regularization
----> 2 from .plot_interactive_tree import plot_tree_progressive, plot_tree_partition
      3 from .plot_animal_tree import plot_animal_tree
      4 from .plot_rbf_svm_parameters import plot_svm
      5 from .plot_knn_regression import plot_knn_regression

~\Desktop\Introduction to Machine Learning with Python\ml_project\mglearn\plot_interactive_tree.py in <module>
      6 from sklearn.externals.six import StringIO  # doctest: +SKIP
      7 from sklearn.tree import export_graphviz
----> 8 from scipy.misc import imread
      9 from scipy import ndimage
     10 from sklearn.datasets import make_moons

ImportError: cannot import name 'imread' from 'scipy.misc'   (c:\users\boni\appdata\local\programs\python\python37\lib\site-packages\scipy\misc\__init__.py)

What I need to do for solve the problem?
Thanks!