text:
Q: Refresh value in editext using addToBackStack I have two fragment, "A" and "B".
When I return (BackPressed) to my fragment "A", the values of edittext aren't refresh. Why?
I have this code to call fragment "B".
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.fragment_container_pedido_novo,
            container, false);

    btnAddProduto = (Button) view.findViewById(R.id.btnNovoProduto);
    btnAddProduto.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Fragment fragment = new FragmentContainerProduto(true);
            FragmentManager frgManager = getActivity()
                    .getSupportFragmentManager();
            frgManager.beginTransaction()
                    .replace(R.id.content_frame, fragment)
                    .addToBackStack(null).commit();

        }
    });

    edtCodPedido = (EditText) view.findViewById(R.id.edtCodPedidoNovo);
    edtVlBruto = (EditText) view.findViewById(R.id.edtVlBrutoPedidoNovo);

    edtCodPedido
            .setText(String.valueOf(GlobalUtil.objPedido.getCodPedido()));
    edtVlBruto.setText(String.valueOf(GlobalUtil.objPedido.getVlBruto()));

    return view;
}

Someone?

A: When you return to a fragment from the back stack Android does not re-create the fragment but re-uses the same instance of it and starts with onCreateView() in the fragment lifecycle. The key thing is you should not inflate view again in onCreateView() of the fragment to which you return, because you are using the existing fragment instance. You need to save and reuse the rootView. See here the answer of Vince Yuan How can I maintain fragment state when added to the back stack?.

A: Well, I just need put this code...
@Override
public void onResume() {
    super.onResume();
    edtVlBruto.setText(String.valueOf(GlobalUtil.objPedido.getVlBruto()));
    edtCodPedido
            .setText(String.valueOf(GlobalUtil.objPedido.getCodPedido()));
}


text:
Q: Classifying the roots of polynomials with integer coefficients There is no generalized version of the quadratic formula to find the zeroes of polynomials with integer coefficients of degree $n>4$. I am curious about the forms that these zeroes take. More specifically, can they all be written as nested roots of rationals and rational complex numbers? For example something like $\sqrt{a-\sqrt[3]{b}}$? Or are more exotic constants like $e$ and $\pi$ sometimes appearing?

A: There is a theorem saying that it is impossible to solve any given polynomial of degree $n>4$ with just addition, subtraction, multiplication, division, and radicals. For example, the quintic $x^5-x+1=0$ cannot be expressed this way. However, you could use the Bring Radical, sometimes denoted as $\text{BR}(a)$, the solution to the polynomial
$$x^5+x+a=0.$$
This is like how $\sqrt{a}$ solves $x^2-a=0$.
You could solve any quintic by reducing it to the form
$$x^5+px+q.$$
using Tschirnhaus transformations. From here, you could solve this using
$$\sqrt[4]{-\dfrac{p}{5}}\text{BR}\left(-\dfrac{1}{4}\left(-\dfrac{5}{p}\right)^{\frac{5}{4}}q\right).$$
Therefore, the possible roots for a quintic would be algebraic, meaning that $\pi$ and $e$ could not be solutions. This would also apply to higher degree polynomials.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jmeter - POST API not working I am new to Jmeter and have been struggling to get it working to test my POST API. It works fine for a GET API call where I pass the parameters through the Parameters tab.
Details here:
server name: localhost
port: 8080
path /registerMobileUsingCode
In the request body, I am sending the following:
{
    "clientName": "DemoOrg",
    "code": "9880007615",
    "languageId": "1"
}
My Jmeter setup looks like this:

And my HTTP Request Header looks like this:

The API is in production and works fine with postman.
I am just unable to get it working through JMeter. It is obvious that I am doing something wrong but can't figure out what despite having spent a considerable amount of time Googling for solutions.
Any help would be much appreciated.
UPDATE - 1 - Updated with jmeter log as suggested

Thread Name: Thread Group 1-1 Sample Start: 2017-08-09 17:03:41 IST Load time: 1604 Connect Time: 1525 Latency: 1604 Size in bytes: 399
    Sent bytes:251 Headers size in bytes: 213 Body size in bytes: 186
    Sample Count: 1 Error Count: 1 Data type ("text"|"bin"|""): text
    Response code: 500 Response message: Server Level Exception
    encountered

Response headers: HTTP/1.1 500 Server Level Exception encountered
  Date: Wed, 09 Aug 2017 11:33:43 GMT Access-Control-Allow-Origin: *
  Content-Type: application/json Transfer-Encoding: chunked Server:
  Jetty(9.2.16.v20160414)
HTTPSampleResult fields: ContentType: application/json DataEncoding:
  null

UPDATE-2 - Using Postman and JMeter Recorder
As suggested by @Dimitri T, I downloaded the Linux version of Postman and started it with  --proxy-server=localhost:8888.
I was now able to make a Postman request and capture the request in JMeter. Here is what the request looked like:
Jmeter capture of a Postman Request
As you can see, nothing radically different from what I did. However, this DOES work! So hurray!

A: If your application works fine with Postman the fastest and the easiest way of building JMeter test plan will be just recording it using JMeter's HTTP(S) Test Script Recorder.

*

*Prepare JMeter for recording (you can do it in a few clicks via JMeter Templates Feature)

*

*from JMeter's main menu choose File -> Templates -> Recording and click "Create"

*Expand Workbench - HTTP(S) Test Script Recorder and click "Start"

*Prepare Postman for recording

*

*In order to "tell" Postman to use JMeter as a proxy you need to provide --proxy-server parameter to it like:
C:\Users\YOUR_USER_NAME\AppData\Local\Postman\app-x.x.x\Postman.exe --proxy-server=localhost:8888

*Execute your requests in Postman

*JMeter will capture requests, convert them into HTTP Request samplers and store them under Test Plan -> Thread Group -> Recording Controller
References:

*

*JMeter Proxy Step by Step

*How to configure Postman Native Client App to use an external proxy

A: By seeing the image you have attached you are missing / in the path.
the path should be /registerMobileUsingCode

*

*if it is working fine from POSTMAN, then your port 8080 is fine.

*Can you please confirm what is the data type of your request? looks like languageId is integer so you should be using languageId: 1, instead of languageId: "1". The integer should not be double quotes.


text:
Q: Hyper-V File Shares over Wide Ethernet Dramatically Slower We recently moved a file share machine that runs on 2008 hyper-v to our data center from our local network and now it is periodically extremely slow.
The networks are connected via wide ethernet. Pinging the server returns in less than 1ms and tracert shows only 1 hop again at less than 1ms. Other services provided from that location seem to be unaffected (DC, Active Directory, intranet, etc.)
1 1 ms <1 ms <1 ms 192.168.XX.XX
Other than the location, nothing else changed about the server, including IP address.
A simple excel sheet can take up to 2 minutes to download. Browsing the shares can also be slow.
Any ideas?

A: More things than simple TCP latency can slow down Windows server performance. If you're up to it, throw a sniffer like Wireshark on a client that experiences slow Excel sheet loading and see what it looks like on the wire. Perhaps you'll see suspicious timeouts between packets, like strange 200ms intervals between packets. Then compare similar traffic to an unaffected non-VMed machine to see what it should look like.
Network driver settings. When you moved to HyperV, you unavoidably changed your NIC driver. Settings here can affect traffic in ways that ping can't diagnose or expose. Stuff like this is best exposed by what you're doing: copying files off of the system, creating connections, browsing shares. Even if it moved from one point-rev of HyperV to another, driver versions may be slightly different.
But, the packet flows should shed more light on the problems.

A: A couple of things to check:
Determine if MTU is less than what we would expect for a normal Ethernet.  From the client workstation:
ping -f -l 1472
If it returns "Packet needs to be fragmented but DF set" (or "request timed out"), keep reducing from 1472 until you determine what the maximum payload is.  The MTU is max payload plus 28 bytes (8 bytes for ICMP header + 20 bytes for IP header, normal Ethernet MTU is 1500).
Next, in Wireshark and MS Network Monitor 3.3, you can add the column for "Frame Length".  This will enable you to see if the server is sending oversize Ethernet frames.  Create a display or capture filter for packets > 1514 bytes, however the server really should not be sending packets larger than the MTU.
If there are oversize frames, these are determined by the network adapter properties  "Large Send Offload" and "Jumbo Packets" in your guest.

A: There are good suggestions already made that are worth looking into.  Another common issue I've run into is with the TCP Chimney offloading, especially with Broadcom NICs.  Try disabling it and testing to see if that's coming into play.  http://support.microsoft.com/kb/951037


text:
Q: AppEngine error following upgrade to Java8 and endpoints V2 Following an upgrade to Java 8 and endpoint upgrade to V2 I kept on getting server error and getting the following errors in my appengine logs:
com.google.apphosting.runtime.jetty9.JettyLogger warn: Error xxxxxxxxx (JettyLogger.java:29)
    java.lang.NoClassDefFoundError: com/google/appengine/repackaged/com/google/gson/JsonElement
        at java.lang.Class.getDeclaredConstructors0(Native Method)
        at java.lang.Class.privateGetDeclaredConstructors(Class.java:2673)
        at java.lang.Class.getConstructor0(Class.java:3077)
        at java.lang.Class.newInstance(Class.java:413)

A: Turns out it's because as part of the app engine upgrade the following statements are no longer valid
import com.google.appengine.repackaged.com.google.gson.Gson;
import com.google.appengine.repackaged.com.google.gson.GsonBuilder;
...
Gson gson = new GsonBuilder().create();

you need to use the new Json library instead:
1) add new dependency to your gradle file:
compile 'com.google.code.gson:gson:2.8.1'

2) replace
import com.google.appengine.repackaged.com.google.gson.Gson;
import com.google.appengine.repackaged.com.google.gson.GsonBuilder;

with
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


text:
Q: Smooth transition of images when swiping in jQuery mobile I have an array of image URLs in an Image view.
I scroll the picture using swipe and that works for me.
In swipe function I am dynamically calling the images from the image array.
But the problem is that the image transition is not smooth.I need the image transition as slide.
Code:
var imgStr = "";

Code from comment:
$("#ImageDiv").swiperight(function () {
  if (i < (imgURL.length - 1)) {
    i++
  } else {
    i = 0;
  }
  var imgStr = "";
  $('#ImageDiv').html(imgStr);
});

Any help is appreciated.
Thanks in advance.

A: Instead of doing this,
var imgStr = "";
 $('#ImageDiv').html(imgStr);

Can you do this,
$("#ImageDiv img").attr('src', imgURL[i]);


text:
Q: Two node Tomcat based Load Balancing: Architectural styles Am working on setting up a 2-node load balancer for Tomcat web server either using Apache or employing a commercial tool named Barracuda. The servers are high end Intel servers with powerful configuration (for the requirement under consideration) in terms of CPU, Memory, internal RAID. The two options we got are either to use two nodes as Active-active meaning both tomcat serving requests in a round-robin fashion or to use just one node and use the other node only in case the first node fails. One disadvantage with active-active configuration would be that the architecture won't be Shared Nothing type as the two tomcats potentially needs to share the web-content using a disk-array.
Would highly appreciate if anyone can provide some inputs regarding the above architectural styles.


text:
Q: how do I add asynchronous switching between related collections C# I have project where I need to gather files from a database by id, zip those files up, upload zipped file to third party web service, and do something with the response.  I'm using the Parallel.ForEach to try and accomplish this, but I'm having trouble getting this to run asynchonously, and I'm not even sure that this is the best way to do this. Is there a way to run this asynchronously, and more efficiently?
    public async Task<string> UploadZip(string courseID)
    {
         string result = string.empty;
         ids = courseID.Split(',').ToList();

         ConcurrentStack<string> zipPaths  = new ConcurrentStack<string>();

        Parallel.ForEach(ids, (id) =>
         {
             files = rep.GetFiles(id);
            ZipFiles zf = new ZipFile(files);
            zipPaths.Push(zf.ZipFilePath);
             try
             {
                 while (zipPaths.Count > 0)
                 {
                     FileHolder fh;
                     if (fileHolder.TryPop(out fh))
                     {

                             FileInfo file = new FileInfo(fh.EndPoint);

                             if (file != null && file.Length > 0)
                             {
                                 // string fileName = Path.GetFileName(path);
                                result = CallService(zf.PathToZip);
                                 DoSomethingElse oSomethingElse = new DoSomethingElse(result, id, version);
                             }

                     }
                 }
             }
             catch (Exception ex)
             {
                 System.Diagnostics.Debug.WriteLine(string.Concat("HomeController line 123","error ",ex.Message, DateTime.Now.TimeOfDay));
             }
             ITermExtractorContent result = new TermExtractorContent();

         });

        return output;
    }

     private static async Task<string> CallService(string pathToZip)
        {

            using (var client = new HttpClient())
            {
               //headers for client
                try
                {
                    using (var content = new MultipartFormDataContent())
                    {
                        using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            using (var fileContent = new StreamContent(stream))
                            {
                                fileContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(path) + "\"");
                                content.Add(fileContent, "file", Path.GetFileName(pathToZip));
                                using (
                                   var message =
                                       await client.PostAsync(baseEndpoint, content))
                                {
                                    output = await message.Content.ReadAsStringAsync();

                                }
                            }
                        }
                    }//end using

                }
                catch (Exception ex)
                {
                    log(ex);
                }

            }// using (var client = new HttpClient())
            return output;
        }

A: The only reason why I can see this needing to be async is to prevent from blocking a UI thread.  I'm not sure what DoSomethingElse() does (Is this the method you are trying to run concurrently?) and how you use the result variable as a parameter but I feel that the above line result = CallService(zf.PathToZip); should be result = await CallService(zf.PathToZip);  As the current function is marked as async it will signal the compiler to create a callback to execute when the task has returned and will resume execution there.  When your program hits that method, it will not continue to execute until it is returned.  Other threads (like the one that called the async method) will continue to execute.  To call you UploadZip() method it would be used something like:
public void DoThings()
{
    UploadZip("MyString");
    DoSomethingElseConcurrently();
}

Please also bear in mind thread safety (race conditions, deadlocking etc) as this is asynchronous programming.  There are some minor things when using the TPL here as you may find yourself nesting async method calls (like you are doing here).  Outer async calls can not use the .Result() method as it blocks that thread.  The inner async thread will try to return to that method that called it and thus entering into a deadlock.


text:
Q: "Call Stack" for C++ errors in Visual Studio 2005 Is there a "call stack" for compiler errors in Visual Studio 2005 (C++)?
For example, I am using a boost::scoped_ptr as the value in a QHash. This is however causing the following compile error:
1>c:\qt\include\qtcore\../../src/corelib/tools/qhash.h(743) : error C2248: 'boost::scoped_ptr<T>::operator =' : cannot access private member declared in class 'boost::scoped_ptr<T>'

From the build output I know which of my source files is causing the error and the line number in the qhash.h that is causing the error but I am trying to track down the line number in my source file that is generating the error (hence the "call stack" idea).
Please note, I am not looking for the solution to the problem of using a scoped_ptr in a QHash but the problem of tracking down where compile errors are generated. This would also be useful for helping track down weird warnings. More often than not I run into this problem when using templated classes.
Thanks!

A: Sometimes with strange errors it helps to preprocess the file and look at that output. With VS look for "Generate Preprocessed File" under preprocessor settings (or set the /P switch). This will generate XXX.i from XXX.cpp which may help you figure out the problem.
Make sure you turn off the switch after, with this option turned on it won't generate an obj file.

A: If you look at the build output, you should see which project and which .cpp file was being compiled when this error occurred.
There is really no notion of "call stack" here, because the compiler processes one source file at a time.  You have a compiler error in the header file, so you need to find out which source file including that header was being compiled.

A: These types of errors can be hard to track down. Usually I end up comment out code and finding the offending line and working from there. After doing it a while you will learn to better read the error messages and understand what tripped up the compiler. As it stands the compilers error messages are just horrible.
In this case it is saying that you have an object of type boost::scoped_ptr<T> that it is trying to copy but the class won't let you (operator= and the copy ctor are both hidden). So you need to look at how the class is used and see why it is trying to copy it. Maybe a scoped_ptr isn't what you need. Maybe you need a shared_ptr?


text:
Q: "socket.error: [Errno 99] Cannot assign requested address" in python I tried creating an ICMP network sniffer as follows:
import socket,os
host="192.168.1.7"
#create a socket protocol
socket_protocol=socket.IPPROTO_ICMP
sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
sniffer.bind((host, 6677))
sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
print(sniffer.recvfrom(65565))

"192.168.1.7" is a local address of another PC connected to the router that my wireless network interface is connected to. I obtained this address doing a wireshark capture.
when the codes are execute, I recieve the following error
Traceback (most recent call last):
  File "/root/test.py", line 18, in <module>
    sniffer.bind((host, 6677))
socket.error: [Errno 99] Cannot assign requested address

When I use my wireless network card interface local ip address ("192.168.1.9"), everything goes fine.
What can I do to prevent this error...Thanks in advance!


text:
Q: How do I iterate a generic reflected method? In my CMS I have a load of modules which allow me to do some clever item listing stuff. I am trying to use them to pull out a list of their child objects via reflection, but am getting stuck with the level of generics involved.
I have got as far as this method:
var myList = moduleObj.GetType().GetMethod("ChildItems").Invoke(moduleObj, new object[] { });

which returns a List. Each modulespecificobject is bound it an IItemListable interface which has the methods in it I am trying to access.
I am unsure how I can cast or iterate the myList object as a set of IItemListable objects access the methods required.
Thanks
A few of the classes:
public interface IItemListable
{
    IQueryable GetQueryableList();
    string GetIDAsString();
    IItemListable GetItemFromUrl(string url, List<IItemListable> additionalItems);
    bool IsNewItem();
    IItemListable CreateItem<T>(ItemListerControl<T> parentList) where T : class, IItemListable;
    IItemListable LoadItem(string id);
    IItemListable SaveItem();
    RssToolkit.Rss.RssItem ToRssItem();
    void DeleteItem();
    string ItemUrl();
}

public interface IItemListModule<T> where T: IItemListable
{
    List<T> ChildItems();
}

public class ArticlesModule : ItemListModuleBase<Article>, IItemListModule<Article>
{
    #region IItemListModule<Article> Members

    public new List<Article> ChildItems()
    {
        return base.ChildItems().Cast<Article>().Where(a => a.IsLive).ToList();
    }

    #endregion
}

A: You can direct cast while iterating:
IList myList = (IList)moduleObj.GetType().GetMethod(
             "ChildItems").Invoke(moduleObj, new object[] { });
foreach (IItemListable o in myList)
{

}

Edit: I would better mark ChildItems as virtual in the base then you could write
public override List<Article> ChildItems()
{
  return base.ChildItems().Where(a => a.IsLive).ToList();
}

and
var myList = moduleObj.ChildItems();
foreach (IItemListable o in myList)
{
}

without any need to cast, avoiding the use of the new keyword and without having to use reflection.

A: Maybe this will help:
http://devlicio.us/blogs/louhaskett/archive/2007/06/13/how-to-cast-between-list-t-s.aspx
(Also some extra links in the comments)


text:
Q: Проблема с границей сайта в мобильной версии Отчего могла возникнуть ситуация, как на видео?
Сайт продолжается за футером.
Ссылка на видео

@import url("/css/oblacheniya.css");
@import url("/css/oblacheniya-type-select.css");
@import url("/css/product-page.css");
@import url('https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz');
*,
*:before,
*:after {
  box-sizing: border-box;
}

html,
body {
  height: 100%;
  padding: 0;
  margin: 0;
  background-color: #B63D32;
}

#page-wrapper {
  width: 100%;
  height: 100%;
}

#content-wrapper {
  width: 80%;
  height: 100%;
  display: inline-block;
  float: right;
}

header {
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: row;
  position: relative;
  border-top: 2vh solid black;
  border-left: 2vh solid black;
  border-right: 2vh solid black;
  border-bottom: 1vh solid black;
}

.container1 {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.logo {
  width: 11.1vh;
  height: 11vh;
  padding-top: 0.8vh;
  padding-right: 11.5vh;
}

.logo img {
  width: 11.3vh;
  height: 11vh;
  margin: 0vh auto;
  padding-top: 0vh;
}

.main_title {
  padding-top: 0.2vh;
  margin-left: 0vh;
  padding-right: 0vh;
  font-size: 4vh;
  font-family: Impact, sans-serif;
  color: #fff;
  text-shadow: 0vh 0.4vh rgba(0, 0, 0, .34);
  text-align: center;
}

.subtitle {
  font-size: 2vh;
  font-family: Lobster, sans-serif;
  letter-spacing: 0.14vh;
  font-weight: normal;
  color: #fff;
  text-align: center;
  margin-top: -0.3vh;
  padding-right: 0vh
}

.second_subtitle {
  font-size: 2.3vh;
  color: #000000;
  font-family: Impact, sans-serif;
  text-shadow: 0.1vh 0.05vh 0.3vh rgba(255, 255, 255, 0.6);
  background-color: #666666;
  -webkit-background-clip: text;
  -moz-background-clip: text;
  letter-spacing: -0.055vh;
  text-align: center;
  margin-top: -0.2vh;
}

.top_navigation-menu {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-top: 1.5vh;
  text-align: center;
}

.top_navigation-menu li {
  width: 100%;
}

.top_navigation-menu a {
  text-decoration: none;
  color: white;
}

.top_navigation-menu li {
  display: block;
  margin: 0 auto;
  width: 100%;
  text-align: center;
}

.top_navigation-menu li a {
  color: white;
  text-decoration: none;
  font-size: 2.35vh;
  font-family: Courier, sans-serif;
  font-weight: bolder;
}

.container1 ul {
  padding-bottom: 0vh;
  margin-bottom: 0vh;
}

.container1 ul li {
  padding-bottom: 0vh;
  margin-bottom: 0vh;
}

.container1 ul li>a:hover {
  color: black;
  transition: 0.4s;
}

main {
  width: 100%;
  height: 114vh;
}

/*ЛЕВОЕ МЕНЮ*/

/*ЛЕВОЕ МЕНЮ*/

.spisok {
  display: flex;
  justify-content: center;
  position: fixed;
  height: 100%;
  width: 20%;
  background-color: #7B2019;
  background-repeat: no-repeat;
  /*border*/
  border-top: 1.6vh solid black;
  border-bottom: 2vh solid #000;
  border-left: 1.5vh solid #000;
  border-right: 0vh solid #000;
  /*border ends*/
}

li {
  list-style-type: none;
}

.spisok li {
  width: 24vh;
  list-style-image: none;
  height: 5.5vh;
  background-image: url(/img/span_menu.png);
  background-size: 100% 100%;
  -webkit-background-size: 100% 100%;
  background-repeat: center no-repeat;
  transition: All 0.3s ease-in-out;
  margin-top: 0.45vh;
}

#oblacheniya {}

.spisok li a {
  width: 100%;
  height: 100%;
  text-decoration: none;
  font-family: CyrillicOldBold, sans-serif;
  letter-spacing: 0.05vh;
  color: white;
  text-decoration: none;
  font-size: 2vh;
  font-weight: normal;
}

.spisok ul>li:hover {
  background-image: url(/img/span_menu_hover.png);
  background-size: 100% 100%;
  -webkit-background-size: 100% 100%;
  background-repeat: center no-repeat;
  -webkit-transition: All 0.3s ease-in-out;
  -moz-transition: All 0.3s ease-in-out;
  -o-transition: All 0.3s ease-in-out;
  -ms-transition: All 0.3s ease-in-out;
  transition: All 0.3s ease-in-out;
}

.spisok ul li>a:hover {
  text-shadow: gold 0 0 4vh;
  /* Свечение голубого цвета */
  color: white;
}

ul {
  padding-left: 0vh;
}

.button.block {
  display: flex;
  justify-content: center;
  padding-left: 0vh;
}

.spisok ul {
  list-style-image: none;
  display: flex;
  justify-content: center;
  -webkit-flex-direction: column;
  -moz-flex-direction: column;
  -ms-flex-direction: column;
  -o-flex-direction: column;
  flex-direction: column;
}

.spisok ul li a p {
  display: flex;
  justify-content: center;
}

#ugol {
  background-image: url(/img/span_menu_black.png);
}

.text-div {
  width: 15.8vh;
  height: 3vh;
}

.letter-spacing {
  letter-spacing: 0.1vh;
}

.ryasi {
  letter-spacing: 0.2vh;
}

/*Начало SECTION*/

section {
  background: url(/img/fon.png);
  background-color: #BFBFBF;
  background-size: cover;
  display: flex;
  justify-content: flex-start;
  flex-direction: row;
  align-items: flex-start;
  width: 100%;
  height: 114vh;
  /*РАМКА*/
  border-left: 2vh solid black;
  border-top: 0vh solid black;
  border-right: 2vh solid black;
  border-bottom: 0vh solid black;
  /*Конец РАМКИ*/
}

.container2 {
  width: 100%;
  height: 109.9vh;
}

.Nashi_Tseny {
  width: 100%;
  height: 106.9vh;
}

.photo-price {
  height: 100vh;
}

.text-price {
  position: relative;
  margin: 0 auto;
  width: 100vh;
  height: 98vh;
  border: solid transparent;
  border-width: 25vh 10vh 15vh 10vh;
  border-image: url(//i.stack.imgur.com/wky2z.png);
  border-image-slice: 800 250 338;
  border-image-repeat: round;
}

.text-price {
  font-size: 2.3vh;
  font-family: Yanone Kaffeesatz, sans-serif;
  font-style: normal;
  text-decoration-skip-ink: none;
}

.text-price p {
  padding-left: 2vh;
}

#first_abzac {
  margin-top: -2vh;
}

.photo-price {
  height: 97vh;
  width: 100%;
}

.border-price {
  max-width: 10vh;
}

.choose_otstup {
  margin-left: 1vh;
}

h2 {
  margin-top: 3vh;
  font-size: 4.7vh;
  font-family: Impact;
  font-weight: 400;
  padding-top: 0.5vh;
  text-decoration: underline;
  text-decoration-skip-ink: none;
  text-align: center;
}

strong {
  font-weight: bolder;
  font-size: 2.1vh;
}

.vosem_tis {
  font-style: italic;
  font-weight: 900;
  font-family: Lobster, sans-serif;
  font-size: 1.9vh;
}

/*НАЧАЛО FOOTER*/

footer {
  width: 100%;
  height: 15vh;
  border-left: 2vh solid black;
  border-right: 2vh solid black;
  ;
  border-top: 1vh solid black;
  ;
  border-bottom: 2vh solid black;
  ;
}

/*КОНЕЦ FOOTER*/

#leftmenu-wrapper {
  float: left;
  display: inline-block;
  width: 20%;
  height: 100%;
}

/*@media only screen and (max-width: 1024px) {
h2{
  padding-right: 11%;
}
}
@media only screen and (min-width: 1999px) and (max-width: 1400px) {
h2{
  margin-left: 13.5vh;
}
}
@media only screen and (min-width: 1400px) {
h2{
  padding-left: 520px;
}
}
@media only screen and (min-width: 1220px) {
h2{
  padding-left: 120px;
}
}
@media only screen and (min-width: 1355px) {
h2{
  padding-left: 300px;
}
}
@media only screen and (min-width: 1504px) {
h2{
  padding-left: 380px;
}
}
@media only screen and (min-width: 1700px) {
h2{
  padding-left: 520px;
}
}
@media only screen and (max-width: 1100px) {
h2{
  padding-right: 90px;
}
}
*/

Наши цены:

Облачения:

-иерейские шелковые от 9000   рублей с шикарными галунами

-иерейские парчевые от 10000  рублей*

Подрясники:

Подризники:

Рясы:

Стихари:

Скуфии: от 800 рублей;

Камилавки: от 1700

Крещальные:

Облачения для храма:

Вышитые кресты:

Кадильный уголь:

*парчевые облачения с индийскими галунами шьются по заказу

@media (max-width: 970px) {
  .spisok li {
    width: 22vh;
    list-style-image: none;
    height: 5.5vh;
    margin: 0 auto;
    display: block;
    background-image: url(/img/span_menu.png);
    background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-repeat: center no-repeat;
    transition: All 0.3s ease-in-out;
  }
  .spisok ul li a p {
    padding-top: 2vh;
    margin-top: 0.42vh;
  }
}

@media (max-width: 920px) {
  .spisok li {
    width: 16.5vh;
    list-style-image: none;
    height: 5.5vh;
    margin: 0 auto;
    display: block;
    background-image: url(/img/span_menu.png);
    background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-repeat: center no-repeat;
    transition: All 0.3s ease-in-out;
  }
}

@media (max-width: 650px) {
  #content-wrapper {
    width: 100%;
  }
  .spisok {
    display: none;
  }
}

@media (max-width: 1325px) {
  .spisok li {
    width: 20vh;
    list-style-image: none;
    height: 5.4vh;
    margin: 0 auto;
    display: block;
    background-image: url(/img/span_menu.png);
    background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-repeat: center no-repeat;
    transition: All 0.3s ease-in-out;
  }
}

@media (max-width: 1250px) {
  .spisok li {
    width: 20vh;
    list-style-image: none;
    height: 6.5vh;
    margin: 0 auto;
    display: block;
    background-image: url(/img/span_menu.png);
    background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-repeat: center no-repeat;
    transition: All 0.3s ease-in-out;
  }
}

@media (max-width: 1295px) {
  .text-price {
    position: relative;
    margin: 0 auto;
    width: 90vh;
    height: 98vh;
    border: solid transparent;
    border-width: 25vh 10vh 15vh 10vh;
    border-image: url(//i.stack.imgur.com/wky2z.png);
    border-image-slice: 800 250 338;
    border-image-repeat: round;
  }
}

@media (max-width: 1155px) {
  .text-price {
    position: relative;
    margin: 0 auto;
    width: 70vh;
    height: 98vh;
    border: solid transparent;
    border-width: 25vh 10vh 15vh 10vh;
    border-image: url(//i.stack.imgur.com/wky2z.png);
    border-image-slice: 800 250 338;
    border-image-repeat: round;
  }
}

@media (max-width: 1090px) {
  .text-price {
    position: relative;
    margin: 0 auto;
    width: 70vh;
    height: 98vh;
    border: solid transparent;
    border-width: 25vh 10vh 15vh 10vh;
    border-image: url(//i.stack.imgur.com/wky2z.png);
    border-image-slice: 800 250 338;
    border-image-repeat: round;
  }
  .spisok li {
    width: 16.5vh;
    list-style-image: none;
    height: 5.5vh;
    margin: 0 auto;
    display: block;
    background-image: url(/img/span_menu.png);
    background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-repeat: center no-repeat;
    transition: All 0.3s ease-in-out;
  }
  .spisok li a {
    width: 100%;
    height: 100%;
    text-decoration: none;
    font-family: CyrillicOldBold, sans-serif;
    letter-spacing: 0.05vh;
    color: white;
    text-decoration: none;
    font-size: 1.6vh;
    font-weight: normal;
  }
}

@media (max-width: 900px) {
  .text-price {
    position: relative;
    margin: 0 auto;
    width: 60vh;
    height: 99vh;
    border: solid transparent;
    border-width: 25vh 10vh 15vh 10vh;
    border-image: url(//i.stack.imgur.com/wky2z.png);
    border-image-slice: 800 250 338;
    border-image-repeat: round;
  }
  .spisok li {
    width: 15.8vh;
    list-style-image: none;
    height: 5.5vh;
    margin: 0 auto;
    display: block;
    background-image: url(/img/span_menu.png);
    background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-repeat: center no-repeat;
    transition: All 0.3s ease-in-out;
  }
  .spisok li a {
    width: 100%;
    height: 100%;
    text-decoration: none;
    font-family: CyrillicOldBold, sans-serif;
    letter-spacing: 0.05vh;
    color: white;
    text-decoration: none;
    font-size: 1.4vh;
    font-weight: normal;
  }
}

@media (max-width: 360px) {
  header {
    border-top: 1vh solid black;
    border-left: 1vh solid black;
    border-right: 1vh solid black;
    border-bottom: 0.8vh solid black;
  }
  section {
    border-left: 1vh solid black;
    border-top: 0vh solid black;
    border-right: 1vh solid black;
    border-bottom: 0vh solid black;
  }
  .text-price {
    width: 100%;
    height: 100%;
    border: 0;
    font-size: 2.8vh;
    position: relative;
    margin: 0 auto;
  }
  .spisok li {
    width: 15.8vh;
    list-style-image: none;
    height: 5.5vh;
    margin: 0 auto;
    display: block;
    background-image: url(/img/span_menu.png);
    background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-repeat: center no-repeat;
    transition: All 0.3s ease-in-out;
  }
  .spisok li a {
    width: 100%;
    height: 100%;
    text-decoration: none;
    font-family: CyrillicOldBold, sans-serif;
    letter-spacing: 0.05vh;
    color: white;
    text-decoration: none;
    font-size: 1.4vh;
    font-weight: normal;
  }
}

A: Нашел решение проблемы.
В коде был лишний блок, который вылазил за футер.


text:
Q: Jenkins Pipeline - how not to exit on error? I'm new to Jenkins and I wrote a Pipeline with the following code:
build job: 'Dummy_Test',
            parameters:[
                        [$class: 'StringParameterValue', name: 'TEST_EVENT_NAME', value: 'integrated test' ],
                        [$class: 'StringParameterValue', name: 'TEST_TEAM', value: 'testing' ],
                        [$class: 'StringParameterValue', name: 'TEST_INDEX', value: '1' ],
                       ]
build job: 'Dummy_Test',
            parameters:[
                        [$class: 'StringParameterValue', name: 'TEST_EVENT_NAME', value: 'test feature 1' ],
                        [$class: 'StringParameterValue', name: 'TEST_TEAM', value: 'testing' ],
                        [$class: 'StringParameterValue', name: 'TEST_INDEX', value: '2' ],
                       ]
build job: 'Dummy_Test',
            parameters:[
                        [$class: 'StringParameterValue', name: 'TEST_EVENT_NAME', value: 'feature 1' ],
                        [$class: 'StringParameterValue', name: 'TEST_TEAM', value: 'dev' ],
                        [$class: 'StringParameterValue', name: 'TEST_INDEX', value: '1' ],
                       ]
build job: 'Dummy_Test',
            parameters:[
                        [$class: 'StringParameterValue', name: 'TEST_EVENT_NAME', value: 'fix bug' ],
                        [$class: 'StringParameterValue', name: 'TEST_TEAM', value: 'dev' ],
                        [$class: 'StringParameterValue', name: 'TEST_INDEX', value: '2' ],
                       ]

This Pipeline builds job Dummy_Test with different parameters, one after another.
If a job build fails, the job defined after that job in the Pipeline will not run.
How do I change this behavior and make Jenkins continue executing the Pipeline?

A: You are probably looking for the catchError built-in, which acts as a try-catch block and continues the script. You would simply wrap each of your build job: statements with it.
Note that it will set the build status to FAILURE, if any of the jobs fail, even though it won't halt the script.


text:
Q: javascript captcha validation part return the whole form instead of proceed I'm using a contact form from elated.com and I try to implement a basic math captcha. However, when I submit the form, regardless the captcha is correct or wrong, it pop out the error message of wrong captcha instead of submitting the form.
This part of code is the one I edited:
function submitForm() {
    var contactForm = $(this);
    if ( !$('#senderName').val() || !$('#senderEmail').val() || !$('#message').val() ) {

        $('#incompleteMessage').fadeIn().delay(messageDelay).fadeOut();
        contactForm.fadeOut().delay(messageDelay).fadeIn();

    }
    // this is the part of the code I added the captcha verification.
    if(('#captcha') != captcha_c) {
        $("#captchaError").slideDown(500);
        $("#captchaError").delay(messageDelay).slideUp(500);
    } else {

            $('#sendingMessage').fadeIn();
            contactForm.fadeOut();

            $.ajax( {
            url: contactForm.attr( 'action' ) + "?ajax=true",
            type: contactForm.attr( 'method' ),
            data: contactForm.serialize(),
            success: submitFinished
        });
    }

  return false;
}

The HTML form:
<form id="contactForm" action="processForm.php" method="post">

Send us an email...

            Your Name
            <input id="senderName" maxlength="40" name="senderName" placeholder="Please type your name" required="required" type="text" />

            Your Email Address
            <input id="senderEmail" maxlength="50" name="senderEmail" placeholder="Please type your email address" required="required" type="email" />

            Your Message
            <textarea id="message" cols="80" maxlength="10000" name="message" placeholder="Please type your message" required="required" rows="10"></textarea>

            <input id="captcha" name="captcha" placeholder="Enter the captcha" required="required" type="text" />

        <input id="sendMessage" name="sendMessage" type="submit" value="Send Email" />
        <input id="cancel" name="cancel" type="button" value="Cancel" />

</form>

Sending your message. Please wait...

Thanks for sending your message! We'll get back to you shortly.

There was a problem sending your message. Please try again.

Please complete all the fields in the form before sending.

Are you sure about your calculations?

If I remove out the comment part, the form is working and proceed to send the email, where did I go wrong in my javascript part?
Here is the working live example

A: Change this:
if(('#captcha') != captcha_c) {

to this:
if($('#captcha').val() != captcha_c) {

Also you have the same id for your label as your input so change this:

to

A: You forgot the $ sign before ('#captcha')
in if(('#captcha') != captcha_c).


text:
Q: how to connect an IBOutlet to textview control in iOS? I'm really a newbie on iOS and I don't know how to connect the UITextView object to the textview control on *.xib file? Is there any way to set the unique ID to a control on iOS?
Currently, I have declare an IBTextView as below:
HelloViewControler.h file:
@interface HelloViewController : UIViewController{
   IBOutlet UITextView *txtTextMe;
}
@property (retain,atomic) UITextView *txtTextMe;
- (IBAction)buttonPressed:(id)sender;
@end

HelloViewControler.m:
@synthesize txtTextMe;
- (IBAction)buttonPressed:(id)sender{
    txtTextMe.text = @"Button clicked";

}

Code to update a string to textview control:
    txtTextMe.text = @"Button clicked";

No Error. But when I run the code, the string "Button Clicked" wasn't updated to the textview.

A: Hold CTRL and click and drag from the item in the .xib into the code.  This will create either an IBOutlet or IBAction (you chose via popup) and link it to the object on the .xib.
It can also be done via the left hand inspector if you have already created the code.
If you are new to iOS programming and Xcode I would very strongly recommend you look at Apple's tutorials on the developer portal.  They have some excellent introductory guides with step by step instructions.  The second one covers using storyboards and is a really great introduction to storyboards, Xcode and the iOS SDK - link below.
Your Second iOS App: Storyboards

A: *

*Right-click on the textview control in the NIB file. A HUD-style menu should appear.

*Under "Referencing Outlets", drag from the circle to the right of "New Referencing Outlet" to "File's Owner" in the "Placeholders" section to the left. When you release the mouse button, another popup menu should appear.

*Pick txtTextMe from the menu.

*Build and enjoy :-)

A: This is my fault. I drag a UITextField to *.xib file but I declare an IBTextView in my code. Thanks all.


text:
Q: Where are all the builtin macros defined in clang? I see that __GNUC__ is availble in clang, but they are not found here. Is there a place that has a complete list of all builtin macros in clang?
https://clang.llvm.org/docs/LanguageExtensions.html

A: Any macros defined by clang can be found with this command:
clang -dM -E -x c /dev/null

And any macros defined by clang++ can be found by this command:
clang++ -dM -E -x c++ /dev/null

Reference: this link


text:
Q: MergeSorting LinkedList in Java recursively So the task is to implement a linked-list and merge-sort which sorts linked-lists. I am fully aware that in industry I most likely won't have to implement any of these but I feel it's a good way to practice Java. Here is what I've got up to this point:
Node class:
public class Node<E extends Comparable<E>>
    {

    public E data;
    public Node<E> next;

    public Node(E data)
    {
        this.data = data;
        next = null;
    }

    public void printData()
    {
        System.out.print(data + " ");
    }
}

LinkedList class:
public class LinkedList<E extends Comparable<E>>
{

    protected Node<E> root;
    protected int size = 0;

    public LinkedList()
    {
        root = null;
    }

    public void addBeg(E e)
    {

        Node<E> newNode = new Node<E>(e);
        newNode.next = root;
        root = newNode;

        size++;
    }

    public Node deleteBeg()
    {
        Node<E> temp = root;
        if(!isEmpty())
        {
            root = root.next;
            size--;
        }
        return temp;
    }

    public void setRoot(Node<E> newRoot)
    {
        root = newRoot;
    }

    public boolean isEmpty()
    {
        return root == null;
    }

    public Node<E> getRoot()
    {
        return root;
    }

    public void printList()
    {
        Node<E> cur = root;
        while(cur!=null)
            {
                cur.printData();
                cur=cur.next;
            }
        System.out.println();
    }
}

MergeSorter Class:
public class MergeSorter<E extends Comparable<E>>
{

    public MergeSorter()
    {

    }

    private void split(LinkedList<E> list, LinkedList<E> firHalf, LinkedList<E> secHalf)
    {
        //if 0 or only 1 elements in the list - it doesn't seem to work, however
        if(list.getRoot() == null || list.getRoot().next == null)firHalf = list;
        else{
            Node<E> slow = list.getRoot();
            Node<E> fast = list.getRoot().next;
            while(fast!=null)
            {
                fast = fast.next;
                if(fast!=null)
                {
                    fast = fast.next;
                    slow = slow.next;
                }
            }
            //If I use the following line firHalf list is empty when in the caller of this method (it's not in this method, however). Don't understand why ):
            //firHalf = list;
            firHalf.setRoot(list.getRoot());
            secHalf.setRoot(slow.next);
            slow.next = null;
        }

    }

    private LinkedList<E> merge(LinkedList<E> a, LinkedList<E> b)
     {
        LinkedList<E> mergedList = new LinkedList<E>();
        Node<E> dummy = new Node<E>(null);
        Node<E> tail = dummy;

        while(true)
        {
            if(a.getRoot() == null){
                tail.next = b.getRoot();
                break;
            }
            else if(b.getRoot() == null){
                tail.next = a.getRoot();
                break;
            }

            else
            {
                if(a.getRoot().data.compareTo(b.getRoot().data) <= 0)
                {
                    tail.next = a.getRoot();
                    tail = tail.next;
                    a.setRoot(a.getRoot().next);
                }

                else
                {
                    tail.next = b.getRoot();
                    tail = tail.next;
                    b.setRoot(b.getRoot().next);
                }
                tail.next = null;
            }

        }
        mergedList.setRoot(dummy.next);
        return mergedList;
    }

    public void mergeSort(LinkedList<E> list)
    {
        Node<E> root = list.getRoot();
        LinkedList<E> left  = new LinkedList<E>();
        LinkedList<E> right = new LinkedList<E>();

        if(root == null || root.next == null) return; //base case
        split(list, left, right); //split

        mergeSort(left);
        mergeSort(right);

        list = merge(left, right); // when this mergeSort returns this list should be
                                   // referenced by the left or right variable of the
                                   // current mergeSort call (but it isn't!)
    }
}

I am fairly new to Java (coming from a C background) so I am sincerely sorry in advance if my code is utterly false. When I test the split and merge methods in the MergeSorter class independently, everything seems to work (splitting a list consisting of 0 or 1 element is not working and is driving me crazy but this is not needed for merge-sorting). The mergeSort method, however, is not working and I can't seem to figure out way. I tried to debug it myself and there's seems to be a problem when two halves are merged into one list and then the recursion returns. The newly merged list should be referenced by either the left or right variable of the current mergeSort call but instead I get only the last element instead of the whole list.

A: Method arguments in Java are always passed by value.
This can be a bit confusing, since objects are always accessed via references, so you might think they're passed by reference; but they're not. Rather, the references are passed by value.
What this means is, a method like this:
public void methodThatDoesNothing(Object dst, Object src) {
    src = dst;
}

actually does nothing. It modifies its local variable src to refer to the same object as the local variable dst, but those are just local variables that disappear when the function returns. They're completely separate from whatever variables or expressions were passed into the method.
So, in your code, this:
firHalf = list;

does not really do anything. I guess what you want is:
while (! firHalf.isEmpty()) {
    firHalf.deleteBeg();
}
if (! list.isEmpty()) {
    firHalf.addBeg(list.root().data);
}

which modifies the objected referred to by firHalf so it has the same zero-or-one elements as list.


text:
Q: Add attributes to my products via XML and wp all import Hi to all i have this structure of xml, that i want to do and i wait for tips is with someway to add atributes in my product via wp all import!
I have three attributes Materials, Feature, Color. Is there any way with this xml to add attributes and import it to my products?
I want to loop throught Filters/filter find group with id=6 and get the value! I can't figure it out and i want some help!
     <Filters>
        <filter>
          <group id="6">Materials</group>
          <value id="35">Wood</value>
        </filter>
        <filter>
          <group id="6">Materials</group>
          <value id="36">Steel</value>
        </filter>
        <filter>
          <group id="6">Materials</group>
          <value id="37">Fire</value>
        </filter>
        <filter>
          <group id="8">Feature</group>
          <value id="63">Feature 2</value>
        </filter>
        <filter>
          <group id="8">Feature</group>
          <value id="64">Feature 1</value>
        </filter>
        <filter>
          <group id="7">Color</group>
          <value id="1">White</value>
        </filter>
        <filter>
          <group id="7">Color</group>
          <value id="2">Black</value>
        </filter>
      </Filters>


text:
Q: Altium STEP export has missing 3D parts I'm relatively new with Altium Designer and I'm trying to export a pcb to a STEP model in order to build a chasis in solidworks, but when I export it, there are missing parts. Let the images guide you:

The fisrt is from Altium and the second from Solidworks.
When exporting, I have tried this already:
1- Reloading every generic3D models in the pcb library.
2- Every exporting settings or options have been tried.
3- Cried a lot, nothing's changed.
Nothing on the web has helped me yet. Thank you.
\
\
EDIT#1:
I have done some changes, corrected all the errors (don't know if it is linked) but now I get this message of error:

The problem is that the unsupress button, in the view panel is geryed out... Can't do nothing but do nothing.

A: We do such imports (Altium -> STEP -> SWX) all the time and never ever did we get such error message (some boards have ~2k parts). Try changing the 3D Model for the connector to .. say .. an extruded Box in your library, then try to export it again. I have a feeling that the model might be faulty.
Also, make 100% sure that you're not using a variant in Altium and double check that your OutputJob settings for the 3D STEP export are set to "No Variants" so it exports all parts. At least for this try.

A: Thank you your replies, but it was not exactly what solved my problem. I'll share my findings:
1- If it happens to someone, look first of all if all your models on altium are already in STEP, because they HAVE to be. The models that disapeared for me were SLDPRT (solidwork parts). I changed them to STEP and everything worked, but one of the pieces was still missing.
2- sometimes, solidworks decides that an assembly is too complex and supresses some parts. To forbid solidworks from doing that you need to go to the template file of the part/assembly file located in: ProgramData/SolidWorks/Templates. Open thoses files and go in the properties tab on the left. In advanced options, uncheck to "Supress new component" box. Save it all and start loading your file again.
Those two steps solved it for me. Thank you!


text:
Q: Запрос на выборку с двух связанных таблиц Не понимаю, как правильно сделать выборку с двух таблиц. Использую Doctrine. Суть такова: игрок хочет найти подходящую ему игру, если она не находится, то создаётся новая, в которой ожидается противник. И если другой пользователь захочет найти игру, то проходим по всем ожидающим играм и ищем подходящую под тип игры и опыт второго игрока. Если не находим, создаётся новая, и т.д.
То есть:

*

*Проходим по ожидающим играм;

*Ищем игры, в которых pending_game.type = желаемому типу игрока. Их всего два: cost и free.

*Так же добавить в условие, что опыт игрока и опыт противника могут отличаться только на 100 единиц. То есть, игрок с опытом 500 может играть только с игроками, у которых опыт от больше 400 меньше 600. Например: player.experience = 500, pending_game.player.experience = 550, игрок, который сейчас ищет игру, и тот, кто ожидает противника может встретиться.

CREATE TABLE player
(
    id                       INT AUTO_INCREMENT    NOT NULL,
    name                     VARCHAR(255)          NOT NULL,
    experience               INT         DEFAULT 0 NOT NULL,
    PRIMARY KEY (id)
) DEFAULT CHARACTER SET utf8mb4
  COLLATE `utf8mb4_unicode_ci`
  ENGINE = InnoDB

CREATE TABLE pending_game
(
    id        INT AUTO_INCREMENT NOT NULL,
    player_id INT                NOT NULL,
    type      VARCHAR(24)        NOT NULL,
    UNIQUE INDEX UNIQ_57ADA99634DFEB (player_id),
    PRIMARY KEY (id)
) DEFAULT CHARACTER SET utf8mb4
  COLLATE `utf8mb4_unicode_ci`
  ENGINE = InnoDB

ALTER TABLE pending_game ADD CONSTRAINT FK_57ADA99634DFEB FOREIGN KEY (player_id) REFERENCES player (id)

A: Проверка наличия игры:
SELECT id
FROM pending_game pg
JOIN player p1 ON p1.name = @player_name /* или p1.id = @player_id */
JOIN player p2 ON pg.player_id = p2.id
              AND p2.experience BETWEEN p2.experience - 100 AND p2.experience + 100
WHERE pg.type = @needed_type
ORDER BY pg.id ASC
/* раскомментировать, если нужна одна игра, иначе вернутся все, пусть выбирает */
-- LIMIT 1

Если предыдущий запрос не вернул записей (или игрок ничего не выбрал), то
INSERT INTO pending_game (player_id, type)
SELECT id, @needed_type
FROM player
WHERE name = @player_name
/* или
INSERT INTO pending_game (player_id, type)
VALUES ( @player_id, @needed_type )
*/

@player_name - имя текущего игрока
@player_id - ID текущего игрока
@needed_type - выбранный тип игры


text:
Q: Font.createTrueTypeFont not working Font f = Font.createTrueTypeFont("Airstrike 3D Regular", "airstrike3d.ttf").derive(50, Font.STYLE_BOLD);
img.getGraphics().setFont(f);

This is the code for adding ttf font. I copied .ttf file in src directory. When I am drawing text on image, its all the same. I tried with different font as well.
This is the code for drawing the text on image.
img.getGraphics().drawString("Inlet", 250, 100, getUnselectedStyle().TEXT_DECORATION_NONE);

I am not able to increase font size. Suggestions please.

A: You need to use:
Graphics g = img.getGraphics();
g.setFont(...);
g.drawString....


text:
Q: Protect the login from malacious input Flask login redirects to /login?next=/protected/123 when I am not logged in. Anybody can as well use /login?next=phishingsite.com/give_me_your_password_again since I use:
redirect(request.args.get('next','/')

How do I verify that the URL is present in the same app?

A: You can add a function called next_is_valid to check if the next originated from the same host like so:
from urlparse import urlparse

def next_is_valid(url):
    parsed = urlparse(url)
    if parsed.hostname and parsed.hostname == request.url_root:
        return True

    # if there is no hostname since it's a relative URL
    elif not parsed.hostname:
        return True
    return False

# in your flask app route handler check if next_is_valid returns True
if not next_is_valid(request.args.get('next')):
    abort(400)


text:
Q: SQL Server: Generate WHERE clause from resultset ids? I have a query that produces the following resultset:
ID (text)    VAL
 1           A
 2           B
 3           C

I want to generate a WHERE clause from the resultset IDs:
where id in ('1','2','3')

With  Oracle, I can use the following query to generate a WHERE clause:
with a as (

  <my_query>

)
select 'where id in ('
  || listagg(id, ',') within group(order by id)
  || ')' as where_clause
from a

Is there a way to do the same sort of thing using SQL Server?

Related: Oracle: Generate WHERE clause from resultset ids?

A: Just try this.
with a as (

  <my_query>

)
SELECT 'WHERE id IN (' +
  STRING_AGG(id, ',') WITHIN GROUP(ORDER BY id)
  + ')' as where_clause
FROM a

then you will get WHERE id IN (1,2,3)
If you want to get WHERE id IN ('1','2','3')
then you can change like following
SELECT 'WHERE id IN (''' +
      STRING_AGG(id, ''',''') WITHIN GROUP(ORDER BY id)
      + ''')' as where_clause
FROM a

A: You can just use a normal IN
with a as (

  <my_query>

),
b as (

  <Other Query>

)
select *
from b
where b.id in (
  select a.id
  from a
);


text:
Q: Changing App title - Google Play store issue Trying to release a new version of my app on the play store - and I'm changing the App's name from the 'Store Listing' section. But I keep getting this error :
You need to choose a different title for your app.
This one is already the title of tmp.xxxxxxxxxxxxx.xxxxxxxxxxxxx.
I realized that the name I'm trying to enter is what is stored in the @string/app_name variable for the APK that is in release right now - is this why I'm getting the error? Will changing this name in the new APK fix the issue? Or am I missing out on something?

A: No, But you can set same or differ name from @string/app_name & its not affect your app, so don't worried about that.
But which Name you tried, that already taken by other so please add any extra phrase to your app name. Its only for show on Play Store.


text:
Q: I am unable to convert an ArrayBuffer stored in DB to an image My app takes a photo which is converted to an ArrayBuffer and stored in DB as such. I want to then retrieve that data and convert it to an image without storing the resulting file.
I have looked RN-Fetch-blob and FileReader but am unclear about a few things.
Here is what I've tried with variable combinations after reading many different posts on the issue:
var arrayBufferView = new Uint8Array(expense.receipt);
const blob = new Blob(expense.receipt,"image/jpeg" );
//const blob = new Blob([expense.receipt],"image/jpeg" ); <-error
 //const blob = new Blob(arrayBufferView,"image/jpeg" ); <-error

//console.log (blob);
const fileReaderInstance = new FileReader();
fileReaderInstance.readAsDataURL(blob);  // tried 'readAsBufferArray' but RN complained that that function is not implemented.
fileReaderInstance.onload = () => {
 const base64data = fileReaderInstance.result;
 console.log(base64data);
};
 var imageBase64 = 'data:'+"image/jpeg"+';base64,'+blob;
 console.log (imageBase64)
});

What am I doing wrong?
Thanks in advance.

A: Converting an image from Array Buffer to:
Blob:
var arrayBufferView = new Uint8Array(expense.receipt);
const blob = new Blob([arrayBufferView], {type:"image/jpeg"} );
const img = createObjectURL(blob); //Remember to revokeObjectURL when done

Base64:
var arrayBufferView = new Uint8Array(expense.receipt);
const charArr = arrayBufferView.reduce((data, byte)=> (data + String.fromCharCode(byte)), ''));
const img = btoa(charArr);


text:
Q: How to access a parameter in jrxml file and Print it? My query is, I have set a parameter in my java file like given below
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("ReportTitle", "MRSG Quarterly Report");

How to access this in my jrxml file and Print it as a text?

A: You need to declare the parameter in your jrxml
 <parameter name="ReportTitle" class="java.lang.String"></parameter>

Then call it in a text field
<textField isBlankWhenNull="true">
  <textFieldExpression class="java.lang.String"><![CDATA[$P{"ReportTitle"}]]>
  </textFieldExpression>
</textField>

A: You can put in the select (sql report) a parameter and then use it as a Field, lika this:
<![CDATA[SELECT $P{FechaFin} as fechaFinal, ....]]>

You can use fechaFinal as a Field and print it in your report.


text:
Q: Nodejs Apple native authentication i'm a nodejs backend developer and i have an app with nodejs backend and the client side is ios, swift. I need to to do the feature sign in with apple
I figure out there are 2 ways to sign in with apple. One is using restful api, one is sign in with native device.
I know how to do the sign in with apple using restful api, because i worked with passportjs and i did the sign in with fb, twitter before. However i don't understand how the sign in with apple (the native way) work on the nodejs side.
Here is the article: https://auth0.com/docs/connections/apple-siwa/add-siwa-to-native-app

A: As you are using regular web app (node), you should use web based flow. Native implementation is not applicable in your case. You can enable Sing In with Apple like any other social login in Auth0.
https://auth0.com/docs/connections/apple-siwa/add-siwa-to-web-app


text:
Q: Where can I find a copy of Erlang/OTP R14B05? I'm trying to find the source for R14B05.
The reason is that I want to see how Precise Explanation of Typing Errors was implemented. That page provides a link to the source code, but it doens't seem to be version-controlled. So I want to diff against the code is based on in order to see what changed.
The page that links to the paper says that the code is based on R14B05, so now I'd like to try diffing against R14B05.
I look at https://github.com/erlang/otp/releases?after=OTP_R16B01_RC1 or git tag -l in the repo, I can only find R14B04, then the R15 series–no R14B05.

A: I see no R14B05 anywhere, only R14B01-R14B04.
http://erlang.org/download/ and http://erlang.org/documentation/ seems to have old files.
doc-5.8.5 is for Erlang/OTP R14B04, and the next one, which is doc-5.9, is for Erlang/OTP R15B. There does not appear to be a R14B05 one, so perhaps it indeed could be a typo. Perhaps they thought 5.8.5 was R14B05?
You could try contacting the authors as well, just in case.


text:
Q: Node EJS - Cannot keep the data on form after submit I have following Server.js code
var result = null;
app.get('/reset',function(req,res){
res.render('index',{result:""})
})

app.post('/',function(req,res){
/* some logic... */
res.render('index',{result:some_value})
})
app.listen(/* Starting Server */);

Index.ejs
<form method="post" action="/">
/* 4 Text box for input */
/* 1 Text area for JSON output <%= result %> */
/* 1 Submit button */
/* 1 Reset button */
</form>

I am submitting 4 text fields from the form and based on that a output is generated which is displaying in the text area.
The problem is:-
1) I am not able to refresh the text area when I click the reset button as the output is from the server side variable.
2) I am not able to keep the form data, it refreshes on submit.
I have tried:-
1) Stopping the propogation on submit by specifying jquery  e.preventDefault().
2) Tried clearing textarea.
Could some one please help me with the same?
Also let me know if any further information is required for the question.


text:
Q: how does 'window.location.href' work? there is some code in "new.html" like
$('#publish').click(function(){
    window.location.href = "/index";
    alert(window.location.href);
    return false;
})

when it works with chrome debug, it display:
Navigated to http://127.0.0.1/new
Navigated to http://127.0.0.1/index

why it can redirect to index?
if i remove "return false", it doesn't work conversely...I don't understand it...please give me some pointers...thank you!

A: If the button is in a form, the default action of clicking on the button is to submit the form. When the form is submitted, any Javascript that was in progress is cancelled. This includes a pending redirect from assigning to window.location.
When you return false from the click handler, you prevent the default action. This allows the redirect to be followed.


text:
Q: Parsing large XML documents with Nokogiri vs Libxml2 I'm working on transforming a ~3GB XML document, structured as a list of similar <Element>. The document is too large to XSL transform directly. But each <Element> can be transformed independently, so I'm parsing the XML and separating them.
When testing with Nokogiri, I found performance quickly climbed into multiple minutes. As a test, I wrote an example parser in C using libxml2 directly, which is much faster.
Code and results:
https://gist.github.com/adilosa/d4277dc1c683da91990515352ffe5420
Is it reasonable to expect 10x overhead with Nokogiri vs C? Is it worth it then to handle large documents in C?


text:
Q: Extending a continuous function by one point, is the resulting function continuous as well? Let's say I have a continuous function $f: \mathbb{R} - \{0\} \rightarrow \mathbb{R}$. Suppose I extend $f$ to a function $g$ such that  $g:\mathbb{R} \rightarrow \mathbb{R} \cup \{\infty\}$ where $g(x) = f(x)$ for all $x \neq 0$ and $g(0) = \infty$. Is the resulting function $g$ continuous?
I have an idea to use the pasting lemma somehow, but I cannot seem to convince that the part I'm pasting, $g(0) = \infty$ is actuall continuous. Thanks.

A: No. Let $f: \mathbb{R} \to \mathbb{R}$ be continuous. Then $f$ is also continuous on $\mathbb{R}-{0}$. Clearly, the corresponding function $g$ (refering to your notation) is not continuous.

A: You cannot apply the pasting lemma here because you are pasting the closed set $\{0\}$ with the open set given by its complement. The pasting lemma applies to sets both open or both closed.


text:
Q: Passing array into a constructor and getting "cannot convert double[] to int" error I'm trying to pass a simple array into a constructor of a class and kept getting a "cannot convert double[] to int" error. I'm really lost as to why.
import java.util.*;

public class Demo {
    public static void main(String[] args) {
        double[] data = {1,2,3,4,5,6,7,8,9,10,11,12};
        Rainfall[] rain = new Rainfall[data];
    }
}

import java.util.*;

public class Rainfall {
    private double[] monthlyRain;

    public Rainfall(double [] array) {
        monthlyRain = array;
    }
}

My IDE kept showing a red squiggly line underneath the "data" in
Rainfall[] rain = new Rainfall[data];

in the main method.

A: Use this instead...you are invoking constructor wrongly... with Rainfall[] rain = new Rainfall[data];
public class Demo {
    public static void main(String[] args) {
        double[] data = {1,2,3,4,5,6,7,8,9,10,11,12};
        // Rainfall[] rain = new Rainfall[data];   wrong...
           Rainfall[] rain = new Rainfall[]{new Rainfall(data) }; // correct
    }
}

The thing is... Rainfal[] only holds an array of Rainfall objects...not one..
So thats..the correct way...sorry for error...


text:
Q: Infinite While loop in C++ I am teaching myself c++ and am building a simple menu program. Im a complete noob to C++ so I apologize in advance for the question if it seems foolish. My code continuously calls getNum() and never exits, despite the correct menu selections. What am I doing wrong? Here is my code:
#include <iostream>
#include <string>
using namespace std;

void calc();
void pass();
string getNum(string num);

int main(int argc, const char * argv[])
{
    string num = "0";
    string menu = "Enter... \n 1 For calculator \n 2 for Passwords";
    cout << "Hello this is a sample menu program" << endl;

    while(num != "1" || num != "2")
    {
    getNum(num);
    cout << "You selected: " << num << endl;
    }

    if(num == "1"){
        calc();
    }
    else {
        pass();
    }
}
void calc() {
    cout << " You are running the calculator" << endl;
}
void pass() {
    cout << "You are running passwords" << endl;
}
string getNum(string num) {
    cout << "What would you like to do?" << endl;
    cout << "Enter... \n 1 For calculator \n 2 for Passwords" << endl;
    getline(cin, num);
    return num;
    }

A: Change this condition
while(num != "1" || num != "2")

to
while(num != "1" && num != "2")

To write the condition correctly you should consider that the loop should not be repeated if num either equal to "1" or "2". This condition can be written as
num == "1" || num == "2"

However the loop shall be repeated if this condition is not true. So the condition for the loop will be repeated will look like
! ( num == "1" || num == "2" )

According to the mathematical logic this condition is equivalent to
num != "1" && num != "2"

It would be better to rewrite the loop like
string num;

//...

do
{
    getNum(num);
    cout << "You selected: " << num << endl;
} while ( num != "1" && num != "2")

At least one iteration should be done in any case should not it?
Also define the function as
void getNum(string &num);

//...

void getNum( string &num) {
    cout << "What would you like to do?" << endl;
    cout << "Enter... \n 1 For calculator \n 2 for Passwords" << endl;
    getline(cin, num);
    }

A: getNum(num);

In getNum you have a return statement that returns what the user entered. When you call getNum you don't save that return value.
num = getNum(num);

To make things clearer, I would remove the input parameter from getNum. You don't need to pass anything to it since it's job is to prompt for a number and return that number.
string getNum() {
    cout << "What would you like to do?" << endl;
    cout << "Enter... \n 1 For calculator \n 2 for Passwords" << endl;

    string num;
    getline(cin, num);
    return num;
}

Then change the call to:
num = getNum();

Another issue is your loop condition.
while(num != "1" || num != "2")

Think about what this will do if num were, say, "1". You'd want the loop to stop, right? Look what happens if we evaluate and reduce the expression bit by bit:
while(num != "1" || num != "2")
while("1" != "1" || "1" != "2")
while(false || true)
while(true)

Well that's not right. It should have evaluated to false. The || should be &&.
while(num != "1" && num != "2")

A: Line
while(num != "1" || num != "2")

be DeMorgan laws is the same as
while(!(num == "1" && num == "2"))

So you need
 (num == "1" && num == "2")

to be true
Hence the difficulty
apart from the other bits of the code that are in error

A: You have written  while(num != "1" || num != "2")
so either num would be equal to "1" or "2" or none of these. In any condition one of these condition is true( i.e.  either num is not equals to 1 , this is true or num is not equals to 2 , this is true), therefore your while loop is always true and continuously run without stop

A: this condition
while(num != "1" || num != "2")
will always return true for all inputs. for example, "1", it is false on num != "1" but will still return true on the other condition num != 2, thus it will never exit (true || false == true)
also it should be
else if(num == '2') {
        pass();
    }

correct condition should be while(!(num != "1" && num != "2")) to only allow "1" and "2" inputs


text:
Q: Parameter passing to subroutine x64 inline assembly(Vc++ 2015 with Intel c++ compiler 2017) I coded
main()
{
  unsigned char *memory;
  unsigned int a=15;
  float sigma=5.0f;

  gaussian_filter();

}
gaussian_filter()
{
    unsigned __int64 evacuate_rbp;
    unsigned __int64 evacuate_rsp;

 __asm
 {
         mov eax, a
         ...
         mov evacuate_rbp, rbp
         mov evacuate_rsp, rsp
         ...

         mov rsp, memory
         ...

         movss xmm0, sigma

         ....

         mov rbp, evacuate_rbp
         mov rsp, evacuate_rsp
      }
}

I want to non-parameter passing to use rbp and rsp registers as an address index of memory.
In Build with Intel C++ compiler,  error is occured. Why?.


text:
Q: General session handling in java I work with multiple languages like PHP, C, JAVA etc.
I am trying to fully understand how session is implemented in java.
Question : In php I can create a session and use the session in any class even utility classes. In Java why session is meant to be handled normally only in servlet classes? why not in any basic POJO classes without actually passing session or context object ? (I know other classes can, using complex techniques, but why not easily as servlet or as in other languages ).
I do know that the correct way to do things is use session in Servlet to retrieve object/values and pass object/values to other utility classes and get results.
Please let me know if there is in fact an easy way to get session in basic POJO classes.

A: I had flagged to delete this question as I found the answer in another SO link Retrieving Web Session from a POJO Outside the Web Container . Since it has not been deleted till now , I am answering my own question.
What are servlet and why we use them ?
A Java servlet is a Java program that extends the capabilities of a server.
Although servlets can respond to any types of requests, they most commonly implement applications hosted on Web servers.
Such Web servlets are the Java counterpart to other dynamic Web content technologies such as PHP and ASP.NET.
More information about java servlet at the link https://en.wikipedia.org/wiki/Java_servlet
Servlet vs POJO/normal Java classes ( why session access only in servlet ?)
A servlet class too is a java class. Servlet is a java class which comply servlet specification, so that it can be run in a server. Java class not required to comply Java Servlet API
A servlet container (e.g. Tomcat) is designed to be able to recognise servlet classes and, if configured correctly, treat them in a particular way. There's nothing magical about this - you can always write your own application that can treat any type of class in a specific way - but there's a standard that all servlet containers follow that means you can write a servlet class and know how it will be used.
Java was designed to be a platform independent language to create software to be embedded in various consumer
electronic devices. Soon it was apparent that the Java can be used in client/server programming environment because of its inherent portability. Hence servlet and applet were introduced in java. Java applets helped create dynamic, self-executing program on client side. Java servlet is a small program that executes on the server. Just as applets dynamically extend the functionality of a web browser, servlets dynamically extend the functionality of a web server.
Since servlet part of java is used in server side programming , this has access to session. POJO classes are also used in server side programming but code which uses session is usually written in servlet.
POJO Vs PHP classes(server side)
Java is used in many development environments like desktop,mobile,embedded and Web. PHP is a server-side scripting language designed for web development.It can also be used for general purpose programming but I am limiting the discussion to class used in php in server side programming(ie .php pages). So it is better to compare php classes in php pages with servlet/JSP - server side development part of JAVA.
Again servlet puts html code inside Java code. JSP puts java code inside html code. So JSP in java is more comparable to PHP .
If we understand this then we can infer that there is no good reason to compare POJO in java to PHP classes (server side). It is like comparing applies to oranges. if you are interested in comparison between php and jsp please visit http://www.withoutbook.com/DifferenceBetweenSubjects.php?subId1=57&subId2=2&d=Difference%20between%20PHP%20and%20JSP
In modern web development we use template engines ie instead of JSP we use servlet with template engine(Freemarker,Velocity). PHP has its own template engines.
How to access session in POJO classes ? Why it is hard / Is there any easy way ?
First of all it should not be done as it would be a bad programming practice. Secondly it can be done but there is hardly any scenario where this would be necessary. Since there is no need for the same the ways to implement it are not easy.
It should not be done , If you have to there are two ways.

*

*We can pass session and request objects from servlet to POJO classes(via methods or constructors).

*Store the request in a ThreadLocal in a Filter (and clean it afterwards)

Also look at the SO links for sample code
get HttpSession|Request from simple java class not servlet class
Retrieving Web Session from a POJO Outside the Web Container
I asked this question when I was stuck at a particular scenario . I used to program in PHP and wondered why I never had the issue there and got confused. People who usually move from php to java , also have a hard time understanding the how it all works , so attaching one more part to the answer.
Why servlets require servlet containers like tomcat while php runs on a http server/webserver (Apache).?
The question is incorrect in assumptions made but the answer will highlight why .
A web server is software that helps to deliver web content (web pages) to the clients (e.g. web browser)
through the Internet using HTTP protocol. HTTP is a simple request /response protocol underpinning most web
applications on the Internet, regardless of whether they are written in Java. An HTTP request can correspond to
one of the seven HTTP methods: GET, POST, HEAD, OPTIONS, TRACE, PUT and DELETE
The server side technologies like JSP/Servlets, ASP, and PHP etc. will require their software libraries to be installed
at the server. Without these libraries a web server won't be able to execute those server technologies and is just an HTTP Server.
An HTTP server can handle HTML and other client side technologies which don't require any server capability.
The Apache HTTP Server is an example of an HTTP server.
Regarding Servet/JSP : Servlet can be run on a servlet container.Tomcat is normally called a servlet container.A Servlet container is basically a web server for Java Servlets and JSP pages. Tomcat has an HTTP listener inside it, but in addition to that it has a servlet/JSP engine. A servlet, in the end, is a Java class. JSP files (which are similar to PHP, and older ASP files) are generated into Java code (Servlet), which is then compiled to .class files by the server and executed by the Java virtual machine.
Regarding PHP : PHP will not work in pure Apache or any HTTP server. We are able to run php in apache because it is linked to Apache(SAPI - server API) Using mod_php5.so(or similar) modules. We do not normally start any php daemon. Apache starts the php interpreter along with itself.
If oracle wants, it can develop a module similar to PHP module which will make it easier to host Java code on an HTTP server. But using a servlet container model has many benefits compared to the PHP interpreter model even with the disadvantage of increase in complexity.

A: From Servlet class pass session to any helper class(Create HTTPSession as helper class propertiy).
Now in your POJO class get session from helper class that you have set previously from servlet.

A:
Question : In php I can create a session and use the session in any
  class even utility classes. In Java why session is meant to be handled
  normally only in servlet classes? why not in any basic POJO classes
  without actually passing session or context object ? (I know other
  classes can, using complex techniques, but why not easily as servlet
  or as in other languages )

Every language has its own design & structure. There is no universal session handling protocol that it should be handled the same way in all the server side languages. In java if handling session in controllers i'e servlet setting & getting attributes serves your purpose why would anyone want to get a session object in a POJO. You can save a POJO in a session in a servlet.
Besides if there are exceptional out of the norm requirements you can always write custom code.


text:
Q: can't use scikit-learn - "AttributeError: 'module' object has no attribute ..." I'm trying to follow this tutorial of scikit-learn (linear regression).
I've installed scikit through pip install -U scikit-learn, I use python 2.7 and Ubuntu 13.04
When I try to run the first lines of code there I get an error and it happens every time I'm trying to run anything with scikit-learn.
import pylab as pl
import numpy as np
from sklearn import datasets, linear_model

# Load the diabetes dataset
diabetes = datasets.load_diabetes()

I get the following:
AttributeError: 'module' object has no attribute 'load_diabetes'

When I try:
regr = linear_model.LinearRegression()

I get :
AttributeError: 'module' object has no attribute 'LinearRegression'

It seems to me that it's either I'm using the package wrong (but I've copied from their tutorial), or I've installed something wrong (but the package is loaded successfully).
Can anyone help?

A: This worked for me:
from sklearn.datasets import make_moons

A: I faced same issue but then i realized that my program name was sklearn.py . In case if any one sees this type of error also check that you program name is not same as the package name , or else you will get module object has no attribute error, as in the question .

A: Another cause of this problem (not the problem with the OP's code) - but the one that got me - is that python does not automatically import subpackages or modules unless that is explicitly done by the package developer. And sklearn does not automatically import its subpackages, so if you have
import sklearn
diabetes = sklearn.datasets.load_diabetes()

then you will get
AttributeError: module 'sklearn' has no attribute 'datasets'

This is a highly misleading error message, because sklearn does have a subpackage called datasets - you just need to import it explicitly
import sklearn.datasets
diabetes = sklearn.datasets.load_diabetes()

A: OK.. Found it finally.. Posting it here in case someone will get into the same problem.
I had another version of sklearn (probably because of apt-get install) in a different directory. It was partially installed somehow but it was the one that got loaded.
Make sure to look at your pip script's output to see where does it install the package, and when you load it from python, check sklearn.__path__ to see where is it taking it from.

A: It seems that the package loaded from sklearn were the one from the distribution library and not the one installed from pip. Solution for me (debian) was to reinstall the pip package. This can be checked with:
import sklearn
sklearn.__path__

If this shows /usr/lib/python/, then is it using the distribution.
The problem got solved by uninstalling and reinstalling sklearn.
 $ pip uninstall scikit-learn
 $ pip install scikit-learn

A: I ran into a similar issue and this post with:

"*** AttributeError: 'GaussianProcessRegressor' object has no attribute '_y_train_mean"

when I updated scikit-learn and loaded a pickled model and attempted to predict using the model. I simply needed to retrain the model and it solved my issue.

A: Try this:
from sklearn.datasets import load_diabetes
diabetes = load_diabetes()

A: I had a similar problem and tried troubleshooting based on this article by Nick Coghlan since none of the suggested answers seemed to fix my problem.
I fell into the so-called "Double Import trap". what I had was something like:
import sklearn
import sklearn.preprocessing

by removing one of the imports and resetting my workspace I managed to fix the problem.

A: I solved this issue by inserting the following lines of code:
import sklearn
from sklearn.linear_model import LinearRegression

A: I had named the python file as sklearn.py that was the reason of this ATTRIBUTEERROR with me.
Renamed that and resolved it.


text:
Q: CustomTableModel + JTable = table isn't filled I'm trying to implement my own table model to show the schedule in JTable. I implemented it, but table even isn't filled. Maybe I lost some methods which are required to be implemented? Here is my code:
public class ScheduleTableModel extends AbstractTableModel {

    private ArrayList<TimeInterval> timeIntervals;
    private ArrayList<Day> days;
    private LinkedHashMap<ScheduleSlot, Lesson> fullSchedule;
    private LinkedHashMap<ScheduleSlot, Lesson> partialSchedule;
    private ScheduleType scheduleType;

    public ScheduleTableModel(ArrayList<TimeInterval> timeIntervals, ArrayList<Day> days, LinkedHashMap<ScheduleSlot, Lesson> fullSchedule, LinkedHashMap<ScheduleSlot, Lesson> partialSchedule) {
        this.timeIntervals = timeIntervals;
        this.days = days;
        this.fullSchedule = fullSchedule;
        this.partialSchedule = partialSchedule;
        this.scheduleType = ScheduleType.PARTIAL;
        fireTableStructureChanged();
    }

    public ScheduleTableModel(LinkedHashMap<ScheduleSlot, Lesson> fullSchedule) {
        this.fullSchedule = fullSchedule;
        this.scheduleType = ScheduleType.GENERAL;
        fireTableStructureChanged();
    }

    @Override
    public int getRowCount() {
        if (scheduleType == ScheduleType.PARTIAL) {
            return timeIntervals.size() + 1;
        } else {
            return fullSchedule.size();
        }
    }

    @Override
    public int getColumnCount() {
        if (scheduleType == ScheduleType.PARTIAL) {
            return days.size() + 1;
        } else {
            return 3;
        }
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        if (scheduleType == ScheduleType.PARTIAL) {
            if (columnIndex > 0 && rowIndex > 0) {
                for (Map.Entry<ScheduleSlot, Lesson> entry : partialSchedule.entrySet()) {
                    if (entry.getKey().getDay().equals(getColumnDay(columnIndex)) && entry.getKey().getTime().equals(getRowTimeInterval(rowIndex))) {
                        return entry;
                    }
                }
            } else if (rowIndex == 0 && columnIndex > 0) {
                return days.get(columnIndex);
            } else if (columnIndex == 0 && rowIndex > 0) {
                return timeIntervals.get(rowIndex);
            } else if (rowIndex == 0 && columnIndex == 0) {
                return "";
            }
        } else {
            List<Map.Entry<ScheduleSlot, Lesson>> scheduleIterator = new ArrayList<Map.Entry<ScheduleSlot, Lesson>>(fullSchedule.entrySet());
            switch (columnIndex) {
                case 0: {
                    scheduleIterator.get(columnIndex).getKey().getTimeSlot();
                }
                case 1: {
                    scheduleIterator.get(columnIndex).getKey().getPlaceSlot();
                }
                case 2: {
                    scheduleIterator.get(columnIndex).getValue();
                }
            }
        }
        return "";
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }

    public Day getColumnDay(int columnIndex) {
        return (Day) getValueAt(0, columnIndex);
    }

    public TimeInterval getRowTimeInterval(int rowIndex) {
        return (TimeInterval) getValueAt(rowIndex, 0);
    }

    @Override
    public Class getColumnClass(int columnIndex) {
        if (scheduleType == ScheduleType.GENERAL) {
            switch (columnIndex) {
                case 0: {
                    return fullSchedule.entrySet().iterator().next().getKey().getTimeSlot().getClass();
                }
                case 1: {
                    return fullSchedule.entrySet().iterator().next().getKey().getPlaceSlot().getClass();
                }
                case 2: {
                    return fullSchedule.entrySet().iterator().next().getValue().getGroup().getClass();
                }
                case 3: {
                    return fullSchedule.entrySet().iterator().next().getValue().getProfessor().getClass();
                }
                case 4: {
                    return fullSchedule.entrySet().iterator().next().getValue().getCourse().getClass();
                }

            }
        } else {
            return String.class;
        }
        return String.class;
    }

    @Override
    public String getColumnName(int column) {
        if (scheduleType == ScheduleType.GENERAL) {
            switch (column) {
                case 0: {
                    return "";
                }
                case 1: {
                    return "";
                }
                case 2: {
                    return "";
                }
                case 3: {
                    return "";
                }
                case 4: {
                    return "";
                }
            }
        }
        return "";
    }
}

Could anybody point me on my mistakes? Thanks everyone in advance!
p.s. I'm not sure if it is necessary to implement setValueAt for Jtable be filled. If I'm right and it is necessary could you show an example of the implementation of this method?
ADDITION:
Implemented setValueAt(), but nothing changed:
@Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        if (scheduleType == ScheduleType.PARTIAL) {
            Map.Entry<ScheduleSlot, Lesson> entry = (Map.Entry<ScheduleSlot, Lesson>) aValue;
            if (columnIndex > 0 && rowIndex > 0) {
                Day day = getColumnDay(columnIndex);
                TimeInterval timeInterval = getRowTimeInterval(rowIndex);
                TimeInterval entryInterval = entry.getKey().getTime();
                Day entryDay = entry.getKey().getDay();
                if (day.equals(entryDay) && timeInterval.equals(entryInterval)) {
                    fullSchedule.put(new ScheduleSlot(new TimeSlot(entry.getKey().getTime(), entry.getKey().getDay()),
                            new PlaceSlot(entry.getKey().getRoom(), entry.getKey().getBuilding())), entry.getValue());
                }
            } else if (rowIndex == 0 && columnIndex > 0) {
                days.add((Day) aValue);
            } else if (columnIndex == 0 && rowIndex > 0) {
                timeIntervals.add((TimeInterval) aValue);
            }
        }

        fireTableDataChanged();
    }

Here is the picture of tablemodel structure how I see it:

I wanna yellow part be filled from timeIntervals list, green part - from days list and the purpule part - from partialSchedule hashmap.

A: *

*your AbstractTableModel missing important setXxx() method(s)

*why did you use too hard methods fireTableStructureChanged(); use proper fireXxxXxx()methods, this code example contains most of important methods for AbstractTableModel with proper fireXxxXxx()

*I'd be use DefaultTableModel based on Vector<Vector<Object>> rather than XxxMap or XxxHashMap, this way required depest knowledge about JTable, XxxTableModel and XxxMap or XxxHashMap works together


text:
Q: How do I test for a non-zero exit status of a command in Bash? I have a script that checks the exit status of the following function:
function is_git_repository {
    git branch &> /dev/null
}

Which returns 0 if you're in a git repo, and 128 if you're not.
I have no problem testing to see if the return value is 0; the following works as expected:
if is_git_repository ; then
    echo you are in a git repo
else
    echo you are NOT in a git repo
fi

But it's when I'm trying to test for an exit status that is anything OTHER than 0 when I'm running into problems. I've tried the following, but none of them work:

*

*if [[ "$(is_git_repository)" != "0" ]] ; ... always evaluates to true (link)

*if [[ "$(is_git_repository)" -ne "0" ]] ; ... always evaluates to false

*if [[ "$(is_git_repository)" != 0 ]] ; ... always evaluates to true

*if [[ "$(is_git_repository)" -ne 0 ]] ; ... always evaluates to false

*if [[ ! "$(is_git_repository)" ]] ; ... always evaluates to true

*if !is_git_repository ; ... just echoes the command back to me, but without the bang (wtf?)

What is the correct way to check for a non-zero exit status of a command in an if statement?

A: Consider boolean shortcut instead of an if statement:
is_git_repository || echo you are NOT in a git repo

A: I soon figured out that if ! is_git_repository ; then ... works as intended (look under 7.1.2.1. Testing exit status in Introduction to if), but why? I would have expected that #1 would work at the very least, but I don't know why it doesn't.
Also, what is up with #6?!


text:
Q: How to prevent rollback operation for each test in TestNg + Spring + H2 database? I am using spring boot integration test with h2 database and testNg for integration tests.
And my spring boot application uses spring data jpa.
For each test, i am unable to see data saved by the previous tests.
Below is my Integration test class:-
import org.springframework.test.annotation.Rollback;
import org.testng.annotations.Test;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;

@ActiveProfiles("test")
@SpringBootTest(classes = APP.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public class IntegrationTest extends AbstractTestNGSpringContextTests {

    @Test(priority = 1)
    @Rollback(false)
    private void m1() {
        // save data.
    }

    @Test(priority = 1)
    @Rollback(false)
    private void m2() {

        // retrieve saved data. (Failed)
    }

 }

I am using TestRestTemplate to test test PUT and POST Rest endpoints.

A: You are using @SpringBootTest annotation, which means you will start an entire spring-boot application. @Commit and @Rollback are to use with @DataJpaTest, or something similar, when your test is @Transactional to have a good control.
Here is what I think:

*

*Either there is a problem with TestNG and Spring, in which case, there is not much I can do

*Or your code is in fault. Have you tried using some breakpoints to see if your code goes through all your layers.

Could you show more of your code ? The test code, the controller, the service and data layer. And of course, your configuration classes, that would be great in order to help

You have to use the annotation @Commit and not @Rollback
@ActiveProfiles("test")
@SpringBootTest(classes = APP.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public class IntegrationTest extends AbstractTestNGSpringContextTests {

    @Test
    @Commit
    private void m1() {
    }
 }

Alternatively, you could use TransactionTemplate for a more grained control. See this: How to force transaction commit in Spring Boot test?.

A: Execute your repository calls within a transaction.
    final TransactionTemplate transactionTemplate = new TransactionTemplate(txManager);
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    return transactionTemplate.execute(new TransactionCallback<R>() {
        @Override
        public R doInTransaction(final TransactionStatus status) {
            myRepository.save(myEntity);
        }
    });


text:
Q: ASP.NET Session variables only being set 2nd time around I have three Session variables that I assign values to in an ASMX web service like so:
Session["Stats1"] = items;
Session["Stats2"] = items;
Session["Stats3"] = items;

Each assignment happens in its own web method, and when I debug, each one is hit and the 'items' variable is not null. Just as background info, 'items' is a List of the following class:
public class BindableStat
{
    public string a { get; set; }
    public string b { get; set; }
    public string c { get; set; }
}

When I need to cast and use the Session variables I do:
if (Session["Stats1"] != null && Session["Stats2"] != null && Session["Stats3"] != null)
{
    // stuff
}

The problem is, the first time I assign values to and then use the variables, only 'Session["Stats1"]' is not null, the others are null. Assigning the values a second time and any amount of times thereafter produces the expected result: each variable is not null and has the correct value.
web.config looks like this:
<sessionState mode="InProc" timeout="120" customProvider="DefaultSessionProvider">
  <providers>
    <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
  </providers>
</sessionState>

Why could Session be failing first time around?
edit: I've managed to fix the problem by assigning a random value to the Session the first time the page loads (I suppose I could do this the first time the app runs). In Page_Load I just set 'Session["x"] = "x";'. I still have no idea why Session needs to be initialized like this.


text:
Q: Calculating the top margin %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[12pt]{book}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{libertine}
\usepackage[showframe, paperwidth=40pc, paperheight=40pc, margin=4pc]{geometry}
\usepackage{kantlipsum}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{fancyhdr}
\pagestyle{fancy}
\lhead{}
\chead{\thepage}
\rhead{}
\cfoot{}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
\setlength{\headheight}{15pt}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{titlesec}
\titleformat{\chapter}
    [block]
    {\Huge}
    {\thechapter\quad}
    {0pt}
    {}
    \assignpagestyle{\chapter}{empty}
\titlespacing*{\chapter}{0pt}{-30pt}{40pt}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\chapter{Test}
\kant[1-4]
\end{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

How do calculate whatever I need to calculate so that the vertical space between the top of the page and the main body text is the same in both the first page of the chapter and the following page?

A: This is not an answer, rather some hints towards one which are too long for a comment.
You want the general textblock to be the height of the text following the chapter title. You will also need a large topmargin to get the main text with lots of space above. You can set these for your document via the geometry package.
You will need to change the position of the chapter title so that it fits into the top margin, taking up no space in the textblock.
Being a GOM and not liking the result you want to achieve, that's it from me. Good luck.