text:
Q: Vk и переключение музыки кнопкой на клавиатуре На клавиатурах бывает кнопка переключения музыки. Так вот, она работает в VK, и даже если открыть две вкладки с Вконтакте, переключается музыка с обоих. Но если перейти на другой сайт, это уже работать не будет.
Как можно передать это нажатие кнопки с любого другого сайта на вкладку браузера, где открыт сайт VK?
Возможно, это можно сделать с помощью расширения Chrome?

A: Для перехвата команд понадобится chrome.commands, а для работы с вкладками chrome.tabs.

Подготовим manifest.json:
"background": {
  "scripts"   : ["command.js"],
  "persistent": false
},

"content_scripts":[
   {
      "matches":["*://*.vk.com/*"],
      "js"     :["changeTrack.js"]
   }
],

"permissions":["tabs"],

"commands":{
   "nextTrack":{
      "suggested_key":{
         "default":"MediaNextTrack"
      },
      "description":"nextTrack"
   },
   "prevTrack":{
      "suggested_key":{
         "default":"MediaPrevTrack"
      },
      "description":"prevTrack"
   }
}

Задача changeTrack.js принимать команды, которые будет перехватывать command.js.
Командам nextTrack и prevTrack назначаются клавиши MediaNextTrack и MediaPrevTrack.

command.js
Для перехвата команд используется событие chrome.commands.onCommand.
function sendMessage(tabInfo, command) {

    // Получаем вкладку по заданным характеристикам
    chrome.tabs.query(tabInfo, function (tabs) {

        // Если вкладка найдена
        if (tabs.length != 0) {

            // Отправляем ей сообщение
            chrome.tabs.sendMessage(tabs[0].id, command);
        }
    });
}

function changeTrack(command) {

    // Если это команды для смены трека
    if (command == "nextTrack" || command == "prevTrack") {

        // Отправляем сообщение вкладке, которая удовлетворяет характеристикам
        sendMessage({url: "*://*.vk.com/*", audible: true}, {command: command});
    }
}

// Перехватываем команды
chrome.commands.onCommand.addListener(changeTrack);

Сообщения будут отсылаться только в одну вкладку, потому что в tabInfo определен шаблон url и свойство audible, то есть отправка идет во вкладку, в которой открыта страница VK с проигрывающимся аудио.
Активный аудио источник на странице может быть только один, так как при включении нового, предыдущий ставится на паузу.

changeTrack.js
function changeTrack(command) {

    // Ищем элемент на странице, если его нет - плеер не активен.
    // Источником аудио в таком случае является приложение или видео
    if (!document.getElementsByClassName("fl_l playing")[0]) {

        console.log("Music not playing");

        return;
    }

    // Если плеер активен

    // Выбираем элемент в зависимости от команды и выполняем функцию click
    switch (command) {

        case "nextTrack" : document.getElementsByClassName("next ctrl")[0].click();
            break;
        case "prevTrack" : document.getElementsByClassName("prev ctrl")[0].click();
            break;
    }
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

    // Если получена команда для смены трека
    if (request.command) {

        changeTrack(request.command);
    }
});

Под элементами подразумеваются кнопки плеера, т.е DOM элементы.
Воспроизведение/пауза - div с изменяющимся классом. Когда идет воспроизведение установлен класс fl_l playing.

chrome.commands | chrome.tabs | Message Passing


text:
Q: Deadlock when using netty with Apache Camel i have a serious problem. I have a situation where i need to send multiple messages to netty, which are all generated by camel in the same place and then get a response to every single message.
The code is something like that:
from("direct:status")
.split().method("splitMessage", "split").to("direct:device")

from("direct:device")
.to("netty:tcp://4533sync=true&decoders=#myDecoders&encoders=#myEncoders")
.to("direct:send")

The splitMessage class generates at least 10 messages, if not more
After the first message is generated, then netty will receive it, it will send reply and forward it.
And now the second message is generated, it is sent to netty and this is where the problem starts. I will always get an error like that:
2011-10-14 10:27:14,326 [ent worker #1-3] ERROR DefaultErrorHandler            - Failed delivery for exchangeId: ID-Stenver-LapTop-60537-1318576334993-0-24. Exhausted after deliver y attempt: 1 caught: java.lang.IllegalStateException: await*() in I/O thread causes a dead lock or sudden performance drop. Use addListener() instead or call await*() from a differ ent thread.
java.lang.IllegalStateException: await*() in I/O thread causes a dead lock or sudden performance drop. Use addListener() instead or call await*() from a different thread.

I have tried to circumvent the problem by delaying the messages, but it doesnt help. I can get past the error by disabling the deadlock, but thats not really a solution.
Can anyone help?

A: Do you call ChannelFuture.await(..) within your encoder/decoder ? If not then it may be the camel-netty component which does it. In any case you should never call ChannelFuture.wait(..) from within an I/O-Thread.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to distribute padding equally among I've got three images side by side.. equal width..
How to percentage the padding-left property to fits multiple devices?
by percentage of padding-lefts, I don't want the images to be right beside themselves.. want to distribute them among the available screen width evenly
img { padding-left: some% }

considering the equal width of images.. if the padding-left is to much it pushes the 3rd image to the next row with some devices

A: This pure CSS2 solution does the job:
Markup:

Style sheet (provided images e.g. 100px wide):
#images {
  overflow: hidden;
}
#images div {
  position: relative;
  margin: 0 -50px;
  font-size: 0;
}
#images img {
  position: relative;
  left: 25%;
  margin-left: -50px;
}
#images img + img {
  position: absolute;
  left: 50%;
}
#images img + img + img {
  left: 75%;
}

Explanation:

A: You can use media queries in your CSS to target specific screen widths and then use the padding-left % to compensate for different screens for e.g
@media only screen and (max-device-width: 480px) { }

This will only target screens with a maximum width of 480px

A: Without requiring extra markup, Flexbox will do what you need and it is automatically flexible.  The down side is that it isn't widely supported yet.
http://jsfiddle.net/hv3Gk/ (prefixes not included, try Opera)
div.container {
  display: flex;
  width: 100%;
  justify-content: space-between;
  flex-flow: row wrap; /* or nowrap if you know its guaranteed to fit no matter what */
}

div.container img {
  flex: 0 0 100px;
  width: 100px;
  min-height: 100px;
  background: red;
}

Otherwise, you could use the display: table properties, but it requires extra markup.  It will work in IE8+ and just about any other browser version released in the last 5 years.
http://jsfiddle.net/hv3Gk/1/
div.container {
  display: table;
  width: 100%;
}

div.container div {
  display: table-cell;
}

div.container div:first-child + div {
  text-align: center;
}

div.container div:last-child {
  text-align: right;
}

div.container img {
  width: 100px;
  min-height: 100px;
  background: red;
}


text:
Q: How to pass ${__threadNum} value in selenium javascript? I used Webdriver sampler and write selenium -Javascript. Now in my script for achieving some result we need total number of users so I want to know how add ${__threadNum} value in my script?
or is there any way when multiple users run and some operations execute for only  one user?

A: *

*Either put the ${__threadNum} function to the "Parameters" section and refer it in the script as WDS.args[0] where required
var threadNum = WDS.args[0]

*Or use WDS.ctx shorthand for JMeterContext class, there you will have access to getThreadNum() function. It will return zero-based number of thread so to get the same value you will need to increment it by 1
var threadNum = (WDS.ctx.getThreadNum() + 1)

Demo:

More information: The WebDriver Sampler: Your Top 10 Questions Answered article for more information if needed


text:
Q: R - Keep the same color for each group in different boxplots Long time reader first time poster, sorry in advance for any mistakes.
I have a dataset with several factors and I wolud like to asign a color for each factor in such way that when I plot a subgroup of factors the colors keep constant.
I can give a simple example.
# Generating a random dataset
df <- data.frame(values = runif(20, min=0, max=10), groups = rep(c("A","B","C","D"), each = 5))
df$groups <- as.factor(df$groups)

df

values groups
1  9.3959013      A
2  6.0607064      A
3  3.3956529      A
4  7.9427183      A
5  9.4938858      A
6  4.4047519      B
7  0.7775106      B
8  2.0356925      B
9  6.9077875      B
10 3.8141609      B
11 2.6100288      C
12 8.5189150      C
13 3.5696664      C
14 7.8106244      C
15 7.2489862      C
16 6.4197579      D
17 6.4479676      D
18 8.9319776      D
19 2.0124674      D
20 5.2652708      D

When I plot each group I want to asign "red" to A, "yellow" to B and so on:
ggplot(df, aes(x=groups, y=values, fill=groups))+
geom_boxplot()+
scale_fill_manual(values=c("red", "yellow", "green", "blue"))

plot 1
Now, if I only want to plot A, C and D, I'd like for A to keep being red, C green and D blue
ggplot(df[!df$groups=="B",], aes(x=groups, y=values, fill=groups))+
geom_boxplot()+
scale_fill_manual(values=c("red", "green", "blue"))

plot 2
Or if I only plot C and D, I'd like them to keep being green and blue.
I don't usually asign colors manually, y use a predesigned color palette such as viridis, but if I use scale_fill_viridis the first group shown in the boxplot will always be purple, and the last, yellow.
I've thought of creating a palette asigning a color for each factor:
palette <- data.frame(factors= levels(df$groups),  colors= viridis_pal()
(length(levels(df$groups))))

palette

factors    colors
1       A #440154FF
2       B #31688EFF
3       C #35B779FF
4       D #FDE725FF

But I don't know how to integrate this into ggplot.
Many thanks!

A: You could convert the df with the colors to a named vector via tibble::deframe which can then be passed to scale_fill_manual like so:
library(ggplot2)

set.seed(42)

df <- data.frame(values = runif(20, min=0, max=10), groups = rep(c("A","B","C","D"), each = 5))
df$groups <- as.factor(df$groups)

palette <- data.frame(factors = levels(df$groups),  colors= scales::viridis_pal()(length(levels(df$groups))))
palette <- tibble::deframe(palette)

ggplot(df, aes(x=groups, y=values, fill=groups))+
  geom_boxplot()+
  scale_fill_manual(values = palette)


text:
Q: Android Alert Dialog Force Close Is there any way to build an Alert Dialog with a Button "Force Close" that close the app?
Thanks

A: That depends on you activity life cycle.
If you always finish your activities after starting a new one, you can simply create a dialog with one button and on click of the button, you simply call finish() and thats it.
A general "close the whole application" is not how the life cycle should be used.


text:
Q: Best multi relationship table object type design I have a table called Feed. That table will keep track social objects of different types (Photos, Events, Statuses, etc...) created by users. Now I have 2 design choices.
CHOICE 1: objectTypeId, objectId:
CREATE TABLE [dbo].[Feed](
[feedId] [int] IDENTITY(1,1) NOT NULL,
[objectTypeId] [int] NULL,
[objectId] [datetime] NOT NULL

)
CREATE TABLE [dbo].[ObjectType](
[typeId] [int] IDENTITY(1,1) NOT NULL,
[name] [NVARCHAR] NULL

)
Object type would then hold a list of all the possible types.
But I hate this method. Reason is, I cannot enforce referential integrity on the database.
If an object is deleted in one of the tables, the objectId value in Feed is pointing to a non-existing object.
Plus, the Join statement here is a mess. You have to hard code tables with hard values like LEFT JOIN Events ON feed.objectTypeId=2 AND feed.objectId=Events.eventId etc...
CHOICE 2: ADD eventId NULL, photoId NULL, statusId NULL or any other objectTypeId to Feed Table
PRO: Referential integrity can be enforced. Null columns don't cause much problems since they store nothing. No need to create additional Object Type table.
CREATE TABLE [dbo].[Feed](
[feedId] [int] IDENTITY(1,1) NOT NULL,
[eventId] [int] NULL,
[photoId] [int] NULL,
[statusId] [int] NULL,
)

but this table does not really feel normalized.
So, what is the best way to do what I am trying to do, and accomplish my goals. Referential integrity without having to change the schema every time I add a new object type.
UPDATE:
Forgot to point out that there exist tables of those objects... I have tables
CREATE TABLE [Events](

eventId INT,
other cols only dealing with events.
)
CREATE TABLE [Photos](

photoId INT,
other cols that only deal with photos
)
CREATE TABLE [Status](

statusId INT,
other cols that only deal with statuses
)

A: Choice 2 is terrible and will lead to nightmares. You will have to add a new column for every new type of content.
I don't know why you think Choice 1 needs complex joins. To retrieve all Events, for example:
SELECT * FROM Feed where objectTypeID =
    (SELECT objectTypeID from ObjectType WHERE name = 'Event')

As for referential integrity:

if an object is deleted in one of the tables, the objectId value in Feed is pointing to a non-existing object.

I don't understand. If the object in Feed is deleted, there are no dangling references. If an ObjectType is deleted, what are you planning to do with the objects of that type?
I'm assuming you realize that the ObjectType table is small, with only one row for each type of object...right?
Edited to add:
The additional tables you've mentioned each need a FeedID column. You should not put the object IDs in the Feed table. (This assumes that each object belongs to only one feed.)

A: If the number of feed types is smaller, will it not be better to have separate table for each of the feed types?
The following could be divided into each of its own table.

*

*Photos

*Events

*Statuses

A: Faced with similar problems, I've chosen to create a separate table for each type of object.  Each table will have a unique identification, e.g. PhotoId, for each row.  It will also have an appropriate foreign reference, e.g. to FeedId.  (If objects can be shared then linking tables can be added to allow objects to be in more than one place.)  That allows maximum flexibility to keep the right data in the right place, e.g. Height and Width may apply to photographs.
Triggers are used to validate and coordinate updates, as needed.
Views can be used to pull together data.  They centralize the connections between tables and can enforce additional rules.


text:
Q: Hashbangs and UTM parameters I am trying to run some campaigns to garner registrations and would like to use UTM parameters. Problem is my website urls contain hashbangs in it. Can i still generate UTM parameters tag for my urls with hashbangs in it?

A: Yes, you can still generate UTM tags, but make sure that any URL builder puts the hash tags towards the end, i.e. after the UTM parameters are added. Otherwise there's a risk that the hash bang won't work as you intended. Not all URL builders do it correctly, but Google URL builder does create correct URLs.
e.g. After adding UTM parameters to
www.example.com/#top
it should be
www.example.com/?utm_source=twitter&utm_medium=social&utm_campaign=launch#top
You could also try Terminus which implements it correctly. (Disclaimer: I'm the founder and Terminus is a paid service.)

A: The safest solution might be to encode the character, using functions like encodeURIComponent() in Javascript, or similar in other languages.


text:
Q: Syntax error when creating a function I am rather new to python and working through it. I am trying to create a function that will create a time message. The word "year" in my code comes back highlighted and showing it is invalid syntax. The code is incomplete at the moment and a few things I need to fix, I am just kind of lost at the moment.
the problem I am trying to solve is:
create function timeMessage
Arguments: None
Body: Import asctime function from time module
Create newtimeline using day of week, space, month, space, day, space, year, space time from asctime function
Return newtimeline
my code:
def timeMessage():

    from time import asctime
    from time import localtime
    asctime
    localtime
    myTime = timestring
    myTime = myTime.split(" ")
    newTimeline = week + " " + month + " " + day + " " year + " " + localtime
    return newTimeline

A: You need to add + showing that you are including the year variable after the " ".
Like this:
def timeMessage():

    from time import asctime
    from time import localtime
    asctime
    localtime
    myTime = timestring
    myTime = myTime.split(" ")
    newTimeline = week + " " + month + " " + day + " " + year + " " + localtime
    return newTimeline


text:
Q: mysql join include the attributes in joining conditon Let i have three tables comments, attachments, descendant_comments

*

*comments has many comments i.e self join

*comments has many attachments

*descendent_comments contains the hierarchy of comments (parent child, grand child relation)

Code:
SELECT comments.*, count(attachments.id)
FROM comments com
LEFT JOIN descendant_comments dc
    ON dc.comments_id = com.id
LEFT OUTER JOIN attachments atch
    ON (atch.comment_id = dc.child_comment_id OR atch.comment_id = com.id)
WHERE com.id = 77

i dont want t use the OR because it is not an optimal way to it.
there is any way to replace this line of "OR atch.comment_id = com.id"


text:
Q: how to get databases names in sqlite3? I'm trying to valid a SQL injection challenge on root-me.org. I want to retrieve the databases names with the command
1' SELECT * FROM my_db.sqlite_master WHERE type='table';

But i get the following error: SQLite3::query(): Unable to prepare statement: 1, near "SELECT"
Any idea ?

A: SELECT name
FROM master.dbo.sysdatabases

Possible duplicate of
sqlite3 - how to list out database name using .databases command?


text:
Q: Adding SubView to window close the app in ipad I have ipad application in which i want to add splitViewController once LoginViewController is loaded and user press sign in button then the following notification works,but what happens by adding following code it close the app and again open then it shows.
 -(void)actionNotificationData:(NSNotification *)notification {

 [self.loginViewController removeFromSuperview];

UIWindow* window = [UIApplication sharedApplication].keyWindow;
if (!window)
    window = [[UIApplication sharedApplication].windows objectAtIndex:0];
[[[window subviews] objectAtIndex:0] addSubview:splitViewController];

 }

A:  [self.loginViewController removeFromSuperview];

removeFromSuperview is expecting a UIView's subclass and you are passing a UIViewController.


text:
Q: Django Adding a delete action to a template I have a dashboard template where users can upload files and it displays them.  I want to add a delete action to this.  I have a few ideas but need some help ironing them out.
I am also not sure where I should be using FileStorage or a custom FileStorage backend.  Would using these make it easier/simpler for managing files (deleting them, listing them, etc.) than the solution I have now?
First my code...
The view:
@login_required(login_url='/dashboard-login/')
def dashboard(request):
    current_user = request.user
    current_client = request.user.client

    files = ClientUpload.objects.filter(client=current_client)

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            dz_files = request.FILES.getlist('file_upload')
            for f in dz_files:
                new_file = ClientUpload(client=current_client, file_upload=f)
                new_file.save()
                logger = logging.getLogger(__name__)
                logger.info("File uploaded from " + current_client.company)
        else:
            logger = logging.getLogger(__name__)
            logger.warning("Upload Failed")

        return HttpResponseRedirect(reverse('dashboard'))
    else:
        form = UploadFileForm()

    data = {'form': form, 'client': current_client, 'files': files}
    return render_to_response('dashboard.html', data, context_instance=RequestContext(request))

This is my dashboard view.  If the request is POST then I process the form.
And here is my model:
@python_2_unicode_compatible
class ClientUpload(models.Model):

    client = models.ForeignKey(Client)
    created_at = models.DateTimeField(auto_now_add=True)

    file_upload = models.FileField(upload_to=generate_filename)

    def __str__(self):
        return self.client.company

    class Meta:
        verbose_name_plural = _("Client Uploads")
        verbose_name = _("Client Upload")

The ideas I had are these:
First, could I use the else for when it is not a POST method and try processing the delete action there?  What I am trying to delete is the ClientUpload model which represents the file.  Does the delete model action use POST?  I would assume it does, so how could I tell whether they are submitting the form or deleting something?
Which brings me to my second idea?
Second, could I just make a second view?  Called something like dashboard_delete.  And process it that way just making sure I return the same template and context as my normal dashboard view?  I could use a CBV with DeleteView, but I'm not so sure, I still have the same questions as the first idea, as well as will it work with this approach?  Having two views that render the same template, but delete will only be called when you press the delete button which will be a link that routes to this view?  Are there any problems here?
Third, should I use a class based view for this?  By overriding dispatch and post?  Are there any other methods I can override for the delete?  I would rather not do this one.
Basically which would work the best of these 3 solutions?  Is there a better solution for this?  I essentially have them log in, but they are not staff and cannot access the admin interface.  I know they should be able to delete these files as they uploaded them, but do I need another permission for this?  Is there a way I can customize this delete action via overriding or anything?
Any help and examples would be a tremendous benefit for me, I've been stuck for a bit on this and could use any help.
I just really need help finding the best approach, which seems to be the second solution, I'm just not sure how to implement it exactly and whether I can customize the things I mentioned like the delete method (can I send the deleted files to a hidden recycle bin(just another folder) so that only the admin can see them?).  Will it work the way I intend?
Any information would help a lot as my testing always seems to have issues.  Will keep posting updates as I keep testing, but any input would help a lot, as I said I've been stuck a bit.
Thanks in advance.
EDIT:
Template for file list:
{% load i18n %}
{% load staticfiles %}
{% load sasite_filters %}

    {% blocktrans %}Filename{% endblocktrans %}
    {% blocktrans %}Size (Bytes){% endblocktrans %}
    {% blocktrans %}Upload Time{% endblocktrans %}
    {% blocktrans %}Actions{% endblocktrans %}

{% for file in files %}
    {% with uploaded_file=file.file_upload %}

    {{ uploaded_file.name|pathend}}
    {{ uploaded_file.size }}
    {{ file.created_at }}
    Delete, Downloads, etc.
    {% endwith %}
{% endfor %}

A: You could use GenericViews if you wanted: https://docs.djangoproject.com/en/1.8/ref/class-based-views/generic-editing/#django.views.generic.edit.DeleteView
It's very simple. For example:
views.py:
class ClientUploadDelete(DeleteView):
    model = ClientUpload
    success_url = reverse_lazy('dashboard')
    template_name = 'client_upload_delete.html'

urls.py:
url(r'^delete/(?P<pk>\d+)/$', ClientUploadDelete.as_view(), name="delete_client_upload"),

html:
<button type="button">
    Delete
</button>

That's it. The user will be prompted with a screen that verifies if they want to delete the object. If they say yes, it will redirect them to dashboard.html in the example above.
EDIT:
client_upload_delete.html

    {% if request.user == object.user %}

Are you sure you want to delete this object?

        # Put your object here (image, text item, etc.)
        <form action="" method="POST">
            {% csrf_token %}
            <input type="submit" value="Delete" />
            <input type="button" value="Cancel" onclick="window.location='{% url 'dashboard' %}'"/>
        </form>
    {% else %}

You're not allowed to be here.

        Dashboard
    {% endif %}

A: It could actually be pretty simple, write another view method to handle the delete event. Give each entry in the template a button, which should point to the url that links to your deletion view method. In the view you can do whatever you like to delete the model object, then redirect to your dashboard view.
Rough example:
from django.http import HttpResponseRedirect

def delete(request, upload_id):
    p = ClientUpload.objects.get(pk=upload_id)
    p.delete()
    return HttpResponseRedirect('your-dashboard-url')


text:
Q: What is kthreadd_task In the definition of kthread_create a task is waken up, does any one know what is this task doing ?
struct task_struct *kthread_create

{

    struct kthread_create_info create;

    create.threadfn = threadfn;
    create.data = data;
    init_completion(&create.done);

    spin_lock(&kthread_create_lock);
    list_add_tail(&create.list, &kthread_create_list);
    spin_unlock(&kthread_create_lock);

    **wake_up_process(kthreadd_task);**
    wait_for_completion(&create.done);

    if (!IS_ERR(create.result)) {
            struct sched_param param = { .sched_priority = 0 };
            va_list args;

            va_start(args, namefmt);
            vsnprintf(create.result->comm, sizeof(create.result->comm),
                      namefmt, args);
            va_end(args);
            /*
             * root may have changed our (kthreadd's) priority or CPU mask.
             * The kernel thread should not inherit these properties.
             */
            sched_setscheduler_nocheck(create.result, SCHED_NORMAL, &param);
            set_cpus_allowed_ptr(create.result, cpu_all_mask);
    }
    return create.result;
}

A: kthreadd is a kernel daemon,it is started during kernel boot.
init/main.c ---> kernel_thread(kthreadd,...)

(architecture dependent code for e.g arch/arm/kernel/process.c)

As you can see here, kernel_thread() returns a pid. From pid we determine the task_struct and assign it to kthreadd_task.
So whenever a call for creation of kernel thread i.e., kthread_create(), kthreadd_task is waken up, which inturn calls kthreadd() (defined in kernel/kthread.c).

A: kthreadd_task is pointer to task_struct of kernel thread runnind kthreadd() function defined at http://lxr.linux.no/#linux+v2.6.36/kernel/kthread.c#L231
kthreadd() is main function (and main loop) of daemon kthreadd which is a kernel thread daemon, the parent of all other kernel threads.
So in the code quoted, there is a creation of request to kthreadd daemon. To fulfill this request kthreadd will read it and start a kernel thread. Then it will change the flag. In the code you have a waiting on this flag. After flag changing your function will check the status of new kthread creation.


text:
Q: Equation for simultaneous cooling and conduction Imagine a long, uniform metal rod placed on the positive $x$-axis being heated with a power $P$ from its end at $x=0$. It is cylindrical in shape and the cross-section is a circle of radius $r$. Looking at a thin slice of the rod $dx$ (these vertical slices are assumed to have uniform temperature) at distance $x$ from the origin, heat will flow through it according to Fourier's conduction law: $q_x=-k\frac{d}{dx}T(x,t)$. At the same time, heat will escape the rod from its surface according to Newton's law of cooling: $P_N=-hA(T(x,t)-T_0)=-hA2\pi r\int(T(x,t)-T_0)dx$.
I'm trying to write a differential equation that will give me $T(x,t)$ when both of these mechanisms are accounted for so I could answer things like what the equilibrium temperature will be for a certain material at various $P$ and $x$, but that is proving to be beyond my ability. Is this function even analytically obtainable? The only thing I could find anywhere was the math for a fully insulated rod and I was unable to implement Newton's law into that.

A: It seems like you want to treat this as a time-dependent problem.  If you do a heat balance on the portion of the rod between x and $x+\Delta x$, you have that the rate of change on internal energy with respect to time is equal to the axial heat flow in minus the axial heat flow out minus the rate of heat loss through the surface:$$\rho\pi r^2\Delta x C\frac{\partial T}{\partial t}=\pi r^2q(x)-\pi r^2q(x+\Delta x)-2\pi r\Delta x h(T-T_0)$$where C is the heat capacity of the rod material.  If we divide this equation by the volume of the segment of rod and take the limit as $\Delta x$ approaches zero, we obtain,$$\rho C\frac{\partial T}{\partial t}=-\frac{\partial q}{\partial x}-\frac{2h}{r}(T-T_0)$$with$$q=-k\frac{\partial T}{\partial x}$$  So, if we combine these last two equations, we obtain:
$$\rho C\frac{\partial T}{\partial t}=k\frac{\partial^2 T}{\partial x^2}-\frac{2h}{r}(T-T_0)$$
I hope this is what you were looking for.


text:
Q: Are there different uses of the arrow mark '->' used by pointers in C++? How exactly is it used? Are there different uses of the -> symbol? (I think it's called overloading).
One of them that I know is that a pointer uses it to access a member of the object to which the pointer points to. For example:
class fruit{
      char colour[10];
};

fruit mango;
fruit *pointertofruit = &mango;  // Will it work without using the '&'?
pointertofruit->colour = '______';

Can I take it that the pointer is telling that "I point to an object whose data member is 'colour', so allow me to make that '______'"?

A: There are two uses for ->:

*

*it dereferences a raw pointer to access a member (as you describe).

*it is an operator that a class/struct can overload to return whatever it wants, as long as that something can also be dereferenced by ->.  This is most commonly done in smart-pointer classes, like std::unique_ptr/std::shared_ptr, CComPtr/CComQIPtr, etc to dereference an internally held pointer, eg:
class fruit_ptr {
    fruit *m_f;
public:
    fruit_ptr(fruit *f) : m_f(f) {}
    ~fruit_ptr() { delete m_f; }
    fruit* operator->(){ return m_f; }
};

fruit_ptr pointertofruit(new mango);
pointertofruit->colour = ...; // calls: pointertofruit.operator->()->colour = ...;


text:
Q: How to develop Google maps in Windows Phone I am fresher for Windows Phone. I am working on windows phone 7.1. I worked on Bing maps control.
But I want to know is there any possibility to get the google maps api key for windows phone.
If there any solution please let me know.

A: This may help you,
http://www.codeproject.com/Articles/153467/Google-Maps-for-Windows-Phone-7-using-Bing-Map-Con
Steps to create:
http://www.c-sharpcorner.com/UploadFile/cd3310/starting-with-google-map-in-windows-7-phone-application/


text:
Q: Is there a way to set the placeholder color of a UITextField with UIAppearance I have found that I can set the placeholder color by changing the textColor of a label contained with UITextField.
[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor lightGrayColor]];

But this also changes UITextField text color. Is there a way to specify them both separately from UIAppearance?
I tried to use the the setValue:forKey: but then I read that my app can be rejected for using KVC.

A: Building off @Synmax answer, I've put together this category you can use to add a placeholder text color to a UITextField:
@interface UITextField (Placeholder)

@property UIColor* placeholderTextColor;

@end

@implementation UITextField (Placeholder)

-(UIColor*)placeholderTextColor {
    return [self.attributedPlaceholder attribute:NSForegroundColorAttributeName atIndex:0 effectiveRange:nil];
}

-(void)setPlaceholderTextColor:(UIColor*)placeholderTextColor {
    if(self.attributedPlaceholder) {
        NSMutableAttributedString* as = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedPlaceholder];
        if(placeholderTextColor) {
            [as setAttributes:[NSDictionary dictionaryWithObject:placeholderTextColor forKey:NSForegroundColorAttributeName] range:NSMakeRange(0, self.attributedPlaceholder.length)];
        } else {
            [as removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, self.attributedPlaceholder.length)];
        }
        self.attributedPlaceholder = as;
    } else if(self.placeholder) {
        self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:[NSDictionary dictionaryWithObject:placeholderTextColor forKey:NSForegroundColorAttributeName]];
    }
}

@end

You can then set the placeholder text color using appearance like this...
[UITextField appearance].placeholderTextColor = UIColor.grayColor;


text:
Q: Representing points in 2D and 3D spaces with Prolog I need an example for Representing points in 2D and 3D spaces with Prolog

A: How about terms that look like
point(X,Y,Z)

where X,Y,Z are numbers (floats, integers, rationals, ...).
Then you can do thinks like:
:- use_module(library(clpfd)).

% move(PointIn,PointOut,Vector)

move(point(X,Y,Z),point(NX,NY,NZ),point(VX,VY,VZ)) :-
   NX #= X + VX,
   NY #= Y + VY,
   NZ #= Z + VZ.

Then:
?- move(point(1,2,3),New,point(5,5,5)).
New = point(6, 7, 8).


text:
Q: Adding a light to javascript w/ ping test I want to display this light if a certain condition is true in javascript using an if statement. How can I add an external CSS class to a javascript if statement?
Here is my css code:
.beacon{
  position:absolute;

  background-color:#32CD32;
  height:1.5em;
  width:1.5em;
  border-radius:50%;
  -webkit-transform:translateX(-50%) translateY(-50%);
}
.beacon:before{
  position:absolute;
  content:"";
  height:1.5em;
  width:1.5em;
  left:0;
  top:0;
  background-color:transparent;
  border-radius:50%;
  box-shadow:0px 0px 2px 2px #32CD32;
  -webkit-animation:active 2s infinite linear;
  animation:active 2s infinite linear;
}

@-webkit-keyframes active{
  0%{
    -webkit-transform:scale(.1);
    opacity:1;
  }
  70%{
    -webkit-transform:scale(2.5);
    opacity:0;
  }
  100%{
    opacity:0;
  }
}

@keyframes active{
  0%{
    transform:scale(.1);
    opacity:1;
  }
  70%{
    transform:scale(2.5);
    opacity:0;
  }
  100%{
    opacity:0;
  }
}

this is the javascript code:
<div class="too white">
<script language="javascript">
url = "http://www.511virginia.org/"
ping = new XMLHttpRequest();
ping.onreadystatechange = function(){
    if(ping.readyState == 4){
                if(ping.status == 200){
          document.write("Website is up");
        }
                else {
                  document.write("Website is down");
                                }
}
}
ping.open("GET", url, false);
ping.send();
</script>
</div>

A: It depends on any framework you're using. For example, if you're using jQuery then change a DOM element's CSS using .css(property, value). Angular has it's own methods. For raw DOM manipulation take a look at the w3c page on JavaScript HTML DOM - Changing CSS, which shows the following.
document.getElementById(id).style.property = new style


text:
Q: Solving the system $a+be^{-\lambda t_i}\cos(wt_i)=\epsilon_i$ (with $i=1,2$) for $\lambda$ and $w$ I have the following system of equations:
$$\begin{align}
a+be^{-\lambda t_1}\cos(wt_1)&=\epsilon_1 \\
a+be^{-\lambda t_2}\cos(wt_2)&=\epsilon_2
\end{align}$$
$a$, $b$, $t_1$, $t_2$, $\epsilon_1$ and $\epsilon_2$ are given. I need to solve for $\lambda$ and $\omega$ and I know that $\lambda$ and $\omega$ are both real and positive.
How can I solve for those?
I did the following:
$$a+be^{-\lambda t_1}\cos(wt_1)=\epsilon_1\rightarrow\lambda=-\frac{1}{t_1}\cdot\ln\left(\frac{\epsilon_1-a}{b}\cdot\frac{1}{\cos(wt_1)}\right)$$
So:
$$a+b\exp\left(-\left\{-\frac{1}{t_1}\cdot\ln\left(\frac{\epsilon_1-a}{b}\cdot\frac{1}{\cos(wt_1)}\right)\right\}t_2\right)\cos(wt_2)=\epsilon_2$$
And only $\omega$ I do not know but I do not know how to solve the last equation.


text:
Q: Extending and overriding interface properties I'm trying to extend interface and can't seem to grasp the idea on generics. As you can see I'm trying to add property auth inside the props.
My code works but do I really need to re-import every properties on the extended interface? It seems that I'm doing something wrong here.
Inertia-JS Typescript Definition
export interface PageProps {
    [key: string]: unknown;
}

export interface Page<SharedProps = PageProps> {
    component: string;
    props: PageProps & SharedProps & {
        errors: Errors & ErrorBag;
    };
    url: string;
    version: string | null;
    scrollRegions: Array<{
        top: number;
        left: number;
    }>;
    rememberedState: Record<string, unknown>;
    resolvedErrors: Errors;
}

My Code:
export type User = {
  id: number;
  name: string;
  email: string;
}

interface PropsInterface extends Page {
  props: PageProps & {
    errors: Errors & ErrorBag;
    auth: {
      user: User
    }
  }
}

JSX
import { Page, PageProps } from '@inertiajs/inertia';
import { ErrorBag, Errors } from '@inertiajs/inertia/types/types';
import { usePage } from '@inertiajs/inertia-react';

export default function Topbar(): JSX.Element {
  const { url, component, props } = usePage<PropsInterface>();
  const { user } = props.auth
}

A: Try this
export type User = {
  id: number;
  name: string;
  email: string;
}

interface PropsInterface extends Page<{ auth: { user: User } }> {}


text:
Q: What shutdown timers with/without GUI are there available? What shutdown timers with/without GUI are there available?

*

*any type of action possible? shutdown hibernate etc but also custom command?

*how to set time? time to go or at specific timestamp?

*integration with desktop environment - progress bar to specified time

*warning before action - possibility to prolong/adjust/cancel?

*keep default setting, eg 1 hour

A: There are a couple of shutdown timers available on Launchpad that look interesting.
Easyshutdown - simply shuts down your PC

ComplexShutdown - it has much more options such as hibernate/suspend etc.

A: The simplest one would be at, and it can be used to schedule any command.

A: Shutdown GTimer

A: as BigStack said, using crontab is a very easy/non install way to do it.
As a tutorial here suggests:
If you open terminal you can type
sudo gedit /etc/crontab

this will open your systems crontab file in gedit.
you can then add this line to it:
00  22   *    *   *   root   poweroff

where 00 is the minutes, 22 is the hours, and the *s mean every day (you can see more info on this in the link). root says which user is to execute the command, and poweroff is the command to run.
I've done this and it works perfectly in Ubuntu 13.04

A: Crontab: Its's easy to setup a cron job for poweroff

A: I know on a Mac you can use a crontab. Here are the steps. I did get it to work, but on my new system I have had some problems, you can try it. You need to do this in the terminal.
Type
sudo crontab -e

You'll need to enter your login password and then press Enter.
You'll now be in a text editor (vim). Carefully input the following keystrokes.
Press i once (this will allow you to enter text)
Let's say you want the machine to shutdown at 2am every day, we'd now enter:
* 2 * * * /sbin/shutdown -h now

If you wanted the machine to shutdown at 2:30am every day, you'd enter:
30 2 * * * /sbin/shutdown -h now

When you've typed this in, press esc
Then press shift+z shift+z (that's uppercase "z" twice, to write the changes and quit the editor).
You should now be dropped back to the command line where you started.
You're done!

A: SGTimer has a variety of options and is actively maintained on Launchpad.

Figure 1: Main interface on Ubuntu 15.10


text:
Q: Unable to use jquery within chrome local storage, how to use .remove() jquery method for css :has pseudoselector using only javascript? So I have used the line of jquery successfully elsewhere, but now I need to run it inside a chrome extension.
Also, alert works perfectly, so the problem is the line of jquery not working here.
When I look in the inspection, I see the error "$ is undefined". Perhaps there is another way to do this exact thing below with pure javascript?
(function() {
    chrome.storage.local.get('mystoreitem-aaa', function(results) {
        if (results['mystoreitem-aaa']) {
            // alert("hi");
            $('.someclasslala:has(div.anotherclasslala)').remove();
        };
        return;
    });
})();

update - was able to resolve the undefined jquery error on the page by including the jquery script before the script above in the manifest:
  "content_scripts": [ {
        "js": [ "js/jquery.js""js/myscript.js" ],

However, the code is not working on the page, which is weird, because the alert above it is working which means the code is injected properly... I think I'm going to change this to not just run the jquery but inject a new script into the head with the jquery instead.

SOLVED!! (solution to the issue moved to an answer format below as requested)

A: SOLVED!!
so the first thing was including jquery in the manifest above, which is not necessary if I include a script into the head. But the reason it wasn't working AFTER it was no longer giving the error is because I needed to change the script to run at document_end NOT document_start. Because the element that was to be removed needed to be loaded first.
This issue is solved!
note - it is worth noting, that, probably due to asynchronous loading issue, this javascript won't work if I just inject it into the head. it works however if I do the manifest as above and set it to load at document_end.


text:
Q: Intent to launch call history and contacts for a particular person? I have a contact's phone number and name. With this information, how can I launch the contact:

*

*call history details activity

*edit contacts activity

I'm able to launch just the starting activity of call history and contacts. Instead I want to directly navigate into a person's record. Any idea how to achieve this?

A: This is working fine for me. Please take a look.
   contactNumber = Uri.encode(contactNumber);

   int phoneCallLogID = new Random().nextInt();
   Cursor callLogLookupCursor = context.getContentResolver().query(Uri.withAppendedPath(android.provider.CallLog.Calls.CONTENT_FILTER_URI,contactNumber),null, null, null, null);
       while(callLogLookupCursor.moveToNext()){
           phoneCallLogID = callLogLookupCursor.getInt(callLogLookupCursor.getColumnIndexOrThrow(CallLog.Calls._ID));

           }
       callLogLookupCursor.close();
        Uri uri = Uri.withAppendedPath(
                android.provider.CallLog.Calls.CONTENT_URI, String.valueOf(phoneCallLogID));

   Intent intent = new Intent(Intent.ACTION_VIEW);
   intent.setData(uri);
   startActivityForResult(intent,0);


text:
Q: Getting data from column with range of values I want to get data on particular range of column in a table. but the data is of type varchar.
Suppose i have table student and a column is ID and the value in the ID is as AB12346854, and I need to find all the students in range of id AB12346854  to DE12548847 I tried using the query as
select * from students where id>='AB12346854' and id<='DE12548847'.

I am getting rows with id value as null .( id is not primary key)

A: You can use this:
select * from students where id BETWEEN 'AB12346854' AND 'DE12548847'
It works for strings too.

A: select * from test where ID >= 'AA0000001' and ID <= 'DD0000004'
tis is working perfectly fine... even if u ve null values for your ID column


text:
Q: Object # has no method 'catch' My user lib have following code for register
function register {
// do some validation on lib level

//user is instance of user collection
user.save()
    .then(function(error,records, numberOfRecords) {
        // got any kind of error
        if (error) {
            next('fail',msg,{error_code : 510, exception : ex} )
            return ;
       }
        next('success','good', records );
    })
    .catch(function(ex) {
        var msg =  ex.message;
        error = ex
        system.log.error(msg);
        next('fail',msg,{error_code : 510, exception : ex} );
    }).done();
}

In my mongooes modal, I have implemented middle-ware
    User.pre('save', function (next) {

          // just checking error is available in catch schope or not
          var err = new Error('I am doing some experiment on it');
          next(err);
    });

var Promise = require('bluebird');

var User = mongoose.model('User');
Promise.promisifyAll(User);
Promise.promisifyAll(User.prototype);

Getting following issue
TypeError: Object #<Promise> has no method 'catch'
    at User.register (/server/core/modules/user.js:69:10)
    at router.post.http.request (/server/routes/user.js:55:8)
    at Layer.handle [as handle_request] (/node_modules/express/lib/router/layer.js:82:5)
    at next (/node_modules/express/lib/router/route.js:110:13)
    at Route.dispatch (/node_modules/express/lib/router/route.js:91:3)
    at Layer.handle [as handle_request] (/node_modules/express/lib/router/layer.js:82:5)
    at /node_modules/express/lib/router/index.js:267:22
    at Function.proto.process_params (/node_modules/express/lib/router/index.js:321:12)
    at next (/node_modules/express/lib/router/index.js:261:10)
    at Function.proto.handle (/node_modules/express/lib/router/index.js:166:3)
    at router (/node_modules/express/lib/router/index.js:35:12)
    at Layer.handle [as handle_request] (/node_modules/express/lib/router/layer.js:82:5)
    at trim_prefix (/node_modules/express/lib/router/index.js:302:13)
    at /node_modules/express/lib/router/index.js:270:7
    at Function.proto.process_params (/node_modules/express/lib/router/index.js:321:12)
    at next (/node_modules/express/lib/router/index.js:261:10)
    at /server/router.js:45:3

My Question is ::
How to resolve this issue ??
How can I catch error from mongooes middleware to my lib function (catch)??

A: It seems you're not using Bluebird, but mongoose promises (mpromise), which don't have a .catch method.
You can fix that by

*

*using user.saveAsync().then(…), as you've promisified the User model

*using Promise.resolve(user.save()).then(…) to cast the mongoose promise into a Bluebird one


text:
Q: Security value of log contract and stochastic calculus I am studying the geometric Brownian motion of stock S with an expected return and volatility. And we can write the standard GBM as the form $dS(t) = \mu S(t)dt + \sigma S(t)dZ(t)$ where Z follows a standard normal distribution. And we can use it to calculate some derivatives based on stock S. And there is a special derivative called log contract $L(S,t)$ that pays off $\ln S(T)$, where S(T) is the value of the stock price at time T.
Based on previous GBM and Ito process, we can get
$$d\ln S(t) = (\mu - \frac{\sigma^2}{2})dt + \sigma dZ(t)$$
Could someone explain how to calculate the value of the security $L(S,t)$ in terms of stock price $S(t)$ at time t? And will this solution also satisfy the Black-Scholes PDE? I think the previous one satisfies.

A: The value $L(S(t),t)$ at time $t < T$ is the discounted expectation conditioned on information known at $t$ of the contract payoff at time $T$ under the risk-neutral probability measure $Q$, that is
$$L(S(t),t)) = e^{-r(T-t)}\mathbb{E}^Q[\ln S(T) \, |\, \mathcal{F}_t],$$
where $r$ is the risk-free rate.
In the risk-neutral world, the security follows the process
$$d\ln S(t) = (r - \frac{\sigma^2}{2})\,dt + \sigma \,dZ(t)$$
Integrating over $[t,T]$, we get, in terms of a standard normal random variate $\xi \sim \mathcal{N}(0,1)$,
$$\ln S(T) = \ln S(t) + (r - \frac{\sigma^2}{2})(T-t) + \sigma\sqrt{T-t}\,\xi,$$
and, taking the expected value,
$$\tag{*}L(S(t),t))  = e^{-r(T-t)} \left[\ln S(t) + (r - \frac{\sigma^2}{2})(T-t) \right]$$
This could also be obtained by solving the Black-Scholes PDE for $L(S,t)$,
$$\frac{\partial L}{\partial t} + r S \frac{\partial L}{\partial S} + \frac{1}{2} \sigma^2 S^2 \frac{\partial L^2}{\partial S^2} - r L = 0,$$
with terminal condition $L(S,T) = \ln S$. Assuming a solution of the form $L(S,t) = \alpha(t) + \beta(t) \ln S$ and substituting into the PDE, leads to the same solution as in (*).


text:
Q: Webpack handlebars loader - is there a way to inject context/parameters? I'm currently trying to setup webpack-dev-middleware (the middleware used in webpack-dev-server, but hosted in my own node application).
One of the requirements I have is to be able to parse my application "index.hbs" through handlebars & then inject everything that normally html-webpack-plugin injects. (a couple scripts with built bundle)
I already found an option to use the handlebars-loader and prepared the configuration for it (according to this)
{
    test: /\.hbs$/,
    loader: "handlebars-loader"
}

This almost works.. The 'almost' part is that normally I used to render my index.hbs like this (the snippet is from node+express app):
app.get(`${ACCESS_PATH}/index`, (req, res) => {
  res.render('index', {
    query: req.query
  });
});

That means that I was actually parsing the template based on query parameters. After lengthy explanation the question is:
Is there any way I can pass "context"/parameters using webpack handlebars-loader to achieve the same behavior now using webpack for serving my file?
Please note that that is development only setup.


text:
Q: How to clear a file via adb? Similarly to how I view file, using adb functionality:
adb shell cat /path/to/file

I would like to clear a file, without having to enter adb shell, like so:
adb shell clear /path/to/file

Second example is a pseudo-code ofc.

A: This should clear the file, removing every text in the file:
adb shell "> /path/to/file"


text:
Q: Android get id for an edit text field from a context xml file I have an activity called PeopleActivity, with a layout xml of activity_people.xml.
This activity is using the Android Studio Navigation Drawer Activity template.
I have a list view in the content_people.xml file named people_list.  When I attempt to associate this control in the back end, it is unable to find the id.  I am attempting it as:
peopleList = (ListView) findViewById(R.id.people_list);

Any insight would be greatly appreciated.
EDIT:  Did an update to the code section to reflect the correct control referenced.

A: you should declare your listview like this:
peopleSearch = (ListView) findViewById(R.id.people_list);

not as EditText

A: I found the answer.  You cannot use capital letters in the naming of your controls.  Once I fixed this, everything worked fine.


text:
Q: ts-node import not defined at runtime I have the following reference import { STORE } from "../data/store"; It's part of a react project and works as expected.
However I need to run some code separately over STORE and accessed it the same way as it is in the react project, but ran via ts-node.  When I try to access STORE by let data = STORE[videoId].labels;, with videoId set as "home" I get TypeError: Cannot read property 'home' of undefined.
Might anyone know what I'm missing --- must be something specific to ts-node...? Thanks!

A: In case someone arrives on this page because of imports issue, like I did, here's what my problem was:
I had three files : index.ts, File.json and File.ts
In index.ts:
import { thing } from "./File";

was working well in VS Code: I had auto-completion for thing and everything.
But when running ts-node index.ts, thing was undefined!
When I remembered that I had the json file, I just renamed File.ts to File.module.ts and changed the import to:
import { thing } from "./File.module";

and it was sorted.

A: It sounds like the property STORE is undefined..
If you change import { STORE } from "../data/store"; to import * as STORE from "../data/store" does it work?


text:
Q: How can I "grep" patterns across multiple lines? It seems I am misusing grep/egrep.
I was trying to search for strings in multiple line and could not find a match while I know that what I'm looking for should match. Originally I thought that my regexes were wrong but I eventually read that these tools operate per line (also my regexes were so trivial it could not be the issue).
So which tool would one use to search patterns across multiple lines?

A: Here's a simpler approach using Perl:
perl -e '$f=join("",<>); print $& if $f=~/foo\nbar.*\n/m' file

or (since JosephR took the sed route, I'll shamelessly steal his suggestion)
perl -n000e 'print $& while /^foo.*\nbar.*\n/mg' file

Explanation
$f=join("",<>); : this reads the entire file and saves its contents (newlines and all) into the variable $f. We then attempt to match foo\nbar.*\n, and print it if it matches (the special variable $& holds the last match found). The ///m is needed to make the regular expression match across newlines.
The -0 sets the input record separator. Setting this to 00 activates 'paragraph mode' where Perl will use consecutive newlines (\n\n) as the record separator. In cases where there are no consecutive newlines, the entire file is read (slurped) at once.
Warning:
Do not do this for large files, it will load the entire file into memory and that may be a problem.

A: Supppose we have the file test.txt containing :
blabla
blabla
foo
here
is the
text
to keep between the 2 patterns
bar
blabla
blabla

The following code can be used :
sed -n '/foo/,/bar/p' test.txt

For the following output :
foo
here
is the
text
to keep between the 2 patterns
bar

A: I solved this one for me using grep and -A option with another grep.
grep first_line_word -A 1 testfile | grep second_line_word

The -A 1 option prints 1 line after the found line. Of course it depends on your file and word combination. But for me it was the fastest and reliable solution.

A: Here's a sed one that will give you grep-like behavior across multiple lines:
sed -n '/foo/{:start /bar/!{N;b start};/your_regex/p}' your_file

How it works

*

*-n suppresses the default behavior of printing every line

*/foo/{} instructs it to match foo and do what comes inside the squigglies to the matching lines. Replace foo with the starting part of the pattern.

*:start is a branching label to help us keep looping until we find the end to our regex.

*/bar/!{} will execute what's in the squigglies to the lines that don't match bar. Replace bar with the ending part of the pattern.

*N appends the next line to the active buffer (sed calls this the pattern space)

*b start will unconditionally branch to the start label we created earlier so as to keep appending the next line as long as the pattern space doesn't contain bar.

*/your_regex/p prints the pattern space if it matches your_regex. You should replace your_regex by the whole expression you want to match across multiple lines.

A: The grep alternative sift supports multiline matching (disclaimer: I am the author).
Suppose testfile contains:

<book>
  <title>Lorem Ipsum</title>
  <description>Lorem ipsum dolor sit amet, consectetur
  adipiscing elit, sed do eiusmod tempor incididunt ut
  labore  et dolore magna aliqua</description>
</book>

sift -m '<description>.*?</description>' (show the lines containing the description)
Result:

testfile:  <description>Lorem ipsum dolor sit amet, consectetur
testfile:  adipiscing elit, sed do eiusmod tempor incididunt ut
testfile:  labore  et dolore magna aliqua</description>

sift -m '<description>(.*?)</description>' --replace 'description="$1"' --no-filename (extract and reformat the description)
Result:
description="Lorem ipsum dolor sit amet, consectetur
  adipiscing elit, sed do eiusmod tempor incididunt ut
  labore  et dolore magna aliqua"

A: One way to do this is with Perl.  e.g. here's the contents of a file named foo:
foo line 1
bar line 2
foo
foo
foo line 5
foo
bar line 6

Now, here's some Perl which will match against any line that begins with foo followed by any line that begins with bar:
cat foo | perl -e 'while(<>){$all .= $_}
  while($all =~ /^(foo[^\n]*\nbar[^\n]*\n)/m) {
  print $1; $all =~ s/^(foo[^\n]*\nbar[^\n]*\n)//m;
}'

The Perl, broken down:

*

*while(<>){$all .= $_} This loads the entire standard input in to the variable $all

*while($all =~ While the variable all has the regular expression...

*/^(foo[^\n]*\nbar[^\n]*\n)/m The regex: foo at the beginning of the line, followed by any number of non-newline chars, followed by a newline, followed immediately by "bar", and the rest of the line with bar in it. /m at the end of the regex means "match across multiple lines"

*print $1 Print the part of the regex that was in parenthesis (in this case, the entire regular expression)

*s/^(foo[^\n]*\nbar[^\n]*\n)//m Erase the first match for the regex, so we can match multiple cases of the regex in the file in question

And the output:
foo line 1
bar line 2
foo
bar line 6

A: I generally use a tool called pcregrep which can be installed in most of the linux flavour using yum or apt.
For eg.
Suppose if you have a file named testfile with content
abc blah
blah blah
def blah
blah blah

You can run the following command:
$ pcregrep -M  'abc.*(\n|.)*def' testfile

to do pattern matching across multiple lines.
Moreover, you can do the same with sed as well.
$ sed -e '/abc/,/def/!d' testfile

A: If we want to get the text between the 2 patterns excluding themselves.
Supppose we have the file test.txt containing :
blabla
blabla
foo
here
is the
text
to keep between the 2 patterns
bar
blabla
blabla

The following code can be used :
 sed -n '/foo/{
 n
 b gotoloop
 :loop
 N
 :gotoloop
 /bar/!{
 h
 b loop
 }
 /bar/{
 g
 p
 }
 }' test.txt

For the following output :
here
is the
text
to keep between the 2 patterns

How does it work, let's make it step by step

*

*/foo/{          is triggered when line contains "foo"

*n               replace the pattern space with next line, i.e. the word "here"

*b gotoloop      branch to the label "gotoloop"

*:gotoloop       defines the label "gotoloop"

*/bar/!{         if the pattern doesn't contain "bar"

*h               replace the hold space with pattern, so "here" is saved in the hold space

*b loop          branch to the label "loop"

*:loop           defines the label "loop"

*N               appends the pattern to the hold space.
Now hold space contains :
"here"
"is the"

*:gotoloop      We are now at step 4, and loop until a line contains "bar"

*/bar/          loop is finished, "bar" has been found, it's the pattern space

*g              pattern space is replaced with hold space that contains all the lines between "foo" and "bar" that have saved during the main loop

*p              copy pattern space to standard output

Done !
sed multiline loop

A: Simply a normal grep which supports Perl-regexp parameter P will do this job.
$ echo 'abc blah
blah blah
def blah
blah blah' | grep -oPz  '(?s)abc.*?def'
abc blah
blah blah
def

(?s) called DOTALL modifier which makes dot in your regex to match not only the characters but also the line breaks.

A: grep -E "pattern1|pattern2"

would list all lines matching with either <pattern1> or <pattern2>.


text:
Q: Bridging: OpenBSD vs Linux The bridge interface under Linux is quite dumb. In the end, it's just very inconvenient to use: you have to delete all IP configurations from the attached interfaces and somehow migrate the configuration to the bridge interface. I don't understand why (it doesn't make sense at all - normally, a bridge is not an endpoint for communication).
OpenBSD is much better; a bridge interface acts exactly like a physical switch. You create it, add the interfaces and you're done. Is it somehow possible to get similar behavior in Linux?

A: Bridges in Linux actually behave exactly like a physical switch.
Hey, let's take a look at my physical switch now. Can't get much switchier than a Cisco switch, right?
core-sw1#sh ip int brief
Interface              IP-Address      OK? Method Status                Protocol
Vlan1                  unassigned      YES NVRAM  up                    up
Vlan2                  192.168.0.2     YES NVRAM  up                    up
Vlan53                 10.53.0.2       YES NVRAM  up                    up

Hmm… on my Cisco switch the IP addresses are actually assigned to… the bridge interface. Not a single port.
Yep, you're thinking about it wrong. Consider what an IP address assigned to a single interface on a bridge would mean.

A: you can use openvswitch in bridge mode.


text:
Q: Nested Json deserialize c# I have a json string like this;
[
  {
    "ID": 123456789,
    "userInf": {
      "Name": "NameSurname1",
      "Adress": "example adress"
    },
    "price": "3898.30",
    "kdv": "701.69",
    "total": "4599,99",
    "note": "example note"
  },
  {
    "ID": 98756431,
    "userInf": {
      "Name": "NameSurname2",
      "Adress": "example address2"
    },
    "price": "1116.10",
    "kdv": "82.90",
    "total": "1199.00",
    "note": "example note2"
  }
]

And build up classes like this;
public partial class Sale
{
    public long ID { get; set; }
    public UserInf UserInf { get; set; }
    public string Price { get; set; }
    public string Kdv { get; set; }
    public string Total { get; set; }
    public string note { get; set; }
}

public partial class UserInf
{
    public string Name { get; set; }
    public string Adress { get; set; }
}

And I call json with this code and deserialize;
var data = JsonConvert.DeserializeObject<Sale>(jsonstring);
var shapedData = Enumerable.Range(0, 1).Select(x =>
                    new
                    {
                        ID = data.ID,
                        userInf = data.UserInf.Name,
                        price = data.Price,
                        kdv = data.Kdv,
                        total = data.Total,
                        note= data.Note
                    }).ToList();

DataTable dt = ToDataTable(shapedData);
dataGridView1.DataSource = dt;

and I get error. But if I change my json and cut the second half and delete the [,] symbols code just works perfectly fine. I need to deserialize multiple like above and tried multiple ways to deserialize but this is the closest way I get so far.
I get the error on this line ;
var data = JsonConvert.DeserializeObject<Sale>(jsonstring);

Error is

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type .. and so.

I know I'm missing something very basic but I have no coder friend to ask.
I would be grateful if you could suggest a better way to do it.

A: You should deserialize it as collection;
JsonConvert.DeserializeObject<List<Sale>>(jsonstring);

And your linq query looks like;
var shapedData = data.Select(x =>
    new
    {
       ID = x.ID,
       userInf = x.UserInf.Name,
       price = x.Price,
       kdv = x.Kdv,
       total = x.Total,
       note = x.note
    }).ToList();

A: can you try like this , dont make use of var as you already know return type
List<Sale> data = JsonConvert.DeserializeObject<List<Sale>>(jsonstring);

as your string return array of data


text:
Q: Can a mobile phone receive signal on 868.4 MHz frequency? I have a device that transmits data over 868.4 MHZ frequency with GFSK modulation. I have read some articles and I think, that classic mobile phones can receive a signal on this frequency, if not please tell me.
Can I receive this signal with my phone and use the application in it to provide info about demodulation and make transmitted data readable on that device?
Thanks for answers.


text:
Q: Python 3.4 CSV Deleting items using the in function This is my current code, the current issue I have is that search returns nothing. How do I achieve a string value for this variable.
count = 0
with open("userDatabase.csv","r") as myFile:
    with open("newFile.csv","w") as newFile:
        row_count = sum(1 for row in myFile)
        print("aba")
        for x in range(row_count):
            print("aaa")
            for row in myFile:
                search = row[count].readline
                print(search)
                if self.delName.get("1.0","end-1c") in search:
                    count = count + 1
                else:
                    newFile.write(row[count])
                    count = count + 1

The output is:
aba
aaa
aaa

So it runs through it twice, which is good as my userDatabase consists of two rows of data.
The file in question has this data:
"lukefinney","0000000","0000000","a"
"nictaylor","0000000","0000000","a"

A: You cannot just iterate over an open file more than once without rewinding the file object back to the start.
You'll need to add a file.seek(0) call to put the file reader back to the beginning each time you want to start reading from the first row again:
myFile.seek(0)
for row in myFile:

The rest of your code makes little sense; when iterating over a file you get individual lines from the file, so each row is a string object. Indexing into strings gives you new strings with just one character in it; 'foo'[1] is the character 'o', for example.
If you wanted to copy across rows that don't match a string, you don't need to know the row count up front at all. You are not handling a list of rows here, you can look at each row individually instead:
filter_string = self.delName.get("1.0","end-1c")

with open("userDatabase.csv","r") as myFile:
    with open("newFile.csv","w") as newFile:
        for row in myFile:
            if filter_string not in row:
                newFile.write(row)

This does a sub-string match. If you need to match whole columns, use the csv module to give you individual columns to match against. The module handles the quotes around column values:
import csv

filter_string = self.delName.get("1.0","end-1c")

with open("userDatabase.csv", "r", newline='') as myFile:
    with open("newFile.csv", "w", newline='') as newFile:
        writer = csv.writer(newFile)
        for row in csv.reader(myFile):
            # row is now a list of strings, like ['lukefinney', '0000000', '0000000', 'a']

            if filter_string != row[0]:  # test against the first column
                # copied across if the first column does not match exactly.
                writer.writerow(row)

A: One problem is that row_count = sum(1 for row in myFile) consumes all rows from myFile. Subsequent reads on myFile will return an empty string which signifies end of file. This means that for loop later in your code where you execute for row in myFile: is not entered because all rows have already been consumed.
A way around this is to add a call to myFile.seek(0) just before for row in myFile:. This will reset the file pointer and the for loop should then work.
It's not very clear from your code what it is that you are trying to do, but it kind of looks like you want to filter out rows that contain a certain string. Try this:
with open("userDatabase.csv","r") as myFile:
    with open("newFile.csv","w") as newFile:
        for row in myFile:
            if self.delName.get("1.0","end-1c") not in row:
                newFile.write(row)


text:
Q: Handling class imbalance in Passive Aggresive Online Learner in Scikit learn I am currently working on a large scale multi class image classification problem. I am currently using an Online learning strategy making use of Passive Aggressive algorithm implementation in scikit learn.
(owing to it's faster convergence compared to SGD implementation). I am following a One Vs  All (OVA) approach by building N (number of classes) OVA classifiers.
To handle the large amount of training data, I basically break my dataset into stratified minibatches and run them through the Online learners (each OVA's) over several iterations, until performance on the validation batch plateaus off.  (Model initialization and hyper param selection is done on the first batch)
My measure is primarily MAP or mean average precision.
(average over scores from sklearn.metrics.average_precision_score of each OVA model).
With this framework, everytime I have new labels available, I can create a new batch and run them through the partial fit operation, improving the model performance further.
My concern is weather this approach would be able to handle the class imbalance that would occur in the mini batches or as more mini batches are added in the future. I suspect that because of the class imbalance, the model would get biased with majority classes leading to low recall of minority classes.
One quick fix is to use class_weight='auto' during the learning but this is only supported with "SGD" implementation and not with passive aggressive implementation. ? Any reason for this given that both use the same underlying sgd implementation.
Other option i could think of is to make balanced mini - batches thus ensuring the models are not biased towards majority classes.
It would be great to have views on the architecture and it's possible drawbacks.
- is MAP the right measure ?
- How to handle online learning in unbalanced classes scenario.
- Any other linear algorithm instead of Passive Aggressive and SGD that might better suit the problem
Thanks

A: The Passive Aggressive classifier doesn't "converge" like most algorithms you are used to. Indeed, if you read the paper the point of PA is to make the update that completely corrects the loss yet causes the minimum change in the norm of the weight vector. NOTE that the regularization parameter in PA keeps it from fully correcting on a per example basis.
In this way, PA is meant specifically for online and not batch training, and thus - the running of PA on mini batches until it stabilizes is likely not helping (and maybe hurting) your generalization accuracy.

is MAP the right measure

Depends entirely upon your data and needs.

Any other linear algorithm instead of Passive Aggressive and SGD that might better suit the problem

Depends entirely upon your data and needs

One quick fix is to use class_weight='auto' during the learning but this is only supported with "SGD" implementation and not with passive aggressive implementation. ? Any reason for this given that both use the same underlying sgd implementation.

Yes, see my description of PA. PA's method of learning doesn't allow for that addition. While you could implement it by an alteration of the regularization on a per class basis, I don't think it would make any sense. See the original paper if you need to know more.
You can search for "class imbalance" to find more methods of trying to deal with that problem, but it all depends on your data.
If you are willing to use Java, JSAT has a directly multi-class implementation of PA called SPA. It may or may not be more accurate for your problem.


text:
Q: React-native flex height I have 3 components and I am trying to set their heights (header, body, footer) but when it renders, each component has just the height of one line of text it contains.
import React from 'react';
import { View, Text } from 'react-native';
import Header from './Header';
import Body from './Body';
import Footer from './Footer';
import * as globalStyles from '../styles/global';

const HomeScreen = () => (
  <View style={{ flex: 1 }}>
    <Header style={{ flex: 1 }} title={'MyTitle'}>
      <Text>Component</Text>
    </Header>
    <Body style={{ flex: 3 }}>
      <Text>my body</Text>
    </Body>
    <Footer style={{ flex: 1 }}>
      <Text>my footer</Text>
    </Footer>
  </View>
);

export default HomeScreen;

App
import React from 'react';
import { Provider } from 'react-redux';
import HomeScreen from './components/HomeScreen';
import createStore from './createStore';

const store = createStore();

export default () => (
  <Provider store={store}>
    <HomeScreen />
  </Provider>
);

Header
import React, { PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as globalStyles from '../styles/global';

const Header = ({ children, title }) => (
  <View>
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
      {title}
      {title}
    </Text>
  </View>
);

Header.propTypes = {
  children: PropTypes.node
};

const styles = StyleSheet.create({
  header: {
    paddingTop: 20
  }
});
export default Header;

Footer
import React, { PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as globalStyles from '../styles/global';

const Footer = ({ children }) => (
  <View>
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
    </Text>
  </View>
);

Footer.propTypes = {
  children: PropTypes.node.isRequired
};

const styles = StyleSheet.create({
  header: {
    marginTop: 20,
    flex: 1,
  }
});
export default Footer;

Body
import React, { PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as globalStyles from '../styles/global';

const Body = ({ children, title }) => (
  <View>
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
      {title}
      {title}
    </Text>
  </View>
);

Body.propTypes = {
  children: PropTypes.node
};

const styles = StyleSheet.create({
  header: {
    marginTop: 20,
    flex: 1,
  }
});
export default Body;

global styles
import { StyleSheet } from 'react-native';

export const BG_COLOR = '#343336';
export const BAR_COLOR = '#4e4d52';
export const TEXT_COLOR = '#e5dbda';
export const HEADER_TEXT_COLOR = '#fff';
export const MUTED_COLOR = '#8e8786';
export const LINK_COLOR = '#48e9d9';
export const ACCENT_COLORS = ['#d31d65', '#751c53', '#c248c0', '#7d6e8b', '#bbc6f7'];

export const COMMON_STYLES = StyleSheet.create({
  pageContainer: {
    backgroundColor: BG_COLOR,
    marginTop: 0,
    paddingTop: 5,
    paddingHorizontal: 10
  },
  text: {
    color: TEXT_COLOR,
    fontFamily: 'Helvetica Neue'
  }
});

My understanding is that the Body should be 3 x the height of header or footer.
React-native:
react-native-cli: 2.0.1
react-native: 0.41.2

A: EDIT
Flex should be given to your root containers of the header, body and footer components. Header, Footer and Body are custom components, the style props won't be applicable to them, the style you applied just get passed as a prop
const Footer = ({ children }) => (
  <View style={{ flex: 1 }}>  // root container of footer
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
    </Text>
  </View>
);

const Body = ({ children, title }) => (
   <View style={{ flex: 3 }}>
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
      {title}
      {title}
    </Text>
   </View>
);

const Header = ({ children, title }) => (
  <View style={{ flex: 1 }}> // root container of header
    <Text style={globalStyles.COMMON_STYLES.text}>
      {children}
      {title}
      {title}
    </Text>
  </View>
);

Hope its working for you


text:
Q: Window exe API cors issue when calling from any webapp. C++ We've created one EXE file using the CPP language and create one API like http://localhost:5800/get-id/. when I open in browser return me the perfect output.
When I used fetch in HTML > script page, then getting No "Access-Control-Allow-Origin" header is present on the requested resource.
Code1:
fetch("http://localhost:5800/get-id/", {method: 'GET').then(function(response) {
  console.log(response.text());
}).catch(function(error) {
  console.log('Request failed', error)
});

After research, I've added the mode: no-cors error lost but getting an empty response.
Code2:
fetch("http://localhost:5800/get-id/", {method: 'GET', mode: 'no-cors'}).then(function(response) {
  console.log(response.text());
}).catch(function(error) {
  console.log('Request failed', error)
});

If I use code2 in any inspect console then getting an empty body but when I open http://localhost:5800/get-id/ in the browser and try to hit code2 in the console then getting the perfect parameter.
It means, localhost domain it's working fine but when it's fetched from any domain through my error.
What is the proper solution for it? In C/CPP language how can we allow cors?
Strange:
when I hit from console, it's show me empty

For same request I checked network tab, show 200 OK with proper response / preview data

A: CORS is a complex topic, I usually use CORS middleware to handle it in Node.JS in Express server (maybe the code will be useful to solve this).
It's goal is to allow API on domain api-domain to list web applications that can use it, for example your application is on webapp-domain domain.
When application calls fetch('http://api-domain/get-id/') to another domain it is referred to as cross-origin call.
All browser do CORS preflight call like this to check for allowance:
OPTIONS /get-id/
Access-Control-Request-Method: GET
Access-Control-Request-Headers: origin, x-requested-with
Origin: http://webapp-domain

(please note it's an OPTION request to the API, not GET)
And response should list webapp-domain as allowed (and specify which HTTP methods are allowed)
HTTP/1.1 204 No Content
Connection: keep-alive
Access-Control-Allow-Origin: http://webapp-domain
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
Access-Control-Max-Age: 86400

After the successful preflight call like this the browser will continue with fetch, for example, it will send GET request to http://api-domain/get-id/
P.S.
One of the ways to skip CORS is to set HTTP proxy in webapp-domain which will call api-domain on server-side and is not limited by CORS. See this answer for details.


text:
Q: ASP.NET MVC 5 errors while loading the project to Visual Studio Code I had Install Visual Studio 2015 and Created  web app project from ASP.NET 5 Templates then i Installed the Visual Studio code open my project with it it gives me some recommends to install some extensions like C# .. etc after installing the extensions the project give me these error i searched for some solution like install .NET Core SDK but it didn't solve my problem another I tried to open the terminal and write dotnet restore command it gives me an error that error MSB4019:

The imported project "C:\Program
  Files\dotnet\sdk\1.0.4\Microsoft\VisualStudio\v14.0\DNX\Microsoft.DNX.Props"
  was not found. Confirm that the path in the  declaration is
  correct, and that the file exists on disk.

then i check the DemoCore.xproj file and i found an wrong path in it    but i don't know what to do
these errors in the screenshotshows the problem in the visual studio code

A: Have you installed .NET Core 1.0.4? See the stackoverflow question here. Note that the selected answer in that linked question recommends installing Visual Studio 2015 Tools, which comes with .NET Core 1.0.1.. You'll want 1.0.4 or higher from here, and may need to upgrade the target .NET Core framework version of your project in order to get it to build if you end up installing .NET Core 1.1 or 2.0.


text:
Q: How to actually do Data Binding in WPF I am new to WPF  I want to  bind my data grid to a table in data base . I am unable to understand the procedure , do I have to specify binding to each column or it can be at once?
Kindly some one explain clearly how to do that , will be really grateful to you.


text:
Q: Inversion count for 100000 integers using merge sort reading from a text file. But not able to get the correct inversion count Below is the code I have written to read the 100000 integers from a text file and to sort them using merge sort.
Issues:

*

*The sorted integers are getting displayed in correct order only in the eclipse console, but when I try to write them to an output text file the order is getting changed.

*The inversion count value of 100000 integers from the given text file should be around 2407905288 as per my knowledge but I am getting a value of 8096.
Kindly do help me fix these two issues. thank you so much in advance.
package com.inversioncount;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class inversioncount {

    public static int mergeSort(Integer[] arr, int array_size) {
        int temp[] = new int[array_size];
        return _mergeSort(arr, temp, 0, array_size - 1);
    }

    /* An auxiliary recursive method that sorts the input array and
      returns the number of inversions in the array. */
    public static int _mergeSort(Integer arr[], int[] temp, int left, int right) {
        int mid, count = 0;
        if (right > left) {
            /* Divide the array into two parts and call _mergeSortAndCountInv()
               for each of the parts */
            mid = (right + left) / 2;

            /* Inversion count will be sum of inversions in left-part, right-part
               and number of inversions in merging */
            count  = _mergeSort(arr, temp, left, mid);
            count += _mergeSort(arr, temp, mid + 1, right);

            /* Merge the two parts */
            count += merge(arr, temp, left, mid + 1, right);
        }
        return count;
    }

    /* This method merges two sorted arrays and returns inversion count in
       the arrays.*/
    static int merge(Integer arr[], int temp[], int left, int mid, int right) {
        int x, y, z;
        int count = 0;

        x = left; /* i is index for left subarray*/
        y = mid;  /* j is index for right subarray*/
        z = left; /* k is index for resultant merged subarray*/
        while ((x <= mid - 1) && (y <= right)) {
            if (arr[x] <= arr[y]) {
                temp[z++] = arr[x++];
            } else {
                temp[z++] = arr[y++];
                count = count + (mid - x);
            }
        }

        /* Copy the remaining elements of left subarray
           (if there are any) to temp*/
        while (x <= mid - 1)
            temp[z++] = arr[x++];

        /* Copy the remaining elements of right subarray
           (if there are any) to temp*/
        while (y <= right)
            temp[z++] = arr[y++];

        /* Copy back the merged elements to original array*/
        for (x = left; x <= right; x++)
            arr[x] = temp[x];

        return count;
    }

    // Driver method to test the above function
    public static void main(String[] args) throws FileNotFoundException {
        try {
            BufferedReader br = new BufferedReader(new FileReader("IntegerArray.txt"));
            List<Integer> lines = new ArrayList<Integer>();
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(Integer.parseInt(line));
            }
            br.close();
            Integer[] inputArray = lines.toArray(new Integer[lines.size()]);
            inversioncount.mergeSort(inputArray, inputArray.length - 1);
            System.out.println("Number of inversions are " + mergeSort(inputArray, inputArray.length));
            //BufferedWriter writer = null;
            //writer = new BufferedWriter(new FileWriter("OutputLatest.txt"));
            for (Integer i : inputArray) {
                System.out.println(i);

                // Writing sorted lines into output file
                //writer.write(i);
                //writer.newLine();
            }
        } catch (IOException ie) {
            System.out.print(ie.getMessage());
        }
    }
}

A: Your recursive calls are from left to mid and mid+1 to right as seen here:
count  = _mergeSort(arr, temp, left, mid);
count += _mergeSort(arr, temp, mid+1, right);

Therefore the correct merge function call should be:
count += merge(arr, temp, left, mid, right);

There are also some mistakes in merge definition. Let me point them out to you:
x should vary from left to mid. y should vary from mid+1 to right
  x = left; /* i is index for left subarray*/
  y = mid+1;  /* j is index for right subarray*/
  z = left; /* k is index for resultant merged subarray*/
  while ((x <= mid) && (y <= right))

Also the inversion count is actually count = count + (mid - x) + 1;. You can figure that out by taking  a small array of 5 elements.
Also the indices for temp always start from 0.
Therefore the correct merge function is:
static int merge(Integer arr[], int temp[], int left, int mid, int right)
{
  int x, y, z ;
  int count = 0;

  x = left; /* i is index for left subarray*/
  y = mid+1;  /* j is index for right subarray*/
  z = 0; /* k is index for resultant merged subarray*/
  while ((x <= mid) && (y <= right))
  {
    if (arr[x] <= arr[y])
    {
      temp[z++] = arr[x++];
    }
    else
    {
      temp[z++] = arr[y++];

      count = count + (mid - x) + 1;
    }
  }

  /* Copy the remaining elements of left subarray
   (if there are any) to temp*/
  while (x <= mid)
    temp[z++] = arr[x++];

  /* Copy the remaining elements of right subarray
   (if there are any) to temp*/
  while (y <= right)
    temp[z++] = arr[y++];

  /*Copy back the merged elements to original array*/

  z = 0;

  for (x=left; x <= right; x++)
    arr[x] = temp[z++];

  return count;
}

A: This is task from Hackerrank/Practice/Tutorials/Cracking the Coding Interview/Merge Sort: Counting Inversions:
static long mergeSort(int[] arr, int l, int r) {
    long swaps = 0;

    if (l < r) {
        int p = (l + r) / 2;
        swaps += mergeSort(arr, l, p);
        swaps += mergeSort(arr, p + 1, r);

        // Merge
        int[] la = Arrays.copyOfRange(arr, l, p + 1);
        int[] ra = Arrays.copyOfRange(arr, p + 1, r + 1);

        int i = l, lai = 0, rai = 0;
        while (lai < la.length && rai < ra.length) {
            if (ra[rai] < la[lai]) {
                arr[i++] = ra[rai++];
                swaps += la.length - lai;
            } else {
                arr[i++] = la[lai++];
            }
        }
        while (lai < la.length) {
            arr[i++] = la[lai++];
        }
        while (rai < ra.length) {
            arr[i++] = ra[rai++];
        }
    }
    return swaps;
}

A: Use long instead of int for inv_count. Also, change the return type from int to long.
As with the above solution, int is overflowing.

A: There are multiple issues in your code:

*

*you use type int to compute the number of inversions. The maximum value for type int is 2147483647. You should instead use type long which can handle values up to 9223372036854775807.

*you call mergeSort twice in the main() method, with conflicting array sizes:
    inversioncount.mergeSort(inputArray, inputArray.length - 1);
    System.out.println("Number of inversions are " + mergeSort(inputArray, inputArray.length));

You should instead call it just once with the correct length:
    long inversion_count = mergeSort(inputArray, inputArray.length);
    System.out.println("Number of inversions is " + inversion_count + "\n");

*It is confusing to specify right as the index of the last element in the slice. A much more regular and idiomatic approach uses right as the index of the first element past the end of the slice.
Here is a corrected version:
package com.inversioncount;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class inversioncount {

    public static long mergeSort(Integer[] arr, int array_size) {
        int temp[] = new int[array_size];
        return _mergeSort(arr, temp, 0, array_size);
    }

    /* An auxiliary recursive method that sorts a slice of the input array and
      returns the number of inversions. */
    static long _mergeSort(Integer arr[], int[] temp, int left, int right) {
        long count = 0;
        if (right - left > 1) {
            /* Divide the array into two parts and call _mergeSort() for each of the parts */
            int mid = (right + left + 1) / 2;

            /* Inversion count will be sum of inversions in left-part, right-part
               and number of inversions in merging */
            count += _mergeSort(arr, temp, left, mid);
            count += _mergeSort(arr, temp, mid, right);

            /* Merge the two parts */
            count += merge(arr, temp, left, mid, right);
        }
        return count;
    }

    /* This method merges two sorted slices of the array and returns the inversion count */
    static long merge(Integer arr[], int temp[], int left, int mid, int right) {
        long count = 0;

        int x = left; /* x is index for left subarray */
        int y = mid;  /* y is index for right subarray */
        int z = left; /* z is index for resultant merged subarray */
        while (x < mid && y < right) {
            if (arr[x] <= arr[y]) {
                temp[z++] = arr[x++];
            } else {
                temp[z++] = arr[y++];
                count += mid - x;
            }
        }

        /* Copy the remaining elements of left subarray if any */
        while (x < mid)
            temp[z++] = arr[x++];

        /* Copy the remaining elements of right subarray if any */
        while (y < right)
            temp[z++] = arr[y++];

        /* Copy back the merged elements to original array */
        for (x = left; x < right; x++)
            arr[x] = temp[x];

        return count;
    }

    // Driver method to test the above function
    public static void main(String[] args) throws FileNotFoundException {
        try {
            BufferedReader br = new BufferedReader(new FileReader("IntegerArray.txt"));
            List<Integer> lines = new ArrayList<Integer>();
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(Integer.parseInt(line));
            }
            br.close();

            Integer[] inputArray = lines.toArray(new Integer[lines.size()]);
            long inversion_count = mergeSort(inputArray, inputArray.length);
            System.out.println("Number of inversions is " + inversion_count + "\n");

            //BufferedWriter writer = null;
            //writer = new BufferedWriter(new FileWriter("OutputLatest.txt"));
            for (Integer i : inputArray) {
                System.out.println(i);

                // Writing sorted lines into output file
                //writer.write(i);
                //writer.newLine();
            }
        } catch (IOException ie) {
            System.out.print(ie.getMessage());
        }
    }
}


text:
Q: Could we define inner measure instead of outer measure? We all have seen outer measure in measure theory.It is the precursor of a measure.It is defined as follows:
Let $A\subset \mathbb R$,then the outer measure $\mu^*:\mathcal P(\mathbb R)\to [0,\infty]$ is a function defined by, $\mu^*(A)=\inf\{\sum\limits_{n=1}^\infty \ell(I_n):I_1,I_2,...$ are open intervals such that $A\subset \bigcup\limits_{n=1}^\infty I_n\}$.
The basic idea is to approximate a set from outside by open intervals.A question comes naturally to our mind.Is it possible to approach the set from inside i.e. $\mu_*(A)=\sup\{\sum\limits_{n=1}^\infty \ell(I_n):I_1,I_2,...$ are open intervals such that $A\supset \bigcup\limits_{n=1}^\infty I_n\}$.I think it is not a good idea because there are sets that do not contain intervals.For example $A=(\mathbb {R\setminus Q})\cap [0,1]$,clearly $\mu^*(A)=1$ but $\mu_*(A)$ cannot be defined.So,is there a way to define inner measure?When is it defined and when is it equal to the outer measure?Clearly,measurabilty is not sufficient as we saw in this example.Can someone tell me more on this?


text:
Q: Pandas - groupby cumulative timeperiod Here's my problem:
Imagine a dataframe indexed by time.
df = pd.DataFrame(index=["00:00:00",
"00:00:08","00:00:14","00:00:21","00:00:23","00:00:49"],data={"col1":["a",
"b","a","a", "c", "d"], "col2":[4,4,4,6,6,7], "col3":[2,17,2,2,3,50]})

I would now like to apply a function and group the data based on cumulative time in 15 second intervals, i.e. for timestamps between 00:00:00 - 00:00:15, 00:00:00 - 00:00:30, 00:00:00 - 00:00:45, etc.
Let's say for example, I want to sum all values of col2, col3 and divide one by the other, if the value in col1 is "a" in each of those intervals.
The output should be something like:
         output
00:00:15    2
00:00:30    2.3333

Appreciate any help!

A: First convert index to timedeltas by to_timedelta and add 15 seconds for shifting it, then filter only a rows by boolean indexing and Series.eq (==).
Then DataFrame.resample sum, then DataFrame.cumsum and last divide columns by Series.div:
df.index = pd.to_timedelta(df.index) + pd.Timedelta(15, unit='s')

df = df[df['col1'].eq('a')].resample('15S').sum().cumsum()
df['out'] = df['col2'].div(df['col3'])
print (df)
          col2  col3       out
00:00:15     8     4  2.000000
00:00:30    14     6  2.333333

Alternative is converting to datetimes:
df.index = pd.to_datetime(df.index) + pd.Timedelta(15, unit='s')

df = df[df['col1'].eq('a')].resample('15S').sum().cumsum()
df['out'] = df['col2'].div(df['col3'])
print (df)
                     col2  col3       out
2019-03-21 00:00:15     8     4  2.000000
2019-03-21 00:00:30    14     6  2.333333

A: df = pd.DataFrame(index=["00:00:00", "00:00:08","00:00:14","00:00:21","00:00:23","00:00:49"],data={"col1":["a","b","a","a", "c", "d"], "col2":[4,4,4,6,6,7], "col3":[2,17,2,2,3,50]})
df.index = pd.to_datetime(df.index, format='%H:%M:%S')
df = df[df['col1']=='a'].resample('15s', how='sum').cumsum()
df['output'] = df['col2']/df['col3']


text:
Q: how set alarm along with notification? i've been doing on my alarm project..
my code is like this :
    String a = interval.getText().toString();

   Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);
   pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);

            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND, 10);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), Integer.parseInt(a)*1000, pendingIntent);

            NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

            int icon = R.drawable.alarm_icon;
            CharSequence tickerText = "Hello";
            long when = System.currentTimeMillis();

            Notification notification = new Notification(icon, tickerText, when);

            Context context = getApplicationContext();
            CharSequence contentTitle = "My notification";
            CharSequence contentText = "Hello World!";
            Intent notificationIntent = new Intent(AndroidAlarmService.this, AndroidAlarmService.class);
            PendingIntent contentIntent = PendingIntent.getActivity(AndroidAlarmService.this.getBaseContext(), 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

            notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

            final int HELLO_ID = 1;

            mNotificationManager.notify(HELLO_ID, notification);

   Toast.makeText(AndroidAlarmService.this, "Start Alarm", Toast.LENGTH_LONG).show();
  }});

i've got a problem, the notification always came out once, it's not come out repeatly.
i want to set a repeatable alarm along with notification, so everytime the alarm active, the notification will come out too... for the example, when i set an alarm every 1 hours, so every one hours, the alarm will trigger and the notification will also come out..
anyone can help me? thanks before

A: pass your Notification in Service class i.e inside the onStartCommand()


text:
Q: How to correctly close an Entity Manager in doctrine I was having a memory leak problem in a Doctrine2 script that was aparently caused by a piece of code that was supposed to eliminate memory problems.
Before I knew you could (and should) clear the Entity Manager, every 20 iterations i did the following:
if ($this->usersCalculated % 20 == 0) {
   $this->em->close();
   $this->em = \Bootstrap::createEm();
   $this->loadRepositories();
}

And the Bootstrap::createEm looks like this:
public static function createEm() {
    $em = EntityManager::create(Bootstrap::$connectionOptions, Bootstrap::$config);
    $em->getConnection()->setCharset('utf8');
    return $em;
}

The reason that I recreated the Entity Manager in the first place was because my UnitOfWork was growing wild and I didn't know about the $em->clear() method.
So, even if my current memory leak seems solved at the moment (or at least reduced), i still have to create a new Entity Manager whenever I need to do a separate insert/update query without relying that someone else do the flush. For example, whenever I send an email, I insert a row in the database to indicate so, and the code looks like this:
    $emailSent = new \model\EmailSent();
    $emailSent->setStuff();
    // I do it in a new em to not affect whatever currentunit was doing.
    $newEm = \Bootstrap::createEm();
    $newEm->persist($emailSent);
    $newEm->flush();
    $newEm->close();

From what I've learned from before, that leaves some memory leaked behind.
So my question is, what am I doing wrong here? why is this leaking memory and how should I really close/recreate an entity manager?

A: Have you tried:
$this->em->getConnection()->getConfiguration()->setSQLLogger(null);

I've read that this turns off the SQL Logger which is not cleared and sometimes produces memory leaks like you are experiencing.

A: Have you tried actually using the clear method instead of close?
I hope this helps you---> Batch Processing


text:
Q: Using built-in checkstyle configuraiton from command line I'm new to Java programming and had thought that it would be beneficial for me to instill good style habits from the beginning. Upon downloading the checkstyle-7.6.1-all.jar file, I tried to run the following from the Bash command line:
java -jar checkstyle-7.6.1-all.jar -c /google_checks.xml TimeConvert.java

and was presented with the message:
Could not find config XML file 'C:/Program Files/Git/google_checks.xml'.

What I had ran from the command line was what was recommended by the Checkstyle website.
From what I've gathered so far, it seems that the XML file containing the google style specifications should be contained within the .jar file I downloaded.
My guess is that I need to specify more precisely the location of the XML file, but I'm not sure.
When I search the internet for answers, a lot of the information I find is for advanced users looking to write a custom checkstyle configuration.
Any help here would be appreciated.

A: In git bash, '/' refers to the installation folder of Git.
You need to get the full path of that google_checks.xml file mentioned in the checkstyle "Download and Run" section:
/c/path/to/google_checks.xml