text:
Q: Elicit a Proper informative priors I need help with eliciting,deriving and plotting two proper informative prior.
One with mean and standard deviation
Another with LQ, UQ and Median
Is the first one using a normal distribution while the second uses a scaled beta distribution? I'm not honestly very good at priors, so any help would be very appreciated.

A: I'm answering on the premise that this is a homework question. Disclosure: I'm not a Bayesian, but I'm familiar with some concepts.
From comments, you appear to want to elicit a prior that describes a fraction. You seem to be asking, what sort of prior is conceptually sound for this? You seem like you may be debating between a normal prior and a beta prior.
The normal distribution has support of -$\infty$ to $\infty$. So, in principle, assuming a normal prior could mean that you have fractions less than zero or over 1. That might not be substantively sound.
The beta distribution has support (0, 1), i.e. 0 to 1 exclusive of 0 and 1. If you Google, you should find that it's often used as a prior for fractions. It has two key parameters, $\alpha$ and $\beta$. If you had $\alpha + \beta$ trials and you got $\alpha$ successes, you can derive the appropriate parameters for a beta distribution expressing that as a probability.
Imagine you asked 10 patients for their preference, and 3 said they'd prefer the treatment, i.e. 30% of the sample prefer the treatment, but it's a small sample, so we're not sure the 'true' proportion is 30% (clearly I'm a frequentist). That's a beta distribution with $\alpha = 3$ and $\beta = 7$, and its cumulative distribution function looks like this:

If you had instead asked 1000 patients for their preference, and 300 said they'd prefer the treatment, you have $\alpha = 300$ and $\beta = 700$, you still think that 30% of patients prefer the treatment, but you're a lot more certain about that value, as illustrated by this very different CDF:

If you want to make similar plots, you can just go to Wolfram Alpha and tell it, for example, "plot a beta distribution with a = 300 and b = 700".
I'm not sure how you are eliciting priors from experts on this. In principle, if you asked a statistician who had studied this area for a prior, she might respond, "I think the probability of choosing T follows a beta distribution with $\alpha = 3$ and $\beta = 7$, and unlike Mr. Ng, I'm a real Bayesian." It doesn't seem likely you'd get this sort of response. I rather suspect you would be asking a bunch of experts, maybe 10, if they think that the average patient would prefer C or T. Thus, you would be able to parameterize your prior according to how many respond C or T. If they give a more complex response, then I guess you will have to ask them to choose one or the other (or bribe them, or threaten them, or whatever).
I'm not familiar with "scaled" beta distributions. However, I hope this gets you on the right track to think about how and why you might use the beta distribution as a prior.


text:
Q: How to integrate my image editing app into photo's "Edit" section as an available editor in Lumia? I have an image editing app for Windows Phone 8.1. I want it to be displayed in the list of available editors, when I go to my photos' folder, select an image and press Edit. How should I do this?
P.S.I have done a "similar thing" with sharing. I added "Share Target" in Declarations tab of "Package.appxmanifest". When I press Share on some photo from my gallery, there is a list item with my app's name. Then I overrode "OnShareTargetActivated" in app.Xaml and did what I wanted.
Is there an analogical way of doing this with "edit" section?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android Mobile Browser Changing href attr to # I'm having a problem with the href attr showing as '#' when using an Android Browser. In the desktop browsers I have tried (Chrome/Firefox) it alerts correctly as "http://test/dir/action/" but on Android 2.3 & 4.0 devices I have tried it comes up only as '#'.
See jsfiddle:
http://jsfiddle.net/7gfm3/

A: It appears this was fixed in the current test version of JQuery Mobile. See:
https://github.com/jquery/jquery-mobile/issues/4372


text:
Q: Rails 4: Devise Invitable Unpermitted Parameter I am using the Devise Invitable gem to invite users and after creating the user, I create a client with a user_id that is equal the id of the user that was just created
class User < ActiveRecord::Base
    after_create :create_client

    def create_client
        new_client = Client.new()
        new_client.user_id = self.id
        new_client.save
    end
end

This works, but once I tried to add location_id to the parameters, I see:
Unpermitted parameter: location_id

Here is the new method with location_id
def create_client
    new_client = Client.new()
    new_client.user_id = self.id
    new_client.location_id = self.location_id
    new_client.save
end

I've read a lot of responses about this issue, but cannot seem to find a real solution to whitelist this parameter.  Does anyone have a method that works in Rails 4 with Devise 3.5

A: It was crucial to whitelist the params for :invite and not just for :accept_invitation.  The following worked when I added it to my application_controller:
def configure_permitted_parameters
    devise_parameter_sanitizer.for(:accept_invitation) << [:location_id]
    devise_parameter_sanitizer.for(:invite) << [:location_id]
end


text:
Q: how to get the spark broadcast variable in the executor? spark-core here, I have one app which has two jobs. And in the first job, i want to set the broadcast such as setting the broadcast variable "true", accessing the broadcast in the executor. and in the second job, i want to set the broadcast variable "false". and How to achieve the requirement?
my code is:
val conf = new SparkConf()
val sc = new SparkContext(conf)
var setCapture = true
sc.broadcast(setCapture)
val file = lc.textFile("file" ,2)
val flatMap = file.flatMap(line => line.split(" ")).map(word => (word, 1)).reduceByKey(_ + _)
val report = counts.collect()
setCapture = false
sc.broadcast(setCapture)
val packageResult = sc.parallelize(report).filter(_._1 == "package")
packageResult.collect.foreach(println)

and I want to access the broadcast variable  " setCapture " in the
org.apache.spark.scheduler.ResultTask,
org.apache.spark.rdd.HadoopRDD,
org.apache.spark.util.collection.ExternalAppendOnlyMap,
org.apache.spark.shuffle.hash.HashShuffleWriter.
What should i do?

A: From Spark documentation

Broadcast variables are created from a variable v by calling SparkContext.broadcast(v). The broadcast variable is a wrapper around v, and its value can be accessed by calling the value method. The code below shows this:

scala> val broadcastVar = sc.broadcast(Array(1, 2, 3))
broadcastVar: org.apache.spark.broadcast.Broadcast[Array[Int]] = Broadcast(0)

scala> broadcastVar.value
res0: Array[Int] = Array(1, 2, 3)

After the broadcast variable is created, it should be used instead of the value v in any functions run on the cluster so that v is not shipped to the nodes more than once. In addition, the object v should not be modified after it is broadcast in order to ensure that all nodes get the same value of the broadcast variable (e.g. if the variable is shipped to a new node later).


text:
Q: DirectoryIndex ignoring index.php I am trying to setup my Apache2 from scratch, it installed with no modules enabled, or any relavant default configuration for what could be considered a 'web host' (in fact html displayed as text, and PHP files downloaded)
Anyways I have this in my httpd.conf
# Default Directory Settings
<Directory />
     DirectoryIndex index.html index.php
     Options FollowSymLinks
     AllowOverride All
</Directory>

index.html seems to work find by default but index.php will not work. What am I doing wrong?
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    <IfModule mod_php5.c>
        AddType application/x-httpd-php .php
        AddType application/x-httpd-php-source .phps
        php_flag magic_quotes_gpc Off
        php_flag track_vars On
        php_flag register_globals Off
        php_value include_path .
    </IfModule>
    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    DocumentRoot /home/was/www
    <Directory /home/was/www/>
        Options FollowSymLinks
        Options +ExecCGI Indexes FollowSymLinks MultiViews
        DirectoryIndex index.html index.php
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
    <Location /cgi-bin >
        SetHandler cgi-script
        Options +ExecCGI
    </Location>
    <Directory /usr/lib/cgi-bin>
        AllowOverride None
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Order allow,deny
        Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Notice all the hacks just to get things to work, like PHP. It's annoying.

A: Apparently, if you don't have a site enabled, Apache2 may still load up the file and use some of it's settings.
This file, particularily, declared one of my IPs to use, and forward to a new www document root, on a new port. That was working, even with the site disabled, but the <directory> and other settings were not working, until I enabled it.
My bad, but weird functionality on Apache2's part.


text:
Q: SQL Server Pivot Trouble Does anyone know how I can pivot this query so that the Manufacturer.name are the columns and the rows are the months, which are calculated in the sub-queries.
SELECT Manufacturer.manufacturer_id
      ,Manufacturer.name
      ,(SELECT ISNULL(SUM(SalesOrderLineItem.price*SalesOrderLineItem.quantity), 0)
        FROM SalesOrderLineItem
        INNER JOIN Products
            ON SalesOrderLineItem.product_id = Products.product_id
        INNER JOIN SalesOrder
            ON SalesOrderLineItem.order_id = SalesOrder.sales_order_id
        INNER JOIN Client
            ON SalesOrder.client_id = Client.client_id
        WHERE products.manufacturer_id = Manufacturer.manufacturer_id
          AND Client.client_id = '224'
          AND SalesOrder.order_placed BETWEEN '2014-09-01 00:00:00' AND '2014-09-30 23:59:00') AS 'sep-14'
      ,(SELECT ISNULL(SUM(SalesOrderLineItem.price*SalesOrderLineItem.quantity), 0)
        FROM SalesOrderLineItem
        INNER JOIN Products
            ON SalesOrderLineItem.product_id = Products.product_id
        INNER JOIN SalesOrder
            ON SalesOrderLineItem.order_id = SalesOrder.sales_order_id
        INNER JOIN Client
            ON SalesOrder.client_id = Client.client_id
        WHERE products.manufacturer_id = Manufacturer.manufacturer_id
          AND Client.client_id = '224'
          AND SalesOrder.order_placed BETWEEN '2014-10-01 00:00:00' AND '2014-10-31 23:59:00') AS 'oct-14'
      ,(SELECT ISNULL(SUM(SalesOrderLineItem.price*SalesOrderLineItem.quantity), 0)
        FROM SalesOrderLineItem
        INNER JOIN Products
            ON SalesOrderLineItem.product_id = Products.product_id
        INNER JOIN SalesOrder
            ON SalesOrderLineItem.order_id = SalesOrder.sales_order_id
        INNER JOIN Client ON SalesOrder.client_id = Client.client_id
        WHERE products.manufacturer_id = Manufacturer.manufacturer_id
          AND Client.client_id = '224'
          AND SalesOrder.order_placed BETWEEN '2014-11-01 00:00:00' AND '2014-11-30 23:59:00') AS 'nov-14'
      ,(SELECT ISNULL(SUM(SalesOrderLineItem.price*SalesOrderLineItem.quantity), 0)
        FROM SalesOrderLineItem
        INNER JOIN Products
            ON SalesOrderLineItem.product_id = Products.product_id
        INNER JOIN SalesOrder
            ON SalesOrderLineItem.order_id = SalesOrder.sales_order_id
        INNER JOIN Client
            ON SalesOrder.client_id = Client.client_id
        WHERE products.manufacturer_id = Manufacturer.manufacturer_id
          AND Client.client_id = '224'
          AND SalesOrder.order_placed BETWEEN '2014-12-01 00:00:00' AND '2014-12-31 23:59:00') AS 'dec-14'
FROM Manufacturer

Many thanks.

A: Give it a try:
WITH DATA
AS
(
    SELECT Manufacturer.name AS ManufacturerName
          ,MONTH(SalesOrder.order_placed) AS MonthNumber
          ,ISNULL(SUM(SalesOrderLineItem.price*SalesOrderLineItem.quantity), 0) AS Total
    FROM SalesOrderLineItem
    INNER JOIN Products
        ON SalesOrderLineItem.product_id = Products.product_id
    INNER JOIN SalesOrder
        ON SalesOrderLineItem.order_id = SalesOrder.sales_order_id
    INNER JOIN Client
        ON SalesOrder.client_id = Client.client_id
    INNER JOIN Manufacturer
        ON products.manufacturer_id = Manufacturer.manufacturer_id
       AND Client.client_id = '224'
       AND SalesOrder.order_placed BETWEEN '2014-09-01 00:00:00' AND '2014-12-31 23:59:00'
)
SELECT MonthNumber, [ManufacturerName1], [ManufacturerName2]
FROM DATA
PIVOT (MAX(Total) FOR ManufacturerName IN ([ManufacturerName1], [ManufacturerName2])) AS P;

Unfortunately, you have to hard code the Manufacturer names in the query or use dynamic SQL for unknown Manufacturers.


text:
Q: creating barplots using for loop using pandas/matplotlib I have below code:
def OS_Usage_Zone_Wise(data,zone):
   data_os = data['os'].value_counts().plot("bar",figsize=(12,4),fontsize=10)
   data_os.set_title("OS usage in "+zone+" region",color='g',fontsize=20)
   data_os.set_xlabel("OS name",color='b',fontsize=20)
   data_os.set_ylabel("use count",color='b',fontsize=20)

zone = ["east","west","south","central"]
i = 0
data_os = [data_east,data_west,data_south,data_central]
for data in data_os:
     OS_Usage_Zone_Wise(data,zone[i])
     print("now "+zone[i])
     i = i+1

I am trying plot for every zone using a for loop,but its displaying oly graph
for 'central' zone,I understand thats it showing the last bar and not displaying
the previous ones,is there any way to plot graph for all zones using a loop(dont
want to do generate graph by using same code again and again)

A: You can use matplotlib to create separate axes and then plot each histogram on a different axis. Here is some sample code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Create some dummy data
data = pd.DataFrame()
zones = ["east","west","south","central"]

data['zone']=np.hstack([[zone]*np.random.randint(10,20) for zone in zones])
data['OS Usage']=np.random.random(data.shape[0])

# Now create a figure
fig, axes = plt.subplots(1,4, figsize=(12,3))

# Now plot each zone on a particular axis
for i, zone in enumerate(zones):
    data.loc[data.zone==zone].hist(column='OS Usage',
                                   bins=np.linspace(0,1,10),
                                   ax=axes[i],
                                   sharey=True)
    axes[i].set_title('OS Usage in {0}'.format(zone))
    axes[i].set_xlabel('Value')
    axes[i].set_ylabel('Count')

fig.tight_layout()
fig.show()

Which produces the following figure:

Notes:

*

*You can use enumerate to loop through the zones and simultaneously generate an index to specify the axis used.

*The tight_layout() will ensure all the labels, title, etc. fit nicely in the figure.

*By specifying the axes you have much more control over them.

Hope this helps!


text:
Q: Creating a dictionary from a separate list of keys and values using dict comprehension in Python A friend of mine and me were facing a tricky task today I thought would be worth sharing here.
This is the basis:
keys = ["name", "surname", "age"]
values = ['John    Miller    20',
          'James   Smith     30',
          'Gary    Jones     50'
         ]
d = {}

We would like to create a dictionary in the following format:
{'name': ['John', 'James', 'Gary'],
 'surname': ['Miller', 'Smith', 'Jones'],
 'age': [20, 30, 50]}

The tricky part is that we would like to do it in only one line.
I'm very interested in the approaches you'll come up with!

A:
The tricky part is we would like to do it in only one line.

You could tie a few zips together.
d = dict(zip(keys, list(zip(*[value.split() for value in values]))))

If you now do print(d) it would output:
{'name': ('John', 'James', 'Gary'), 'surname': ('Miller', 'Smith', 'Jones'), 'age': ('20', '30', '50')}

This is of course assuming that value.split() always results in 3 values.
Edit: If you want the tuples to be lists, then throw list(a) for a in ... into the mix:
d = dict(zip(keys, list(list(a) for a in zip(*[value.split() for value in values]))))

Which outputs:
{'name': ['John', 'James', 'Gary'], 'surname': ['Miller', 'Smith', 'Jones'], 'age': ['20', '30', '50']}

A: How about using numpy?
import numpy as np

d = dict(zip(keys, np.array([i.split() for i in values]).transpose().tolist()))

{'age': ['20', '30', '50'],
 'name': ['John', 'James', 'Gary'],
 'surname': ['Miller', 'Smith', 'Jones']}

Benchmarks: Looks like @Vallentin's answer is faster
time d = dict(zip(keys, list(zip(*[value.split() for value in values]))))

CPU times: user 23 µs, sys: 1 µs, total: 24 µs
Wall time: 29.1 µs

time d = dict(zip(keys, np.array([i.split() for i in values]).transpose().tolist()))

CPU times: user 41 µs, sys: 6 µs, total: 47 µs
Wall time: 47.9 µs


text:
Q: Does Synthetic Meat patent improve food production in all subsequent weeks of the campaign mode missions? The Synthetic Meat patent's description says "Greenhouse Farm is permanently boosted" but what does it mean exactly? Does it increase the production by 1 level and last for the entire duration of the remaining weeks in the mission?

A: Synthetic Meat is a patent available on Io that makes farms act as if they are affected by an Adrenaline Boost. This means they will produce twice as much food and use twice as much water and power. This does not stack with other Adrenaline Boosts from the black market.
In the campaign, it behaves like any other patent, lasting until the end of the campaign if bought, or for multiple weeks if awarded for a mission.


text:
Q: Drawing in canvas from base 64 image as source I'm using cropping plugin from http://deepliquid.com/content/Jcrop.html to select an image area. When working with a common URL src image, the cropping preview works. When the src is a base 64 string, it doesn't.
Been Googling about possible reasons, but no luck.
Code looks like this:
function updatePreview(c)
{
    if(parseInt(c.w) > 0)
    {
        var img = new Image,
        src = $('.jcrop-holder img').attr('src'),
        cvs = document.getElementById('preview'),
        ctx = cvs.getContext('2d');
        img.crossOrigin = "Anonymous";
        img.onload = function()
        {
            console.log('Onload event fired!');
            var ctx = cvs.getContext("2d");
            ctx.drawImage(img, c.x, c.y, c.w, c.h, 0, 0, cvs.width, cvs.height);
            var dataURL = cvs.toDataURL();
            new_image = dataURL;
        }
        img.src = src;
        if ( img.complete || img.complete === undefined )
        {
            console.log('Undefined!');
            img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
            img.src = src;
        }

    }
};

Also, when I start dragging the area selector, with the code64 image it suffers from certain delay.

A: The base 64 I have comes from another canvas, I have found here: Display canvas image from one canvas to another canvas using base64 that the best option is to use the originary canvas as source for the drawimage(). The problem is still the performance, but I will write another question more specific.


text:
Q: jdbcTemplate.batchUpdate for list of inserts doesn't work I'm out of nerves cells and I really need your help guys.
For some reason I can't get list of answers inserted to database
I use jdbcTemplate to do that and my code looks like this
public void insertVastaukset(List<Vastaus> vastaukset) {
    final String sql = "insert into vastaus (kysymysID, vastausteksti) values(?,?)";
    getJdbcTemplate().batchUpdate(sql,
            new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i)
                        throws SQLException {
                    Vastaus vastaus = vastaukset.get(i);
                    ps.setInt(1, vastaus.getKysymysID());
                    ps.setString(2, vastaus.getVastausteksti());

                }

                @Override
                public int getBatchSize() {
                    return vastaukset.size();
                }
            });}

And for some reason the program gives no error! When i tried it couple days ago it gave me null pointer, but now its fixed but still no inserts are created into database. Help me please, Thank you very much!

A: Use the below catch block to examine the exceptions
    int[] updateCounts;
    try {
        updateCounts = getJdbcTemplate().batchUpdate("insert into test123 (id, value) values (?,?)",
                new BatchPreparedStatementSetter() {

                //// YOUR CODE HERE

                });
    }
     catch (Exception sqle) {
        Throwable s2 = sqle;
        System.out.println("=============v"+s2.getClass().getName()+"=====================");
        while (s2!=null) {
            s2.printStackTrace();
            s2 = s2.getCause();
            if(s2 instanceof java.sql.BatchUpdateException) {
                System.out.println("======================^^^^^^======================");
                ((java.sql.BatchUpdateException) s2).getNextException().printStackTrace();
            }
        }
        throw sqle;
    }


text:
Q: Spring OAuth Filter Chain & Java Config I'm trying to add in spring-security-oauth to an existing app with spring-security. I'm using Java config.
I have an existing amended filter chain in place (with some custom filters added in) but requests to '/oauth/token' aren't using it, but are using the 'default' filter chain. How can i get access to the filter chain that's securing the oauth endpoints so that i can use the custom filters there also or can I wire in the OAuth endpoint(s) into the existing setup?

A: there is indeed a slightly smoother way using the interface AuthorizationServerConfigurer.
You can stick to the annotation @EnableAuthorizationServer and implement above interface in your configuration file. This will enable you to alter the oauth2-filter-chain by doing something like this:
@Configuration
@EnableWebSecurity
@EnableAuthorizationServer
public class SecurityConfig extends WebSecurityConfigurerAdapter
implements AuthorizationServerConfigurer
    // some configuration ...

    public void configure(AuthorizationServerSecurityConfigurer oauthSecurity) throws Exception {
        oauthSecurity.addTokenEndpointAuthenticationFilter(new YourFilter());
    }

    // more configuration ...
}

In contrast to the addFilterXYX-methods of HttpSecurity you have no fine-grained influence here where the filter will be positioned in the filter chain. Any filter added by addTokenEndpointAuthenticationFilter will be inserted before the BasicAuthenticationFilter.
If you need to control the position of you filter in a more detailed way you could create a bean extending AuthorizationServerConfigurerAdapter instead of using the annotation @EnableAuthorizationServer. I did not try that but I guess you could then extend AuthorizationServerSecurityConfigurationlike systemfreund suggested without having to specify @Order(-1) because only your custom configuration gets imported. Probably you would also have to @Import AuthorizationServerEndpointsConfigurationlike it is done in the convenience annotation @EnableAuthorizationServer.

A: It's probably not the best way to do it, but I did not manage to find a better approach. The idea is to provide a custom AuthorizationServerSecurityConfiguration instance and override the default instance which is @Imported via @EnableAuthorizationServer. We just need to make sure to add an @Order annotation with higher precendence than the default configuration:
@EnableAuthorizationServer
@Import(CustomSecurityConfig.class)
public class Application {
}

@Configuration
@Order(-1)
public class CustomSecurityConfig extends AuthorizationServerSecurityConfiguration {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http); // do the default configuration first

        http
            .addFilterBefore(new MyFilter(), ...);
    }

}


text:
Q: How to provide subscriber with routing capability I have following path for stream -
 kafkaStream[message] ->
 kafkaStream[message] -> mergedKafkaStream[message] -> stream[EnrichedMessage] -> I/O
 kafkaStream[message] ->

I am not sure how to write this in akka stream way.
I tried following (pseudo).
KafkaStream extends ActorPublisher[message] {

}

IOHandler extends ActorSubscriber {

}

k1, k2, k3 are kafka streams publishers
f = Flow[message].map(_.enrichMessage)

FlowGraph { b =>
  k1 ~> merge
  k2 ~> merge
  k3 ~> merge
  merge ~> f ~> ioHandlerSink
}

So this is the way I connect publisher to sink. But here the problem that I want to resolve is slow IO. IOHandler actor is very slow for processing message, so how I can have multiple IOHandlers and I should be able to distribute the tasks. And I also want to maintain the back pressure so not using fire and forget using router.
I am very new to akka stream, so suggest me a way out.
Thanks

A: You can route to multiple IOHandler sinks using a Balance junction in your FlowGraph.


text:
Q: Replace multiple words in string I have multiple words I want to replace with values, whats the best way to do this?
Example:
This is what I have done but it feels and looks so wrong
string s ="Dear <Name>, your booking is confirmed for the <EventDate>";
string s1 = s.Replace("<Name>", client.FullName);
string s2 =s1.Replace("<EventDate>", event.EventDate.ToString());

txtMessage.Text = s2;

There has to be a better way?
thanks

A: You can chain the Replace operations together:
s = s.Replace(...).Replace(...);

Note that you don't need to create other strings to do this.
Using String.Format is the appropriate way, but only if you can change the original string to suit the brace formatting.

A: When you do multiple replaces it's much more efficient to use StringBuilder instead of string. Otherwise replace function is making a copy of the string every time you run it, wasting time and memory.

A: Try this code:
string MyString ="This is the First Post to Stack overflow";
MyString = MyString.Replace("the", "My").Replace("to", "to the");

Result: MyString ="This is My First Post to the Stack overflow";

A: You could use String.Format.
string.Format("Dear {0}, your booking is confirmed for the {1}",
   client.FullName, event.EventDate.ToString());

A: Use String.Format:
const string message = "Dear {0}, Please call {1} to get your {2} from {3}";
string name = "Bob";
string callName = "Alice";
string thingy = "Book";
string thingyKeeper = "Library";
string customMessage = string.Format(message, name, callName, thingy, thingyKeeper);

A: If you're planning on having a dynamic number of replacements, which could change at any time, and you want to make it a bit cleaner, you could always do something like this:
// Define name/value pairs to be replaced.
var replacements = new Dictionary<string,string>();
replacements.Add("<Name>", client.FullName);
replacements.Add("<EventDate>", event.EventDate.ToString());

// Replace
string s = "Dear <Name>, your booking is confirmed for the <EventDate>";
foreach (var replacement in replacements)
{
   s = s.Replace(replacement.Key, replacement.Value);
}

A: To build on George's answer, you could parse the message into tokens then build the message from the tokens.
If the template string was much larger and there are more tokens, this would be a tad more efficient as you are not rebuilding the entire message for each token replacement.  Also, the generation of the tokens could be moved out into a Singleton so it is only done once.
// Define name/value pairs to be replaced.
var replacements = new Dictionary<string, string>();
replacements.Add("<Name>", client.FullName);
replacements.Add("<EventDate>", event.EventDate.ToString());

string s = "Dear <Name>, your booking is confirmed for the <EventDate>";

// Parse the message into an array of tokens
Regex regex = new Regex("(<[^>]+>)");
string[] tokens = regex.Split(s);

// Re-build the new message from the tokens
var sb = new StringBuilder();
foreach (string token in tokens)
   sb.Append(replacements.ContainsKey(token) ? replacements[token] : token);
s = sb.ToString();

A: Improving on what @Evan said...
string s ="Dear <Name>, your booking is confirmed for the <EventDate>";

string s1 = client.FullName;
string s2 = event.EventDate.ToString();

txtMessage.Text = s.Replace("<Name>", s1).Replace("EventDate", s2);


text:
Q: how to convert this HTML file into a PDF using python I am having a process where my python code needs to generate a PDF.
I have an HTML file as follows:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./proforma_supply_bill.css">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Karla:wght@400;600;700&family=Rajdhani:wght@700&display=swap"
        rel="stylesheet">
    <title>Proforma bill of supply</title>

PROFORMA Bill of Supply

                    Proforma Invoice No.:
                    {{PROFORMA_INV_NO}}

                    Reference No. & Date.:
                    {{REF_NO}}

                    Buyer's Order No.:
                    {{BUYER_ORDER_NO}}

                    Vessel/Flight No.:
                    {{VESSEL_NAME}}

                    City/Port of Loading:
                    {{POL}}

                    Terms of Delivery:
                    {{DELIVERY_TERMS}}

                    Dated:
                    {{INV_DATE}}

                    SAIL Date:
                    {{SAIL_DATE}}

                    Place of Receipt by Shipper:
                    {{PLACE_OF_RECEIPT}}

                    City/Port of Discharge:
                    {{POD}}

                Buyer (Bill to)

XPORTIFY TECHNOLOGIES PRIVATE LIMITED

                    3rd Floor, 313-314, A/3, BGTA Ganga Premises, Wadala Truck Terminal, Near Wadala RTO, Wadala East,
                    Mumbai

                    GSTIN/UIN:
                    27AAACX2283M1ZX

                    PAN No:
                    AAACX2283M

State Name: Maharashtra, Code: 27

                    CIN:
                    U74999MH2017PTC295494

{{BUYER_COMPANY_NAME}}

                    {{BUYER_ADDRESS}}

                    GSTIN/UIN:
                    {{BUYER_GST}}

State Name: {{BUYER_STATE}}

                    Place of Supply:
                    {{BUYER_PLACE_OF_SUPPLY}}

Sr. No.

Description of Services

HSN/SAC

Quantity

Rate

Per

                            Amount

1

Freight Charges

$ 1938/20x1x@74.97

996521

1

7,900.00

Container

USD
                            7,900.00

Total

USD 7,900.00

Amount Chargeable (in words)

USD Seven Thousand Nine Hundred Only

E & O.E

HSN/SAC

Taxable Value

996521

INR 1,45,291.86

Total

INR 1,45,291.86

            Tax Amount (in words):
            NIL

            Declaration

            We declare that this invoice shows the actual price of the goods described and that all particulars are true
            and correct.

            for XPORTIFY TECHNOLOGIES PRIVATE LIMITED

Authorised Signatory

I want to convert this HTML file into a PDF using Python.
I have one option of using wkhtmltopdf package but I have to run it using the command line everytime.
Which is the most optimal way of doing this without hampering the flow of my code?

A: *

*Install pdfkit package
 pip install pdfkit

*Install wkhtmltopdf https://wkhtmltopdf.org/downloads.html

*PDF to HTML in the current folder
import pdfkit
import glob

3.1 Set wkhtmltopdf executable file path
config = pdfkit.configuration(wkhtmltopdf='C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe')

3.2 Convert all html files in the current folder
for file in glob.glob('./*.html'):
    pdfkit.from_file(file, file[:-4]+'.pdf', configuration=config)


text:
Q: Выравнивание элементов внутри div Тема наверняка избитая, но остаются непонятки.
Пытаюсь сверстать окошко div-ами. Получился вот такой код:

Вопрос такой: почему для объекта класса arrow нельзя никак задать отступ, кроме как margin? Какие-нибудь padding-top и top принимают значение auto, даже если их задать явно. popup-left тоже нельзя сдвинуть.
A: Все блочные элементы имеют отступы margin и padding. Например, тут желтый фон - это margin, а красный - это padding. Однако, в режиме разметки strict img могут быть рендерится
как inline элементы, по этому часто для всех img явно задают свойство display: block;
Для того, что бы позиционировать элементы относительно текущего местоположения при помощи свойств top, bottom, etc, необходимо выставить свойство position: relative; К примеру, что бы отцентрировать по вертикали элементы с классом arrow, можно задать стиль:
.arrow {
    position: relative;
    top: 50%;
    /* height: 50px; */  /* высота позиционируемого элемента */
    margin-top: -25px;   /* эта величина равна половине высоты элемента  */
}

http://cssdesk.com/2KR6S
A: Я не очень понял вопроса, но можно задать свойство у popup_left и popup_right
position: relative,

а у arrow, сталбыть,
position: absolute

Ну и top работать будет.
A: .arrow добавьте position:relative;
А добавлять padding изображению - странная идея.
A: Самое простое, это переделать весь popup_conteiner.
В торопях набросал пример, можете оттолкнуться от него - https://jsfiddle.net/ausooyy2/1/

Чтоб сайт не ругался:

CSS:
div#popup_container {width: 240px; height: 150px; left: 359px; top: 206px; background-color: #e2d5e9;}
div#wrap {display: table; width: 100%; height: 100%;}
div#popup_arrow, div#popup {display: table-cell; vertical-align: middle;}
div#popup_arrow {width: 9px; cursor: pointer;}
div#popup {width: 200px;}
div#popup_arrow {background-repeat: no-repeat; bacground-position: center; background-size: 8px;}
div#popup_arrow.left {background-image: url("imgs/arrow_left.png");}
div#popup_arrow.right {background-image: url("imgs/arrow_right.png");}
#img_big {display: block; width: 100%; height: 100%;}


text:
Q: Why triggering and simulation of button clicking from typescript code in html doesn't work? I have a button component in my navbar.component.html as shown below. I would like to simulate and trigger clicking in button Upload from navbar.component.ts file. When I click Upload button it automatically opens file selector for instance on my mac it is finder.
Then I select the file and it is uploaded to the backend. I want to achieve the same action but using typescript code. So I just want to simulate as the user would click Upload button what will cause opening file selector and then all other activities will be the same as he would click button. Any ideas why it is not working? I did everything as was shown here.
In navbar.component.ts:
      event.preventDefault();
      let element: HTMLElement = document.getElementById('trigger') as HTMLElement;
      element.click()

I tried also:
  @ViewChild('myTrigger') myTrigger: ElementRef;

this.myTrigger.nativeElement.click();
              let el: HTMLElement = this.myTrigger.nativeElement as HTMLElement;
              el.click();

uploadFile():
uploadFile(){

    this.UploaderService.uploader = new FileUploader({url: URL + localStorage.getItem('current_path') + '/', autoUpload: true , itemAlias: 'file', authToken: 'token ' + localStorage.getItem('userToken')});

    this.UploaderService.uploader.onCompleteItem = (item:any, response:any , status:any, headers:any) => {

            this.UploaderService.displayAllFiles();
            this.ExecuteWhenSidebarClose();
        }

                this.UploaderService.uploader.onBeforeUploadItem = (item) => {
        item.withCredentials = false;
}

this.UploaderService.uploader.onAfterAddingFile = (item) => {
  // item.method = "PUT";
  item.withCredentials = false;
}

}

In navbar.component.html:

    Upload

      <input type="file" name="fileUplaod" id="fileUpload" multiple ng2FileSelect [uploader]="this.UploaderService.uploader">


text:
Q:  tag producing error: React.createElement: type is invalid Error in React Router's link tag while switching from 0.14 to v15.5. This worked fine in the former version and it throws the following error in the latter.

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of Navbar.

navbar.js
import React, { Component } from 'react';
import Link from 'react-router-dom';

class Navbar extends Component
{
  render()
  {
     return (

           <Link className="btn btn-primary btn-block" to="/about">
           About Us
           </Link>

     );
  }

  export default Navbar;

index.js
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

import HomePage from './components/homepage/homepage';
import AboutPage from './components/aboutpage/aboutpage';

render
(
    <BrowserRouter>
        <Switch>
            <Route path="/about" component={AboutPage} />
            <Route path="/" component={HomePage} />
        </Switch>
    </BrowserRouter>,
    document.getElementById('app')
);

A: this error generally comes if you have not imported or exported a component successfully in your components.For more more info you can read react documentation of when to use curly braces while import and when not:)
import { Link } from "react-router-dom";

.

<Link to="x">x</Link>

<Link to="y">y</Link>

<Link to="z">z</Link>


text:
Q: Javascript d3.js reading local CSV file So I need to read a .CSV file using a HTML webpage loaded locally (e.g with file:///) and plot the contants on a graph using d3.js. So far I have attempted to join two examples together without success...
If you open it, it is able to read the contents of the local csv file, but for some reason the graph does not appear.
Any help much appreciated!
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="chrome=1" />
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>

    <meta http-equiv="Access-Control-Allow-Origin" content="*"/>
    <title>Process local CSV file</title>

A: svg is being selected here but its not there in dom:
var svg = d3.select("svg"),

Either add svg element in the html or append to body using d3 by replacing the above code with:
var svg = d3.select("body").append('svg').attr('width', 300).attr('height', 300),


text:
Q: In stress-strain diagrams, why is the dependent axis ($y$) used to represent stress and the independent axis ($x$) to represent strain? why this convention is used

despite the fact that strain is influenced by stress (cause -> stress, effect -> strain)

A: Because the equipment used to measure stress-strain curves works by applying a strain that increases linearly with time and measuring the stress. The strain is the independent variable.
The problem with measuring strain as a function of stress is that it's not uncommon for the stress to fall with increasing strain once a yield point is reached, like this:

Picture from this page
If you used a linearly increasing stress your measurements would miss this behaviour.

A: Besides the very good answer by John Rennie, a couple of other notes:

*

*You can choose whatever axis orientation you deem appropriate, it is based on conventions, and people often do what other people do without thinking too deeply about it. This simplifies (and is actually the basis of) communication.

*Everyone draws $F(x)$ diagrams, so what should be strange about $\sigma(\epsilon)$ diagrams?

*What is cause and what is effect is often undecidable on this most basic level. In technology it is most often a matter of what variable is controlled. A CNC milling machine for example does not (primarily) control force to cut the workpiece, because this would require a complicated calculation (involving tool shape, Young's modulus, plastic properties, possible defects, heat conduction, axis/tool speed...) to determine the right force, and any small irregularity in the material would then cause the cutter to be drawn in and produce an undesired shape. Controlling position limits any undesired movement (even though it cannot prevent it completely). On the other hand, the motor that drives the axis of the CNC machine is often controlled on the lowest level by providing a certain set point electric current (which somehow results in force control). It would be much too unreliable/unstable to calculate beforehand (i.e. open-loop/uncontrolled) the voltage needed to apply to the motor, because there is a complicated relationship between voltage and motor force (involving Ohmic resistance, induction, load, speed, temperature...). So the overall control guides position, but the desired current this controller provides is fed into the underlying current/force controller which adjusts voltage until it satisfies the given current.

As John Rennie already emphasized, a testing machine controls position (strain), not least because if the workpiece fails (tears), force control would result in very fast motion that bears the risk of damaging the machine itself.

A: I would like to emphasize that stress is a intensive physical quantity and strain is a extensive physical quantity. I prefer to graph the stress on the vertical axis and the strain on the horizontal axis, taking the intensive physical quantity on the vertical axis and the extensive physical quantity on the horizontal axis.


text:
Q: Проблема с установкой фона кнопки пытаюсь применить фон к кнопке описал данный фон в папке res/drawable.
Код фона:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF"/>
        </shape> </item> <item android:top="1dp">
    <shape android:shape="rectangle"> <solid android:color="#2D2D2D"/>
    </shape>
</item>
</layer-list>

Применяю фон к кнопке следующим образом: btnAnswer1.setBackground(Drawable.createFromPath("@drawable/btn_top_border"));
Ошибки не возникает, но фон кнопки в приложении отличается от того, который я пытаюсь выставить.
Код метода onCreate:
@Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);

        ct1 = (ConstraintLayout) findViewById(R.id.cl1);

        btnSound = (ImageButton) findViewById(R.id.btnSound);
        btnMenu = (ImageButton) findViewById(R.id.btnMenu);

        tvLearningWords = (TextView) findViewById(R.id.tvLearningWords);
        tvTranscription = (TextView) findViewById(R.id.tvTranscription);

        setTitle("Новые слова");

        btnAnswer1 = (Button) findViewById(R.id.btnAnswer1);
        btnAnswer2 = (Button) findViewById(R.id.btnAnswer2);
        btnAnswer3 = (Button) findViewById(R.id.btnAnswer3);
        btnAnswer4 = (Button) findViewById(R.id.btnAnswer4);
        btnAnswer5 = (Button) findViewById(R.id.btnAnswer5);

        btnSound.setOnClickListener(this);
        btnMenu.setOnClickListener(this);
        btnAnswer1.setOnClickListener(this);
        btnAnswer2.setOnClickListener(this);
        btnAnswer3.setOnClickListener(this);
        btnAnswer4.setOnClickListener(this);
        btnAnswer5.setOnClickListener(this);

        SharedPreferences sp = getSharedPreferences(MY_SETTINGS, Context.MODE_PRIVATE);

        boolean hasVisited = sp.getBoolean("hasVisited", false);
        themen = sp.getString("themen", "Night");
        mDBHelper = new DatabaseHelper(this);
        mDb = mDBHelper.getWritableDatabase();

        btnAnswer1.setBackground(Drawable.createFromPath("@drawable/btn_top_border"));

        if (!hasVisited) {
            writeFile();
            readFile();

            startActivity(new Intent(this, FirstStartActivity.class));

            SharedPreferences.Editor e = sp.edit();
            e.putBoolean("hasVisited", true);
            e.commit();
        }
}

A: Drawable.createFromPath разве не с абсолютными путями работает?
Попробуйте лучше:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
    btnAnswer1.setBackground(getResources().getDrawable(R.drawable.btn_top_border));
else
    btnAnswer1.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_top_border));

или
btnAnswer1.setBackgroundResource(R.drawable.btn_top_border);


text:
Q: Query para atualizar campo de uma tabela com base em outra Bom dia, estou precisando atualizar os valores de uma tabela com base nos valores que estão em outra.
Preciso que a primeira tabela atualize somente os dados contido na segunda, por exemplo, na primeira tabela tenho 3 mil itens e na segunda 330, então preciso atualizar somente 330 itens.
Acredito que pra fazer isso tenho que usar SELECT encadeado então montei algo assim:
SELECT lvi.IdProduto, lvi.VlCustoUnitario
FROM LoteInventarioItem lvi
WHERE lvi.IdProduto IN (SELECT pe.IdProduto FROM Produto_Empresa pe)

Essa query me traz os 330 itens porém preciso atualizar o campo lvi.vlCustoUnitario com o dados da segunda tabela contidos em pe.VlPrecoCusto.

A:
(...) preciso atualizar o campo lvi.vlCustoUnitario com o dados da segunda tabela contidos em pe.VlPrecoCusto.

Esboço do código, considerando-se que não há linhas repetidas pela coluna IdProduto:
-- código #1
UPDATE LVI
  set vlCustoUnitario= PE.VlPrecoCusto
  from Produto_Empresa as PE
       inner join LoteInventarioItem as LVI on LVI.IdProduto = PE.IdProduto
  where ...;


text:
Q: How to send form data to MongoDB using Flask I'm a student and trying to make a simple image uploading API using form data and MongoDB. But I'm having hard time solving errors.
I think it's the server side that keeps making the problems but I really can't find what exactly is wrong.
@app.route("/insta_feed1", methods=["POST"])
def feed_post():
    file = request.form.get['file']
    image = request.form.get['image']
    content = request.form.get['content']
    user_id = request.form.get['user_id']
    doc = {'file': file, 'image': image, 'content': content, 'user_id': user_id}
    db.insta_feed1.insert_one(doc)
    return jsonify({'msg': 'image uploaded'})

I have files and contents appeded like this.


text:
Q: Что необходимо сделать чтобы hibernate установил соединение с БД mysql? При выполнение учебного задания возникла проблема. Hibernate не может подключиться к БД, логин и пароль правильные. При написание в идеи скрипта SELECT * FROM test.parts_list, таблица выводится. В чем заключается моя ошибка?
import model.CompDetail;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class Test2 {
    private static SessionFactory sessionFactory;

    private Test2() {
    }

    public static void main(String[] args) {
        if (sessionFactory == null) {

            Configuration configuration = new Configuration().configure();
            configuration.addAnnotatedClass(CompDetail.class);
            StandardServiceRegistryBuilder builder = new
            StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties());
            sessionFactory =
                        configuration.buildSessionFactory(builder.build());

        }
    }
}

hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/test/</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">12345</property>
        <property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
    </session-factory>
</hibernate-configuration>

Ошибка:
мая 21, 2019 11:36:46 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.1.Final}
мая 21, 2019 11:36:47 PM
org.hibernate.annotations.common.reflection.java.JavaReflectionManager
<clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
мая 21, 2019 11:36:47 PM
org.hibernate.engine.jdbc.connections.internal
.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for
production use!)
мая 21, 2019 11:36:47 PM
org.hibernate.engine.jdbc.connections.internal
.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL
[jdbc:mysql://localhost:3306/test/]
мая 21, 2019 11:36:47 PM
org.hibernate.engine.jdbc.connections.internal
.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
мая 21, 2019 11:36:47 PM
org.hibernate.engine.jdbc.connections.internal
.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
мая 21, 2019 11:36:47 PM
org.hibernate.engine.jdbc.connections.internal
.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
мая 21, 2019 11:36:47 PM
org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator
initiateService
WARN: HHH000342: Could not obtain connection to query metadata : null
мая 21, 2019 11:36:47 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
мая 21, 2019 11:36:47 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper
logExceptions
WARN: SQL Error: 0, SQLState: 08001
мая 21, 2019 11:36:47 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper
logExceptions
ERROR: Could not create connection to database server.
Exception in thread "main" org.hibernate.service.spi.ServiceException:
Unable to create requested service
[org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl
.createService(AbstractServiceRegistryImpl.java:275)
    at
org.hibernate.service.internal.AbstractServiceRegistryImpl
.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl
.getService(AbstractServiceRegistryImpl.java:214)
at
org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory
.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl
.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl
.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl
.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl
.<init>(InFlightMetadataCollectorImpl.java:175)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess
.complete(MetadataBuildingProcess.java:118)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess
.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl
.build(MetadataBuilderImpl
.java:473)
at org.hibernate.boot.internal.MetadataBuilderImpl
.build(MetadataBuilderImpl.java:84)
at org.hibernate.cfg.Configuration
.buildSessionFactory(Configuration.java:689)
at Test2.main(Test2.java:19)
Caused by: org.hibernate.exception
.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.exception.internal
.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:48)
at org.hibernate.exception.internal
.StandardSQLExceptionConverter
.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper
.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.connections.internal
.BasicConnectionCreator.convertSqlException
(BasicConnectionCreator.java:118)
at org.hibernate.engine.jdbc.connections.internal
.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
at org.hibernate.engine.jdbc.connections.internal
.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
 at org.hibernate.engine.jdbc.connections.internal
 .DriverManagerConnectionProviderImpl$PooledConnections
 .addConnections(DriverManagerConnectionProviderImpl.java:321)
 at org.hibernate.engine.jdbc.connections.internal
 .DriverManagerConnectionProviderImpl$PooledConnections.<init>
 (DriverManagerConnectionProviderImpl.java:240)
 at org.hibernate.engine.jdbc.connections.internal
 .DriverManagerConnectionProviderImpl$PooledConnections.<init>
 (DriverManagerConnectionProviderImpl.java:218)
 at org.hibernate.engine.jdbc.connections.internal
 .DriverManagerConnectionProviderImpl$PooledConnections$Builder
 .build(DriverManagerConnectionProviderImpl.java:359)
 at org.hibernate.engine.jdbc.connections.internal
 .DriverManagerConnectionProviderImpl
 .buildPool(DriverManagerConnectionProviderImpl.java:98)
 at org.hibernate.engine.jdbc.connections.internal
 .DriverManagerConnectionProviderImpl
 .configure(DriverManagerConnectionProviderImpl.java:73)
 at org.hibernate.boot.registry.internal
 .StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl
 .java:107)
 at org.hibernate.service.internal
 .AbstractServiceRegistryImpl.initializeService
 (AbstractServiceRegistryImpl
 .java:246)
 at org.hibernate.service.internal.AbstractServiceRegistryImpl
 .getService(AbstractServiceRegistryImpl.java:214)
 at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator
 .buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
 at org.hibernate.engine.jdbc.env.internal
.JdbcEnvironmentInitiator.initiateService
(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator
.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl
.initiateService(StandardServiceRegistryImpl.java:101)
at org.hibernate.service.internal.AbstractServiceRegistryImpl
.createService(AbstractServiceRegistryImpl.java:263)
... 13 more
Caused by:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
 Could not create connection to database server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:400)
at com.mysql.jdbc.Util.getInstance(Util.java:383)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:958)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:937)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:872)
at   com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl
.java:2326)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2079)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:794)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl
.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl
.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:400)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
at com.mysql.jdbc.NonRegisteringDriver
.connect(NonRegisteringDriver.java:325)
at org.hibernate.engine.jdbc.connections.internal
.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 28 more
Caused by: java.lang.NullPointerException
at     com.mysql.jdbc.ConnectionImpl
.getServerCharset(ConnectionImpl.java:2999)
at com.mysql.jdbc.MysqlIO.sendConnectionAttributes(MysqlIO.java:1885)
at
com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO
.java:1814)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1207)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2249)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly
(ConnectionImpl.java:2280)
... 39 more

Мавен:
 <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.1.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
    </dependencies>

драйвер: MySql for 5.1


text:
Q: bad array lengths, notification manager causes phone crash on 4.4 I launched app into BETA testing and multiple users with 4.4 Devices reported that the app causes whole phone to crash, phone pretty much restarts after app launch even though app doesn't even have such permissions.
The report I got from testers is as follows:
java.lang.RuntimeException: bad array lengths
at android.os.Parcel.readIntArray(Parcel.java:820)
at android.app.INotificationManager$Stub$Proxy.enqueueNotificationWithTag(INotificationManager.java:348)
at android.app.NotificationManager.notify(NotificationManager.java:139)
at android.app.NotificationManager.notify(NotificationManager.java:112)
at als.wakeup.Awake_Alarm$MyLocationListener.onLocationChanged(Awake_Alarm.java:272)
at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:279)
at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:208)
at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:224)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5293)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)

This works fine on 4.2, 4.3 but it seems that Galaxy Note 3 and Galaxy S5 which run 4.4 restart.
What could the cause be? Is it app related or could it be glitch in new OS?
Just found out it works fine on Xperia Z1 with 4.4 and no crashes. It seems that only samsung causes this, any tips?
Notification Creating function:
public Notification CreateNotification(double distance){

    Intent notificationIntentStop = new Intent(this.getApplicationContext(), StopService.class);
    PendingIntent contentIntentStop = PendingIntent.getActivity(this.getApplicationContext(), 0, notificationIntentStop, 0);

    Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
    Shortcuts shorts = new Shortcuts(this);
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.logo)
            .setContentTitle("Localarm Running")
            .setLargeIcon(largeIcon);
    //mBuilder.addAction(R.drawable.ico, "Stop", contentIntentStop);
    if(distance > 0){
    mBuilder.setContentText(String.valueOf(roundTwoDecimals(shorts.ConvertUnits(distance))+" "+shorts.GetUnitNames(distance)+" to Alarm."));
    }
    else{
    mBuilder.setContentText(String.valueOf("You've reached your destination"));
    }
    mBuilder.setPriority(Notification.PRIORITY_MAX);
    Notification bui = mBuilder.build();

    bui.flags|= Notification.FLAG_NO_CLEAR;
        Intent notificationIntent = new Intent(this.getApplicationContext(), Intro.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, notificationIntent, 0);
        bui.contentIntent = contentIntent;

    return bui;

}

it gets called by: onLocationChanged()
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, CreateNotification(dist_difference-alert_range));

A: This is an issue in Android. Unfortunately, I don't think you can do anything about it.


text:
Q: How do i loop through the string and find out how many words are there? I need help with my problem:
Right now I have a WPF application with a form that includes a button and a textbox.
Also, I have an open file directory - that opens .cs and .txt files.
I need to loop through the string of those files and display the most common words in them, starting from the largest to the smallest.
For example, a string would be:

"The sun is bright. The sun is yellow".

Would return:

The = 2;
sun = 2;
is = 2;
bright = 1;
yellow = 1;

My code right as of now:
private void btn1_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text Documents |*.cs;*.txt", ValidateNames = true, Multiselect = false };
        if (ofd.ShowDialog() == true)
            rtb.Text = File.ReadAllText(ofd.FileName);

        string[] userText = rtb.Text.ToLower().Split(new char[] { ' ', ',', '=', '+', '}', '{', '\r', '\n', '(', ')', ';' }, StringSplitOptions.RemoveEmptyEntries);

        var frequencies = new Dictionary<string, int>();

        foreach (string word in userText) //search words in our array userText that we declared at the beginning.
        {

        }
   }

I am not sure how to continue from here... Help is appreciated.

A: Using the example and expected output that you have provided for us, I was able to accomplish this by using .GroupBy along with creating an anonymous class.
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        // example string
        var myString = "The sun is bright. The sun is yellow";

        // split the string into an array based on space characters and the period
        var stringArray = myString.Split(new char[] {' ', '.'}, StringSplitOptions.RemoveEmptyEntries);

        // group the items in the array based on the value, then create an anonymous class with the properties `Word` and `Count`
        var groupedWords = stringArray.GroupBy(x => x).Select(x => new { Word = x.Key, Count = x.Count() }).ToList();

        // print the properties based on order of largest to smallest count to screen
        foreach(var item in groupedWords.OrderByDescending(x => x.Count))
        {
            Console.WriteLine(item.Word + " = " + item.Count);
        }

        // Output
        ---------
        // The = 2
        // sun = 2
        // is = 2
        // bright = 1
        // yellow = 1
    }
}

Let me know if this helps!

A: This almost sounds like the original definition of a dictionary, so that might be a good place to start:
IDictionary<string, int> actualDictionary = new Dictionary<string, int>();

You can place words in the dictionary, and increment their count each time you find them.
    IDictionary<string, int> actualDictionary = new Dictionary<string, int>();

    foreach (string word in userText) //search words in our array userText that we declared at the beginning.
    {
        if (!actualDictionary.ContainsKey(word)) {
            actualDictionary[word] = 0;
        }

        actualDictionary[word]++;
    }

    foreach(var thing in actualDictionary) {
        Console.WriteLine(thing.Key + " " + thing.Value);
    }

See a running example on .NET Fiddle.

A: I would go with @GTown-Coder 's approach as the easiest.  But if you really just want to know how to implement the same code using a dictionary as in your sample...
private void btn1_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text Documents |*.cs;*.txt", ValidateNames = true, Multiselect = false };
    if (ofd.ShowDialog() == true)
        rtb.Text = File.ReadAllText(ofd.FileName);

    string[] userText = rtb.Text.ToLower().Split(new char[] { ' ', ',', '=', '+', '}', '{', '\r', '\n', '(', ')', ';' }, StringSplitOptions.RemoveEmptyEntries);

    var frequencies = new Dictionary<string, int>();

    foreach (string word in userText) //search words in our array userText that we declared at the beginning.
    {
      // Sample here
      if (frequencies.Contains(word))
      {
         frequencies[word]++;
      }
      else
      {
         frequencies.Add(word,1);
      }
    }

    foreach (var kvp in frequencies)
       Console.WriteLine("Word: {0} \t Frequency: {1}",kvp.Key, kvp.Value);
}


text:
Q: Turn off sound for friendlogin on xbox 360 but not for achievment pop? Is it possible to just turn off sound for friendlogin on xbox 360 but not for achievment pop?

A: There seem to be two methods.
One is to (in the guide) go to preferences, online, and set yourself to busy. Busy, by default, only has one notification sound that plays; the achievement sound. Unfortunately, you'd have to do this everytime you turn on the console... (as described here)
The second, is to check the notifications tab (Guide, Personal Settings, Notifications) and see if there is an option to turn it off. I know there is a permanent one for all sound, but i'm not sure if you can turn off individual sounds (I will be able to check later...)


text:
Q: c# webbrowser click radio button in a form I am using webbrowser element in my code to automate some stuff. I am loading a form in this webbrowser, which contains several radiobutton in. My purpose is just to select one of the radi buttons. However, in the html code, there is a JS code which changes the form action target depending on the selected radio button. So if I use,
webBrowser1.Document.GetElementById("chicken").SetAttribute("checked", "checked");

it selects the radio button that I want but just that. I mean it doesn't trigger the JS code. In this JS Code, it also submits the page, so my code above only selects the radio button and calls the same page. How can I solve this?
Form tag is like the following:
<form id="choose_dept" method="POST" action="/place/">

JS code is like this:
<script type="text/javascript">
<!--
$("#choose_dept").change(function(){
  $("#choose_dept").attr('action', '/place/' + ('input[name=department]:checked').val()
   + '/' );
  this.submit();
});

-->

Last edit:
        String sc = @"$(document).ready(function(){" +
        "$(\"input:radio[name=department]\").change(function() {" +
        "$(\"#choose_dept\").attr('action','place/'+$(this).val());" +
        "$(\"#choose_dept\").submit();" +
        "});" +
        "});";

        HtmlElement headElem = (HtmlElement)webBrowser1.Document.GetElementsByTagName("head")[0];
        HtmlElement scriptElem = (HtmlElement)webBrowser1.Document.CreateElement("script");
        IHTMLScriptElement elem = (IHTMLScriptElement)scriptElem.DomElement;
        elem.text = sc;
        headElem.AppendChild(scriptElem);

        webBrowser1.Document.GetElementById("chicken").SetAttribute("checked", "checked");
        webBrowser1.Document.InvokeScript("ready()");

A: I think in your case more than c# code your problem is your jquery code. Try the code below:
$(document).ready(function(){
$("input:radio[name=department]").change(function() {
$("#choose_dept").attr('action','place/'+$(this).val());
$("#choose_dept").submit();
});
});

Edit: (Since you mentioned that you have no control with the HTML code then you could just add on the fly the JavaScript that I just showed you with the code like the one below:
        String sc = @"$(document).ready(function(){
               $("input:radio[name=department]").change(function() {
               $("#choose_dept").attr('action','place/'+$(this).val());
               $("#choose_dept").submit();
               });
               });";

        var doc = webBrowser1.Document;
        var headElem = (HtmlElement) doc.GetElementsByTagName("head")[0];
        var scriptElem = (HtmlElement) doc.CreateElement("script");
        var elem = (IHTMLScriptElement)scriptElem.DomElement;
        elem.text = sc;
        headElem.AppendChild(scriptElem);

However, you need to add Reference
 Microsoft.mshtml

The you need to add also at the top of your code
 using mshtml;

Now, if you don't want to change it on the fly and you really want just to call the javascript method then you could use the one below:
webBrowser1.Document.InvokeScript("methodnamehere()");

Latest Edit based on your code:
I think you need to simulate a click in your browser once you check your radio button.
So, it would be like this now:
 String sc = @"$(document).ready(function(){" +
        "$(\"input:radio[name=department]\").change(function() {" +
        "$(\"#choose_dept\").attr('action','place/'+$(this).val());" +
        "$(\"#choose_dept\").submit();" +
        "});" +
        "});";

        HtmlElement headElem = (HtmlElement)webBrowser1.Document.GetElementsByTagName("head")[0];
        HtmlElement scriptElem = (HtmlElement)webBrowser1.Document.CreateElement("script");
        IHTMLScriptElement elem = (IHTMLScriptElement)scriptElem.DomElement;
        elem.text = sc;
        headElem.AppendChild(scriptElem);

        webBrowser1.Document.GetElementById("chicken").SetAttribute("checked", "checked");

        HtmlElement simulateClick = webBrowser1.Document.GetElementById("chicken");
        simulateClick.InvokeMember("click");

A: try
webBrowser1.Document.GetElementById("chicken").RaiseEvent("onchange");


text:
Q: How to stop overscroll in Safari in this case? I have a website-slider where every section has height of 100vh. So each section is a slide. At the bottom of the website I need to have a simple footer. It works fine in all browsers but in Safari it kind of jumps because of overscroll.
Link to example
Gray div is an image which is outside my slider and is kind of behind all of the slides beacuse I need to change it's opacity on scroll. My footer is outside of slider as well.

SECTION 1

SECTION 2

  SECTION 3

FOOTER HERE

CSS
  * {
      margin: 0;
      padding: 0;
    }

    .section3,
    .section2,
    .section1 {
      width: 100vw;
      height: 100vh;
      overflow: hidden;
      position: relative;
      z-index: 2;
      background: #000;
      color: white;
      margin-top: 15%;
    }

    .section3 {
      background: transparent;
      margin-top: 0;
      z-index: 10;
    }

    .bg {
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background-image: linear-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, .5)), url(bf34577….png);
      background-repeat: no-repeat;
      background-size: cover;
    }

    footer {
      display: flex;
      position: absolute;
      -webkit-align-items: center;
      -ms-flex-align: center;
      align-items: center;
      padding: 0 10px;
      z-index: 9;
      width: 100vw;
      height: 65px;
      object-fit: cover;
      background: #000;
      color: #727272;
    }

So when overscroll is happening footer jumps up and behind it you can see an image which shouldn't happen.
It can be fixed if I give footer position: fixed and bottom: 0 but I don't need it to be position: fixed, I just need it to be at the bottom of the page.


text:
Q: Having problems loading a csv file into a combobox in java Ok so I have my code done, or so I thought, but it is not loading the account numbers from the csv file that I have to read from. I am completely lost and not understanding why it is not reading those accounts into the combobox. Can someone please help me figure out why the accounts are not showing up in the combobox. The following is Controller Package that runs the program:
import edu.tridenttech.cpt237.bank.model.Bank;
import edu.tridenttech.cpt237.bank.view.StartWindow;
import javafx.application.Application;
import javafx.stage.Stage;

public class MainApp extends Application
{
    @Override
    public void start(Stage primaryStage) throws Exception
    {
        Bank bank = new Bank();
        bank.loadTransactions("Transactions.csv");

        StartWindow ui = new StartWindow(primaryStage);
        ui.show();
    }

    public static void main(String [] args)
    {
        Application.launch(args);
    }
}

The following is the Bank class in the Model Package:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;

public class Bank
{
    private static Bank instance = new Bank();

    private ArrayList<Account> accounts = new ArrayList<>();

    /**
     * Gets the Singleton Bank instance
     * @return Returns the singleton Bank instance
     */
    public static Bank getInstance()
    {
        return instance;
    }

    /**
     * Open a new savings account and place it in the list of bank accounts.
     *
     * @param accntNum the number of the new account
     * @param initialBal the initial balance
     * @return Returns true if an account is created; false if the account already exists or the balance is invalid
     */
    public boolean openSavingsAccount(String accntNum, double initialBal)
    {
        if (findAccountByNum(accntNum) != null || initialBal < 0) {
            return false;
        }

        SavingsAccount savings = new SavingsAccount(accntNum, initialBal);

        return accounts.add(savings);
    }

    /**
     * Open a new checking account and place it in the list of bank accounts.
     *
     * @param accntNum the number of the new account
     * @param initialBal the initial balance
     * @return Returns true if an account is created; false if the account already exists or the balance is invalid
     */
    public boolean openCheckingAccount(String accntNum, double initialBal, double minBalance)
    {
        if (findAccountByNum(accntNum) != null || initialBal < 0) {
            return false;
        }

        CheckingAccount checking = new CheckingAccount(accntNum, initialBal);

        return accounts.add(checking);
    }

    /**
     * Finds the account specified by the given account number
     * @param accntNum the number of the account to be found
     * @return Returns the account matching the number if found; null if the account is not found
     */
    public Account findAccountByNum(String accntNum)
    {
        Account acnt = null;
        Optional<Account> match = accounts.stream().filter(e -> e.getAccountNumber().equals(accntNum)).findFirst();
        if (match.isPresent()) {
            acnt = match.get();
        }
        return acnt;
    }

    /**
     * Transfers the specified amount from the fromAccount to the toAccount.  This method can fail if either
     * of the account numbers is invalid, or if the fromAccount has insufficient funds to make the transfer.
     * @param fromAccountNum The account number of the account from which the money is to be withdrawn.
     * @param toAccountNum The account number of the account to which the money is to be deposited.
     * @param amount The amount to be transfered.
     * @return Returns true if the transfer was successful, false otherwise
     */
    public boolean makeTransfer(String fromAccountNum, String toAccountNum, double amount)
    {
        Account fromAccnt;
        Account toAccnt;

        fromAccnt = findAccountByNum(fromAccountNum);
        toAccnt = findAccountByNum(toAccountNum);

        if (fromAccnt == null || toAccnt == null) {
            return false;
        }

        if (fromAccnt.withdraw(amount)) {
            toAccnt.deposit(amount);
            return true;
        } else {
            return false;
        }
    }

    /**
     * Pulls all of the account numbers from the accounts and returns them as a list of strings.
     * @return The list of account numbers.
     */
    public List<String> getAllAccountNumbers()
    {
        ArrayList<String> accountNums = new ArrayList<>();
        accounts.stream().forEach(e -> accountNums.add(e.getAccountNumber()));
        return accountNums;
    }

    /**
     * Loads the transactions from the specified comma separated values file.  The format of the file is as follows:
     *     O,num,type,amount
     *     D,num,type,amount
     *     W,num,type,amount
     *     T,from,to,amount
     * @param filePath Path to the file containing the transactions
     * @throws FileNotFoundException
     */
    public void loadTransactions(String filePath) throws FileNotFoundException
    {
        Scanner input;
        input = new Scanner(new File(filePath));

        while (input.hasNext())
        {
            String line = input.nextLine();
            // creates an string array called fields and populates each item
            // splitting by comma.
            String[] fields = line.split(",");
            // System.out.println("number of fields: " + fields.length);
            // first field and first character
            switch (fields[0].charAt(0)) {
                case 'O':
                case 'o': {
                    double minBalance = 0;
                    // open a new account
                    String accntNum = fields[1];
                    String type = fields[2];
                    double initialBalance = Double.parseDouble(fields[3]);
                    if (fields.length == 5)
                    {
                        minBalance = Double.parseDouble(fields[4]);
                    }

                    createAccount(accntNum, type, initialBalance, minBalance);
                } break;
                case 'D':
                case 'd': {
                    // deposit into an account
                    String accntNum = fields[1];
                    String type = fields[2];
                    double amount = Double.parseDouble(fields[3]);

                    Account account = findAccountByNum(accntNum);
                    account.deposit(amount);

                } break;
                case 'W':
                case 'w': {
                    String accntNum = fields[1];
                    String type = fields[2];
                    double amount = Double.parseDouble(fields[3]);
                    Account account = findAccountByNum(accntNum);
                    account.withdraw(amount);
                } break;
                case 'T':
                case 't': {
                    String fromAccount = fields[1];
                    String toAccount = fields[2];
                    double amount = Double.parseDouble(fields[3]);
                    makeTransfer(fromAccount, toAccount, amount);
                } break;
                default: {
                    System.out.println("Does not meet requirements");

                }

            }
        }
        input.close();
    }

    private void createAccount(String accntNum, String type, double initialBalance, double minBalance)
    {
        switch (type.charAt(0)) {
            case 's':
            case 'S': {
                openSavingsAccount(accntNum, initialBalance);
            } break;

            case 'c':
            case 'C': {
                openCheckingAccount(accntNum, initialBalance, minBalance);
            } break;
        }
    }
}

And this last class is the StartWindow in the View Package:
import edu.tridenttech.cpt237.bank.model.Bank;
import edu.tridenttech.cpt237.bank.view.NewAccount;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class StartWindow implements EventHandler<ActionEvent>
{
    private Stage myStage;
    private Transaction transaction;
    private NewAccount account;
    private Transfer t;
    private ComboBox<String> AccountsCB = new ComboBox<>();
    Button display;
    Button open;
    Button transfer;
    Button exit;

    public StartWindow(Stage stage)
    {
        transaction = new Transaction();
        FlowPane pane = new FlowPane();
        Scene scene = new Scene(pane);
        myStage = stage;
        myStage.setScene(scene);
        myStage.setTitle("Starting Window");

        pane.getChildren().add(AccountsCB);
        AccountsCB.getItems().setAll(Bank.getInstance().getAllAccountNumbers());
        account = new NewAccount(AccountsCB);
        display = new Button("Display Current Account");
        pane.getChildren().add(display);
        display.setOnAction(this);

        open = new Button("Open New Account");
        pane.getChildren().add(open);
        open.setOnAction(this);

        transfer = new Button("Transfer Funds Between Accounts");
        pane.getChildren().add(transfer);
        transfer.setOnAction(this);

        t = new Transfer();

        exit = new Button("Exit");
        pane.getChildren().add(exit);
        exit.setOnAction(this);

    }

    public void handle(ActionEvent event)
    {
        Button button = (Button) (event.getSource());

        if (button == display)
        {
            if (!transaction.isShowing())
            {
                transaction.show(AccountsCB.getValue());
            }
            else
            {
                transaction.toFront();
            }
        }

        if (button == open)
        {
            if (!account.isShowing())
            {
                account.show();
            }
            else
            {
                account.toFront();
            }
        }

        if (button == transfer)
        {
            if (!t.isShowing())
            {
                t.show();
            }
            else
            {
                t.toFront();
            }
        }

        if (button == exit)
        {
            myStage.close();
        }
    }

    public void show()
    {
        myStage.show();
    }
}

When I run the program, it lets me create a new account, but when I want to transfer funds between accounts or open an existing account, it is not loading the accounts from the Transactions.csv file.

A: You are attempting to implement Bank as a singleton, but you have not prevented creation of additional instances of Bank. Consequently, in your start() method you are able to create a new instance of Bank and load the transactions in that instance:
Bank bank = new Bank();
bank.loadTransactions("Transactions.csv");

Clearly this is not the same instance of Bank as is returned by Bank.getInstance(), so in your StartWindow class, when you call Bank.getInstance(), you receive a Bank instance with no transactions loaded.
If you want to make Bank a singleton, you should make the constructor private so as to prevent creation of any additional instances:
public class Bank {

    private static Bank instance = new Bank();

    private ArrayList<Account> accounts = new ArrayList<>();

    /**
     * Gets the Singleton Bank instance
     * @return Returns the singleton Bank instance
     */
    public static Bank getInstance() {
        return instance;
    }

    // private constructor:
    private Bank() { }

    // existing code....
}

and then of course do
@Override
public void start(Stage primaryStage) throws Exception {

    Bank.getInstance().loadTransactions("Transactions.csv");

    StartWindow ui = new StartWindow(primaryStage);
    ui.show();
}

The singleton pattern is generally considered an anti-pattern by many programmers. I would recommend just creating a Bank instance in the usual way and passing it to the StartWindow instance (and to anywhere else that needs it):
public class Bank {

    // private static Bank instance = new Bank();

    private ArrayList<Account> accounts = new ArrayList<>();

    /**
     * Gets the Singleton Bank instance
     * @return Returns the singleton Bank instance
     */
    // public static Bank getInstance() {
    //    return instance;
    //}

    /**
     * Open a new savings account and place it in the list of bank accounts.
     *
     * @param accntNum the number of the new account
     * @param initialBal the initial balance
     * @return Returns true if an account is created; false if the account already exists or the balance is invalid
     */
    public boolean openSavingsAccount(String accntNum, double initialBal)
    {
        if (findAccountByNum(accntNum) != null || initialBal < 0) {
            return false;
        }

        SavingsAccount savings = new SavingsAccount(accntNum, initialBal);

        return accounts.add(savings);
    }

    // existing code ...
}

Then create a bank instance, load its transactions, and pass it to your StartWindow:
public class MainApp extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        Bank bank = new Bank();
        bank.loadTransactions("Transactions.csv");

        StartWindow ui = new StartWindow(primaryStage, bank);
        ui.show();
    }

    public static void main(String [] args) {
        Application.launch(args);
    }
}

and
public class StartWindow implements EventHandler<ActionEvent> {

    private Bank bank ;

    private Stage myStage;
    private Transaction transaction;
    private NewAccount account;
    private Transfer t;
    private ComboBox<String> AccountsCB = new ComboBox<>();
    Button display;
    Button open;
    Button transfer;
    Button exit;

    public StartWindow(Stage stage, Bank bank) {

        this.bank = bank ;

        transaction = new Transaction();
        FlowPane pane = new FlowPane();
        Scene scene = new Scene(pane);
        myStage = stage;
        myStage.setScene(scene);
        myStage.setTitle("Starting Window");

        pane.getChildren().add(AccountsCB);

        // note:
        AccountsCB.getItems().setAll(bank.getAllAccountNumbers());
        account = new NewAccount(AccountsCB);
        display = new Button("Display Current Account");
        pane.getChildren().add(display);
        display.setOnAction(this);

        open = new Button("Open New Account");
        pane.getChildren().add(open);
        open.setOnAction(this);

        transfer = new Button("Transfer Funds Between Accounts");
        pane.getChildren().add(transfer);
        transfer.setOnAction(this);

        t = new Transfer();

        exit = new Button("Exit");
        pane.getChildren().add(exit);
        exit.setOnAction(this);

    }

    // etc ...
}


text:
Q: How to display http_build_query result one page to another page using PHP? I am able to display records on same page but i have to display record one page to another page.I have seen many examples but can't quite get it right though.Would you please help me in this?
   one.php
$ids = $row["ID"];
$username = $row["Name"];
$search_d = array(
    'id'       => $ids,
    'username' => $username,
);
$search_details = http_build_query($search_d);
header('Location: index.php?$search_details=1');

second.php
if(!empty($_GET['$search_details'])):
$name = $_GET['$search_details'];
print_r($name);
echo '<script>
setTimeout(function() {
    swal({
        title: "details done",
        type: "success",
        timer: 1500
    });
}, 1000);
</script>';
endif;

A: You didn't concatenate the $search_details variable in the argument supplied to header.
$ids = 1;
$username = 'hassan';
$search_d = array(
    'id'       => $ids,
    'username' => $username,
);
$search_details = http_build_query($search_d);
header('Location: index.php?' . $search_details);

on second page you have to do like that .
echo $_GET['id'];
echo $_GET['username'];

you dnt need to get search_details variable .
This should work as you expect.

A: Where to begin...
In one.php:
header('Location: index.php?$search_details=1');

You're using $search_details within single quotes, meaning the variable will not be used.  This will literally be the string index.php?$search_details=1.
$search_details = http_build_query($search_d);

This will build a query string like ids=value&name=value.  Thus having a =1 after it doesn't make any sense.
In second.php:
If you correct one.php, you should be able  to access $_GET['name'] and $_GET['ids'].  $search_details is again in single quotes which makes little sense and that variable has no context in second.php.

To me, it seems like you have a lot of learning to do still, you should not be on Stackoverflow or building your own code yet, but reading and following guides.


text:
Q: [C#]Как прикрутить прокси? Есть такой код, хочу прикрутить прокси, чтобы не кидало в спам и все сообщения доходили, помогите. Использую rumbler для отправки сообщений. Из вот этой темы: https://ru.stackoverflow.com/questions/771073/Подключение-прокси-в-smtpclient  ответ не подходит, так как вылазит ошибка такая ошибка:

MailMessage mail = new MailMessage();
SmtpClient cs = new SmtpClient("smtp.rambler.ru");
string nik = guna2TextBox7.Text;
mail.From = new MailAddress(MyEmails[schetchik], nik);
mail.To.Add(emails[i]);
mail.Subject = Subject;
mail.Attachments.Add(new Attachment(Pathis));
mail.Body = message;

cs.Port = 587;
cs.EnableSsl = true;
string log = MyEmails[schetchik];
string pass = MyEmails[schetchik + 1];
cs.Credentials = new NetworkCredential(MyEmails[schetchik], MyEmails[schetchik + 1]);
cs.Send(mail);


text:
Q: Compile iptables from source make error I'm trying to compile latest iptables 1.6, but I receive the following error:
(./configure it's OK)
then I call make and:
xtables-config-parser.y:20:28: error: libnftnl/table.h: No such file or directory
xtables-config-parser.y:21:28: error: libnftnl/table.h: No such file or directory
....
NFTNL_TABLE_FAMILY undeclared

I configure with:
./configure --prefix=/usr      \
            --sbindir=/sbin    \
            --disable-nftables \
            --enable-libipq    \
            --with-xtlibdir=/lib/xtables &&
make

and make install it's OK, but when I call iptables I get this error:
iptables symbol lookup error: iptables undefined symbol: iptc_ops

Debian Squeeze on VirtualBox
Kernel 4.3.3
x86
iptables version 1.6
Any ideas about how to fix it?


text:
Q: On the Number of Consecutive Leading $0$s in $1/N$ and $(1/N)_{b}$ Let $N > 10$ be an integer.
Let $N_{b}$ be its base-$b$ representation.
Consider the decimal expansions of $\frac{1}{N}$ and $\left( \frac{1}{N} \right)_{b}$.
(1) Will there be $\lfloor \log n \rfloor$  and $\lfloor \log_{b} n \rfloor$  consecutive zeros immediately following the decimal point of $\frac{1}{N}$ and $\left( \frac{1}{N} \right)_{b}$, respectively?
(2) If so, how would one prove this?
Thank you.

A: There would be $m$ consecutive zeros following the decimal point of a number $x \in [0, 1)$ in base $b$ iff $$0.1_b=\frac{1}{b} \le x \cdot b^m < 1$$
Or in other words, if the number created by shifting the decimal point right $m$ times would be exactly one more right shift from being above $1$, then $m$ is the number of consecutive zeros following the decimal point.
This means that $\frac{1}{bx} \le b^m \to m\ge \log_b\left( \frac{1}{bx}\right)$. Since we are trying to find the minimal integer value of $m$ satisfying this condition, we can take the ceiling to get $$m = \left\lceil\log_b\left( \frac{1}{bx}\right)\right\rceil = \left\lceil -1+\log_{b}\left(\frac{1}{x}\right) \right\rceil$$
Since $x = \frac{1}{N}$, this is $$\left\lceil -1+\log_{b}\left(N\right) \right\rceil$$
which would only disagree with your results when $N$ is an integer power of $b$.


text:
Q: Can we get listener of screen off gesture in our app? Can we get listener of screen off gesture in our app?
Like i want to make call to particular contact or send message on gesture of some sign while screen is off. Is it possible?


text:
Q: Why is my laptop keyboard laggy after Ubuntu upgrade? A few days ago I upgraded my Dell XPS 13 laptop from Ubuntu 19 to Ubuntu 20.04. Had no problems for the first few days.
Today I left my laptop temporarily and when I returned I discovered that the charger was no longer working. When I started to log in to Ubuntu I also found that the keyboard was extremely laggy. The keyboard does work but usually will not recognise a stroke unless I press firmly.
I plugged in a wireless USB keyboard and that works perfectly.  I also have had no problems with the wireless mouse. The laptops trackpad works perfectly.
I checked that the Universal Accessibility doesn't have slow keys on. I updated xserver-xorg-input-all (including reinstall).
Is there anything else I can check or should I assume maybe a power surge damaged the laptop?

A: This is probably a driver issue and not related to Ubuntu (but not entirely sure).
After my charger was destroyed I used a ThunderBolt charger from another laptop (the original wasn't ThunderBolt). On Dell forums I found the following link which led me to try pulling out the ThunderBolt cable, and then that led to my laptop keyboard being as good as normal:
https://www.dell.com/community/XPS/XPS-13-9370-amp-TB16-USB-Keyboard-Lag-Missing-Keystrokes/td-p/6070559/page/3
So if I am charging via Thunderbolt the keyboard is too laggy to use but an external keyboard is fine; if I stop charging via Thunderbolt then the laptop keyboard works fine.


text:
Q: Взять значение из textarea Пишу чат на node.js, для ввода сообщений использую textarea, но у меня не получается взять текст из textarea. Получаю ошибку Uncaught TypeError: Cannot read property 'value' of null при попытке считывания значения из textarea. В чем может быть проблема?
function keypress(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) { //Enter keycode
        var inpt = document.getElementById('chat-input');
        var msg = inpt.value;
        inpt.value = "";
        socket.json.send({'event':'message', 'message':msg});
        }
    }

<textarea class="chat-input" name="chat-input" cols="40" rows="5" onkeypress='keypress(event)'></textarea>

в чем может быть проблема?

A: нашел ошибку, не указал id у textarea


text:
Q: How do I parse specific parts of a .txt file with Python? I have a .txt with data I need to parse to an object that should then be put in a list. The .txt file i huge but here's a sample:
5764;3/13/2015 8:00:00 AM;3/13/2015 1:00:00 PM;
C5CA;1/3/2015 12:30:00 PM;1/3/2015 1:00:00 PM;

It's all in one chunk, separated with semicolons. The sample consists of two objects with id, time_start and time_end
I have created a class that looks like this:
class Employee:

def __init__(self, id, time_start, time_end):
    self.id = id
    self.time_start = time_start
    self.time_end = time_end

The main part looks like this, with opening the file and trying to parse it:
my_array_with_objects = []

my_file = open("test.txt", "r")

for item in my_file:
    temp_employee = Employee()
    temp_employee.id = item_first_semicolon_part
    temp_employee.time_start = item_second_semicolon_part
    temp_employee.time_end = item_third_semicolon_part

    my_array_with_objects.append(temp_employee)

myFile.close()

So, the problem is, I don't know how to access the specific parts of the .txt file, separated by the semicolons. Obviously "item_first_semicolon_part" won't work. But how do I access the first part of the text file so that I do get the id number and nothing else (and then the start and end times)? Is there an elegant way of doing this or simply a matter of using if ; do this.
Thanks in advance. I have looked through similar questions, but don't think there was anything that could help me through this.
UPDATE
I got a great answer from @Alderven that worked, but I just noticed that the parsed object cuts away a part of the id. I simplified the id for the sake of this question. Full id (with the rest of the data) looks like this:
57646786307395936680161735716561753784;3/13/2015 8:00:00 AM;3/13/2015 1:00:00 PM;C5CAACCED1B9F361761853A7F995A1D4F16C8BCD0A5001A2DF3EC0D7CD539A09AA7DDA1A5278FA07554B0260880882CCBB30B3399C3C0974C587A8233E5788A81DEAD2921123CB12D13CC11318C38B9679D868145315F1BE24333202D12B3787E51D1BBF97BB25482B0EF7E97DE637BAACEDD74E89E2AC52139EE9369F1D64A6
259939411636051033617118653993975778241;1/3/2015 12:30:00 PM;1/3/2015 1:00:00 PM;
The part:
 C5CAACCED1B9F361761853A7F995A1D4F16C8BCD0A5001A2DF3EC0D7CD539A09AA7DDA1A5278FA07554B0260880882CCBB30B3399C3C0974C587A8233E5788A81DEAD2921123CB12D13CC11318C38B9679D868145315F1BE24333202D12B3787E51D1BBF97BB25482B0EF7E97DE637BAACEDD74E89E2AC52139EE9369F1D64A6
seems to be missing. Perhaps because it is on the same row as the first object. The last part of the id is still there:
259939411636051033617118653993975778241
How do I get the full id?

A: Actually it is CSV format with ; delimiter. Basically:
import csv

with open('test.txt', newline='\n') as f:
    reader = csv.reader(f, delimiter=';')
    for row in reader:
        print(row)

If you want to parse data to your Employee class, then:
import csv

class Employee:
    def __init__(self, id, timeStart, timeEnd):
        self.id = id
        self.timeStart = timeStart
        self.timeEnd = timeEnd

myArrayWithObjects = []
with open('test.txt', newline='\n') as f:
    reader = csv.reader(f, delimiter=';')
    for row in reader:
        myArrayWithObjects.append(Employee(row[0], row[1], row[2]))

A: You need to split the line by ; using str.split:
>>> line = "5764;3/13/2015 8:00:00 AM;3/13/2015 1:00:00 PM;"
>>> parts = line.split(";")
>>> parts
['5764', '3/13/2015 8:00:00 AM', '3/13/2015 1:00:00 PM', '']
>>> ID = parts[0]
>>> start = parts[1]
>>> end = parts[2]
>>> ID
'5764'
>>> start
'3/13/2015 8:00:00 AM'
>>> end
'3/13/2015 1:00:00 PM'

You can shorten this by removing the last ; from the line and assigning multiple values at once:
>>> line = "5764;3/13/2015 8:00:00 AM;3/13/2015 1:00:00 PM;"
>>> line = line.strip(";")
>>> ID, start, end = line.split(";")
>>> ID
'5764'
>>> start
'3/13/2015 8:00:00 AM'
>>> end
'3/13/2015 1:00:00 PM'

A: you can split a row using item.split(';') to get turn it into a list.
you could also parse it as a csv into an array using csvreader or pandas, but that is a separate approach.
if the order is right you can unpack that directly into an employee object using tmpemployee = Employee(*item.split(';'))

A: You can use the csv.reader method with ; as the delimiter, but slice only the first 3 items of each row since you have a redundant trailing ; on each line of the input:
import csv
with open("test.txt", "r") as f:
    myArrayWithObjects = [Employee(*row[:3]) for row in csv.reader(delimiter=';')]