text:
Q: Format text with a timezone I am parsing date and time information and then setting my TextView's text with a formatted version of the information.
The problem I am having is the the time is set to the timezone of my device. I would like the formatted text to be in the original timezone from the Event.getDateTime() String which contains timezone information. I seem to be missing something since the timezone information is no longer stored in the Date object. How can I format my text with the original timezone?
I don't need to display the original timezone in my TextView, just have the time set to it.
private void onProcessDateTime(TextView content3, Card item, ViewGroup parent)
{
    final Event event = ((EventCard) item).getEvent();
    Locale locale = Locale.getDefault();
    Date date = null;
    SimpleDateFormat parse = null;
    DateFormat format = null;
    if (event.getDateTime() != null
            && !event.getDateTime().equals("null"))
    {
        parse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", locale);
        try
        {
            date = parse.parse(event.getDateTime());

        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        format = DateFormat.getDateTimeInstance
                (DateFormat.MEDIUM, DateFormat.SHORT, locale);
    }
...
    content3.setText(format.format(date));
}

A: Trying to store and recreate local times is a heap of trouble. Far better to Store globally, Present locally. When you get a date-time, immediately convert to UTC. Work in UTC, and store in UTC. Convert to time zones only as necessary or upon presentation to the user.
If you must serialize a date-time to text, do so in a clean standard way. Usually that means ISO 8601.
And obtain a decent date-time library such as Joda-Time or the new JSR 310 java.time.* in Java 8. Some folks use Joda-Time in Android. I've not done so, therefore I can't verify if the code works on that platform.
Here's some Joda-Time example source code. Joda-Time 2.3 in Java 7 on Mac OS X Mountain Lion.
From DateTime to String
// Capture the current moment.
// The no-arg constructor automatically uses the user's default (and presumably local) time zone.
org.joda.time.DateTime nowInDefaultTimeZone = new org.joda.time.DateTime();
// Convert to UTC.
org.joda.time.DateTime nowPutInUtc = nowInDefaultTimeZone.toDateTime( org.joda.time.DateTimeZone.UTC );
// Or, if you don't need local time zone, create instance in UTC.
org.joda.time.DateTime now = new org.joda.time.DateTime( org.joda.time.DateTimeZone.UTC );

// Joda-Time by default converts to a String by using an ISO 8601 formatter.
String nowAsString = now.toString();

From String To DateTime
// Pretend we read that string from storage. Reconstitute a DateTime.

// Use the built-in ISO 8601 formatter to parse string.
// ISODateTimeFormat is automatically set to user's own time zone.
// By the way, you may obtain that time zone explicitly: org.joda.time.DateTimeZone.getDefault()
org.joda.time.DateTime nowReconstitutedInUserTimeZone = org.joda.time.format.ISODateTimeFormat.dateTime().parseDateTime( nowAsString );

// Create string to present to user.
// 'forStyle' uses a two-character pattern.
// The first character is the date style, and the second character is the time style.
// Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full.
// A date or time may be omitted by specifying a style character '-'.
org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forStyle( "MS" );
String nowAsStringAgain = nowReconstitutedInUserTimeZone.toString( formatter );

// Back to UTC if you need it.
org.joda.time.DateTime nowReconstitutedAndConvertToInUtc = nowReconstitutedInUserTimeZone.toDateTime( org.joda.time.DateTimeZone.UTC );

// Or reconstitute directly into UTC.
org.joda.time.DateTime nowReconstitutedInUtc = org.joda.time.format.ISODateTimeFormat.dateTime().withZoneUTC().parseDateTime( nowAsString );

Output to Console
System.out.println( "now: " + now );
System.out.println( "nowReconstitutedInUserTimeZone: " + nowReconstitutedInUserTimeZone );
System.out.println( "nowReconstitutedAndConvertToInUtc: " + nowReconstitutedAndConvertToInUtc );
System.out.println( "nowReconstitutedInUtc: " + nowReconstitutedInUtc );
System.out.println( "nowAsStringAgain: " + nowAsStringAgain );

When run in Seattle US…
now: 2013-11-26T02:54:21.299Z
nowReconstitutedInUserTimeZone: 2013-11-25T18:54:21.299-08:00
nowReconstitutedAndConvertToInUtc: 2013-11-26T02:54:21.299Z
nowReconstitutedInUtc: 2013-11-26T02:54:21.299Z
nowAsStringAgain: Nov 25, 2013 6:54 PM

Actually, the best way to store date-times is as date-times such as in a date-time savvy database like Postgres. For the sake of this question I assumed we were forced to serialize a date-time as text.


text:
Q: Getting link from HTML (Selenium and Python) I have the following HTML:

I want to get that selected image URL.
Till the moment, i've just tried:
quest = driver.find_element_by_xpath('//div[@class="table--database"]/div/div[2]/div/div')
print(quest.get_attribute('outerHTML'))

but when I execute it I get:
div class="table__empty instead of div class = table__body
What's going on?

A: you can try this Xpath
quest = driver.find_element_by_xpath('//div[@class="table--database"]//div[@class="table__body"]//img')
# or
# quest = driver.find_element_by_xpath('//div[@class="table--database"]//img')
# quest = driver.find_element_by_xpath('//div[@class="table__body"]//img')
print(quest.get_attribute('src')) # URL only
print(quest.get_attribute('outerHTML'))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Transfer file from remote server to my server via sftp in bash script I wanna transfer a big file (1.3G) from remote server to my server via sftp/ftp in bash script (not in separated commands).
Just for instance: my server IP is 10.10.10.1 and remote server is 10.10.10.2
I connect to remote server with sftp root/123456 (user + pass).
Let me know for more information.

A: sftp can read commands from either standard input or from a "batch file".
For example, to get a file from the remote host, you would use the get command:
echo 'get /path/to/file' | sftp user@10.10.10.2

Or, you could use a here-document to pass the command(s) to sftp:
sftp user@10.10.10.2 <<'END'
get /path/to/file
END

Or you could have the same get command in a file that you refer to with the -b command line option of sftp:
sftp -b somefile user@10.10.10.2

The file or files that you transfer to the local system would be put into the current directory (unless this is changed with lcd, "local cd", in the commands that you send to sftp).
To connect without having to give a password, arrange with public and private SSH keys as described in "How to make the script automated to take password on its own?".  Note that a remote system may well have disabled SSH access for the root user (this is a sane way to configure an SSH server).


text:
Q: Highcharts: multiple charts in the same pane with different Y axis? Here is an example of my code: https://jsfiddle.net/delux123/y9h46Le8/27/ where I have two series of data, referenced as ohlc and volume. I need them both displayed at one pane (as in example I provided) but they will need to have separate Y axises.
The data for volume series will always have values that are above the ohlc series and the ohlc series will not be visible because of this overlapping. In the example I provided, we can see how it's already overlapping for some points. Considering that in my data this will be the case for all points, that means my ohlc series will never be visible.
So what I wonder is, if there is a way where two different series will be placed on the same pane, but will have different range of Y axis?
This is just an example of one idea that I have: Since I need ohlc series to be in the main focus, maybe we can set min value of the ohlc series to always be above 30% of the pane and the max value of the current visible volume series can always be below the 30% of the pane. Something like limiting the min/max value of the series in the current pane:

I found something similar here: https://www.tradingview.com/script/A1cPrGLb-Example-Monte-Carlo-Simulation/ so that way will work as well. I wonder if this is feasible with highcharts?


text:
Q: function return None after execution of a function I have this code to split a DNA strand into groups of 3. Everything in the result is intended except for that last "None"
def codons(x):
    for i in range(0, len(x), 3):
        result = print(x[i:i + 3])
    return result

When using with
print(codons('ATGCTCAAGTAGR'))

Returns:
ATG
CTC
AAG
TAG
R
None

A: You can save the result in a list
 def codons(x):
        result=[]
        for i in range(0, len(x), 3):
            result.append(x[i:i + 3])
        return result

A: Everything is right, just get rid of the return and the print when calling the function.
def codons(x):
    for i in range(0, len(x), 3):
        print(x[i:i + 3])
codons('ATGCTCAAGTAGR')


text:
Q: auth0 user store vs. own user store - how do they work together? I'm familiarizing myself with auth0 and setting it up on a rails 6 api only app. I'm planning to have a database around different resources etc. One of these resources is a User resource. This will be used for authentication, authorization, and some user data, followers/following relationships etc.
Auth0 provides their own user store, claims this is the most performant, and probably is the easiest thing to set up cause they do everything for you, storing encrypted passwords etc. I'd love to take advantage of this but I'm wondering about how customizable this auth0 user store is. How easily does it work together with my own database, which would store the other resources like follower/following relationships etc.?
And what if I want to add more custom attributes to the user table?
Users will be a fundamental part of my app and will have complex calculations and actions centered around them. Is the auth0 database suitable for this? Or is it more meant as a simple login store for mostly static websites? Does anybody have experience with this?
Any advice appreciated!

A: auth0 provides an authentication mechanism based on the OAuth protocol.
The service allows you to outsource user authentication management from your application. It is based around the OAuth protocol, this is not really different from a classic OAuth integration (like facebook or google sign in).
Following this tutorial the simplest way to achieve what your want is to create a users table in your database and import information during authentication callback. The request.env['omniauth.auth'] hash contains all the information about the users who signed in from auth0, including email etc. There's a unique id in that hash that you can user to map the auth0 user to your current database one. If the user does not exist, simply create it.
# auth hash structure from auth0:
#{
#  :provider => 'auth0',
#  :uid => 'auth0|USER_ID',
#  :info => {
#    :name => 'John Foo',
#    :email => 'johnfoo@example.org',
#    :nickname => 'john',
#    :image => 'https://example.org/john.jpg'
#  },
#  :credentials => {
#    :token => 'ACCESS_TOKEN',
#    :expires_at => 1485373937,
#    :expires => true,
#    :refresh_token => 'REFRESH_TOKEN',
#    :id_token => 'JWT_ID_TOKEN',
#    :token_type => 'bearer',
#  },
#  :extra => {
#    :raw_info => {
#      :email => 'johnfoo@example.org',
#      :email_verified => 'true',
#      :name => 'John Foo',
#      :picture => 'https://example.org/john.jpg',
#      :user_id => 'auth0|USER_ID',
#      :nickname => 'john',
#      :created_at => '2014-07-15T17:19:50.387Z'
#    }
#  }
#}

# app/controllers/auth0_controller.rb

class Auth0Controller < ApplicationController
  def callback
    # This stores all the user information that came from Auth0
    # and the IdP

    # request.env['omniauth.auth'] contains all user data
    auth_data = request.env['omniauth.auth']
    user = User.find_or_create_by(auth0_id: auth_data[:uid]) do |user|
      user.email = auth_data[:info][:email]
      # associate any other data from auth0 you need here
    end

    session[:userinfo] = request.env['omniauth.auth']

    # Redirect to the URL you want after successful auth
    redirect_to '/dashboard'
  end

  def failure
    # show a failure page or redirect to an error page
    @error_msg = request.params['message']
  end
end

Since the user information is stored in your session, you can use this data to fetch the current user based on the uid you stored. That way you can any information you need in your own users table.
Hope this helps !


text:
Q: How to prevent an application stealing focus in Ubuntu 18.04 When clicking a link in Thunderbird, Chrome automatically steals focus. I want to keep working in Thunderbird while clicking links open them in Chrome in the background - without stealing focus.
How can I do this?


text:
Q: Core Data Migration - Changing Attribute Type I have an iOS application that is using Core Data Persistent Store.  I have a few people testing the application and need to make some changes to the data model, specifically changing the type of an attribute from 'NSString' to 'int16_t'.
Here is what I have done so far:

*

*Created a new model version

*Changed the attribute type

*Added a mapping model (I am not sure what I need in here.  I have my one EntityMapping with a Custom Policy)

*Created the Custom Policy (listed below)

I am using MagicalRecord.  The migration is being performed, but seems to be clearing the database.  I am able to read the SQLite file locally and can see the table column changes (but not on everytime I clean, load old app version, and perform migration).
How can I get something like this to work?  I would like to dynamically read the string and compute the correct it value. Right now I am setting it to 1 as a NSNumber.  I am not sure how to create a valid NSExpression for an int
Here is my Custom Policy :
@implementation MessageLabelMigration

- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)instance
                                  entityMapping:(NSEntityMapping *)mapping
                                        manager:(NSMigrationManager *)manager
                                          error:(NSError **)error {
    NSArray *_properties = [mapping attributeMappings];
    NSLog(@"_properties: %@", _properties);

    for (NSPropertyMapping *_property in _properties) {
        if ([[_property name] isEqualToString:@"label"]) {
            NSExpression *_expression = [NSExpression expressionForConstantValue:[NSNumber numberWithUnsignedShort:1]];
            [_property setValueExpression:_expression];
        }
    }

    return [super createDestinationInstancesForSourceInstance:instance
                                            entityMapping:mapping
                                                  manager:manager
                                                    error:error];
}

@end


text:
Q: Bitmapdata.draw(MovieClip) Gives Blank BitmapData I'm predrawing all vector element in my game to bitmaps to improve performance - the vector elements are exported as swf files from Illustrator (I suspect that is part of the problem).
When embedding the swf file in as3 like so:
[Embed(source = 'file.swf')] private static const image:Class;

And then adding it to the stage, like so
stage.addChild(new image);

Everything is fine, but if instead I draw it to a bitmap data like so...
genericBitmapData.draw(new image);

It's a blank bitmapdata. I've tried using gotoAndStop on frames 0 and 1 before drawing with no avail. Does anyone have experience with the swf files that Illustrator exports and any insight as to how I can get these drawing as expected?
Here is a link to a really simple .swf that produces the same results

A: Here's my revised solution:
//create movieclip
var mc:MovieClip = new image();
addEventListener(Event.ENTER_FRAME, enterFrameHandler);

//this gets called on next frame
function enterFrameHandler(event:Event):void
{
    removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
    genericBitmapData.draw(mc);
}

A: So it turns out that the object needs to be instantiated before I can use it to draw, and the easiest way to detect when that is is to listen for the ENTER_FRAME event:
(new image).addEventListener(Event.ENTER_FRAME, functionToDrawImage);

And when that function is called, it will be ready to draw to a bitmapdata, and then all is right with the world.


text:
Q: My view is not properly displaying data from the controller store as a javascript object I have this controller trying to pass pageHeader.title and pageHeader.strapline to a jade template view.
Here is the controller.
module.exports.homelist = function(req, res) {
    res.render('locations-list', {
     title: 'Loc8r - find a place to work with wifi',
     pageHeader: {
        title: 'Loc8r',
        strapline: 'Find places to work with wifi near you!'
     }
    });
};

Here is the part of the template that I need to update. (The jade template has given me problems through this whole app. Every little wrong space seems to completely mess it up)
block content
 #banner.page-header
  .row
   .col-lg-6
   h1= pageHeader.title
    small   #{pageHeader.strapline}

The pageHeader objects will not display properly.

A: In jade there are two possibilities that you getting an error,
Indentation and use of space and tab on same page
Maybe,
block content
  #banner.page-header
    .row
      .col-lg-6
        h1= pageHeader.title
          small   #{pageHeader.strapline}

Or need to use
  h1= locals.pageHeader.title

A: I have no idea what was wrong, but I deleted the comma after title: 'Loc8r...' line in the controller which broke the app. Then added it back and saved and voila works perfectly now. Jade gives me too many problems!


text:
Q: SQL select bottom half I want to select second half of records of my table. What I came up with is that:
select top 50 percent column1, column2 from
(
select top (select count(*) from myTable) column1, column2 from myTable
order by column1 desc
) s
order by column1

If I execute all but last line, it does work - it shows top half of records in a descend order, so what I need is to change again their order. Unfortunately, executing the last line makes the result totally different, i.e. top half taken right from original table.
What's wrong with that?

A: You need to do the 50% in the inner query:
select * from
(
select top 50 percent column1, column2 from myTable
order by column1 desc
) s
order by column1 asc


text:
Q: reference object attachement So i have an object which holds an attachment. this object is pretty much an invoice and has the option to be turned into a pdf document for printing purposes. the invoice will hold an image as an attachment within itself. now i need to figure out how to make the image show up on the pdf? the pdf is a visual force page with renderAs="pdf" on it i need to kno how to reference the attachment of any invoice object when i click the "Print PDF" button on any individual invoice.
Help Please

A: assuming there's only one Attachment related to the invoice, this will do the trick
<apex:page standardController="Invoice__c" renderAs="PDF">

  <apex:repeat value="{!Invoice__c.Attachments}" var="a">
     <apex:image
       height="200px"
       value="{!URLFOR($Action.Attachment.Download, a.Id)}"/>

     <apex:outputText value="{!a.Name}"/>

  </apex:repeat>

</apex:page>

A: In your visualforce page, you would simply need to make reference to the URL of the Image, for example:
<img src="/servlet/servlet.FileDownload?file=015b00000005mrz"/>

Where /servlet/servlet.FileDownload?file=015b00000005mrz is a reference to an Image stored as a Document within Salesforce.
You need to make sure your image is externally available I believe.


text:
Q: Как сделать, чтобы высота textarea уменьшалась при удалении текста? Я сделал код, который расширяет нижнюю границу при добавлении текста:
var textarea = document.querySelector('textarea');

textarea.addEventListener('keyup', function(){
  if(this.scrollTop > 0){
    this.style.height = this.scrollHeight + "px";
  }
});

Но обратное сделать не получается.

A: "keyup" не отработает, если вы с помощью контекстного меню (правой кнопкой мыши) вставите, скажем, текст в свой texatrea. Думаю, лучше подойдет event "input"
document.addEventListener('DOMContentLoaded', () => {
    const textarea = document.querySelector('#someArea');

    //Каждые 30 символов будем увеличивать\уменьшать высоту с шагом 20px
    const heightStep = 20, heightPerSymbols = 30;

    textarea.addEventListener('input', event =>
        event.currentTarget.style.height = (Math.ceil(event.currentTarget.value.length / heightPerSymbols) * heightStep) + 'px'
    );
})


text:
Q: Solution to differential equation $f^2(x) f''(x) = -x$ on [0,1] I'd like to solve a differential equation $$ f^2(x) f''(x)=-x $$ where $f(x)$ is defined on $[0,1]$ and has a boundary condition $f(0)=f(1)=0$.
I somehow found out that the solution is fairly close to $f(x) = x^{1/3} \phi^{2/3}(\Phi^{-1}(1-x))$ where $\phi$ and $\Phi$ are pdf and cdf of a standard normal distribution, but it fails to solve the differential equation exactly.

Thank for all comments!
Based on the solution structure of Emden–Fowler Equation, I was able to identify the values of constants that satisfy the boundary conditions. The followings are the details:
Define
\begin{equation}
 Z_R(\tau) \triangleq \sqrt{3} J_{1/3}(\tau) - Y_{1/3}(\tau)
 , \quad
 Z_L(\tau) \triangleq - \frac{2}{\pi} K_{1/3}(\tau)
\end{equation}
where $J, Y, K$ are Bessel functions.
Further define
\begin{equation}
 \bar{\tau} \triangleq \inf\{ \tau > 0; Z_R(\tau) = 0 \} \approx 2.3834
 , \quad
 a \triangleq \frac{1}{ \bar{\tau}^{4/3} Z_R'(\bar{\tau})^2 } \approx 0.2910
 , \quad
 b \triangleq a \left( \frac{9}{2} \right)^{1/3} \approx 0.1763.
\end{equation}
Then, the solution curve $\{ (x, f(x)) \}_{x \in [0,1]}$ is characterized by
\begin{equation}
 \left\{ \left( x_R(\tau), y_R(\tau) \right) \right\}_{\tau \in [0, \bar{\tau}]} \bigcup \left\{  \left( x_L(\tau), y_L(\tau) \right) \right\}_{\tau \in [0, \infty]}
\end{equation}
where
\begin{equation}
 x_R(\tau) \triangleq a \tau^{-2/3}\left[ \left( \tau Z_R'(\tau) + \frac{1}{3} Z_R(\tau) \right)^2 + \tau^2 Z_R(\tau)^2 \right]
 , \quad
 y_R(\tau) \triangleq b \tau^{2/3} Z_R(\tau)^2.
\end{equation}
\begin{equation}
 x_L(\tau) \triangleq a \tau^{-2/3}\left[ \left( \tau Z_L'(\tau) + \frac{1}{3} Z_L(\tau) \right)^2 - \tau^2 Z_L(\tau)^2 \right]
 , \quad
 y_L(\tau) \triangleq b \tau^{2/3} Z_L(\tau)^2.
\end{equation}

In addition to this analytic solution, I also obtained a numerical solution by repeatedly computing
$$ f_{k+1}(x) \gets \left[ \left( f_k(x-2h) + f_k(x+2h) \right) + 4 \left(f_k(x-h)+f_k(x+h)\right) + \frac{8 x h^2}{f_k^2(x)} \right] \big/ 10 $$
on the grid $x \in \{2h,3h,\ldots,1-3h,1-2h\}$ for small $h$ with an initialization $f_0(x) \triangleq 0.5(1-(1-2x)^2)$.
The following figure shows these solutions:

A: I tried the following approach.  Put $y=f(x)$ and $t=2x-1$ so the differential equation becomes $y^2\ddot{y}=-(t+1)/8$ with boundary conditions $y=0$ at $t=\pm 1$.  We can then write $y=\sum_ia_it^i$.  The differential equation gives a recurrence relation expressing all the coefficients $a_i$ in terms of $a_0$ and $a_1$.  We can then truncate the power series to a given order $d$ and solve numerically for the boundary conditions.  This seems to work in a well-behaved way, with good convergence at the endpoints and a result that is stable when we increase $d$.  It looks like $a_0=0.450$ and $a_1=0.120$ to $3$ decimal places.  Maple code is as follows:
with(plots):
Digits := 50:
d := 50:
y := add(a[i] * t^i,i=0..d):
sol0 := solve([coeffs(rem(expand(y^2 * diff(y,t,t) + (t+1)/8),t^(d-1),t),t)]
              {seq(a[i],i=2..d)}):
y0 := expand(subs(sol0,y)):
sol1 := fsolve({subs(t= 1,y0),subs(t=-1,y0)},{a[0]=0.45,a[1]=0.1}):
aa[d] := subs(sol1,[a[0],a[1]]);
y1 := subs(sol1,y0);
y1x := subs(t = 2*x-1,y1):
Phi := unapply((1 + erf(x))/2,x):
phi := unapply(diff(Phi(x),x),x):
display(
 plot(y1x,x=0..1,colour=red),
 plot(x^(1/3) * phi(RootOf(1-x-Phi(_Z)))^(2/3),x=0..1,colour=blue)
);

This generates the following picture.  The power series solution is in red and the function $x^{1/3}\phi(\Phi^{-1}(1-x))^{2/3}$ is in blue.

The coefficients $a_{2i}$ lie on a nice smooth curve, and the coefficients $a_{2i+1}$ lie on a similar curve shifted down slightly.  Logs of the absolute values can be displayed as follows:
display(
  listplot([seq(log(-coeff(y1,t,2*i)),i=3..(d-1)/2)],style=point,colour=red),
  listplot([seq(log(-coeff(y1,t,2*i+1)),i=3..(d-1)/2)],style=point,colour=blue)
);

One could probably get further by finding an exact or approximate formula for these curves.

A: Surprisingly, this case of the Emden-Fowler equation is explicitly solvable:
see formula (2.3.27) in A. Polyanin and V. Zaitsev, Handbook of exact solutions
of ordinary differential equations, Chapman & Hill, 2003.
I copy the formula, without verifying it. Let
$$Z=C_1J_{1/3}(\tau)+C_2Y_{1/3}(\tau),$$
or
$$Z=C_1I_{1/3}(\tau)+C_2K_{1/3}(\tau),$$
where $J,Y$ are Bessel and $I$, $K$ are modified Bessel functions.
Then
$$x=a\tau^{-2/3}[(\tau Z^\prime+(1/3)Z)^2\pm\tau^2Z^2],\quad y=b\tau^{2/3}Z^2$$
satisfy $d^2y/dx^2=Axy^{-2}$ with $A=-(9/2)(b/a)^3.$
For the $+$ sign in $\pm$ take the first formula for $Z$, and for the $-$ the second one.
Remark. Emden-Fowler equation appears for the first time in the famous book by R. Emden, Gaskugeln (1907) and since then frequently arises in the study of stars and black holes.


text:
Q: How can I set a thread to end only when another threads are running? I created 44 threads with only 6 threads running in the same time and I want thread 13 to end only when the value of the semaphore is 0 (another 5 threads are running). I tried with a condition variable something like this:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <fcntl.h>
int curr_threads = 0;
int sem_id;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t end13 = PTHREAD_COND_INITIALIZER;

void P(int sem_id){
    struct sembuf semaphore_op = {0, -1, 0};
    semop(sem_id, &semaphore_op, 1);
}

void V(int sem_id){
    struct sembuf semaphore_op = {0, 1, 0};
    semop(sem_id, &semaphore_op, 1);
}

void* thread_func(void* arg) {
    P(sem_id);
    pthread_mutex_lock(&mutex);
    curr_threads++;
    if(curr_threads == 6) pthread_cond_signal(&end13);
    pthread_mutex_unlock(&mutex);
    int* thread_nr = (int*) arg;
    if(*thread_nr == 13) {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&end13, &mutex);
        pthread_mutex_unlock(&mutex);
    }
    pthread_mutex_lock(&mutex);
    curr_threads--;
    pthread_mutex_unlock(&mutex);
    V(sem_id);
    return (void*) 0;
}
int main(int argc, char** argv) {
    sem_id = semget(1234, 1, IPC_CREAT | 0600);
    pthread_t threads[44];
    semctl(sem_id, 0, SETVAL, 6);
    int aux[44];
    for(int i = 0; i < 44; i++) {
        aux[i] = i + 1;
    }

    for(int i = 0; i < 44; i++) {
        pthread_create(&threads[i], NULL, thread_func, &aux[i]);
    }

    for(int i = 0; i < 44; i++) {
        pthread_join(threads[i], NULL);
    }
    exit(0);
}

But it doesn`t work. Any suggestions?

A: if(*thread_nr == 13) {
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&end13, &mutex);
    pthread_mutex_unlock(&mutex);
}

Condition variables are stateless and require you to use their associated mutex to protect the state. The mutex doesn't protect anything here, so you aren't waiting for anything. You will never get a condition variable to work correctly this way.
Your code is most likely failing because this thread is calling pthread_cond_wait even when there is nothing to wait for, and so it waits forever. You acquired the mutex to check the shared state, but then you didn't do that.
You need to either not use condition variables or learn how they work. In particular, you must understand that fundamentally they provide an atomic "unlock and wait" operation to avoid a race condition where you wait for something that has already happened.
Reading this question and its answers may help.


text:
Q: Call to a non-object workaround? I have a method like this:
public function query ($sql) {
  $this->result = $this->db->query($sql);
}

Binds the query statement to the result variable. This is really handy because I have several methods that output something and another method that then handles the $result variable for other tasks.
However I wanted to use the same kind of method, but on prepared statements(to escape data that gets inserted) and I ran into a problem:
public function prepare ($sql) {
  $this->result = $this->db->prepare($sql);
}

I tried to use it like this:
public function insert ($this, $that) {
  // Then I tried to use my prepare method
  $var = $this->prepare(INSERT INTO Table (Row1, Row2) VALUES (:Val1, :Val2));
  $var->bindValue(":Val1", $this, PDO::PARAM_INT);
  //... and so on
}

The problem shows up on the $var->bindValue() "Call to a member function bindvalue() on a non-object". What is exactly happening here because I don't really understand the error message? If I query my db using the query method it works just fine, but how can I bind values using the prepare method?

A: In:
public function ($sql) {
  $this->result = $this->db->prepare($sql);
}

You forget to return the result. (You also forgot the name of the function in the snippet.)
The error message is quite clear, you're calling a method on something that's not an object. In this case you're calling it on NULL because your own prepare-method doesn't return anything.

A: first off i noticed your methods don't have a name.
public function ($sql) {
  $this->result = $this->db->query($sql);
}
shouldn't it be something like
public function doSomething($sql) {
  $this->result = $this->db->query($sql);
}
secondly, it seems you are calling an instance of another class in your method.
$this->db->query($sql)
if am not wrong the 'db' should be anothe class that you are trying to access its query method...Look at your code again.
Lastly i you are missing a return statement.


text:
Q: Android application Services for notification I've read that services are used to be able to run app on background. I'm planning to have a notifications using this. How should I start? I'm using Xamarin.Android
Sample codes could be helpful

A: In Xamarin.com you can found anything you need to know about backgrounding.
For examples you can look here, tutplus is not free but they give a free trial which is enough for what you need.


text:
Q: Azure DevOps Stage Permissions I have created a release pipeline with multiple stages. Now I would like on users form the Release Manager group or Project Administrators group to be able to deploy some of these stages.
I have tried to denied "Manage Deployments" to the other groups but it seems as soon as Contributors lose this, no one, not even members of the above groups with the permission set to Allow can deploy the stage anymore. BTW, members of the allowed groups are also members of Contributors.
I tried both just updating the permission and removing Inherited permissions and then removing the permission for those groups and still no go.
Is there any way to remove this permission from Contributors but sill allow members of Contributors + Release Manager + Project Managers to deploy?
Thank you

A:
Is there any way to remove this permission from Contributors but sill allow members of Contributors + Release Manager + Project Managers to deploy?

I could reproduce the scene you mentioned. It seems that the permissions of the Contributors group will override the permissions of the other two groups.
To solve this issue, you could set the Manage Deployments as Not Set instead of Deny. At the same time, you need the disable Inheritance option.
Note: If you set Not Set, people in the contributor group cannot deploy, but if some of them are in other groups with this permission, they will inherit the permissions from other groups


text:
Q: INF files for multiple OS's I am trying to edit an INF file for a cypress controller to include more information for 64 bit OS as well a 32 bit. The current INF file is as follows which is only for 32bit, I want to  edit it to work for a 64 bit Win7 OS as well.
[DestinationDirs]
USB.Files.Ext = 10,System32\Drivers ;10 = Windows Directory

[USB.Dev]
CopyFiles=USB.Files.Ext
AddReg=USB.AddReg

[USB.Dev.HW]
AddReg=USB.AddReg.Guid

[USB.Dev.NT]
CopyFiles=USB.Files.Ext
AddReg=USB.AddReg

[USB.Dev.NT.HW]
AddReg=USB.AddReg.Guid

[USB.Dev.NT.Services]
Addservice = USB, 0x00000002, USB.AddService

[USB.AddService]
DisplayName    = %USB.SvcDesc%
ServiceType    = 1                  ; SERVICE_KERNEL_DRIVER
StartType      = 3                  ; SERVICE_DEMAND_START
ErrorControl   = 1                  ; SERVICE_ERROR_NORMAL
ServiceBinary  = %10%\System32\Drivers\USB.sys
LoadOrderGroup = Base

[USB.AddReg]
HKR,,DevLoader,,*ntkern
HKR,,NTMPDriver,,USB.sys

[USB.Files.Ext]
USB.sys

[USB.AddReg.Guid]
;HKR,,DriverGUID,,%USB.GUID%

I am totally new with INF files what does [USB.Dev], [USB.Dev.NT], etc mean? And how do I edit this INF to include 64bit Win7 OS as well. Please guide me through.


text:
Q: C++ gives random value when combining chars I have a string 039 and i have this following code
cout<<str2[1]+str2[0]+str2[2]<<endl;

I expect this to give me 309,but it gives me 156.How is that considering that separately all they give me  3 0 9?

A: It is because you are summing the characters / their underlying integral values together. If you want to output the characters themselves use the << operator, not the +. The characters and their underlying values are (assuming ASCII):
'3'    51
'0'    48
'9'    57

The expression of:
str2[1] + str2[0] + str2[2]

sums the characters together, it does not send them to standard output one by one, so the expression becomes:
51 + 48 + 57

resulting in 156. Use the operator<< instead:
#include <iostream>
#include <string>

int main() {
    std::string str2 = "039";
    std::cout << str2[1] << str2[0] << str2[2] << '\n';
}

As pointed out in the comments, character types are integral types and your char type probably covers the range from -127 to 127. This also assumes you are using ASCII encoding which maps the characters to values given above.

A: If str2[1] is char, then:
Char is just like int, but from -127 to 127(or 0 to 255). See ASCII codes.
Then if you do str2[1]+str2[0]+str2[2], you will get some ASCII code.
In c++ you can't do char+char and get 2 chars.
Do this:
cout<<str2[1]<<str2[0]<<str2[2]<<endl;

A: If you need retrieve result as a string use ostringstream :
#include <sstream>
std::ostringstream stream;
stream << str2[1] << str2[0]<< str2[2];
std::string res = stream.str();
std::cout <<"> " << res << std::endl;


text:
Q: Sorting associated products (configurable) in 1.9.2 I have Magento 1.9.2 and a configurable product with size options (S,M,L,XL) those options are associated simple products. At the moment Magento is sorting the options by ID. Is there anyway to sort by a specified order that I give?
Thank you very much

A: Last column on associated products is used for sorting. Called position


text:
Q: VB.net - Mousehover not sensitive I made picturebox which would change if the mover is over the image but it takes too long. can someone help me please?
Here's my code:
Private Sub button2_MouseHover(sender As Object, e As EventArgs) Handles button2.MouseHover
        button1.Visible = True
        button2.Visible = False
    End Sub

    Private Sub button1_MouseLeave(sender As Object, e As EventArgs) Handles button1.MouseLeave
        button1.Visible = False
        button2.Visible = True
    End Sub

Thanking you in advance

A: If you want to adjust the time the mouse must pause over the image, the docs say;

A typical use of MouseHover is to display a tool tip when the mouse pauses on a control within a specified area around the control (the "hover rectangle"). The pause required for this event to be raised is specified in milliseconds by the MouseHoverTime property.

To achieve that, simply change the value of SystemInformation.MouseHoverTime in your code.
Alternatively, as someone has commented, use a MouseEnter event instead, this will trigger instantly.


text:
Q: Trying to send image from QThread to main or other thread in PyQt I am trying to display an image from another thread in the main thread or possibly even a new thread. The problem is I cannot get the image to show anywhere else. I am using the thread _thread to download the image so it won't freeze the gui but I can't seem to get it out of there properly using QImage or QPixmap.
I know how to use strings and such in signals as shown in the example below but I am not sure how to send the image in a signal properly. I have tried using requests to grab an image url and send it to the main which works but I wasn't able to fetch the string in the main and then just download it there real fast either. That also is not a good option due to freezing the GUI momentarily.
This code is an example that shows that I can do all of the work and download the image in the main if I want to but would rather not.
import urllib2
from PyQt4 import QtGui
from PyQt4.QtCore import QThread, pyqtSignal
from PyQt4.QtGui import QApplication, QPixmap
import sys

class MainWindow(QtGui.QWidget):
    def __init__(self):
        super(self.__class__, self).__init__()
        layout = QtGui.QVBoxLayout(self)
        self._Button = QtGui.QPushButton()
        self._Button.setObjectName("_Button")
        self.line_edit = QtGui.QLineEdit()
        self.line_edit.setObjectName("line_edit")
        self.txt_box = QtGui.QTextEdit()
        self.txt_box.setObjectName("txt_Box")
        self.img_label = QtGui.QLabel()
        self.img_label.setObjectName("img_label")
        layout.addWidget(self._Button)
        layout.addWidget(self.line_edit)
        layout.addWidget(self.img_label)
        layout.addWidget(self.txt_box)

        self.pixmap = QPixmap()
        self._thread = test_thread()
        self._Button.clicked.connect(self.start_thread)
        self.get_Text = self._thread.test_Signal.connect(self.line_edit.setText)

        self.urls = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png'
        data = urllib2.urlopen(self.urls).read()
        self.pixmap.loadFromData(data)
        self.img_label.setPixmap(self.pixmap)

    def start_thread(self):
        self._thread.start()
        self._thread.test_Signal.connect(self.txt_box.setText)

class test_thread(QThread):
    test_Signal = pyqtSignal(str)
    def __init__(self):
        super(test_thread, self).__init__()

    def run(self):
        string = 'This is a test string.'
        self.test_Signal.emit(string)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())

And this code shows more of what I am looking to do.
import urllib2
from PyQt4 import QtGui
from PyQt4.QtCore import QThread, pyqtSignal
from PyQt4.QtGui import QApplication, QPixmap
import sys

class MainWindow(QtGui.QWidget):
    def __init__(self):
        super(self.__class__, self).__init__()
        layout = QtGui.QVBoxLayout(self)
        self._Button = QtGui.QPushButton()
        self._Button.setObjectName("_Button")
        self.line_edit = QtGui.QLineEdit()
        self.line_edit.setObjectName("line_edit")
        self.txt_box = QtGui.QTextEdit()
        self.txt_box.setObjectName("txt_Box")
        self.img_label = QtGui.QLabel()
        self.img_label.setObjectName("img_label")
        layout.addWidget(self._Button)
        layout.addWidget(self.line_edit)
        layout.addWidget(self.img_label)
        layout.addWidget(self.txt_box)

        self.pixmap = QPixmap()
        self._thread = test_thread()
        self._Button.clicked.connect(self.start_thread)
        self.get_Text = self._thread.test_Signal.connect(self.line_edit.setText)

    "...Send signal here and show image. EX:"
    "...self._thread.image_Signal.connect(self.img_label.setPixmap)...."
    "...or...."
    def show_image_here(self):
        "....Send image here after downloaded in thread...."

    def start_thread(self):
        self._thread.start()
        self._thread.test_Signal.connect(self.txt_box.setText)

class test_thread(QThread):
    test_Signal = pyqtSignal(str)

    "....Example image signal...."
    "....image_Signal = pyqtSignal()...."

    def __init__(self):
        super(test_thread, self).__init__()
        self.pixmap = QPixmap()

    def run(self):
        string = 'This is a test string.'
        self.test_Signal.emit(string)

        self.urls = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png'
        data = urllib2.urlopen(self.urls).read()
        self.pixmap.loadFromData(data)
        "....Not sure what to do here...."

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())

Can somebody help me out? Thanks.

A: After looking around some more I came across this thread PySide threading and http downloading
I wish I had found it sooner because I did a lot of searching before my post. The person who answered that thread reclosedev also posted this in the comments:
https://pastebin.com/b4MD5jKh
Which helped me immensely to understand some things better. I used his code and slightly altered it to fit mine and it will work great for what I would like to do.
Here is my full working code using my original example for anyone out there that may find it useful.
import urllib2
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QThread, pyqtSignal
from PyQt4.QtGui import QApplication
import sys

class MainWindow(QtGui.QWidget):
    def __init__(self):
        super(self.__class__, self).__init__()
        layout = QtGui.QVBoxLayout(self)
        self._Button = QtGui.QPushButton()
        self._Button.setObjectName("_Button")
        self.line_edit = QtGui.QLineEdit()
        self.line_edit.setObjectName("line_edit")
        self.txt_box = QtGui.QTextEdit()
        self.txt_box.setObjectName("txt_Box")
        self.img_label = QtGui.QLabel()
        self.img_label.setObjectName("img_label")
        self.imagepreview = ImagePreview()
        layout.addWidget(self._Button)
        layout.addWidget(self.line_edit)
        layout.addWidget(self.img_label)
        layout.addWidget(self.txt_box)
        layout.addWidget(self.imagepreview)

        self._thread = test_thread()
        self._Button.clicked.connect(self.start_thread)
        self._Button.clicked.connect(self.imagepreview.startDownload)
        self.get_Text = self._thread.test_Signal.connect(self.line_edit.setText)

    def start_thread(self):
        self._thread.start()
        self._thread.test_Signal.connect(self.txt_box.setText)

class test_thread(QThread):
    test_Signal = pyqtSignal(str)

    def __init__(self):
        super(test_thread, self).__init__()

    def run(self):
        string = 'This is a test string.'
        self.test_Signal.emit(string)

class DownloadThread(QtCore.QThread):
    data_downloaded = pyqtSignal()

    def __init__(self, url):
        QtCore.QThread.__init__(self)
        self.url = url
        self._data = None

    def run(self):
        self._data = urllib2.urlopen(self.url).read()
        self.data_downloaded.emit()

    def get_data(self):
        return self._data

class ImagePreview(QtGui.QWidget):
    def __init__(self, parent=None):
        super(ImagePreview, self).__init__(parent)
        self.setMinimumSize(50, 50)
        self.pixmap = None

    def paintEvent(self, paintEvent):
        painter = QtGui.QPainter(self)
        if (self.pixmap):
            painter.drawPixmap(0, 0, self.pixmap)

    def startDownload(self):
        self.download_thread = DownloadThread('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png')
        self.download_thread.start()
        self.download_thread.data_downloaded.connect(self.ondownloadFinished)

    def ondownloadFinished(self):
        self.paintImage()
        print("download finished")

    def paintImage(self):
        print("Painting")
        pixmap = QtGui.QPixmap()
        pixmap.loadFromData(self.download_thread.get_data())
        self.setPixmap(pixmap)

    def setPixmap(self, pixmap):
        self.pixmap = pixmap
        self.setMinimumSize(pixmap.width(), pixmap.height())
        self.update()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())


text:
Q: Spring Boot and FlywayTest cause JPA Camel routes to throw exceptions during database reset I have a Spring Boot application that contains a Camel route with a JPA consumer.
When running a test that uses the @FlyTest annotation the database is reset as expected prior to the test but while this is happening the Camel JPA consumer tries to execute an SQL select against the database.
How do I disable the route while FlywayTest is resetting the database?
Any suggestions are appreciated.

A: I worked around the problem by setting consumer.initialDelay=5000 which was sufficient to allow Flyway to reset the DB.

A: A more robust approach to solving this was to suspend the Camel routes in my tests by using:
@Autowired
CamelContext camelContext;

@Before
public void init() throws Exception {
    camelContext.suspend();
}

A: In Camel 2.15 (current master branch) I recently delayed CamelContext startup. The routes should not be started so early then. Therefore the routes should not consume from JPA too early as well.
If you still experience this issue - feel free to drop me a line. I will fix it.

A: I configured my application to start all Camel routes after the Flyway migration is complete. This proved very important on slow machines or large databases where the migration could be very slow.
@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) throws Exception {
        new SpringApplication((Object[])args).run();
    }

    @Bean
    @DependsOn({"flyway","dataSource"})
    CamelContext camelContext(ApplicationContext applicationContext,
                              CamelConfigurationProperties configurationProperties) {
        CamelContext camelContext = new SpringCamelContext(applicationContext);
        SpringCamelContext.setNoStart(true);

        if (!configurationProperties.isJmxEnabled()) {
            camelContext.disableJMX();
        }

        if (configurationProperties.getName() != null) {
            ((SpringCamelContext) camelContext).setName(configurationProperties.getName());
        }

        camelContext.setAutoStartup(false);

        return camelContext;
    }

    @Bean
    FlywayCallback flywayCallback(Flyway flyway, final CamelContext camelContext) {
        FlywayCallback callback = new FlywayCallback() {

            @Override
            public void beforeClean(Connection connection) {}
            @Override
            public void afterClean(Connection connection) {}
            @Override
            public void beforeMigrate(Connection connection) {}
            @Override
            public void afterMigrate(Connection connection) {
                try {
                    camelContext.startAllRoutes();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("Camel startup failed", e);
                }
            }
            @Override
            public void beforeEachMigrate(Connection connection,
                    MigrationInfo info) {}
            @Override
            public void afterEachMigrate(Connection connection,
                    MigrationInfo info) {}
            @Override
            public void beforeValidate(Connection connection) {}
            @Override
            public void afterValidate(Connection connection) {}
            @Override
            public void beforeBaseline(Connection connection) {}
            @Override
            public void afterBaseline(Connection connection) {}
            @Override
            public void beforeInit(Connection connection) {}
            @Override
            public void afterInit(Connection connection) {}
            @Override
            public void beforeRepair(Connection connection) {}
            @Override
            public void afterRepair(Connection connection) {}
            @Override
            public void beforeInfo(Connection connection) {}
            @Override
            public void afterInfo(Connection connection) {}
        };
        flyway.setCallbacks(callback);
        return callback;
    }

}


text:
Q: Show deprecation error when tags account has only one image with instagram api I use this URL to get images from Instagram:
https://api.instagram.com/v1/tags/tag_name/media/recent?access_token=AccessToken

I can retrieve successfully when tags account has many photos.
But when I use my testing account which has only one profile image. I got this error.
{
    "data":[],
    "pagination":{"deprecation_warning":"next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead"},
    "meta":{"code":200}
}

I tried by adding parameters min_tag_id and max_tag_id in the URL but it doesn't work. And I tried all urls of tags from instagram developer website.
Can anyone help me?
I'm really glad if you help me. Thanks in advance.


text:
Q: Как обработать исключение reflect.InvocationTargetException? При попытке вызвать search при незаполненных полях EditText, программа вылетает с ошибкой Caused by: java.lang.reflect.InvocationTargetException.
При попытке обработать эту ошибку в catch, студия пишет, что эту ошибку нельзя обработать в try-catch, поскольку она к ней не относится. Это, конечно, правильно, так и есть, но как же всё-таки можно её перехватить при незаполненных EditText и написать юзеру типа "поля то заполни!"?
Вот для наглядности кусок кода:
public void search (View view) {

        String value = edit.getText().toString();
        letters = Integer.parseInt(value);
        String value2 = editTextQplace1.getText().toString();
        mesto1in = Integer.parseInt(value2);

......
}

Полный текст ошибки:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: ru.golgofa.wordfinder, PID: 26849
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
        at android.view.View.performClick(View.java:6294)
        at android.view.View$PerformClick.run(View.java:24770)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:6294)
        at android.view.View$PerformClick.run(View.java:24770)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.NumberFormatException: For input string: ""
        at java.lang.Integer.parseInt(Integer.java:620)
        at java.lang.Integer.parseInt(Integer.java:643)
        at ru.golgofa.wordfinder.MainActivity.search(MainActivity.java:87)


text:
Q: Replace URL Path Keeping Only Last Part - DB Query We have multiple URL's in the database like:
http://www.example.com/_73737337/dir1/dir2/image.jpg
http://www.example.com/_892/direc/picture.png
http://www.example.com/_029929292929/dir/did/dic/dif/gallery.gif

All different length paths, different directories etc.  What I need is to keep the file name at the end and replace everything before it with a new domain and directory.
For example:
http://www.example.com/_73737337/dir1/dir2/image.jpg

Will become:
http://www.newexample.com/images/image.jpg

AND
http://www.example.com/_029929292929/dir/did/dic/dif/gallery.gif

Will become:
http://www.newexample.com/images/gallery.gif

Is there any way to do this via a query to the database?  There are around 3000 URLs to update.
These URLs sit inside content and not standalone entries in the database.  So the query has to pick them out of the content field and ignore the rest of the content.

A: You could use SUBSTRING_INDEX() with '/' as the delimiter.
Example
SELECT SUBSTRING_INDEX(image_url, '/', -1) AS filename
FROM table_name

Here is a link to the docs for the function:
https://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php


text:
Q: Questions regarding the submodules of a $\mathbb{F}[X]$-module Let $\mathbb{F}$ be a field and $U= \mathbb{F}^2$. U is equipped with a $\mathbb{F}[X]$-module taking the endomorphism $f : U \to U$ given by the matrix
$F =
\begin{bmatrix}
0 & -2\\
2 & 3
\end{bmatrix}$.
Find all the sub-$\mathbb{F}[X]$-modules of $V$.
I know how to solve the exercise but still have some issues understanding the whole concept of $\mathbb{F}[X]$-module.
In this example we take
$\mathbb{F} = \mathbb{R}$.
First I will write down the solution.
Let $W$ be a submodule. It's a vectorial space since $U$ is one.
We try to find the submodules by analyzing the dimension of $W$. If $\dim_{\mathbb{R}}W = 1$, then we can write $W = \text{span}(w)$ (Thus $W$ is generated by one single vector)
Let's find the eigenvalues of $f$. After some calculations we find the characteristic polynomial $-3X + X^2 + 4$ which has no roots in $\mathbb{R}$ since $\Delta < 0$. So $f$ has no eigenvalues which leads to the conclusion that there is no $W$ such that $\dim_{\mathbb{R}}W = 1$.
The only submodules of $U$ as a $\mathbb{R}[X]$-module are $(0)$ and $U$ itself.
As I said, I understand the steps in the solutions but I still don't really understand why we have this endomorphism and why it's given by a matrix $F$.


text:
Q: Adding Items to top of listview with checkbox I have a code here that allows me to add items to the top. If I had 5 items,the way it would work is like this.
0 New Item

1

2

3

4 First item

Then if something is new is added it becomes this.
0 New Item

1

2

3

4

5 First Item

As you can see,whenever a new item is added,it become position 0. This is a problem because if I set a checkbox on that's on position 0 and then a new item is added,the new item becomes position 0 which checks the new item and unchecks the item that was there before.
I want it to work like this while still add items to the top.
4 New item

3

2

1

0 First Item

When a new item is added.
5 New Item

4

3

2

1

0 First Item

Here is my ListView Adapter.
public class TweetArrayAdapter extends ArrayAdapter<Object> implements OnClickListener {

    TweetList tweetMessageObj;
    ViewHolder holder = null;

    public List<TweetList> tweetList = new ArrayList<TweetList>();

    public void add(TweetList object,int position) {
        tweetList.add(position,object);

    }

    public TweetArrayAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    public int getCount() {
        return this.tweetList.size();
    }

    public TweetList getItem(int position) {
        return tweetList.get(position);
    }

    @SuppressLint("ViewHolder")
    public View getView(final int position, View convertView, ViewGroup parent) {
        View row = convertView;
            tweetMessageObj = getItem(position);

            if(convertView == null){

            LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.tweet_list_item, parent, false);
            holder = new ViewHolder();
            holder.twitterUser = (TextView)row.findViewById(R.id.display_name);
            holder.tweet = (TextView) row.findViewById(R.id.display_tweet);
            holder.twitterMention = (TextView)row.findViewById(R.id.display_twitter_mentionname);
            holder.profile_picture = (ImageView)row.findViewById(R.id.profile_picture);
            holder.tweet_picture = (ImageView)row.findViewById(R.id.tweet_image);
            holder.padding = (View)row.findViewById(R.id.view1);
            holder.favorite = (CheckBox)row.findViewById(R.id.favorite_button);
            //holder.retweet = (CheckBox)row.findViewById(R.id.retweet_button);
            //holder.reply = (CheckBox)row.findViewById(R.id.reply_button);

            holder.favorite.setTag(holder);

             row.setTag(holder);
            }else{
                holder = (ViewHolder)row.getTag();
            }

            SpannableString hashtag = new SpannableString(tweetMessageObj.tweet);
            Matcher matcher = Pattern.compile("@([A-Za-z0-9_-]+)").matcher(hashtag);
            Matcher matcher2 = Pattern.compile("#([A-Za-z0-9_-]+)").matcher(hashtag);
            while (matcher.find())
            {
                hashtag.setSpan(new ForegroundColorSpan(Color.rgb(79, 120, 216)), matcher.start(), matcher.end(), 0);
                hashtag.setSpan(new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        // TODO Auto-generated method stub
                         TextView tv = (TextView)widget;
                         String tags = tv.getText().subSequence(tv.getSelectionStart(),tv.getSelectionEnd()).toString();
                         Toast.makeText(getActivity(), tags,  Toast.LENGTH_LONG).show();
                    }
                    public void updateDrawState(TextPaint ds) {// override updateDrawState
                           ds.setUnderlineText(false); // set to false to remove underline
                        }
                },matcher.start(), matcher.end(), 0);
            }
            while (matcher2.find())
            { hashtag.setSpan(new ForegroundColorSpan(Color.rgb(79, 120, 216)), matcher2.start(), matcher2.end(), 0);
                hashtag.setSpan(new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        // TODO Auto-generated method stub
                        TextView tv = (TextView)widget;
                         String tags = tv.getText().subSequence(tv.getSelectionStart(),tv.getSelectionEnd()).toString();
                         Toast.makeText(getActivity(), tags,  Toast.LENGTH_LONG).show();
                    }
                    public void updateDrawState(TextPaint ds) {// override updateDrawState
                           ds.setUnderlineText(false); // set to false to remove underline
                        }
                },matcher2.start(), matcher2.end(), 0);
            }
            holder.tweet.setText(hashtag, BufferType.SPANNABLE);
            holder.tweet.setMovementMethod(LinkMovementMethod.getInstance());
            holder.tweet.setHighlightColor(Color.TRANSPARENT);
            if(tweetMessageObj.tweet.isEmpty()){
                holder.tweet.setVisibility(View.GONE);
            }
            Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "fonts/light.ttf");
            holder.tweet.setTypeface(tf);
            Typeface tf2 = Typeface.createFromAsset(getActivity().getAssets(), "fonts/bold.ttf");
            holder.twitterUser.setText(tweetMessageObj.twittername);
            holder.twitterUser.setTypeface(tf2);
            holder.twitterMention.setText("@" + tweetMessageObj.mentionname);

            Picasso.with(getActivity()).load(tweetMessageObj.pictureURL).into(holder.profile_picture);
            if(tweetMessageObj.tweetPictureUrl != null){
                holder.tweet_picture.setVisibility(View.VISIBLE);
                holder.padding.setVisibility(View.VISIBLE);
                Picasso.with(getActivity()).load(tweetMessageObj.tweetPictureUrl).into(holder.tweet_picture);
            }else{
                holder.tweet_picture.setVisibility(View.GONE);
                holder.padding.setVisibility(View.GONE);
            }

        return row;
    }

}

public static class ViewHolder{
    TextView tweet,twitterUser,twitterMention;
    ImageView profile_picture,tweet_picture;
    CheckBox reply,retweet,favorite;
    View padding;
    boolean isFavorited = false;
}

TweetList
public class TweetList {
    public String twittername,mentionname,tweet,pictureURL,tweetPictureUrl;
    long status_id;

    public TweetList(long status_id,String twittername,String mentionname,String tweet,String pictureURL) {
        super();
        this.status_id = status_id;
        this.twittername = twittername;
        this.tweet = tweet;
        this.pictureURL = pictureURL;
        this.mentionname = mentionname;

    }
    public TweetList(long status_id,String twittername,String mentionname,String tweet,String pictureURL,String tweetPictureUrl) {
        super();
        this.status_id = status_id;
        this.twittername = twittername;
        this.tweet = tweet;
        this.pictureURL = pictureURL;
        this.mentionname = mentionname;
        this.tweetPictureUrl = tweetPictureUrl;

    }

}

A: isFavorited is information that should be inside TweetList.
In this way in getView you can update the value of the CheckBox.
holder.favorite.setChecked(tweetMessageObj.isFavorited);

A: Try this way,hope this will help you to solve your problem.
TweetList.java
public class TweetList {
    public String twittername;
    public String mentionname;
    public String tweet;
    public String pictureURL;
    public String tweetPictureUrl;
    public long status_id;
    public boolean isFavourite;
    public TweetList(long status_id,String twittername,String mentionname,String tweet,String pictureURL,boolean isFavourite) {
        this.status_id = status_id;
        this.twittername = twittername;
        this.tweet = tweet;
        this.pictureURL = pictureURL;
        this.mentionname = mentionname;
        this.isFavourite = isFavourite;
    }
    public TweetList(long status_id,String twittername,String mentionname,String tweet,String pictureURL,String tweetPictureUrl,boolean isFavourite) {
        this.status_id = status_id;
        this.twittername = twittername;
        this.tweet = tweet;
        this.pictureURL = pictureURL;
        this.mentionname = mentionname;
        this.tweetPictureUrl = tweetPictureUrl;
        this.isFavourite = isFavourite;
    }
}

TweetArrayAdapter.java
public class TweetArrayAdapter extends BaseAdapter {

    private Context context;
    public List<TweetList> tweetList;

    public void add(TweetList object,int position) {
        tweetList.add(position,object);

    }

    public TweetArrayAdapter(Context context) {
        this.context=context;
        tweetList = new ArrayList<TweetList>();
    }

    public int getCount() {
        return this.tweetList.size();
    }

    public TweetList getItem(int position) {
        return tweetList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.tweet_list_item, null);
            holder = new ViewHolder();
            holder.twitterUser = (TextView)convertView.findViewById(R.id.display_name);
            holder.tweet = (TextView) convertView.findViewById(R.id.display_tweet);
            holder.twitterMention = (TextView)convertView.findViewById(R.id.display_twitter_mentionname);
            holder.profile_picture = (ImageView)convertView.findViewById(R.id.profile_picture);
            holder.tweet_picture = (ImageView)convertView.findViewById(R.id.tweet_image);
            holder.padding = (View)convertView.findViewById(R.id.view1);
            holder.favorite = (CheckBox)convertView.findViewById(R.id.favorite_button);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder)convertView.getTag();
        }

        SpannableString hashtag = new SpannableString(tweetList.get(position).tweet);
        Matcher matcher = Pattern.compile("@([A-Za-z0-9_-]+)").matcher(hashtag);
        Matcher matcher2 = Pattern.compile("#([A-Za-z0-9_-]+)").matcher(hashtag);
        while (matcher.find())
        {
            hashtag.setSpan(new ForegroundColorSpan(Color.rgb(79, 120, 216)), matcher.start(), matcher.end(), 0);
            hashtag.setSpan(new ClickableSpan() {

                @Override
                public void onClick(View widget) {
                    TextView tv = (TextView)widget;
                    String tags = tv.getText().subSequence(tv.getSelectionStart(),tv.getSelectionEnd()).toString();
                    Toast.makeText(context, tags, Toast.LENGTH_LONG).show();
                }
                public void updateDrawState(TextPaint ds) {// override updateDrawState
                    ds.setUnderlineText(false); // set to false to remove underline
                }
            },matcher.start(), matcher.end(), 0);
        }
        while (matcher2.find())
        { hashtag.setSpan(new ForegroundColorSpan(Color.rgb(79, 120, 216)), matcher2.start(), matcher2.end(), 0);
            hashtag.setSpan(new ClickableSpan() {

                @Override
                public void onClick(View widget) {
                    TextView tv = (TextView)widget;
                    String tags = tv.getText().subSequence(tv.getSelectionStart(),tv.getSelectionEnd()).toString();
                    Toast.makeText(context, tags,  Toast.LENGTH_LONG).show();
                }
                public void updateDrawState(TextPaint ds) {// override updateDrawState
                    ds.setUnderlineText(false); // set to false to remove underline
                }
            },matcher2.start(), matcher2.end(), 0);
        }
        holder.tweet.setText(hashtag, TextView.BufferType.SPANNABLE);
        holder.tweet.setMovementMethod(LinkMovementMethod.getInstance());
        holder.tweet.setHighlightColor(Color.TRANSPARENT);
        if(tweetList.get(position).tweet.isEmpty()){
            holder.tweet.setVisibility(View.GONE);
        }
        Typeface tf = Typeface.createFromAsset(context.getAssets(), "fonts/light.ttf");
        holder.tweet.setTypeface(tf);
        Typeface tf2 = Typeface.createFromAsset(context.getAssets(), "fonts/bold.ttf");
        holder.twitterUser.setText(tweetList.get(position).twittername);
        holder.twitterUser.setTypeface(tf2);
        holder.twitterMention.setText("@" + tweetList.get(position).mentionname);

        Picasso.with(context).load(tweetList.get(position).pictureURL).into(holder.profile_picture);
        if(tweetList.get(position).tweetPictureUrl != null){
            holder.tweet_picture.setVisibility(View.VISIBLE);
            holder.padding.setVisibility(View.VISIBLE);
            Picasso.with(context).load(tweetList.get(position).tweetPictureUrl).into(holder.tweet_picture);
        }else{
            holder.tweet_picture.setVisibility(View.GONE);
            holder.padding.setVisibility(View.GONE);
        }
        holder.favorite.setChecked(tweetList.get(position).isFavourite);

        return convertView;
    }
    static class ViewHolder{
        TextView tweet,twitterUser,twitterMention;
        ImageView profile_picture,tweet_picture;
        CheckBox favorite;
        View padding;
    }

}


text:
Q: LINQ in List> ANY function doesn't give correct response Losing my mind, tried it with something more simple and the function ANY does work ofcourse.
I realise I don't need to convert X,Y to strings, but it didn't work either with points.
Function 'Distinct' isn't an option, I filter those coordinates from a much larger class. This function is a simple check to not add doubles, to avoid a really complex LINQ function.

        public static List<PXML_DocumentOrderProductSlabOutline> FilterMountpart21(List<PXML_DocumentOrderProductSlabOutline> Mountpart21Lijst)
    {
        List<PXML_DocumentOrderProductSlabOutline> Gefilterd = new List<PXML_DocumentOrderProductSlabOutline>();
        List<List<string>> GefilterdeSparingen = new List<List<string>>();

        for (int x = 0; x < Mountpart21Lijst.Count; x++)
        {
            var ShapeMountpart21Lijst = Mountpart21Lijst[x].Shape.First().SVertex;
            List<string> LijstVertex = new List<string>();
            foreach (var xyz in ShapeMountpart21Lijst)
            {
                string Punt = Convert.ToInt32(xyz.X) + ";" + Convert.ToInt32(xyz.Y);
                LijstVertex.Add(Punt);
            }

             //This fails
            if(!GefilterdeSparingen.Any(abc => abc == LijstVertex))
             //

            {
                GefilterdeSparingen.Add(LijstVertex);
                Gefilterd.Add(Mountpart21Lijst[x]);
                System.Windows.MessageBox.Show(ResultaatFilterMountpart21(LijstVertex, GefilterdeSparingen));
            }
        }
        return Gefilterd;
    }


text:
Q: In JavaScript, when creating an element, and then deleting the containing variable, does the element stay in DOM? I have a script that asynchronously loads image src from XML file.
The sources are later assigned to the background of a div, and backgrounds change every 5 seconds.
It works well, but I want to pre-load the actual images to display already loaded image.
I do this by iterating an array, creating an img for each source:
for(var i=0; i < clientLogos.lenght; i++){
    var imgHolder = document.createElements("IMG");
    imgHolder.src = clientLogos[i];
}

It's hard to tell the difference if it has been preloaded in development stage, so my question is:
If I delete or over-write the variable containing the element I just created, does the element stay in DOM, or does it get deleted as well?
I'm pretty sure it stays, but I want to ask the more experienced developers.
I got confused with it:
Does document.createElement() inserts it in the DOM or not?

A: Yes. The newly created element will stay in the DOM unless you explicitly remove it or you overwrite the .innerHTML property of some parent node.
when deleting ("nulling") imgHolder you are only deleting a reference to that node.

A: it will be lost. the only way to access it is by assigning the same to some new variable and delete the DOM variable that holds it value.

A: In your given example element will be freed when its reference count will drop to 0. Have to perform appendChild or such before writing to that variable to prevent it.
var imgHolder;
imgHolder = document.createElement("IMG");  // creates and references new Image
imgHolder.src = 'hello.jpg';                // some manip
/* have to save object here by means of inserting into DOM or merely pushing into array */
/* failure to do so tells JS's garbage collector what old object no longer needed */
imgHolder = document.createElement("IMG");  // deletes old image referenced by variable, creates and refs new one


text:
Q: Command works from command line, but not from Task Scheduler I want a Windows scheduled task to execute an FTP batch file which will upload some files to my server.
If I run the argument below from the command line then it executes successfully.
ftp -i -s:C:\<path-to-file>\ftp.dat

When I try and run this through a scheduled task it always gets to created task process and stays like this; it does not complete or fail. I have also tried this without the put commands and it still does it so it's not as if it is waiting to transfer the files.
I am creating the task through the task scheduler GUI on Windows Vista. Under the general tab I have run whether the user is logged on or not and run with highest privileges set.
Under actions it is set to run C:\\Windows\System32\cmd.exe.
And the argument is
ftp -i -s:C:\<path-to-file>\ftp.dat

The ftp.dat file looks like this:
open ftp.mysite.co.uk
myUsername
myPassword
put C:\<path-to-file>\file.xml
put C:\<path-to-file>\file2.xml
bye

I don't understand why this runs perfectly fine manually from the command line, but not from the scheduled task.

A: It should work when you add /c as parameter for cmd.exe to run the command (ftp):
C:\Windows\System32\cmd.exe
/c ftp -i -s:C:\<path-to-file>\ftp.dat

You can also try this 'whole' thing on the command line:
cmd /c ftp -i -s:C:\<path-to-file>\ftp.dat

Without /c it just opens a console within the console, note executing the command.

A: My suggestion would be run a VBScript script in a scheduled task:
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run "C:\Windows\System32\ftp.exe -i -s:C:\<path-to-file>\ftp.dat", , True

I've always had much more luck with scheduling VBScript scripts over trying to scheduled commands.

A: It sounds like there is still a permissions or file access issue as when not running with a UI some parts of the environment are not available.  It is likely that a file or path is not available since we don't know where  goes...
The best thing to do is to log the output from ftp to see if there are errors.  It would be useful to have anyway to review if there are any future problems like this:
ftp -i -s:C:\<path-to-file>\ftp.dat >c:\ftp.log

You could put the log file in the  but it won't provide a log if you can't access that folder for some reason, so until you've ruled that out you're best to keep it in the root.  Once you've ruled out that problem then you can move it to a more appropriate location.


text:
Q: Hibernate MappingException: Unknown entity on session save I am getting exception on save operation to postgresql database using hibernate when I call addEventAction method from another class.
EventDAO.java:
package com.sessionpoint.session.sessiondr.core;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.sessionpoint.session.sessiondr.db.DrAction;

/**
 * Logic for the database operations related to the actions.
 *
 */
public class EventDAO {

   //To get the logger for class
   Logger log = Logger.getLogger("EventDAO");

    /**
     * Add dispatched event action into the database.
     *
     * @param eventAction
     */
    public void addEventAction(DrAction eventAction) {
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();

        log.info("Connection with the database created successfuly.");

        try {
            trns = session.beginTransaction();
            session.save(eventAction); //exception here
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (trns != null) {
                trns.rollback();
            }
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
    }
}

HibernateUtil.java:
public class HibernateUtil {
    private static SessionFactory sessionFactory;

    //To get the logger for class
    static Logger log = Logger.getLogger("HibernateUtil");

    static {

        log.info("Trying to create a connection with the database.");
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        sessionFactory = configuration.buildSessionFactory(ssrb.build());
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Exception Trace:
org.hibernate.MappingException: Unknown entity: com.sessionpoint.session.sessiondr.db.DrAction
    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1094)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1439)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:116)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:711)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:703)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:698)
    at com.sessionpoint.session.sessiondr.core.EventDAO.addEventAction(EventDAO.java:35)

UPDATE:
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.password">user</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/drcore</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    </session-factory>
</hibernate-configuration>

DrAction.java:
/**
 * DrAction for the dr_action table
 */
public class DrAction implements java.io.Serializable {

    /**
     * Default serial version Id.
     */
    private static final long serialVersionUID = 1L;

    /**
     * Auto increment drActionId.
     */
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long drActionId;
    private String drVName;
    private String drVRequestId;

    private Long vKey;

    public long getDrActionId() {
        return drActionId;
    }
    public void setDrActionId(long drActionId) {
        this.drActionId = drActionId;
    }
    public Long getvKey() {
        return vKey;
    }
    public void setvKey(Long vKey) {
        this.vKey = vKey;
    }
    public String getDrVName() {
        return drVName;
    }
    public void setDrVName(String drVName) {
        this.drVName = drVName;
    }
    public String getDrVRequestId() {
        return drVRequestId;
    }
    public void setDrVRequestId(String drVRequestId) {
        this.drVRequestId = drVRequestId;
    }
}

UPDATE:
Exception Trace 2:
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:89)
    at org.hibernate.id.SequenceGenerator.generateHolder(SequenceGenerator.java:122)
    at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:115)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:711)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:703)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:698)
    at com.sessionpoint.session.sessiondr.core.EventDAO.addEventAction(EventDAO.java:35)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.postgresql.util.PSQLException: ERROR: relation "hibernate_sequence" does not exist
  Position: 17
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2157)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1886)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:555)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:417)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:302)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)

UPDATE:
Exception Trace 3:
Caused by: org.hibernate.MappingNotFoundException: resource: com/sessionpoint/session/sessiondr/db/DrAction.hbm.xml not found
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:767)
    at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2255)
    at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2227)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2207)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2160)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:2075)
    at com.sessionpoint.session.sessiondr.core.HibernateUtil.<clinit>(HibernateUtil.java:24)

A: Add @Entity to DrAction class, and add <mapping class="your.package.DrAction"/> to hibernate.cfg.xml.
@Entity
@Table(name = "dr_action")
public class DrAction implements java.io.Serializable {

hibernate.cfg.xml
...
    <session-factory>
        ....
        <mapping class="your.package.DrAction"/>
    </session-factory>
....

UPDATE
You are probably using Oracle as DB, and Oracle doesn't support auto generated ids. You'll have to specify sequence that will be used for generating ids.
Execute this in database
create sequence DR_ACTION_SEQ;

And change the id mapping to this
@Id
@GeneratedValue(generator="drActionIdSeq")
@SequenceGenerator(name="drActionIdSeq",sequenceName="DR_ACTION_SEQ", allocationSize=5)
private long drActionId;

Note that this expects that your id column is named dractionid, if it is not then you'll have to add a @Column annotation to the field, something like this
@Column(name = "dr_action_id")

You will have to do this for every column whose name isn't the same as column in database table.

A: Add below lines to your hibernate.cfg.xml
<mapping class="xxx.yyy.DrAction"/>//provide full package name

and @Entity and @Table (name="dr_action") annotation onDrAction` class

A: The @GeneratedValue annotation in postgre use sequence tables. since you haven't explicitly provided a name hibernate by default looks for hibernate_sequence sequence table.
Either add a sequence table by name hibernate_sequence in postgre schema or by any other name and add the name in the annotation.


text:
Q: SQL query missing select statement fetching data error I am using SQL query fetching some issue data is not fetching black show.
I am sharing this query here. Please help me.
SQL query here
select * from products where hitproduct='0'  ORDER BY id DESC and  user_id='$user_id'

A: A SQL query only has one where clause.  Presumably, you intend:
select p.*
from products p
where user_id = ? and
      hitproduct = 0 -- looks like a number, so I assume it is
order by id desc;

Note the use of ?.  This represents a parameter placeholder.  Don't munge query strings with parameters values!  Learn to use parameters properly.

A: In your given query and user_id='$user_id' should be before ORDER BY.
 select *
 from products
 where hitproduct='0' and user_id='$user_id'
 ORDER BY id DESC


text:
Q: Send file to Mule inbound-endpoint I'm trying to send a form with a file and two inputs to an Mule inbound-endpoint. I've got a custom-processor, and a flow defined like that:
<custom-processor class="informa.app.classifier.transformers.MyfileUploadProcessor" name="fileuploadprocessor"></custom-processor>
<flow name="httpTest">
    <http:inbound-endpoint
                    address="http://tango.privada.informa:11002/services/fileupload"></http:inbound-endpoint>
    <processor ref="fileuploadprocessor"/>
</flow>

In the class MyfileUploadProcessor:
public class MyfileUploadProcessor implements MessageProcessor {
    @Override
    public MuleEvent process(MuleEvent event) throws MuleException {
        // TODO Auto-generated method stub
        String response = "success";

        MuleMessage mulemessage = event.getMessage();

        String countryCode = mulemessage.getInboundProperty("username");
        String sourceCode = mulemessage.getInboundProperty("password");
        InputStream input = (InputStream) mulemessage.getPayload();

...

And to test, a simple html:

<form action="http://tango.privada.informa:11002/services/fileupload" method="post"
enctype="multipart/form-data">

Country Code :<input type="text" name="username" />

Source Code :<input type="text" name="password" />

File :<input type="file" name="payload" />

<input type="submit" name="submit" value="submit" />
<input type="reset" name="reset" value="reset">

</form>

The issue is I can't create a file from the payload of the mulemessage and I don't know how to get the value of the inputs in the form...what I'm doing wrong? any clues?
Thanks in advance

A: You need to configure the HTTP connector to use the org.mule.transport.http.HttpMultipartMuleMessageFactory in order to handle multipart/form-data HTTP POSTs.
For this, add the following to your configuration:
<http:connector name="httpConnector">
    <service-overrides messageFactory="org.mule.transport.http.HttpMultipartMuleMessageFactory"/>
</http:connector>

With this in place, the payload form field will become the streaming payload of the Mule message and all the other fields values will be in inbound attachments (any part header will be in inbound headers).

A: Great answer from David (a life saver for me !! cudos david)
for what it is worth some extra items I didn't realize at first the httpConnector has to be used as http transport reference a full flow would be
<http:connector name="httpConnector" doc:name="HTTP\HTTPS">
        <service-overrides
            messageFactory="org.mule.transport.http.HttpMultipartMuleMessageFactory" />
    </http:connector>

<flow name="AttachmentTestFlow1" doc:name="AttachmentTestFlow1">
    <http:inbound-endpoint connector-ref="httpConnector" doc:name="HTTP" exchange-pattern="request-response" host="localhost" port="8081"/>
    <component class="ProcessAttachment" doc:name="Java" />
</flow>

I was able to upload using jmeter adding two attachments, the first

*

*has a paramter name = "payload" and mime-type="multipart/form-data"

*the second has a user specificed name, e.g "attachment"

This can then be processed by a normal mule flow, or a component
public String process(@Payload String payload, @InboundAttachments("*") Map<String, DataHandler> headers  ) throws IOException{
    InputStream in  = headers.get("attachment").getDataSource().getInputStream();


text:
Q: MRTK Unity Android Scrolling by touch input is too slow I am trying to make Scrolling Object Collection from MRTK Unity work with Android.
The problem is, that scrolling is just too slow. When I swipe across the whole screen the objects in the list barely move.
If I look at the collection, touch the screen, and then move my phone in the direction I want to scroll, everything works fine.
But that is not how I want users to scroll.
Any ideas how to make the touch behave the same way/have the same impact as moving the phone?


text:
Q: Choosing an automated testing tool My project is compatible only with Internet Explorer. I want the test scripts to get generated automatically as it is done in Selenium IDE.
Can i use Selenium RC to test my application? I could not use Selenium IDE as it can be used only with Mozilla Firefox.

A: seleniumrc works with IE. You can specify the browser and the path to it within the config file.
It can be easily integrated into night builds via ant.
stick to writing the testcase in java.

A: Selenium RC and Selenium Grid are both really good at running tests against IE. You can see all the browsers that are supported by Selenium here and Selenium is Designed to write for one browser and work in the rest. THere are a few little quirks that wont work in every browser but 99% of the time it will.

A: Selenium RC works with IE, but is very buggy with IE 6 (to the point of being unusable). Generating the scripts is not trivial and there are many methods of doing it. We have created a Firefox extension that examines objects via introspection to make click recording easy. There are many options out there but your best bet is to write your tests with Firefox/Firebug (or Chrome). They will make object location much simpler and if you are careful the locator strings should still work in IE.

A: There could be two answer to you question:

*

*Besides Selenium, though it has ample of advantages, I am reading about another tool which uses same API which Selenium use. The only changes in API I have seen so far is it reduces the complexity of functions thus making it more easier and simpler for user who is learning.
The tool is called 'Helium' and it has 50% (and more) less complex functions and code as Selenium has.
The only problem with this tool is it is paid tool for learning purpose and for implementing not-so-big scale project you can use it. But yeah after some time its gonna cost you.

I have implemented some code on Helium. Please let me know , if you face any issue initially or you are thinking to implement it.

*

*Other being, you can use Selenium Builder(http://khyatisehgal.wordpress.com/2014/05/26/selenium-builder-exporting-and-execution/) which is an advanced form of Selenium IDE. It imports your command in different languages and does work more effectively and efficiently as Selenium IDE does(http://khyatisehgal.wordpress.com/2014/05/25/selenium-builder/)

Please let me know , if you have any doubt in any of the tool.

A: I know Watin is compatible with IE and Firefox. If you want to generate the test code you can use the Watin Test Recorder
This of course is implying that you are using .Net

A: ... Or you could just use the .net bindings that comes along with the latest couple of versions, then you can just run 'em through nUnit.

A: For ex. Selenium IDE users Katalon Recorder might be a good match. Supports different browsers.


text:
Q: Why do Liquid-state NMR qubit only work with fermionic nuclei? "The ideal picture of liquid state NMR (LSNMR) quantum information processing (QIP) is based on a molecule in which some of its atom's nuclei behave as spin-½ systems."
https://en.wikipedia.org/wiki/Nuclear_magnetic_resonance_quantum_computer#cite_note-2:~:text=The%20ideal%20picture%20of%20liquid%20state%20NMR%20(LSNMR)%20quantum%20information%20processing%20(QIP)%20is%20based%20on%20a%20molecule%20in%20which%20some%20of%20its%20atom%27s%20nuclei%20behave%20as%20spin%2D%C2%BD%20systems.
Why does it not work with Spin-1 systems?


text:
Q: Implicitly virtual constexpr function Virtual functions cannot be constexpr however, when a function is implicitly virtual through inheritance, the compilers I have tried don't complain about it.
Here is a sample code:
class A
{
    virtual void doSomething() {}
};

class B : public A
{
    constexpr void doSomething() override {} // implicitly virtual constexpr
                                             // but no compilation error
};

class C : public A
{
    virtual constexpr void doSomething() override {} // explicitly virtual constexpr
                                                     // compilation error
};

I tried it with gcc 7.2.0 and clang 5.0.0.
Are those compilers not compliant to the standard in this regard, or are implicitly virtual constexpr functions allowed ?

A: The compilers have a bug. Note that this has been fixed in clang 3.5 already, not sure why you don't get an error, because I do.
The standard is pretty explicit about this in [dcl.constexpr]p3:

The definition of a constexpr function shall satisfy the following requirements:

*

*it shall not be virtual;

*[...]

It does't matter whether doSomething is implicitly virtual or not. In both cases, it is considered to be virtual, and so it violates the point above.


text:
Q: conda not showing updated package I have tried to install pyhive on a server which is not connected to internet by downloading the file from here (https://anaconda.org/anaconda/pyhive/files?sort=basename&sort_order=asc)
The problem is that the package seems to be installed but when I do conda list | grep -i hive I get an old version of the package listed.
Below is my terminal output
(base) raemon@someserver:~$ sudo /opt/anaconda/bin/conda install pyhive-0.6.1-py27_0.tar.bz2
WARNING: The conda.compat module is deprecated and will be removed in a future release.
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
(base) raemon@someserver:~$ conda list | grep -i hive
WARNING: The conda.compat module is deprecated and will be removed in a future release.
WARNING conda.gateways.disk.delete:unlink_or_rename_to_trash(138): Could not remove or rename /opt/anaconda2/conda-meta/thrift-0.9.3-py27h14c3975_1.json.  Please remove this file manually (you may need to reboot to free file handles)
libarchive                3.3.3                h5d8350f_5
pyhive                    0.1.7                    pypi_0    pypi
python-libarchive-c       2.8                      py27_6

When i try to remove the pyhive by using
sudo conda remove --offline pyhive

I get this
WARNING: The conda.compat module is deprecated and will be removed in a future release.
Collecting package metadata: done
Solving environment: /
The environment is inconsistent, please check the package plan carefully
The following packages are causing the inconsistency:

  - <unknown>/linux-64::psycopg2==2.7.6.1=py27h1ba5d50_0
  - <unknown>/noarch::pyviz==0.10.3=py_0
  - <unknown>/linux-64::plotly==3.1.1=py37h28b3542_0
  - <unknown>/noarch::holoviews==1.12.3=py_2
  - defaults/linux-64::anaconda==2019.03=py27_0
done

## Package Plan ##

  environment location: /opt/anaconda2

  removed specs:
    - pyhive

The following packages will be REMOVED:

  pyhive-0.6.1-py27_0

Proceed ([y]/n)? y

Preparing transaction: done
Verifying transaction: done
Executing transaction: done

After that if I do conda list i get that old version.
(base) raemon@someserver:~$ conda list | grep -i hive
WARNING: The conda.compat module is deprecated and will be removed in a future release.
WARNING conda.gateways.disk.delete:unlink_or_rename_to_trash(138): Could not remove or rename /opt/anaconda2/conda-meta/thrift-0.9.3-py27h14c3975_1.json.  Please remove this file manually (you may need to reboot to free file handles)
libarchive                3.3.3                h5d8350f_5
pyhive                    0.1.7                    pypi_0    pypi
python-libarchive-c       2.8                      py27_6

Why is conda not updating the version when I am installing i.e. pyhive-0.6.1-py27_0.tar.bz2 ?


text:
Q: php parsing certain values within long text? I have an array of values, I was wondering how I can parse certain words if the words in my array has the value i'm looking for plus more text?
example:
I'm looking for rest
Array values has
restful
myrestless
rests
resting

What php function, if any, can I use where it will show that there are 4 items that has the word rest?
Thanks in advance!

A: Use array_filter:
$array = array('restful', 'myrestless', 'rests', 'resting');

$needle = 'rest';
$rest_array = array_filter( $array,
    function( $el) use( $needle) {
        return !(strpos( $el, $needle) === false);
    }
);
var_dump( $rest_array);

Note that this requires PHP >= 5.3 (maybe 5.4?). Otherwise you will have to rewrite it to not use anonymous functions and closures.
Demo


text:
Q: Shellscript to monitor a log file if keyword triggers then execute a command? Is there a cheap way to monitor a log file like tail -f log.txt, then if something like [error] appears, execute a command?
Thank you.

A: tail -fn0 logfile | \
while read line ; do
        echo "$line" | grep "pattern"
        if [ $? = 0 ]
        then
                ... do something ...
        fi
done

A: An even more robust approach is monit. This tool can monitor very many things, but one of them is that it will easily tail one or more logs, match against regex and then trigger a script. This is particularly useful if you have a collection of log files to watch or more than one event to trigger.

A: Better and simple:
tail -f log.txt | egrep -m 1 "error"
echo "Found error, do sth."
...

A: I also found that you can use awk to monitor for pattern and perform some action when pattern is found:
tail -fn0 logfile | awk '/pattern/ { print | "command" }'

This will execute command when pattern is found in the log. Command can be any unix command including shell scripts or anything else.


text:
Q: IIS. How rewrite/redirect from url https://site1.com/Repo/* to https://site2.com/Repo/*? Tell me please how i can make rewrite/redirect on IIS from url https://site1.com/Repo/* to https://site2.com/Repo/* ?
I want that for example https://site1.com/Repo/324234234234234 redirect to https://site2.com/Repo/324234234234234
Thank you advanced

A: You can try this rule, the pattern is using a regular expression, to check if {HTTP_HOST} is equal to site1.com, the {R:1} in the action means whatever is in the URL behind the domain name itself.
<rule name="test1">
  <match url="^(.*)$" />
    <conditions>
      <add input="{HTTP_HOST}" pattern="^site1.com$" />
    </conditions>
  <action type="Redirect" url="http://site2.com/{R:1}" />
</rule>