text:
Q: Using one socket to both receiving and sending messages in Python I have a python script, which already sends messages from time to time to peer using socket. I want to add a feature, that socket listens asynchronously for inbound messages and then reacts, for ex. processes content and resends a reply. Is it possible to do it using only one socket? I have to use one socket because my peer creates its socket on localhost:30000.
EDIT:
Here is some code of my tries I have done so far.
Run() method from the listening thread:
def run(self):
    print("Started listening to messages from peer...")
    while True:
        socketLock.acquire()
        try:
            self.listenToInboundMessages()
        finally:
            socketFlag.set()
            socketLock.notify()
            socketLock.release()

def listenToInboundMessages(self):
    clientsocket.settimeout(1)
    received = clientsocket.recv(BUFF)
    print(received)

Run() method for the thread which sends messages:
def run(self):
    print("Ready to send messages.")
    while True:
        print("Attempting to acquire lock...")
        socketLock.acquire()
        while not socketFlag.isAvailable():
            socketLock.wait
        print("Attempting to send message...")
        clientsocket.send("Message for per")
        socketLock.release()
        time.sleep(1)

I use socketLock condition variable and socketFlag class to coordinate both threads.

A: For windows you can use the select class to filter a list of socket connections into 3 lists, sockets that are ready to ready, sockets that are ready to write, and sockets that have errors.
Here is a basic implementation for a p2p socket connection (not class based).
import socket, select, time

s = socket.socket()
s.bind(("10.48.72.71", 8080))
s.listen(10)

connections = [s]

while True:
    time.sleep(.1)

    recv,write,err = select.select(connections,connections,connections)

    for socket in recv:
        if socket == s:
            client,address = socket.accept()
            connections.append(client)
        else:
            msg = socket.recv(4096).decode("UTF-8")
            print("Recieved message from a socket, message was: "+str(msg))

    for socket in write:
        socket.send(bytes("Hi", "UTF-8"))

    for socket in err:
        print("Error with a socket")
        socket.close()
        connections.remove(socket)


text:
Q: CSV value in pivot query here is my table
Manger  EmpID
ABC     5
ABC     6
XYZ     2
XYZ     3

if i  use pivot query i am getting below output.
 ABC    XYZ
 6      3

But actually i want such output.
  ABC   XYZ
  5,6   2,3

I dont' want aggregate value, i want csv values.
can anyone please help me to get such output.
here is my sql code
    Select *
INTO #TEMP
FROM
(SELECT 'ABC' As Manger , 5 as EmpID
union
SELECT 'ABC' As Manger , 6 as EmpID
union
SELECT 'XYZ' As Manger , 2 as EmpID
union
SELECT 'XYZ' As Manger , 3 as EmpID
) A

select *
FROM #TEMP

select *
FROM #TEMP
PIVOT
(
    MAX([EmpID])
    FOR Manger IN ([ABC],[XYZ])
) as P

drop table #TEMP

A: Try this:
SELECT *
FROM (
   SELECT DISTINCT Manager,
          STUFF((SELECT ',' + CAST(EmpID AS VARCHAR(MAX)) AS [text()]
                 FROM #TEMP AS t2
                 WHERE t1.Manager = t2.Manager
                 FOR XML PATH('')), 1, 1, '') AS EmpID
   FROM #TEMP AS t1) AS SRC
PIVOT
(
    MAX([EmpID])
    FOR Manager IN ([ABC],[XYZ])
) as P

The trick is to pre-process your table before applying PIVOT. The above query uses FOR XML PATH to create a comma separated list of EmpID values for each Manager.
Demo here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve value from a Regex code without for loop? Is there a effective way to retrieve the specific value of the myString with support of regex and without using a for loop?
    string myString = "BOX 646,  ff503 15";

    Regex regexp = new Regex(@"BOX [0-9]+");

    if (regexp.Match(myString).Success)
    {

    }

The data also can be
ddfdfdfN 1BOX 116
CAREER SERVICES - BOX 7080
POSTADRESS: BOX 9193
"BOX 15038, 250 15 ffff"
DT-111 87 (BOX 1703)


text:
Q: Xcode Storyboard shows white Controller (blank) I have a problem with my storyboard in Xcode.
9 of 15 View-Controllers in my Storyboard are displayed blank - only the three icons on the top are displayed.
I use a Navigation-Controller to manage my 15 Controllers.
Reboot and cleaning the project not help.

A:
The following table gives an overview of the available Size Classes.

*

*Device Orientation Vertical Size Class/Horizontal Size Class

*iPad Portrait        Regular               /  Regular

*iPad Landscape       Regular          /      Regular

*iPhone Portrait      Regular       /          Compact

*iPhone Landscape     Compact       /          Compact


text:
Q: Manually calling document.ready Is there a way to force the event document.ready to fire through Javascript? The new Rails 4 default of using turbo links by default kills this event from firing when switching pages. This causes problems with more 'traditional' jQuery code that is wrapped in $(function(){});.
I've taken a look around and don't see any way of making this event fire through code and most answers on here offer other work-arounds.
So is it even possible to make document.ready fire through regular Javascript code?

A: Are you using jQuery then?  If you are, try an explicit call to Jquery's $.ready();  function at the end of your code.  This will force all jQuery "ready" functions to be called, both your own and those in any plugins you're using.
If that doesn't work, you can try $(window).load();.
If neither of those work and you're using some type of asynchronous call, you probably have some other issue to weed out first. Good luck!

A: I think the simplest way to do this without a big change on your code is to listen to a custom event instead of ready and inside the ready event fire the custom event.

A: From the turbolinks documentation:
You have to make the document listen to one of the turbolinks custom page events, for example:
$(document).on('page:change', function() {
    // Your code
});

A: The easiest solution:
Insert your Gemfile this:
gem 'jquery-turbolinks', '~> 1.0.0'

Insert your application.js this:
//= require jquery.turbolinks

(Don't forget a bundle update)
If you have in your coffescript code the following it will be triggered for full page reload or for opening a page via link when turbolinks is active:
$ ->
   alert 'Hello World'

($ -> means document.ready)


text:
Q: How to make a cref to method overloads in a  tag in C#? I see in MSDN links such as "CompareOrdinal Overloads". How can I write such a link in C#?
I tried:
<seealso cref="MyMethod">MyMethod Overloads</seealso>

But the compiler gives me a warning about being an ambiguous reference for the method which has other overloads.
(Beginner question: do I actually need to write this tag to link to the overloads, or is it automatically generated by documentation processors?)

A: Xml documentation doesn't have a means to reference all overloads of a method.
The most popular documentation generator for C# projects is Sandcastle.  It will automatically create a link to an overloads list page if necessary.  Hence in a members list page the name of an overloaded method will appear only once, clicking it will navigate you to the list of overloads page for that method and from there to a specific overload.
Placing a link to the overloads list page in Xml documentation would require intimate knowledge of the external tool being used and probably not a good idea.
If you really must have this then perhaps one way is to use an anchor with a specificaly formed ID.  Most document generators provide some arcane means of pre or post processing generated files and should give you the opportunity to pick these anchors out and provide an appropriate href for them.
OTH, it may be more trouble than its worth ;)

A: To target specific members, I believe you just match the signature:
/// <seealso cref="Foo(int)"/>
static void Foo() { }
/// <seealso cref="Foo()"/>
/// <seealso cref="Foo(float)"/> <------ complains
static void Foo(int a) { }

To be honest, I'm not sure how to generate an "all overloads" link; I'd assume that any sensible generator did this automatically.

A: Using Sandcastle it is simple:
<seealso cref="overloads:FullyQualifiedMyMethod">MyMethod Overloads</seealso>

FullyQualifiedMyMethod is the complete route you need to reach the overload, including namespaces and classes, i.e.: System.Linq.Enumerable.Sum
However VB compiler issues a warning saying the attribute can not be resolved, which can be ignored.


text:
Q: Ignore regex when comparing strings
Possible Duplicate:
How to escape text for regular expression in Java

I have a problem where my users have potty mouths....
To elaborate, my Android application uses Google Voice Search to return voice results and if the user has applied the setting to 'Block offensive words' it will return 'go away' as 'g* a***'
When trying to establish what the user has said, I will often use common matching such as:
if(voiceResult.matches(someCommand)) { //do something

If the user has chosen to speak an obscenity, then I will get the following error:
java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index X

I can't really request that all my users either don't swear or turn off the filter, especially as from my tests Google Voice Search seems to have a dirty mind and often returns swear words in the middle of the most random sentences!
So, I'm a little lost with how to deal with this eventuality... I've looked for a way to 'ignore regex' within a string, but I drew a blank and I can't figure out how I would dynamically escape any occurrences of * contained within the string...
At present, my only option seems to detect '*' and then ask them nicely not to swear or to remove the filter!
Suggestions welcome! Unless you think they deserve a force close for their bad manners...
Please Note: 'go away' is not currently filtered - it was an example....
EDIT: The most simple example regex where I confirm a repeat voice request:
String userWords = "g* a***"

if(userWords.matches(userWords)) { // Then go on to compare userWords with other strings

EDIT2:
    String goAway = "g* a***";

    String goAway1 = Pattern.quote(goAway);
    String goAway2 = Pattern.quote(goAway);

    if (goAway1.matches(goAway2)) { \\ do something

A: You can use Pattern.quote() to do the escaping for you, as found here.
String pattern = Pattern.quote("g* a***");

Will give you the following string:
"g\* a\*\*\*"

Note that those backslashes are actual characters in the string. If you wanted to create this string manually, you would use this assignment:
String pattern = "g\\* a\\*\\*\\*";

Now you can use goAway1 as a regex pattern that literally matches g* away*** (because every single character is treated as a literal). So, for instance:
String goAway = "g* a***";
String pattern = Pattern.quote("g* a***");
if (goAway.matches(pattern)) { // we know that goAway was "g* a***"

Of course, you cannot use the pattern to match a quoted string (like you did in your edited code snippet). What you are trying to do is the same as applying the regex
String pattern = "g\\* a\\*\\*\\*";

to this literal subject string:
String subject = "g\\* a\\*\\*\\*";

What happens? g in the pattern, matches g in the subject. Now the pattern contains an escape sequence \* which will match a literal *. But the subject string has a literal \ next. And this fails to match.


text:
Q: how is this model spec working in the discource test suite I am looking through the discourse source code here https://github.com/discourse/discourse/blob/master/spec/models/invite_spec.rb and see code like this:
require 'spec_helper'
describe Invite do

  it { should belong_to :user }
  it { should have_many :topic_invites }
  it { should belong_to :invited_by }
  it { should have_many :topics }
  it { should validate_presence_of :email }
  it { should validate_presence_of :invited_by_id }

I'm unfamiliar with where they are getting a value for it. It seems like they have an implicit object here but I don't see where they are creating it - should this be in a before hook?. They are using Fabricator instead of FactoryGirl - can somebody tell me how these are passing?

A: There is an implicit subject of Invite. This is an RSpec feature:

The first argument to the outermost example group block is
  made available to each example as an implicit subject of
  that example.

See https://www.relishapp.com/rspec/rspec-core/v/2-0/docs/subject/implicit-subject


text:
Q: How to read and load the internal storage .csv file in webview I am working in xamarin android project. I am downloading .CSV file and store it in internal storage. File path is given below.
filepath: /storage/emulated/0/Android/data/com.abc.def/files/ABC/MyListSample.csv
I want to load this .csv file into webview. I tried the below given code but couldn't able to load the .csv file in webview.
_webview = (WebView)FindViewById(Resource.Id.webView);

_webview.SetInitialScale (0);
        _webview.Settings.JavaScriptEnabled = true;
        _webview.Settings.SetSupportMultipleWindows (false);
        _webview.Settings.AllowFileAccess = true;
        _webview.Settings.SetPluginState (WebSettings.PluginState.On);//Try
        _webview.Settings.BuiltInZoomControls = false;
        _webview.Settings.JavaScriptCanOpenWindowsAutomatically = true;

_webview.Settings.AllowUniversalAccessFromFileURLs = true;

_webview.LoadUrl(string.Format("file://" + filepath));

Second method I tried is given below:
 Java.IO.File csv = new Java.IO.File(filepath);

 _webview.LoadUrl(string.Format("file://" + csv));

I don't want any third party library like open csv to view/load this csv file. I have searched a lot and tried many methods but couldn't able to find solution.

A: I have done a sample to test your code. I can open the .html file and the image file with it, but I got a blank webview when I try to load the .csv file.
It seems the webview doesn't support to open the .csv file directly. But I used the following code to open a .csv file online by the google documents view.
 _webview.LoadUrl("https://docs.google.com/viewer?embedded=true&url=" + "https://people.sc.fsu.edu/~jburkardt/data/csv/addresses.csv");

But this code can't load the internal storage .csv file. So you can try to upload the .csv to a server.


text:
Q: Preg Relplace only replace instances of text with a trailing space I have a preg_replace question. I am using preg_replace to generate contextual links in text blocks using the following code:
$contextualLinkStr = 'mytext';

$content = 'My text string which includes MYTEXT in various cases such as Mytext and mytext. However it also includes image tags such as ';
$content = preg_replace('/' . $contextualLinkStr . '/i', '\\0', $content);

The preg_replace is working well on the text and generating the relevant links while retaining case but it's also generating a link within the URL of the image tag. I was thinking If I simply added a trailing space to the expression in the preg_replace function it would fix it due to the fact that all text instances will have a trailing space whereas no image urls will, as follows:
$content = preg_replace('/' . $contextualLinkStr . '/i' . ' ', '\\0' . ' ', $content);

But this doesn't work. Can anybody tell me how I make the trailing space a condition of the match?
Thanks in advance.
Jason.

A: I've just worked it out guys. I was being daft. For reference the relevant code is:
$content = preg_replace('/' . $contextualLinkStr . ' /i', '\\0 ', $content);

Thanks.


text:
Q: Update UIProgressView progress via delegate So I have this weird issue with a UIProgressView. I run a background task via Alamofire fetching some objects through a custom api. Each time a group of objects gets fetched I want to show that through that progressView. However, the progress indicator does not move along the assigned progress but only as soon as the entire progress is finished it just jumps to 100% in one go. The progress is transferred from the background from another class via delegate and its been displayed correctly in log prints. BUT the progressView is not moving alongside.
It gets triggered by:
delegate?.updateProgressF?(progressText: "Some Text", progress: 0.1)

And the Function:
func updateProgressF(progressText: String, progress: CGFloat) {

    let date = Date()
    let calendar = Calendar.current
    let seconds = calendar.component(.second, from: date)
    let nanoSeconds = calendar.component(.nanosecond, from: date)
    print(progress, seconds, nanoSeconds, progressView.progress)

    DispatchQueue.main.async { [self] in
        progressView.setProgress(Float(progress), animated: true)
    }

}

It prints:
0.1 23 123411059 0.0
0.2 28 800351977 0.0
0.4 28 804774999 0.0
0.6 28 806638002 0.0
0.8 28 885470032 0.0
0.9 32 190487980 0.0
1.0 32 253463029 0.9

Any advice is much appreciated

A: I figured it out. So for anyone in the future with similar issue just make sure all the tasks are running in the background then call the progressView on the main thread. In my case I had to specify in my viewDidLoad:
DispatchQueue.global(qos: .background).async {[self] in
    fetchInfo()
}

Then call the UI change on the main thread:
DispatchQueue.main.async { [self] in
    progressView.setProgress(Float(progress), animated: true)
}


text:
Q: Regex implementation with event driven matches? This may sound a little odd, but it would be extremely useful to me. Are there any regex implementations (any language but preferably java, javascript, c, c++) that use an event based model for matches?
I would like to be able to register a bunch of different regular expressions I am looking for in a string via an event based model, feed the string though the regex engine, and just have the events fired off correctly. Does anything like this exist?
I realize this is bordering on the territory of a heavy duty lexer/parser, but I would prefer to stay away from that if at all possible, as my search expressions would need to be dynamic (completely).
Thanks

A: This is very easy to do in Perl regular expressions.  All you do is insert your event callouts at the appropriate point in the pattern in the most straightforward manner imaginable.
First, imagine a pattern for pulling out decimal numbers from string:
my $rx0 = /[+-]?(?:\d+(?:\.\d*)?|\.\d+)/;

Let's expand that out so we can insert our callouts:
my $rx1 = qr{
    [+-] ?
    (?: \d+
        (?: \. \d* ) ?
      |
        \. \d+
    )
}x;

For callouts, I'll just print some debugging, but you could do anything you want:
my $rx2 = qr{
    (?: [+-]                (?{ say "\tleading sign"                })
    ) ?
    (?: \d+                 (?{ say "\tinteger part"                })
        (?: \.              (?{ say "\tinternal decimal point"      })
            \d*             (?{ say "\toptional fractional part"    })
        ) ?
      |
        \.                  (?{ say "\tleading decimal point"       })
        \d+                 (?{ say "\trequired fractional part"    })
    )                       (?{ say "\tsuccess"                     })
}x;

Here's the whole demo:
use 5.010;
use strict;

use utf8;

my $rx0 = qr/[+-]?(?:\d+(?:\.\d*)?|\.\d+)/;

my $rx1 = qr{
    [+-] ?
    (?: \d+
        (?: \. \d* ) ?
      |
        \. \d+
    )
}x;

my $rx2 = qr{
    (?: [+-]                (?{ say "\tleading sign"                })
    ) ?
    (?: \d+                 (?{ say "\tinteger part"                })
        (?: \.              (?{ say "\tinternal decimal point"      })
            \d*             (?{ say "\toptional fractional part"    })
        ) ?
      |
        \.                  (?{ say "\tleading decimal point"       })
        \d+                 (?{ say "\trequired fractional part"    })
    )                       (?{ say "\tsuccess"                     })
}x;

my $string = <<'END_OF_STRING';

    The Earth's temperature varies between
    -89.2°C and 57.8°C, with a mean of 14°C.

    There are .25 quarts in 1 gallon.

    +10°F is -12.2°C.

END_OF_STRING

while ($string =~ /$rx2/gp) {
    printf "Number: ${^MATCH}\n";
}

which when run produces this:
        leading sign
        integer part
        internal decimal point
        optional fractional part
        success
Number: -89.2
        integer part
        internal decimal point
        optional fractional part
        success
Number: 57.8
        integer part
        success
Number: 14
        leading decimal point
        leading decimal point
        required fractional part
        success
Number: .25
        integer part
        success
Number: 1
        leading decimal point
        leading sign
        integer part
        success
Number: +10
        leading sign
        integer part
        internal decimal point
        optional fractional part
        success
Number: -12.2
        leading decimal point

You may want to arrange a more grammatical regular expression for maintainability. This also helps for when you want to make a recursive descent parser out of it. (Yes, of course you can do that: this is Perl, after all. :)
Look at the last solution in this answer for what I mean by grammatical regexes.  I also have larger examples elsewhere here on SO.
But it sounds like you should look at the Regexp::Grammars module by Damian Conway, which was built for just this sort of thing.  This question talks about it, and has a link to the module proper.

A: You might want to check out PIRE - a very fast automata-based regexp engine, tuned to match zillions of lines of text against many regular expressions quickly. It's available in C and has some bindings.

A: It's really not something that's too hard to put together yourself if you can't find any existing library.
Something like this:
public class RegexNotifier {
   private final Map<Pattern, List<RegexListener>> listeners = new HashMap<Pattern, List<RegexListener>>();

   public synchronized void register(Pattern pattern, RegexListener listener) {
      List<RegexListener> list = listeners.get(pattern);
      if (list == null) {
         list = new ArrayList<RegexListener>();
         listeners.put(pattern, list);
      }
      list.add(listener);
   }

   public void process(String input) {
      for (Entry<Pattern, List<RegexListener>> entry : listeners.entrySet()) {
         if (entry.getKey().matcher(input).matches()) {
            for (RegexListener listener : entry.getValue()) {
               listener.stringMatched(input, entry.getKey());
            }
         }
      }
   }
}

interface RegexListener {
   public void stringMatched(String matched, Pattern pattern);
}

The only shortcoming I see with this is that Pattern doesn't implement hashCode() and equals(), meaning it will be less than optimal if equal patterns using different instances are used.  But that usually doesn't happen because the factory method Pattern.compile() is good about caching patterns.


text:
Q: Problem with running 1 test class in Intellij from context menu I'm running test class from context menu(1) and I'm getting mvn install(2) instead running only 1 test class, or even testcase. I want to run only 1 test.
What could be a problem ?
I'm using maven 3.8.4, IntelliJ 2021.3.2 Ultimate, and Java 11.

A: Check that you do not have the Settings (Preferences on macOS) | Build, Execution, Deployment | Build Tools | Maven | Runner | Delegate IDE build/run actions to Maven option enabled.
Also, check that you did not configure any Maven triggers (e.g. before run/build).


text:
Q: Advanced Filter returning wildcard data (no wildcards used) I've got a large data set I'm using Advanced Filter to sort through. It's working well for the most part but I've come across an issue I'm not really sure how to deal with.
I have a list of criteria that corresponds to what is in the data table,
Let's say the criteria are
Food - Dessert - Apple
Advanced Filter is returning not just all the results for "apple" but also for "apple pie", "apple cobbler" etc.
Is there a way I can set this to only return the term being searched for rather than including records that also contain that string?
I've tried inserting quotations around it but that predictably failed.
If anyone has any ideas I'd be very appreciative.
Thanks!
Dim Grp1Criteria As Range: Set Grp1Criteria = WsCriteriaSheet.Range("A1").CurrentRegion

    If DataSheet.FilterMode Then
        DataSheet.ShowAllData
    End If

    WholeMainTable.AdvancedFilter xlFilterInPlace, Grp1Criteria

Note: Current region is isolated so that it's only containing the criteria and the headers corresponding columns in the data table


text:
Q: Spring Security with Hibernate data source problem. Login doesn't respond I have been having a problem that has troubled me for a while. Searching on this site and google hasn't yielded much help. I have already posted the problem on the spring source forum here but nobody has answered yet so I thought I might try here. You always get an answer on stackoverflow :-)
I have a custom UserDetailsService with autowired users dao bean. When I run the application in dev mode I get the login page. On login, nothing happens. Strange enough the app doesn't break or throw an error. I used some println statements to find out the farthest point the login service gets to my UserDaoImpl class on this line,
List<User> temp = getHibernateTemplate().find("select h from users h where username='" + username + "'");

it stops there, any println messages after that don't show on the console. In brief this are my configurations. If you need more details kindly look at detailed explanation I posted on spring source forum.
<http auto-config="true">
   <intercept-url pattern="/gwtsecurity/**" access="ROLE_USER"/>
   <intercept-url pattern="/gwt/**" access="ROLE_USER"/>
   <intercept-url pattern="/**/*.html" access="ROLE_USER"/>
   <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
   <intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
   <form-login login-page="/login.jsp"/>
</http>

<beans:bean id="userDetailsService" class="com.kibyegn.server.auth.UserDetailsServiceImpl">
</beans:bean>

<beans:bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
   <beans:property name="userDetailsService" ref="userDetailsService"/>
</beans:bean>

<beans:bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
   <beans:property name="providers">
       <beans:list>
           <beans:ref local="daoAuthenticationProvider" />
       </beans:list>
   </beans:property>
</beans:bean>

<authentication-manager>
   <authentication-provider user-service-ref="userDetailsService">
   </authentication-provider>
</authentication-manager>

and my hibernate config file
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.postgresql.Driver" />
    <property name="url" value="jdbc:postgresql://127.0.0.1:5432/GwtApp" />
    <property name="username" value="postgres" />
    <property name="password" value="password" />
</bean>
<!-- HIBERNATE CONFIGURATION -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="annotatedClasses">
        <list>
            <value>com.kibyegn.client.model.User</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="userDao"
    class="com.kibyegn.client.dao.UserDaoImpl"
    scope="singleton">
    <property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>

<bean id="userDetailsService"
    class="com.kibyegn.server.auth.UserDetailsServiceImpl">
</bean>

Could someone please save me from my misery. Help is highly appreciated.
Kibet.

A: I fixed it, the problem was that I was importing the Entity and Table class from org.hibernate.annotations instead of javax.persistence. After changing that, I got some errors but I fixed them and it now works.


text:
Q: Character replacement not working enter image description hereI have the following code that is supposed to replace instances of pi (3.14) with the word "pi". For example, "x3.14 3.14 3.14xx" should be turned into "xpi pi pixx". However, my code isn't doing that; why doesn't it work, and how would I fix it?
#include<iostream>
#include<cstring> //dsfsdf
#include<string>
#include<cstdio>//sdfdsf
using namespace std;

void replacepi(char *arr,int i)
{
    //base
    if(arr[i]=='\0')
    {
        cout<<arr<<endl;
        return;
    }
    //recc
    if(arr[i]=='3' && arr[i+1]=='.' && arr[i+2]=='1' && arr[i+3]=='4')
    {
        arr[i]='p';
        arr[i+1]='i';
        for(int j=i+4;arr[j]!='\0';j++)
            arr[j-2]=arr[j];
        arr[strlen(arr)-2]='\0';
    }
    replacepi(arr,i+1);
}

int main() {
    long int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        char arr[1000];
        cin.getline(arr,sizeof(arr));
        replacepi(arr,0);
    }
    return 0;
}

A: Looks like a job for regex_replace. Given you've read your input into arr you can just dump the replacement to the console like this:
regex_replace(ostream_iterator<char>(cout), cbegin(arr), cend(arr), regex("3\.14"), "pi")

Live Example
Naturally arr should be a string as in the example rather than a char[], as given any size char[] the input may be larger, a string will always work.


text:
Q: How do i know the process ID of the parent process? I have a script with loop like
while read host
do
./script &
done

I want to know the process id of the current process which is starting the ./script in background and use it in script.

A: Assuming a POSIX shell (like bash), $$ is the PID of the current shell and $PPID is the PID of the parent. You can pass $$ to the script or check the value of $PPID in the script.

A: The process ID of the current shell is in the special variable $$.
You can pass this to a forked (backgrounded) process:
./script $$ &

In "script", that will be the first argument, so:
parent_pid=$1

There's a summary of bash special variables here.


text:
Q: JavaFX for Presentation Layer in Standalone Desktop App We are going to create a java standalone Desktop application. We are searching for the best solution for the presentation layer. I saw javaFX and really liked it, but I am a bit confused. Can it be used in standalone Desktop applications?
Can I use javaFX in my standalone Desktop app and also use css to style the Ui?

A: It is perfectly possible to use JavaFX in a standalone Desktop app and apply CSS styling to it.
In JavaFX's lingo, this is know as a "Standalone" or "Self-Contained" deployment.
You can even integrate it with Swing or SWT, if the need arises. Note, though, that it's not possible the other way round.


text:
Q: Conditional formatting dates relative to a name in google sheets I'm relatively new to using google sheets and formulas and what not.
I am trying to highlight a row of cells using conditional formatting based on whether or not a name and date are both present in another range of cells.
In the case of the names, I need an exact match which I have figured out already easily enough.
In the case of the dates, I need it to highlight only if the leftDate is less than(prior) or equal to the rightDate displayed in another range of cells.
For example,
Names and Dates
In the left section of  the sheet, the row containing Jacob should be highlighted due to his name being present in the right section of the sheet AND the date being prior.
Where as Nicks row in the left section of the sheet would not be highlighted due to the date being after.
Andrews row on the left would be highlighted due to having the same date.
Mikes row would not due to his name not being present on the right section.
so far for comparing the names I am using a COUNTIF function, and to enable both names and dates to function I have it nested in an AND function, like so
=AND(COUNTIF(leftNames = rightNames),COUNTIF(leftDates>=rightDates in relation to name))
The name portion works it is the date portion I am struggling with, sorry for the long winded explanation. Any help is appreciated!
Thanks

A: try for range A3:D:
=INDEX(IF($B3<VLOOKUP($A3, $F$3:$G, 2, 0), 1,
 MATCH($A3&$B3, $F$3:$F&$G$3:$G, 0)))


text:
Q: UPSERT SALES FORCE OBJECT WITH AZURE DATA FACTORY When I upsert a object with a polymorphic foreign key, the following error is returned:
"type must be specified for polymorphic foreign key field"
How do i specify the type? I have a polymorphic relationship with Account and Contact.


text:
Q: Deleting an event using Event Kit in iPhone I am using Event Kit in my iOS application and creating a event using Event Kit. I am able to create it but I want to give the ability to delete also. But I am not able to do that. I know there is a method for EKEventStore to delete event but I am not able to make event object. I have event identifier as a string but I am not able to create an event object using it. Can someone please guide me to do it?
Regards
Pankaj

A: Refer this as event.eventIdentifier changes value. So you must keep track of the event.title you set to the event and access the event and delete it
NSDate *startDate = <EVENT_START_DATE>;
NSDate *endDate = <EVENT_END_DATE>;

NSPredicate *predicateForEvents = [eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:[NSArray arrayWithObject:[eventStore defaultCalendarForNewEvents]]];
//set predicate to search for an event of the calendar(you can set the startdate, enddate and check in the calendars other than the default Calendar)

NSArray *events_Array = [eventStore eventsMatchingPredicate: predicateForEvents];
//get array of events from the eventStore

for (EKEvent *eventToCheck in events_Array)
{
    if( [eventToCheck.title isEqualToString: @"yourEventTitle"] )
    {
         NSError *err;
         BOOL success = [eventStore removeEvent:eventToCheck span:EKSpanThisEvent error:&err];
         NSLog( @"event deleted success if value = 1 : %d", success );
         break;

    }
}

A: When ever you are creating an event save its id like this:
NSString* str = [[NSString alloc] initWithFormat:@"%@", event.eventIdentifier];

pass the id to delete the event, here is code
EKEventStore* store = [[EKEventStore alloc] init];
    EKEvent* event2 = [store eventWithIdentifier:str];
    if (event2 != nil) {
        NSError* error = nil;
        [store removeEvent:event2 span:EKSpanThisEvent error:&error];
    }

A: Take a look at EKEvent with eventWithIdentifier on iOS
I'm also finding that the following code works
// eventWithIdentifier returns nil for the external identifier
//EKEvent *eventToRemove = [eventStore eventWithIdentifier:self.expiryCalendarExternalIdentifier];
// So I'm using this method, which seems to work.
- (EKEvent *) getEventForIdentifer: (NSString *) eventIdentifier {
    EKEventStore *eventStore = [Settings getEventStore];
    NSArray *items = [eventStore calendarItemsWithExternalIdentifier:eventIdentifier];
    if ([items count] == 1) {
        return items[0];
    } else {
        [LogFile write:@"getEventForIdentifer: more than one occurrence of event, or no event!"];
        return nil;
    }
}

An example of this code in action (untested):
EKEventStore *eventStore = [[EKEventStore alloc] init];

EKEvent *newCalendarEvent = [EKEvent eventWithEventStore:eventStore];
// Just because we created an EKEvent, the calendarItemExternalIdentifier property of that event has been set.

// I store calendarItemExternalIdentifier (an NSString) in a Core Data
// object, and later fetch it back from core data.
// Something like:
NSManagedObjectSubclass *coreDataObject = ...
coreDataObject.externalId = newEvent.calendarItemExternalIdentifier;

// So, now let's say we pull the calendarItemExternalIdentifier string from
// Core Data, and want to remove the event.

NSString *externalId = ... // get calendarItemExternalIdentifier from Core Data

// getEventForIdentifer method from above
EKEvent *eventToRemove = [self getEventForIdentifer:externalId];

NSError *anError = nil;
[eventStore removeEvent:eventToRemove span:EKSpanThisEvent error:&anError];
if (anError) {
   // Something has gone wrong. Report the error.
}


text:
Q: serialized attributes solution in rails 3.2? I upgraded to ruby Rails 3.2 from 3.o
I used this serialized attributes solution:

https://github.com/emmapersky/serialized_attributes

with code that looks like this:
serialized_attr :body_data, :entry_data, :class_name => :hash,
              :accessors => BODY_ATTRS

saving the model still works for me. but reading the model back isn't working. the attribute is coming back nil
is there a different solution for rails 3.2?
thanks
---- edit:
OK i found something. in new entries since the upgrade the hash in the DB looks like this:
---
- !ruby/object:Hash
time: "22"

and before the upgrade it looked like this:
---
- time: "22"

old entries work. and it is able to "read" them back from the DB
so where does that string of ruby came from? and how can i get rid of it?


text:
Q: Remove a column comment in Snowflake From Snowflake's documentation, it's clear how to add or overwrite a comment on a table column, but it doesn't look like you can remove a comment one without re-creating the table.
CREATE TABLE "My_Table" (
  "my_column" INT
);
ALTER TABLE "My_Table" ALTER "my_column" COMMENT 'New Comment';  -- Works
ALTER TABLE "My_Table" ALTER "my_column" COMMENT NULL; -- Fails
ALTER TABLE "My_Table" ALTER "my_column" COMMENT '';  -- Works, but prefer NULL

As shown above, the best I can find is to set the comment to '', but I would really prefer it to be null.  Does anyone know how to remove a comment?

A: steps are:

*

*create a new column column2

*update the table so column2 = column1

*drop column1

*then rename column2 to column1;

Not sure if its worth the effort, but here goes:
alter table my_table add column my_column2 int;

update my_table set my_column2 = my_column;

alter table my_table drop column my_column;

alter table my_table rename column my_column2 to my_column;

describe table my_table ;


text:
Q: How an Ec2 node can contact eni of a different node in different AWS account and vpc I have a requirement that one of my EC2 instance's originating traffic to a specific ip address needs to land to a ENI of a different EC2 instance which is present in different account and different VPC.
To explain, lets say I have a ec2 instance with IP1 and need to transfer data to ec2 with IP3 but traffic has to be routed to ec2 with IP2 which takes care of routing it to IP3. IP1 is in AWS and IP3 is in Azure.
IP2 is of a instance which acts as a gateway which can route direct traffic to IP3.
A cross account vpc peering can not help as it will only direct the traffic to the pcx connection and can only help if IP3 was in IP2's vpc.
Please note  IP1 and IP2 are in different VPC's in AWS and IP3 is in Azure
I already have a set up that if any packet is sent to IP2 instance it will direct to IP3..So all I need is  IP1 needs to hit IP2 ENI..
Any help is appreciated


text:
Q: Stress Test Hard Drive attached to a LSI controller on Hyper-V I have a LSI 9265-8i controller running on Hyper-V.
How can I stress-test the hard disks in-situ?
I'd like to test things like iOPS, seek times etc.


text:
Q: Making two textviews with different font sizes have independent lines I just started android app programming, so this might be a very dumb question, but I can't find the answer anywhere.
I want to have two textviews next to each other, where one shows three lines in a small font and the other contains a number in a very big font (which is as big as the three lines of the other textview). What now happens is that the first line of the textview with the smaller font sizes is aligned to the line of the other textview on the base line. So, I get some whitespace above the first line, because the font size is much smaller, and the three lines don't fit because so much space is wasted.
My code looks like this:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/historytextviewId"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/countertextViewId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="60sp" />
</LinearLayout>

What I want is that the left textview just acts as if the other textview had the same font size.
EDIT: For some reason, replacing android:layout_height="wrap_content" by android:layout_height="fill_parent" in the first TextView worked for me (which I tried because I found some almost completely unrelated question where that was the answer), but I still don't get why that works.


text:
Q: When two polynomials $f(x),g(x)$ over a field $F$ are said to be relatively prime? When two polynomials $f(x),g(x)$ over a field $F$ are said to be relatively prime?

*

*Following the definition given for the integers I guess when two of them have no factors in common other than $1.$ But if we follow such definition it implies $-1$ and $x+1$ are not relatively prime.

My second question is when does $f,g$ are relatively prime provided one of them is $0?$

A: The relevant property here is that any field is a GCD domain, which means that any two nonzero elements have a GCD (ordered by divisibility).  And once $F$ is a GCD domain, $F[x]$ is as well.  "Relatively prime" means that their GCD is 1 (up to units, of course).
In this context $\gcd(-1,x+1)=1$, up to units; so in some sense $F\setminus \{0\}$ is the gcd.  Also for nonzero $\alpha$, $\gcd(\alpha,0)=\gcd(\alpha,\alpha)=\alpha$, again up to units.


text:
Q: A First Chance Exception 've been running through the MSDN help documents to get a hang of Visual Basic. After trying out the example using timers --one drags a label and timer component into the designer and adds the following to the components subroutine
Label1.Text = My.Computer.Clock.LocalTime.ToLongTimeString

The output for the immediate window during debug is the following

A first chance exception of type
  'System.InvalidCastException' occured
  in Microsoft.VisualBasic.dll

  A first
  chance exception of type
  'System.InvalidCastException' occured
  in Microsoft.VisualBasic.dll

The same error occurs on a previous MSDN example using a context menu component. Should I Try...Catch...Finally this error and try to move on? Or, am I dealing with something much more serious?

A: In the Debug menu -> Exceptions, you can enable the debugger to stop when an Exception is first thrown, even if it would be caught later; if you want to find out what's happening, this is the easiest way to do it

A: When you see something about a first chance exception, it only means that an exception was caught within the code you called but does not necessarily mean that the code failed.  If the code runs without causing your program to crash and returns a valid value, then do not have a problem.  You will also see output in the debug window about first chance exceptions when you implement your own try/catch blocks.

A: In the first chance exception examine the details of the exception. You should see a stack frame/trace property. In there you should see what line the error occurs on. This should help you.

A: In the IDE try going to Tools > Options > Projects and Solutions > VB Defaults and setting Option Strict to 'On' - this may help catch casting problems when you compile your project rather than when you run it.
A 'first chance execption' does not necessarily mean you have a problem in your code.  It could mean the IDE or the compiler or any other involved component encountered and handled an error and in the process the debugger is notified and the exception is being reported to the immediate window.  This is an excellent post on the topic:
http://blogs.msdn.com/davidklinems/archive/2005/07/12/438061.aspx

A: A quick and easy solution for debug and diag of First Chance Exception is :
AppDomain.CurrentDomain.FirstChanceException += CurrentDomainOnFirstChanceException;

and then
private void CurrentDomainOnFirstChanceException(object sender, FirstChanceExceptionEventArgs firstChanceExceptionEventArgs)
    {
        if (firstChanceExceptionEventArgs.Exception is NullReferenceException)
        {
            // do your handling and debugging :)
        }
    }

Multiple First Chance Exception during the runtime can cripple the performance of your application because exception handling is expensive. Especially in web apps. You can add this handler and look at specific first chance exceptions and try to avoid/correct them.


text:
Q: notepad-plus-plus snap does not start on Ubuntu I installed notepad-plus-plus on Ubuntu machine. It was working fine. With no evident reason it stopped to work. Icon disappeared from application list. When I launch shell script /snap/notepad-plus-plus/current/bin/notepad-plus-plus I got error message:

You need to connect this snap to the wine-platform-i386 snap.
snap connect :wine-platform-plug wine-platform-i386:wine-base-stable

I removed snapd (sudo apt autoremove --purge snapd) and install it again. Same behavior.
I installed notepad-plus-plus snap on another Ubuntu system and it works fine.
How to 'connect' notepad-plus-plus snap to the wine-platform-i386 snap?

A: I solved this issue by these commamds in Linux.
1.snap install wine-platform-5-stable
2.snap connect notepad-plus-plus:wine-5-stable wine-platform-5-stable
3.snap run notepad-plus-plus

A: I was also facing same problem and I used these commands. Hopefully its working fine now.

1.sudo snap install notepad-plus-plus
2.sudo snap connect notepad-plus-plus:process-control
3.snap connect notepad-plus-plus:wine-platform-plug wine-platform:wine-base-stable

A: I solved my issued by these command:

*

*snap disconnect notepad-plus-plus:wine-6-stable

*snap install wine-platform-6-stable

*snap connect notepad-plus-plus:wine-6-stable wine-platform-6-stable

And then check it again by notepad-plus-plus
Phoungvd.

A: try this on command line :

snap disconnect notepad-plus-plus:wine-platform-plug snap install
wine-platform snap connect notepad-plus-plus:wine-platform-plug
wine-platform:wine-base-stable

then try opening notepad

notepad-plus-plus


text:
Q: React-Native (Android) : Request failed with status code 403 - bscscan api testnet Please help me, I'm so stuck on this problem: I'm making an request BSCSCAN-API-TESTNET with Axios on React Native and the request is working correctly only within the iOS, but it is not working with the Android (403 Forbidden response).
My URL request: https://api-testnet.bscscan.com/api?module=account&action=txlist&address=0x400ee0c820144c8bb559ace1ad75e5c13e750334&sort=desc&apikey=P3A263376TPJHKQ5IXUD4VHUNFQKDJB4G5
I updated the apiKey so don't mind it.
My code: (IOS: oke, android: throw error 403)
try {
  const url =
    'https://api-testnet.bscscan.com/api?module=account&action=txlist&address=0x400ee0c820144c8bb559ace1ad75e5c13e750334&sort=desc&apikey=P3A263376TPJHKQ5IXUD4VHUNFQKDJB4G5';
  const response = await axios.get(url);
} catch (error) {
  throw error;
}

A: Setting the user agent helped me solve the 403 issue.
try {
      const url =
        'https://api-testnet.bscscan.com/api?module=account&action=txlist&address=0x400ee0c820144c8bb559ace1ad75e5c13e750334&sort=desc&apikey=P3A263376TPJHKQ5IXUD4VHUNFQKDJB4G5';
      const response = await axios.get(url, {headers: { "User-Agent": "Mozilla/5.0" }});
    } catch (error) {
      throw error;
    }


text:
Q: How do I turn on a Samsung SyncMaster 2494HM monitor? How do I turn on my brand new Samsung SyncMaster 2494HM monitor?
I can't seem to turn it on. There's a row of monitor control symbols on the bottom right (including the universal I-in-the-O power symbol), but no distinct physical button. I suspect it has some sort of proximity sensor. I've tried pressing on the symbol, on the frame on the below, and on the case behind. Still nothing

*

*I've got it plugged in. I've checked the power cable is seated properly.

*I have the video cable connected. Double checked both ends.

*I've checked the outlet with another device.
Before I pack it up and take it back to the store, is there anything else I've missed?

A: There is a power switch on the back next to where the power cord plugs in on that model.

A: Hate to be a killjoy, but did you look in the manual? It's probably expained there ;-).


text:
Q: typescript - cast json to an interface I have an interface like this:
export default interface IProject extends{
    Id?:number;
    name?:string;
    description?:string;
}

and I when get data from  the server the json file includes more properties like this:
{
    id,
    name,
    description,
    url,
    startDate,
    finishDate
}

but I only need the id, name and description fields. I tried this:
response.data.map((p: any) => p as IProject);

but the object includes the unnecessary data like url, startdate and finishDate
how can I map them correctly?
I know that we can map them like this:
response.data.map((p: any) => {
    return {id:p.id,name:p.name,description:p.description}
});

but is there any other better ways to do that?

A: I'd recommend doing what you're doing, but additionally adding some types for your server response as well. That way you get some intellisense for your mapping functions.
interface IProject {
  id?: number;
  name?: string;
  description?: string;
}

interface IProjectResponse {
  id?: number;
  name?: string;
  description?: string;
  url?: string;
  startDate?: string;
  finishDate?: string;
}

const mapResponse = (response: IProjectResponse[]) => response.data.map((p) => ({
  id: p.id,
  name:p.name,
  description: p.description,
}));

const response = await fetch(/* .. */);
const data = await response.json();

const projects: IProject[] = mapResponse(data);


text:
Q: Java Thread join with two threads and a static variable public class TestThread2 {

    static int count = 0;
    public static void main(String[] args) {

        Thread t = new Thread(new Runnable(){
            public void run()
            {
                for (int i=1; i<=100000; i++) {
                    count++;
                }
            }
        });
        Thread t1 = new Thread(new Runnable(){
            public void run()
            {
                for (int i=1; i<=100000; i++) {
                    count++;
                }
            }
        });
        t.start();
        t1.start();

        try{
            t.join();
            t1.join();
        }
        catch(InterruptedException e){
            e.printStackTrace();
        }

        System.out.println(count);
    }
}

The above code prints various values of count such as 131938, 127518 etc. But I think it should always print 20000 as after join() is called, main thread cannot move to next statement until current thread dies. I know I'm missing a basic concept here, but I'm not able to figure it out so please help.

A: You are not synchronizing the variables. Instead of static int count, use an AtomicInteger.

A: i++ isn't atomic. It's effectively:
int j = i;
i = j + 1;

If two threads are trying to do this at the same time, the reads and writes from different threads could interleave, meaning that the value isn't strictly incrementing in each thread.
Additionally, there is no guarantee that the increased value from one thread is visible to the other thread.
Instead of using int, use AtomicInteger, and addAndGet. AtomicInteger guarantees both the atomicity of the incrementation and the visibility of the value between threads.
static AtomicInteger count = new AtomicInteger();

// In the thread:
count.incrementAndGet();

Note that something very similar to your example is described in the Oracle Java Tutorial.

A: Yes main thread blocks on join(). But the main thread does not write to the variable count, so it does not matter what main thread is doing. You have 2 threads, t and t1, which read and write the same variable count without any synchronization, and indeed it causes unstable results.