text:
Q: How to apply retention time configuration for Dead Letter Queue in Spring Cloud Stream Kafka Binder? I have an application using Spring Cloud Stream Kafka.
For user defined topics I can delete records from specified topics by giving the configuration I mentioned below. But this configuration doesn't work for DLQ Topics.
For example in the configuration below, I configured retention time in binder level. So my producer topic (student-topic) defined under bindings level is correctly configured, I can check that the records are deleted when topic logs exceed specified retention byte(300000000).
But binder level retention time doesn't work DLQ topic(person-topic-error-dlq). Is there any different configuration for cleaning records from DLQ topics other than retention time.
How can I do this?
spring:
  cloud:
    stream:
      kafka:
        bindings:
          person-topic-in:
            consumer:
              enableDlq: true
              dlqName: person-topic-error-dlq
      binders:
        defaultKafka:
          type: kafka
          environment:
            spring:
              cloud:
                stream:
                  kafka:
                    default:
                      producer:
                        topic:
                          properties:
                            retention.bytes: 300000000
                            segment.bytes: 300000000
                    binder:
                      brokers: localhost:19092
      bindings:
        person-topic-in:
          binder: defaultKafka
          destination: person-topic
          contentType: application/json
          group: person-topic-group
        student-topic-out:
          binder: defaultKafka
          destination: student-topic
          contentType: application/json

A: You are only setting the (default) properties for producer bindings.
That said, this still doesn't work for me:
      binders:
        defaultKafka:
          type: kafka
          environment:
            spring:
              cloud:
                stream:
                  kafka:
                    default:
                      producer:
                        topic:
                          properties:
                            retention.bytes: 300000000
                            segment.bytes: 300000000
                      consumer:
                        topic:
                          properties:
                            retention.bytes: 300000000
                            segment.bytes: 300000000

(the properties are not applied to even the primary topic).
Looks like there is a problem with default kafka consumer binding properties.
This works for me; the properties are applied to both the primary and dead letter topics:
spring:
  cloud:
    stream:
      kafka:
        bindings:
          person-topic-in:
            consumer:
              enableDlq: true
              dlqName: person-topic-error-dlq
              topic:
                properties:
                  retention.bytes: 300000000
                  segment.bytes: 300000000


text:
Q: Trying to get the element from a tag after its been updated I am currently trying to get the values from a element tag after my html tag
"main" has been updated by my java script code to include the html values in another php file.
  <main>
       <?php include 'index.php'; ?>
  </main>

     <div id="footer">
     </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="homepage_J.js"></script>
    <!--<script type="text/javascript" src="homepage_A.js"></script>-->

    </body>
  </html>

Above is the relevant part of my php  file that contain the html body. My java script code should change the current value of the  tag then scan to get certain values of the the newly loaded file.
here is the javascript.
 $(document).ready(function(){

 $(window).on('hashchange', function(){
     var pageHash = window.location.hash.substring(1);
     console.log("page hash: "+pageHash);

     if( pageHash.length==0){
        pageHash = "index";
      }

     $('main').load(pageHash + ".php", pageFunctions() );
  });

  $("nav a").on('click', function(event){
      event.preventDefault();
      var page = $(this).attr("href");
      console.log("Loading " + page);
      window.location.hash = formatForHash(page);
      $('main').load(page, pageFunctions());

  });

  $(window).trigger('hashchange',pageFunctions());

});

function pageFunctions() {
    var current_page =  $("#page").text(); //checks to see which file called the javascript

       // Switch case that will load appropriate function based on the file loaded(homepage)
  switch(current_page){
      case "INDEX":
               console.log("HOME loaded");
               break;
      case "INBOX":
               console.log("INBOX loaded");
               break;
      case "REGISTRATION":
              console.log("REGIS loaded");
              break;
      case "COMPOSE":
              compose();
              console.log("compose loaded");
              break;
      default:
              console.log("ERROR IN :" + current_page );
              break;
  }
}

function formatForHash (page)
{
   var hash = page.split('.');
   return hash[0];
}

The console logs were used to help me debug he code. And what i am getting from it is that javascript is return the element form the previous load to main rather than the current values that is loaded to it(what im seeing is not what i am getting).
so the value in var current_page Isn't the page that i am currently on. Its not corresponding. so if i leave from index to compose the value in it is "index", and the reverese would give me a value of "compose".
so my question is how would i get the values of the elements that are currently on the page, after or before a load.
sorry for the lengthy post hopefully i gave it enough detail.

A: $('main').load(page, pageFunctions());

You are immediately executing pageFunctions rather than giving it as a callback.  Take off the () so it will be used as a callback when the load finishes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can we give a color with specific color code in the styles.xml in Android Studio? I want to change the status bar color to a specific color with a color code. Only the default colors can be specified in the code as given below, is there any way to give a specific color code to get that color?
<item name="android:statusBarColor">@color/dark_blue_Shade1</item>

A: create a color.xml into values folder
code for color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
        <color name="dark_blue_Shade1">#000080</color>
</resources>

if the color.xml already exists there then just put the
<color name="dark_blue_Shade1">#000080</color>

inside <resources>   </resources>  tag

A: create color.xml file inside values folder
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="ColorPrimary">#8E67E0</color>
    <color name="ColorPrimaryDark">#59419B</color>
    <color name="LightPrimaryColor">@android:color/holo_blue_bright</color>
    <color name="AccentColor">#ff4081</color>
    <color name="PrimaryText">#212121</color>
    <color name="SecondarText">#727272</color>
</resources>

and then in style.xml file change like this
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/ColorPrimaryDark</item>
        <item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
        <item name="colorAccent">@color/AccentColor</item>
    </style>
</resources>

From this your entire project will take this colors.

ColorPrimaryDark

is your status bar color you dont want to apply it manually system will get colorPrimaryDark as your status bar color


text:
Q: Convert a signed number into 16-bit binary value in little endian format I need to convert an array containing integers both signed and unsigned into binary vale in little endian format. This is what I tried.I am not able to convert big endian to little endian.
data = [-6, -24, -37, -45, -52, -54, -54, -51, -48, -47]
for i in data:
   if (i<0):
       values.append(bin(i & 0xffff).reverse())
   else:
       values.append(bin(i).reverse())

Output I got is
['0b1111111111111010', '0b1111111111101000', '0b1111111111011011', '0b1111111111010011', '0b1111111111001100', '0b1111111111001010', '0b1111111111001010', '0b1111111111001101', '0b1111111111010000', '0b1111111111010001']

Updated
To check if the conversion is correct. I tried converting the resulting binary back to integer. Its giving me the wrong results.
print("Input {}".format(data))
#integer to little endian binary
values = [x.to_bytes(2, byteorder='big', signed=True) for x in data]
reinterpreted = [int.from_bytes(x, byteorder='little', signed=True) for x in values]
for i in reinterpreted:
    if (i<0):
        final.append(bin(i & 0xffff))
    else:
        final.append(bin(i))
print("Binary {}".format(final))

#little endian binary to integer
for i in final:
    integerValue.append(int(i, base=2))
print("Recalculate input {}".format(integerValue))

Input [-6, -24, -37, -45, -52, -54, -54, -51, -48, -47]
Binary ['0b1111101011111111', '0b1110100011111111',
'0b1101101111111111', '0b1101001111111111', '0b1100110011111111',
'0b1100101011111111', '0b1100101011111111', '0b1100110111111111',
'0b1101000011111111', '0b1101000111111111']
Recalculate input [64255, 59647, 56319, 54271, 52479, 51967, 51967,
52735, 53503, 53759]

A: This works perfectly. Converts an integer array into 16bit signed array and vice versa and compares the results.
#integer to little endian binary
values = [x.to_bytes(2, byteorder='big', signed=True) for x in ECG_data]
reintermediate = [int.from_bytes(x, byteorder='little', signed=True) for x in values]
for i in reintermediate:
    if (i<0):
        final.append(bin(i & 0xffff)[2:])
    else:
        final.append(bin(i)[2:])

#little endian binary to integer
data = [(int(i, base=2).to_bytes(2, "little")) for i in final]
reinterpreted = [int.from_bytes(x, byteorder='big', signed=True) for x in data]

if ((reinterpreted == ECG_data) == True):
    print("Interpretation is Proper")
else:
    print("Interpretation is wrong")


text:
Q: using opera unite to build a game server for realtime games I want to ask for help in building an Opera Unite application as the game server for a 1 on 1 RTS game. (or other type of game which is real time)
descriptions:
The game is executed on client side by javascript, and connects to an Unite server for network play.
Users can play the game, without installing Unite, on a standard browser. The Unite server stays connected with the 2 players and synchronizes their game states in 1 on 1 gaming.
It is not intended to be a big server supporting thousands of players. It is to allow people to set up an instant, tiny game party with minimal configuration which Opera Unite fits very well. In this case the server and client are in the same local area network which the data transfer rate should be fast enough for gaming. Hope it also works in a wider network.
The Unite application should:
allows users to login into a room and set up a connection with the server. When two users logged into a room the game can then be started. The connection sends and receives data between server and client at a high rate of 12fps. The data is a string for maybe 200 characters long.
Can you outline the program flow of such a server? i.e. What should be done when receiving request. How to set up a P2P connection. How to ensure the connection is in "synchronization mode", that older data arrives earlier than newer data.
I will be grateful for any help.

A: Did you check the other games in Opera Unite section You can open them by unzipping and finding out how they have been built.


text:
Q: Comparing negative numbers in Pinescript I have a problem using comparison operator "<" in pine script. If i want for example all values under 5 including those negative under 0, like -1, -2, -5, then  "condition < 5" returns only positive numbers till zero. How can i include negative numbers in this condition?

A: -1 < 5 evaluates to "true".
//@version=4
study("")
bgcolor(-1 < 5 ? color.green : na)


text:
Q: IExtension : extensible object pattern : How does it work? I was exploring about Extensible object pattern using (IExtension, IExtensibleObject) interfaces in C#,
I came with a very simple example to convert dates to UTC from local and vice-versa:
public class BaseObject : IExtensibleObject<BaseObject>
{
    private DateTime _startDate;
    private ExtensionCollection<BaseObject> _extensions;

    public DateTime StartDate
    {
        get { return _startDate; }
        set { _startDate = value; }
    }

    public BaseObject()
    {
        StartDate = DateTime.Now;
        _extensions = new ExtensionCollection<BaseObject>(this);
    }

    #region IExtensibleObject<BaseObject> Members

    public IExtensionCollection<BaseObject> Extensions
    {
        get
        {
            return _extensions;
        }
    }

    #endregion
}

public class DateTimeConverterExtension : IExtension<BaseObject>
{
    private BaseObject _owner;

    #region IExtension<BaseObject> Members

    public void Attach(BaseObject owner)
    {
        _owner = owner;
        _owner.StartDate = owner.StartDate.ToUniversalTime();
    }

    public void Detach(BaseObject owner)
    {
        _owner.StartDate = _owner.StartDate.ToLocalTime();
    }

    #endregion
}

class Program
{
    static void Main(string[] args)
    {
        BaseObject obj = new BaseObject();
        Console.WriteLine("Local Time: "+obj.StartDate);

        obj.Extensions.Add(new DateTimeConverterExtension());

        Console.WriteLine("UTC: "+obj.StartDate);

        DateTimeConverterExtension ext = obj.Extensions.Find<DateTimeConverterExtension>();
        obj.Extensions.Remove(ext);

        Console.WriteLine("Local Time: "+obj.StartDate);
    }
}

Output:

Local Time: 4/13/2009 11:09:19 AM
  UTC: 4/13/2009 5:39:19 AM
  Local Time: 4/13/2009 11:09:19 AM
  Press any key to continue . . .

So it works, the question is:
How does .Net framework invoke "Attach" and "Detach" when IExtensionCollection.Add and IExtensionCollection.Detach methods are invoked by the program? Fill in the internal details which I am missing here.

A: The Attach and Detach methods are called by ExtensionCollection<T>.InsertItem and ExtensionsCollection<T>.RemoveItem, respectively.  These methods, in turn, are virtual methods called by SynchronizedCollection<T>.Add and SynchronizedCollection<T>.Remove, which is what your code ends up calling into.  This can be verified by using Reflector.  If you created your own implementation of IExtensionCollection<T>, there's no guarantee that Attach and Detach would be called correctly.


text:
Q: $2$-normed Spaces Someone suggested today that $2$-normed spaces are actually equivalent to normed spaces. Can anyone who's familiar with the topic provide a counterexample? (I can't access Gähler's original paper introducing the notion, and hence have no way of telling whether the answer has already been provided there.)
[Recall: (Gähler, 1963) If $X$ is a vector space over $F$ (either the real or the complex field), then a real-valued, non-negative function $N$ on $X^2$ is said to be a $2$-norm on $X$ iff the following conditions are satisfied:

*

*$N(x,\ y)=0$ iff $x,\ y$ are linearly dependent vectors in $X$;

*$N(x,\ y)=N(y,\ x)$ for every $x,\ y \in X$;

*$N(\lambda x,\ y)=|\lambda|N(x,\ y)$ for every $\lambda \in F$ and for every $x,\ y \in X$;

*$N(x+y,\ z) \le N(x,\ z)+N(y,\ z)$ for all $x,\ y,\ z \in X$.]
Clarification: Gähler shows that (http://books.google.co.in/books?id=T7FMg6nT9KIC&lpg=PA219&ots=fSwZP9PFdY&dq=Geometry%20of%20Linear%202-Normed%20Spaces&pg=PA1#v=onepage&q=Geometry%20of%20Linear%202-Normed%20Spaces&f=false) linear $2$-normed spaces are normable and uniformizable provided the dimension of the space is greater than one. He also proves that if the space is a linear normed space, then it's possible to define a 2-norm on it. However, the converse is not true. This is the part I want the evidence of, preferably from the link to his original paper given below.
Edit: I finally got hold of the relevant paper by Gähler (http://www.mediafire.com/view/5s3x76daiodtkd7/Mathematische_Nachrichten_Volume_28_issue_1-2_1964_[doi_10.1002%2Fmana.19640280102]_Siegfried_Gähler_--_Lineare_2-normierte_Räume.pdf), but it's in German. Since my understanding of that particular language is limited to mere recognition of a few words, I would be grateful if someone helped me out by reading it and translating the answer therein.
P. S.: Please excuse my second link not rendering properly--I am too inexperienced, evidently. Somehow, the angular brackets don't seem to be working.


text:
Q: Webdriver error when using IE and Jenkins I was getting this error while using Webdriver in IE9 "Unexpected error launching Internet Explorer. Protected Mode must be set to the same value (enabled or disabled) for all zones".
I was able to avoid this error by instatiating the driver as follow
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(capabilities);
It worked fine when I was running my test locally But it doesn't seem to work when I trigger them via Jenkins(it gives me the same error again).

A: You need to set all internet zones to the same level, preferable to the lowest one.
You can do that on Control Panel, Internet, Security, for Internet, Local, Trusted sites, etc.
Sorry I can not be more exact about it, because I am currently on a Mac, but please, try that and it will run.


text:
Q: Why I'm getting all history revisions when querying for Iterations or Releases? I'm working with Rally REST API for Java
I want get the list of actual Iterations and Releases
here is the snippet
JsonObject projects = new JsonObject();
    QueryRequest queryProjects = new QueryRequest("release");
    queryProjects.setPageSize(1);
    queryProjects.setLimit(1000);
    queryProjects.setFetch(new Fetch("_refObjectName","Name"));
    QueryResponse queryResponse;
    try {
        queryResponse = restApi.query(queryProjects);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        throw new ServiceException(e);
    }

In result I'm getting the list with a lot of duplicates. After closer inspection it seems I'm getting all versions of object - for the same Iteration/Release I have multiple versions - I can see different "_objectVersion" attribute for such duplicates.
Why is it so?
Can you please help me with the query which will retrieve distinct list of Iterations / Releases - I'm interested in just latest versions.
I can filter it out in Java but have a feeling there is more 'proper' way of doing this. Also getting the list with whole object history is not the best for code performance.
Thanks for any help!

A: When Releases and Iterations are created in Rally in a top project there is an option to propagate them throughout the project hierarchy. For example, if you have top project P1 with child project P2 and grandchild projects P21 and P22, you may create 4 releases with the same name and the same start and release dates. They are not identical releases: they have ObjectID and _ref unique to them. Please verify if this applies to your scenario.
To limit release query to a specific project set request project. Here is an example that returns only three releases that I have in a top project: R1,R2, and R3. Note
String projectRef = "/project/12352608219";

that is used later in the code:
releaseRequest.setProject(projectRef);

Note also the commented out
//String workspaceRef = "/workspace/12352608129";

and
// releaseRequest.setWorkspace(workspaceRef);

If I switch the comments: comment out project reference and uncomment workspace reference I will get what you called duplicates: multiple R1, R2 and R3 releases.
public class FindReleases {

    public static void main(String[] args) throws URISyntaxException, IOException {

        String host = "https://rally1.rallydev.com";
            String username = "user@co.com";
            String password = "secret";
            String projectRef = "/project/12352608219";
            //String workspaceRef = "/workspace/12352608129";
            String applicationName = "RESTExampleFindReleasesByProject";

            RallyRestApi restApi = null;

        try {
                restApi = new RallyRestApi(
                        new URI(host),
                        username,
                        password);
                restApi.setApplicationName(applicationName);

                System.out.println(restApi.getWsapiVersion()); //v.2.0 by default when using 2.0.2 jar and up

                QueryRequest  releaseRequest = new QueryRequest("Release");
                releaseRequest.setFetch(new Fetch("Name"));
                releaseRequest.setLimit(1000);
                releaseRequest.setScopedDown(false);
                releaseRequest.setScopedUp(false);
               // releaseRequest.setWorkspace(workspaceRef);
                releaseRequest.setProject(projectRef);

                QueryResponse releaseQueryResponse = restApi.query(releaseRequest);
                int numberOfReleasesInProject = releaseQueryResponse.getTotalResultCount();
                System.out.println(numberOfReleasesInProject);

                if(numberOfReleasesInProject >0){
                    for (int i=0;i<numberOfReleasesInProject;i++){
                        JsonObject releaseJsonObject = releaseQueryResponse.getResults().get(i).getAsJsonObject();
                        System.out.println(releaseJsonObject.get("Name"));
                    }
                }
        }
        finally{
            if (restApi != null) {
                restApi.close();
            }
        }

    }
}


text:
Q: How to count the Null values in if/else condition using asp.net mvc? I suppose to create a condition that's counting the null value.If the null value counts up to 10 an email will be sent to the people for their to notify that the system didn't scan any barcode labels. Any ideas?
Thanks!

A: var counter=0;
 for(//your range like an array maybe)
 {
  if(your condition==null)
  counter++;
 }
 if(counter=10)
 {
   //do stuff
 }


text:
Q: US date format on VBA import Bloody annoying US dates again, this one I've not seen a solution on my many, many searches.
I have a bit of VBA I found that pulls in data from some htm files generated by our business partner in Detroit:
Dim DirPath As String
Dim I_Row As Integer
Dim FilePath As String
Dim xCount As Long
DirPath = ipsosFolder
If DirPath = "" Then Exit Sub
Application.ScreenUpdating = False
FilePath = Dir(DirPath & "\*.htm")
Do While FilePath <> ""
    With ActiveSheet.QueryTables.Add(Connection:="URL;" _
      & DirPath & "\" & FilePath, Destination:=Range("A1"))
    .Name = "a"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .WebSelectionType = xlAllTables
    .WebFormatting = xlWebFormattingNone
    .WebPreFormattedTextToColumns = True
    .WebConsecutiveDelimitersAsOne = True
    .WebSingleBlockTextImport = False
    .WebDisableDateRecognition = True
    .WebDisableRedirections = False
    .Refresh BackgroundQuery:=False
    FilePath = Dir
    End With
Loop

(Note the .WebDisableDateRecognition = True, that was my first hope at fixing this, have Excel ignore the americanised dates until I could do something to fix them.)
So there's dates in here formatted in the US way - 09/21/2022 for today, for example. Now, this particular date is of no concern as here in Australia, it's invalid, there is no 21st month and I can easily fix this up with a quick =RIGHT(LEFT(B2,5),2)&"/"&LEFT(B2,2)&"/"&RIGHT(B2,10) but my problem comes in when we get to dates like 09/12/2022 as there is a 9th of December as well as 12th of September and Excel, very kindly, converts this to a date integer which breaks the above code as the left / right is no longer referencing 09/12/2022 but 44904.
Anyone with a suggestion on what I can do stop Excel "helping" and converting the dates to an American interpretation - I've been over the machine and double checked all the windows settings are for the correct date format here.
The big issue is I need to compare these dates against some dates we have pulled in from another dataset that're in the "proper" format of d/m/y and not m/d/y like only the Americans seem to insist on using, so need to retain them as dates and accurate = \

A: If (US) Date having month less or equal to 12 are converted swapping day with month and the other ones remain strings/text, please use the next function:
Function convertUSStr_DateToAU(arr As Variant) As Variant
    Dim arrConv, arrStrD, i As Long
    ReDim arrConv(1 To UBound(arr), 1 To 1)
    For i = 1 To UBound(arrConv)
        If IsNumeric(arr(i, 1)) Then
            arrConv(i, 1) = DateSerial(Year(arr(i, 1)), Day(arr(i, 1)), Month(arr(i, 1)))
        Else
            arrStrD = Split(arr(i, 1), "/")
            arrConv(i, 1) = DateSerial(CLng(arrStrD(2)), CLng(arrStrD(0)), CLng(arrStrD(1)))
        End If
    Next i
    convertUSStr_DateToAU = arrConv
End Function

It can be used in the next way:
Sub testConvertUSStr_DateToAU()
     Dim sh As Worksheet, lastR As Long, arrD
     Const Col As String = "B" 'column letter where the data to be correctly converted exists

     Set sh = ActiveSheet
     lastR = sh.Range(Col & sh.rows.count).End(xlUp).row

     arrD = sh.Range(Col & 2 & ":" & Col & lastR).Value2 'Date is taken as number...
     arrD = convertUSStr_DateToAU(arrD)
     'drop the converted array content and format it appropriately:
     With sh.cells(2, Col).Offset(, 1).Resize(UBound(arrD), 1)
            .Value2 = arrD
            .NumberFormat = "dd/mm/yyy"
     End With
End Sub

You must have an empty column immediately after the one to be converted/processed. The actual code returns the converted array in that empty column. But, only to let you check that it returned exactly what you need...
If so, you should modify the With statement range by only removing .Offset(, 1). In this way it will return exactly in the original column needing to have the converted Date.


text:
Q: How to test if something is in cache i created? I created a cache for my images here
            public void putBitmapInDiskCache(URI imageUri, Bitmap avatar) {
                    File cacheDir = new File(this.getCacheDir(), "thumbnails");
                    cacheDir.mkdirs();
                    File cacheFile = new File(cacheDir, ""+imageUri.hashCode());
                    try {
                    cacheFile.createNewFile();
                    FileOutputStream fos = new FileOutputStream(cacheFile);
                    avatar.compress(CompressFormat.PNG, 100, fos);
                    fos.flush();
                    fos.close();
                    } catch (Exception e) {
                    Log.e("error", "Error when saving image to cache. ", e);

                    }

                    }

No i would like to test if something is inside of the cache in my async Task.
Here is my async where i want to test if something is in there. The images i loaded before the application for killed.
 //the important AsyncTask method. running the background thread to get the images and set them to the gallery.
                private class MyTask extends AsyncTask<Void, Void, Void>{

                @Override
                protected Void doInBackground(Void... arg0) {try {
                            getImages();
                            Log.v("MyTask", "Image 1 retreived");
                            getImage2();
                            Log.v("MyTask", "Image 2 retreived");
                            getImage3();
                            Log.v("MyTask", "Image 3 retreived");
                            getImage4();
                            Log.v("MyTask", "Image 4 retreived");
                        } catch (IOException e) {
                            Log.e("MainMenu retreive image", "Image Retreival failed");
                            e.printStackTrace();
                        }
                    return null;
                }

A: You can use the exists function on a file to check if a file exists or not. It returns false if the file does not exist.


text:
Q: issue looping through SQL table C# My application is reading off a SQL query table and matching and displaying values in certain fields in a listview. My query SQL table looks like this

+--------------+---------+-------+----------+--------+
| process name | subtask | total | employee |  date  |
+--------------+---------+-------+----------+--------+
| process 1    | sub1    |     1 |     1111 | 01-May |
| process 2    |         |     1 |     2222 | 05-May |
| process 3    |         |     1 |     3333 | 10-May |
| process 4    |         |     1 |     4444 | 07-May |
+--------------+---------+-------+----------+--------+

I have run into a problem. I have noticed by stepping through my loops (using messegebox) that process 1 is displayed in my messagebox multiple times (in MessageBox.Show(dr[0].ToString());) when it should only be displayed once and when the loop gets to process 4 the messagebox displays process 4 (in (in MessageBox.Show(dr[0].ToString());)) then the loop stops and thus does not grab the total, employee and date values. How can I fix this.

         DateTime now = DateTime.Now;
        var startDate = new DateTime(now.Year, now.Month, 1);
        var endDate = startDate.AddMonths(1).AddDays(-1);

        string[,] report = new string[,] { {"process 1", "sub1", "3", "0",  "", "" },
       {"process 2", "", "3", "0", "", "" },
       {"process 3", "", "3", "0", "", "" }
        *** there are multiple entries in this array *****
       }

    string totalsquery = "select Process_Name, Sub_Process1_Name, count(id) as total, Completed_By_Employee_Number, max(Refresh_Date)  from testDB.dbo.Quality_Data_Master  where Refresh_Date between '" + startDate + "' and '" + endDate + "' group by Process_Name, Sub_Process1_Name,  Completed_By_Employee_Number, Refresh_Date";

  SqlConnection con = new SqlConnection();
        SqlDataAdapter ada = new SqlDataAdapter(totalsquery, con);
        DataTable dt = new DataTable();
        ada.Fill(dt);

        listView1.View = View.Details;
        listView1.Columns.Add("Process Name", 250);
        listView1.Columns.Add(" Sub Task", 200);
        listView1.Columns.Add("Target", 45, HorizontalAlignment.Center);
        listView1.Columns.Add("Total", 40, HorizontalAlignment.Center);
        listView1.Columns.Add("Employee", 100, HorizontalAlignment.Center);
        listView1.Columns.Add("Date", 100);

        for (int i = 0; i < dt.Rows.Count; i++)
        {

            DataRow dr = dt.Rows[i];

            //MessageBox.Show(dr.ToString());
            for (int j = 0; j < report.GetLength(0); j++)
            {

                if (report[j, 0].Equals(dr[0].ToString()))
                {
                    MessageBox.Show(dr[0].ToString());
                    if (report[j, 1].Equals(dr[1].ToString()))
                    {
                        MessageBox.Show(dr[1].ToString());

                        report[j, 3] = (Int32.Parse(report[j, 3]) + (int)dr[2]).ToString();

                        MessageBox.Show(dr[2].ToString());

                        report[j, 4] = report[j, 4] + dr[3].ToString();
                        MessageBox.Show(dr[3].ToString());

                        report[j, 5] = report[j, 5] + dr[4].ToString();

                        MessageBox.Show(dr[4].ToString());
                    }
                }
            }
        }

        String[] temp = new String[7];
        for (int i = 0; i < report.GetLength(0); i++)
        {
            temp[0] = report[i, 0].ToString();
            temp[1] = report[i, 1].ToString();
            temp[2] = report[i, 2].ToString();
            temp[3] = report[i, 3].ToString();
            temp[4] = report[i, 4].ToString();
            temp[5] = report[i, 5].ToString();
            //temp[6] = report[i, 6].ToString();

            ListViewItem listItem = new ListViewItem(temp);
            listView1.Items.Add(listItem);

        }

            con.Close();

A: I recomend to refactor your code, also.
Instead of using ListView, look at DataGridView.
With DataGridView you can simple do:
// dataGridView defined at design
// more info on [msdn][1] pages
DataTable dt = GetDataTable(...);
dataGridView.DataSource = dt;


text:
Q: Circuitikz - remove base pin on PNP transistor I want to remove the base pin at the transistor, using circuitikz. How do I do that?

Here's a MWE:
\documentclass[11pt]{article}

% ------- Enable UTF8 characters ------- %
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

% --------------- Math ----------------- %
\usepackage{amsmath}
\usepackage{amsfonts}

% -------- TikZ --------- %
\usepackage{tikz}
\usepackage{circuitikz}

\begin{document}
 \begin{tikzpicture}[
square/.style={rectangle,draw,minimum width=3.5cm,minimum height=3.5cm,align=top}
]
  \draw (0,8) to[R=$R_1$, -o] (0,10)
  node[anchor=south] {$3.3V$};
  \draw (0,8) to[short, i=$i_1$] (1.25,8);
  \draw (1.25,8) -- (2,8);
  \draw (2,8) to[leDo] (2,6);
  \draw (2,6) -- (0,6);
  \draw (0,6) -- (0,4.5);
  \draw (0,4.5) node[ground]{};

  %\draw (6,10) to[short, o-] (6,8);
  %\draw (6,8) -- (4,8);
  \draw (4,8) to[short, -o] (7,8)
  node[anchor=south] {$24V$};
  \draw (6.5,8) to[short, i=$i_{\text{max}}$] (4,8);
  \draw (4,7) node[pnp] (pnp) {}
  (pnp.base) node[anchor=east] {}
  (pnp.collector) node[anchor=south] {}
  (pnp.emitter) node[anchor=north] {};
  \draw (4,8) -- (4,7.5);
  \draw (4,6.5) -- (4,6);
  \draw (4,6) -- (6,6);
  \draw (6,6) to[short, -o] (7,6)
  node[anchor=south] {$0V$};
  \draw (6,6) to[R=$R_2$] (6,4.5);
  \draw (6,4.5) node[ground]{};

  \node[square, black, dashed] (1) at (3,7) {};
  \node[anchor=west] at (3.5,9) {K827P};
\end{tikzpicture}
\end{document}

Please do come with corrections if I'm coding these circuits in a bad way :)

A: As @John Kormylo wrote in a comment to my answer: "Draw something white on top of it". I realize that I went full retard when posting this question. Here's what I did:
\begin{tikzpicture}[
square/.style={rectangle,draw,minimum width=3.5cm,minimum height=3.5cm,align=center},
whitesquare/.style={rectangle,draw,minimum width=0.5cm,minimum height=1cm, fill=white}
]
  \draw (0,8) to[R=$R_1$, -o] (0,10)
  node[anchor=south] {$3.3V$};
  \draw (0,8) to[short, i=$i_1$] (1.25,8);
  \draw (1.25,8) -- (2,8);
  \draw (2,8) to[leDo] (2,6);
  \draw (2,6) -- (0,6);
  \draw (0,6) -- (0,4.5);
  \draw (0,4.5) node[ground]{};

  \draw (4,8) to[short, -o] (7,8)
  node[anchor=south] {$24V$};
  \draw (6.5,8) to[short, i=$i_{\text{max}}$] (4,8);
  \draw (4,7) node[pnp] (pnp) {}
  (pnp.base) node[anchor=east] {}
  (pnp.collector) node[anchor=south] {}
  (pnp.emitter) node[anchor=north] {};
  \draw (4,8) -- (4,7.5);
  \draw (4,6.5) -- (4,6);
  \draw (4,6) -- (6,6);
  \draw (6,6) to[short, -o] (7,6)
  node[anchor=south] {$0V$};
  \draw (6,6) to[R=$R_2$] (6,4.5);
  \draw (6,4.5) node[ground]{};

  \node[whitesquare, white] (2) at (3.31,7) {};
  \node[square, black, dashed] (1) at (3,7) {};
  \node[anchor=west] at (3.5,9) {K827P};
\end{tikzpicture}

I simply added a white square to remove the black line.


text:
Q: Erro ao gerar apk debug do Ionic Estou gerando o apk com :
ionic build android

até ai tudo bem da BUILD SUCCESSFUL
e quando uso:
ionic emulate android

tambem da BUILD SUCCESSFUL
mais quando emula fica somente uma tela branca!
no:
ionic serve

ele roda sem problemas... oque pode ser ?
segue saida do emulate:
http://pastebin.com/MGH47r5P


text:
Q: iOS keyboard height returned incorrectly on UIKeyboardWillShowNotification/ I am trying to scroll my text view up when keyboard is presented. I am trying to follow Apple's own tutorial at https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html. Instead of scroll views and frames I am using autolayout, but the general idea is same (subscribing to keyboard notifications, and animating the layout constraints accordingly). However, when I display the keyboard, there is a gap between the text view and the keyboard: (this is a screenshot from Turkish keyboard, but the same gap, marked with red, is present in all keyboards installed, including custom ones). (Screenshot from iPhone 6 Plus, but the issue is also present on other screen sizes too)

I've seen can't get correct value of keyboard height in iOS8 and I've tried using both UIKeyboardFrameEndUserInfoKey and UIKeyboardFrameBeginUserInfoKey but they all result in the same gap. I've tried attaching UIKeyboardWillShowNotification and on UIKeyboardDidShowNotification but still, I'm getting the same gap. I think the gap is related to suggestions on some keyboards on iOS 8, but it shouldn't report the keyboard size with suggestions when suggestions is not present.
Here is my code:
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self registerForKeyboardNotifications];
}

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeShown:)
                                                 name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];

}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWillBeShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGRect kb = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

    float height = kb.size.height;
    sendZoneBottomConstraint.constant = height;
    [UIView animateWithDuration:.2 animations:^{
        [self.view layoutIfNeeded];
    }];
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    sendZoneBottomConstraint.constant = 0;
    [UIView animateWithDuration:.2 animations:^{
        [self.view layoutIfNeeded];
    }];
}

sendZoneBottomConstraint is that bottom-most view's bottom spacing to the bottom layout guide.
UPDATE: I've tried changing the keyboard rectangle from window coordinates to my view's coordinates but it didn't change anything. Here is what I tried:
CGRect kb = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
kb = [self.view.window convertRect:kb toView:self.view];
float height = kb.size.height;

UPDATE, VOL 2: I've also seen iOS 8 Orientation change: Keyboard frame does not display correctly but I'm experiencing the issue also on iPhone 5s iOS 7.1 Simulator, so it's not an iOS 8-only issue.
How can I solve this problem? I definitely don't want to hard code any keyboard height values in iOS 8 world.
UPDATE, VOL 3: I've also tried it with English keyboard with suggestions both on and off. It still appears with respect to the total size of the keyboard, so it's not about the suggestions/autocomplete view:

A: Maybe you are using a tab bar controller, if yes, then when u margin the view after keyboard was shown, calculate the margin bottom without tab bar height.
You can find the tab bar height using:
self.tabBarController?.tabBar.frame.height

A: For robust keyboard height calculation you can use the following:
Note: I borrowed some logic from IQKeyboard for this solution.
CGRect kbFrame = [[aNotification userInfo][UIKeyboardFrameEndUserInfoKey] CGRectValue];

CGRect screenSize = [[UIScreen mainScreen] bounds];

CGRect intersectRect = CGRectIntersection(kbFrame, screenSize);//Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381)

CGSize kbSize;
if (CGRectIsNull(intersectRect)) {
    kbSize = CGSizeMake(screenSize.size.width, 0);
} else {
    kbSize = intersectRect.size;
}

//

UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (rootViewController) {
    if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController *navigationController = (UINavigationController *)rootViewController;
        UIViewController *nextRootViewController = [[navigationController viewControllers] lastObject];
        if (nextRootViewController) {
            rootViewController = nextRootViewController;
            continue;
        } else {
            break;
        }
    }
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabBarController = (UITabBarController *)rootViewController;
        UIViewController *nextRootViewController = tabBarController.selectedViewController;
        if (nextRootViewController) {
            rootViewController = nextRootViewController;
            continue;
        } else {
            break;
        }
    }
    if (!rootViewController.presentedViewController) {
        break;
    }
    rootViewController = (UIViewController *)rootViewController.presentedViewController;
}

//

CGFloat navigationBarAreaHeight = [[UIApplication sharedApplication] statusBarFrame].size.height + rootViewController.navigationController.navigationBar.frame.size.height;
CGFloat layoutAreaHeight = rootViewController.view.layoutMargins.top;

CGFloat topLayoutGuide = MAX(navigationBarAreaHeight, layoutAreaHeight);

CGFloat bottomLayoutGuide = rootViewController.view.layoutMargins.bottom;

float magicNumber = 5;//Apple Constant

//

float keyboardHeight = kbSize.height-topLayoutGuide-bottomLayoutGuide+magicNumber;


text:
Q: Action of UITapGestureRecognizer cannot be called while it's already in progress? I have a UITapGestureRecognizer set up which performs a 0.8s UIView animation. What I'm trying to do is allow the user to interrupt during that 0.8s. I'll handle the animation side of things (i.e. making the thing animate from its current position), but the current issue is that any further taps during those 0.8s do not call the @selector from the recognizer. Any subsequent taps are blocked until the first run through the @selector is finished.
Just to confirm, what I need is a means of allowing the same @selector from the same UITapGestureRecognizer to be called, even if it didn't return yet. At that point I can override the animation, tell it to begin from its current position, and have it complete even if the user spams the recognizer.
Is there a way to do this? I considered threading, but I'm under the impression I shouldn't be doing UI updates on background threads so I'm hesitant to try that when there's likely a preferred way.

A: well, if you want to allow user interaction during animation, add UIViewAnimationOptionAllowUserInteraction option, here is example,
[UIView animateWithDuration:0.8
                      delay:0.0
                    options:UIViewAnimationOptionAllowUserInteraction
                 animations:^{
                     // your animations
                 } completion:^(BOOL finished) {
                     // completion
                 }];


text:
Q: Fix array not properly being assigned I am trying to assign a specific part of an array a new value, but it doesn't seem to be inserting the new value into the array.
char matrix[20][8] = {/*160 * '#'*/};

void Draw() {
    system("CLS");
    cout << "Welcome to Primitive Pong v1.0!" << endl;
    for (int i = 0; i < 8; i++) {
        cout << endl;
        for (int j = 0; j < 20; j++) {
            cout << matrix[i][j] << " ";
        }
    }
}

while (gameOver == false) {
    matrix[10][4] = 'O';
    Draw();
    this_thread::sleep_for(chrono::milliseconds(1000));
}

I expect this to output a grid of 160 "#" with a "O" near the middle, but instead it just prints 160 "#". I am trying to make a game of console pong. I have tried using 'matrix[10][4] = {'O'};, but that does nothing different.

A: The problem is that you declare matrix[20][8] but then you access it as if its dimensions are [8][20] instead.
The total is the same but the access doesn't work correctly and, unfortunately, C++ will not check about this kind of mistake. Changing the code to
        cout << matrix[j][i] << " ";

should make things work a you expect.


text:
Q: Setting a Foreign Key Value Back to Null in Entity Framework I have been unable to save a record to a SQL Server database when removing a foreign key value from the record.
As an example, I have an existing BatchDetail record with a primary key BatchDetailID = 10. And it is associated with an existing RunDetail record that has a primary key RunDetailID = 20, and a foreign key BatchDetailID = 10. I want to disassociate the RunDetail from the BatchDetail by setting RunDetails.BatchDetailID to null.
Here is the error message:

A referential integrity constraint violation occurred: The property value(s) of 'BatchDetail.BatchDetailID' on one end of a relationship do not match the property value(s) of 'RunDetail.BatchDetailID' on the other end.

Here are my class definitions:
public class RunDetail
{
    public int RunDetailID { get; set; }
    public Nullable<int> BatchDetailID { get; set; }

    public virtual BatchDetail BatchDetail { get; set; }
}

public class BatchDetail
{
    public int BatchDetailID { get; set; }

    public virtual ICollection<RunDetail> RunDetails { get; set; }
}

The error occurs when a RunDetail object has a BatchDetailID value, and I try to set it back to null:
public class MyController : Controller
{
    private ISvr _myService;

    public ISvr MyService
    {
        get { return _myService ?? (_myService = new MyHandler().GetMyService()); }

        set
        {
            _myService = value;
        }
    }

    public void UpdateBatch(int id)
    {
        foreach (var batchDetail in MyService.ReadBatchDetails(id))
        {
            var runDetail = MyService.ReadRunDetail(batchDetail.RunDetailID);

            runDetail.BatchDetailID = null;
            runDetail.BatchDetail = null; // I have tried with, and without, this line

            MyService.UpdateRun(runDetail );
        }
    }
}

public class MyHandler
{
    public ISvr GetMyService()
    {
        return new MySvr();
    }
}

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerCall)]
public class MySvr : IMySvr
{
    public void UpdateRun(RunDetail runDetail)
    {
        using (var myEntities = new MyEntities())
        {
            myEntities.RunDetails.Attach(runDetail); // This is where the exception hits
            myEntities.Entry(runDetail).State = EntityState.Modified;
            myEntities.SaveChanges();
        }
    }
}

All other record updates, including changing the foreign key value to another, work correctly.
Can anyone see what my flaw is?

A: The problem was rooted in a method that I did not include in my question. When I retrieved the parent BatchDetail record, I included the "RunDetails" records:
public List<BatchDetail> ReadBatchDetails(int id)
{
    using (var myEntities = new MyEntities())
    {
        return myEntities.BatchDetails
            .Include("RunDetails") // This is the problem
            .AsNoTracking().ToList();
    }
}

By creating a new method that does not Include("RunDetails"), the problem is resolved:
public List<BatchDetail> ReadBatchDetailsWithoutRunDetails(int id)
{
    using (var myEntities = new MyEntities())
    {
        return myEntities.BatchDetails.AsNoTracking().ToList();
    }
}

A: I inserted 1 BatchDetail and 1 RunDetail as follow.
using (var db = new AppContext())
{
    db.BatchDetails.Add(new BatchDetail { Id = 1 });
    db.RunDetails.Add(new RunDetail { Id = 1, BatchDetailId = 1 });
    db.SaveChanges();
}

Then here is the result that throws the same error.
using (var db = new AppContext())
{
    // This is okay.
    var x = new RunDetail { Id = 1, BatchDetailId = 1, BatchDetail = new BatchDetail { Id = 1 } };
    db.RunDetails.Attach(x);
}
using (var db = new AppContext())
{
    // This is okay.
    var x = new RunDetail { Id = 1, BatchDetailId = null, BatchDetail = null };
    db.RunDetails.Attach(x);
}
using (var db = new AppContext())
{
    // This is okay.
    var x = new RunDetail { Id = 1, BatchDetailId = 1, BatchDetail = null };
    db.RunDetails.Attach(x);
}
using (var db = new AppContext())
{
    // A referential integrity constraint violation occurred: The property
    // value(s) of 'BatchDetail.Id' on one end of a relationship do not match the property
    // value(s) of 'RunDetail.BatchDetailId' on the other end.
    var x = new RunDetail { Id = 1, BatchDetailId = null, BatchDetail = new BatchDetail { Id = 1 } };
    db.RunDetails.Attach(x);
}

It should be the same in your case.


text:
Q: Post request via QNetworkAccessManager I have a problem while working with  an object of  QNetworkAccessManager class.
I want to send a POST request to a web server.
My code is
 QNetworkAccessManager *manager;
    manager = new QNetworkAccessManager ();
    QNetworkRequest req;
    req.setUrl(QUrl("http://example.com"));
    //Configure the parameters for the post request:
    QByteArray postData;
    postData.append("Login=log_name&");
    postData.append("Password=some_pass");
    //Now create a QCookieJar:
    manager->setCookieJar(new QNetworkCookieJar(manager));
    //Define the Request-url:
    connect (manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinish (QNetworkReply  *)));
    //Send the request:
    manager->post(req, postData);

The code of the used SLOT is:
void MainWindow::replyFinish(QNetworkReply *reply)
   {
    QString answer = QString::fromUtf8(reply->readAll());
     qDebug () << answer;
   }

The problem is that the answer is an empty string,but i believe it should be some html-code that describes
acceptance or rejection of the authorization.
Thank you for your help.

A: Most sites use a HTTP redirection after a login request (or after filling a form). And you need to test for error in the same slot.
You can handle redirections (and errors) with something similar to that code.
Since QNetworkAccessManager already create its own base QNetworkCookieJar object, you don't need to instantiate one if you didn't write a derived class or if you don't share a cookie jar with an other manager. But you'll need to use the same manager (or the same cookie jar) for subsequent request to be able to reuse the cookies set by the server during the login.


text:
Q: Starting React App from pulled github project I've pulled a github repository containing code for a reactjs app into one of my directories but I can't find a way to run the app on my computer. I can start a new app using create-react-app but I can't/(don't know how to) use the existing app for instead ofa freshly created one.
I'm running Ubuntu 16.04.3 on a virtual machine, my node version is 4.2.6.
I've tried sudo apt-get install --only-upgrade nodejs but it simply says my node version is already up to date. (I include this because npm start gives me a bunch of errors and tells me that it may be because I might have to update node) but the app I create with create-react-app works fine?
The error:

Package.json:
{
    "name": "my-app",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
        "bootstrap": "^3.3.7",
        "express": "^4.16.2",
        "package.json": "^2.0.1",
        "prop-types": "^15.6.0",
        "react": "^16.0.0",
        "react-bootstrap": "^0.31.5",
        "react-dom": "^16.0.0",
        "react-router-dom": "^4.2.2",
        "react-scripts": "1.0.14",
        "uuid": "^3.1.0",
        "webpack": "^3.8.1"
        },
    "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test --env=jsdom",
        "eject": "react-scripts eject"
        },
    "devDependencies": {
        "babel-cli": "^6.26.0",
        "babel-preset-env": "^1.6.1"
        }
}

A: Carry out the following steps:
//Step 1:
git clone [repository url]

//Step 2:
cd [local repository]

//Step 3:
//Check package.json file and ensure scripts are notated as below:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

//Step 4:
/* Delete the node_modules folder and any 'lock' files such as
yarn.lock or package-lock.json if present.*/

//Step 5:
npm install

//Step 6:
npm start

To Note: There can be some conflict between yarn and npm when cloning from certain repositories. It's best to assume that every repo may need trimming before ultimately running npm install. I tested the above steps several times under several different factors. This is the best I have so far.

A: In case of issues shown after npm install, run the below to automatically fix the issues:
npm audit fix

Alternatively, use the below to see the errors:
npm audit


text:
Q: Issue turning int array into matrix class to complete operator-overloading I'm trying to multiply 2 matrices together using operator-overloading but I'm getting an error when trying to convert my int array into my matrix class in order to use it. I'm not sure how to fix these errors
#include <iostream>
using namespace std;

struct matrix{
    int array[4][4];
public:
    void make(int A[][4], int size) {
        for (int x = 0; x < size; x++) {
            for (int y = 0; y < size; y++) {
                array[x][y] = A[x][y];
            }
        }
    }
    void operator*(matrix m) {
        int output[4][4];
        for (int x = 0; x < 4; x++){
            for (int y = 0; y < 4; y++){
                array[x][y] = (array[x][y] * m.array[x][y]);
            }
        }

        for (int x = 0; x < 4; x++) {
            for (int y = 0; y < 4; y++) {
                cout << output[x][y] << " ";
            }
            cout << endl;
        }
    }
};

int main(){
    matrix m1, m2;
    int a[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
    //int   c[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    m1.make(a[4][4], 4);
    m2.make(a[4][4], 4);
    m1*m2;

    return 0;
}

A: There are two problem with your code:-
m1.make(a[4][4], 4); // should be m1.make(a, 4); make is expecting a 2D array you are passing an integer

In the operator *function
array[x][y] = (array[x][y] * m.array[x][y]); // your should assign to output[x][y] here

A: You are not using the corect syntax.
int main(){
    matrix m1, m2;
    int a[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
    //int   c[3][3] = {{1,2,3},{4,5,6},{7,8,9}};

    // these are not good, you try to pass a single int, and it is past the
    // end of a.
    //m1.make(a[4][4], 4);
    //m2.make(a[4][4], 4);

    // try this instead:
    m1.make(a, 4);
    m2.make(a, 4);

    m1*m2;

    return 0;
}

Multiplying is a binary operator that takes in 2 matrices, and outputs a third one with the result.
class matrix
{
    // note the friend modifier, which indicates this fonction is a not a member
    // of the class, and can access all of its private members.

   friend matrix operator*(const matrix& m, const matrix& n)
    {
        matrix result;

        for (int x = 0; x < 4; x++)
            for (int y = 0; y < 4; y++)
                result.array[x][y] = (m.array[x][y] * n.array[x][y]);

        // your formula does not seem quite right here...
        // I'll let you fix it.

        return result;
    }

Here is the correct syntax for make() to accept an int[4][4] array:
void make(int (&A)[4][4]) {
    for (int x = 0; x < 4; x++) {
        for (int y = 0; y < 4; y++) {
            array[x][y] = A[x][y];
        }
    }
}

Why don't you have a constructor instead of make?
class matrix{
  private:
    int array[4][4];
public:
    // you want to initialize your data, always (well, almost always, but
    // this is the kind of data that always applies to)...
    matrix()
    {
        for (int x = 0; x < 4; x++)
            for (int y = 0; y < 4; y++)
                array[x][y] = 0;
    }

    explicit matrix(const int(&a)[4][4])
    {
        for (int x = 0; x < 4; x++)
            for (int y = 0; y < 4; y++)
                array[x][y] = a[x][y];
    }

    matrix& operator=(const int(&a)[4][4])
    {
        return *this = matrix(a);
    }

    matrix& operator=(const matrix& m)
    {
        for (int x = 0; x < 4; x++)
            for (int y = 0; y < 4; y++)
                array[x][y] = m.array[x][y];
        return *this;
    }

    // ...
};

Then main() becomes:
int main(){
    matrix m1, m2;
    int a[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};

    matrix m1(a);
    matrix m2(a);

    matrix product = m1 * m2;

    return 0;
}


text:
Q: Codeigniter index() function not being called i am fairly new working with codeigniter. I am currently trying to setup an existing codeigniter project but Main controller's index() method is not being called.
I have gone through almost all related question posted here @ stackoverflow but nothing seems to work for me.
below is my code:
class Main extends CI_Controller {

function __construct()
{
    parent::__construct();
    $this->load->model('Front_main');
    $this->load->model('Front_expertweb');
}

public function index(){
    echo 'im here';
    ....
}
....
}

EDIT
.htaccess :
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
</IfModule>
#<IfModule mod_filter.c>
  SetOutputFilter DEFLATE
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/xml
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE image/*
#</IfModule>

config.php
$config['index_page'] = ''
$config['base_url'] = ''
PHP version: 5.+
Codeigniter: 2.+
would really appreciate if you could route me in the ride direction.
much appreciated.

A: class Main extends CI_Controller {

function __construct()
{
    parent::__construct();
   // $this->load->model('Front_main');
   // $this->load->model('Front_expertweb');
}

public function index(){
    echo 'im here';
    ....
}
....
}

config.php
$config['index_page'] = 'index.php'
$config['base_url'] = 'your project foldername'

A: Bummmmp!
So there was NOTHING wrong with the code. Previous developer had saved configuration URL in database without any documentation.
Thanks to everyone who tried to help.
Cheers.


text:
Q: Definition of $L^1(\mu)$, Lebesgue integrable function with respect to measure $\mu$ Here is an excerpt from Rudin's  Real and Complex Analysis

In Defintion 1.31, I am wondering why Rudin writes $f = u + iv$, where $u$ and $v$ are real measurable functions on X AND $f \in L^1(\mu)$.
Doesn't $f \in L^1(\mu)$ already give that $f$ is complex measurable, according to Definition 1.30??
So, instead of saying what Rudin says, wouldn't this be enough to say that $f = u + iv$, where $u$ and $v$ are real measurable functions on X and $\int_X |f|  < \infty$.
------------------added----------------------

A: How do you know that if $u$ and $v$ are real measurable functions that $f=u+iv$ is complex measurable?
Edit, now that you added the other part. It doesn't matter how you say it. What you say is exactly the same as what he says. It's just style. I see $f\in L^1(\mu)$ much more often than $\int |f| d\mu <\infty$.


text:
Q: How to select records by condition in postgresql , and from this set select records with the same value of some field? There is a table with million records.
like so
select c.id, c.mobile_phone, c.last_name, c.email
from user c
group by c.id, c.mobile_phone, c.last_name, c.email
HAVING count(*) > 1;

takes minutes.
It is necessary to select records with the same mobile_phone, and from the resulting selection, select records that have the same Email.
for example
I done that:
select * from (select * from user where mobile_phone = '00222334422222') ou
where (select count(*) from user inr
       where inr.email = ou.email) > 1;

and so:
SELECT
    *,
    ROW_NUMBER() OVER (
        PARTITION BY email, mobile_phone
        ORDER BY email, mobile_phone) AS Row_Number
FROM (select * from user where mobile_phone = '2225776676788') as "c*";

for example
select * from employee where
        mobile_phone = '75777302722';

the fields shown in Fig. should be in the final data sample.
It's a version
select * from (select * from employee where
                                          mobile_phone = '75777302722') ou
where (select count(*) from employee inr
       where inr.email = ou.email) > 1;

This code does not work on some versions of postgresql.
PostgreSQL 14.7  - it works.
PostgreSQL 13.7 - doen't work.
I get rows with the same phone number, but I can't select only those rows (from this dataset) where the email is the same (at the same time, rows that have Email = null should not be included)
5 users have the same phone number.
Of these 5 users - 2 have the same Email - they should be included in the final data set.
Are there any ideas how to do this?

A: SELECT id, mobile_phone, last_name, email
FROM (
    SELECT *, row_number() OVER (PARTITION BY mobile_phone, email) AS rn
    FROM user ) user_rn
WHERE mobile_phone = '75777302722'
  AND rn = 2;

In the inner query the row_number() function assigns a number to each combination of mobile_phone, email and the outer query then selects those records with multiple hits (note that rows with rn = 3 and higher should not be included because rn = 2 already supplies the combination).
This solution does not use the count(*) function, which is notoriously slow. If performance is an issue, you should add an index on (mobile_phone, email). Any table with more than a few thousand records (or, more precisely: with more than a few physical pages for data storage) will benefit from appropriate indexes tuned to the typical queries.


text:
Q: Question of Conservation of Momentum I think I understand the concept of conservation of momentum in an inelastic collision. However, what if two objects, one being more massive than the other, started out together and then separated (via a mechanism), wouldn't the object of smaller mass gain velocity after the separation due to conservation of momentum?
Examples I can think of are:

*

*A skateboarder riding on a frictionless surface and he jumps up off the skateboard.

*A rocket dropping a stage that is heavier(even after all the fuel is spent) than the next stage.

*An astronaut is holding onto an object more massive than himself in outer space. He then simply lets go of the larger object, not applying any force to the object.

A: These are 'superelastic' collisions - where energy is released.
Yes the smaller mass would gain velocity due to conservation of momentum, but only provided the energy released in the separation pushed the smaller mass 'forwards' in the same direction as the motion
If, for example, the skateboarder jumps forwards off the skate board he (the heavier body) can go forwards at a higher velocity and either slow down, stop, or force the skateboard to go backwards in the opposite direction depending on how hard he pushes back on the skateboard as he jumps.
As pointed out by Sofia in comment, momentum is conserved, but in these cases the total kinetic energy of the bodies increases.
I suppose strictly speaking these events are not collisions - more dissociations - but the are definitely superelastic

A: Two important points:

*

*You must apply Conservation of Momentum to a system, and that system must remain the same throughout the event in question;

*The system must be free of external forces.

In the case of the skateboarder, the system is the skateboarder plus skateboard. If the skateboard has good quality wheels, and the surface is level, then there are no external horizontal forces, and the horizontal momentum is conserved.  If the skateboarder jumps off, then the jumping force is internal and the momentum of the system is conserved.  The skateboard may well shoot ahead, with more momentum, but the skateboarder will correspondingly slow down, with an exactly matching decrease in momentum.
In the case of a rocket separating from a lower stage, there will not be any dropping unless air friction (an outside force) or on board thrusters act to separate the two objects...


text:
Q: Dropdown in admin form I have created some category using admin ui-component form and displayed in ui-component grid.
Also i want created a drop down field(Field name: Parent category) in this form which contains already created categories list ...

How to do this
Thanks

A: Try following code.
protected $category;
protected $categoryRepository;

public function __construct(
        \Magento\Catalog\Helper\Category $category,
        \Magento\Catalog\Model\CategoryRepository $categoryRepository
    ) {
        $this->category = $category;
        $this->categoryRepository = $categoryRepository;
    }

add below code into your function or in execute method
$categories = $this->category->getStoreCategories();
        foreach($categories as $category) {
            echo $category->getName();
            //$categoryObj = $this->categoryRepository->get($category->getId());

        }

follow this link for more details
and refer to this link too


text:
Q: How do I query SQL for the latest record based on latest Date and Time OR Date_Time columns? Situation:
SerialNumber has duplicate rows and I need to select the latest records and get what is the Status value (either it PASS or FAIL does not matter).
SerialNumber must be check based on the previous StationNumber.
Example: I want to get the Status value of the latest record SerialNumber 197601234512345 in Station 2, so value StationNumber = @Station in the command line below is actually "Station 1"
Scenario:
SerialNumber can either be pass or fail in Station 1, then SerialNumber exp:197601234512345 is brought forward to Station 2. In Station 2, need to check what latest Status of that SerialNumber exp:197601234512345 has in the previous StationNumber (Station 1).
Example table in the database db:

ID
SerialNumber
Date
Time
Date_Time
Status
StationNumber

213939
197601234512344
2021-04-28
11.53 AM
2021-04-28 11:53:00
PASS
Station 1

213940
197601234512345
2021-04-28
11.54 AM
2021-04-28 11:54:00
FAIL
Station 1

213941
197601234512345
2021-04-28
12.11 PM
2021-04-28 14:30:00
FAIL
Station 2

213942
197601234512345
2021-04-28
12.11 PM
2021-04-28 14:31:00
FAIL
Station 2

213943
197601234512344
2021-04-28
12.00 PM
2021-04-28 14:35:00
FAIL
Station 3

213944
197601234512344
2021-04-28
12.05 PM
2021-04-28 14:46:00
FAIL
Station 3

213945
197601234512344
2021-04-28
12.10 PM
2021-04-28 14:47:00
PASS
Station 3

Note: All datatype for the columns are VARCHAR(45)
So far, the SQL commands that I have tried has NO Error, but the MySqlreader does NOT Execute the ExecuteReader() which hold the SQL command. How do I know it? By doing the test display label on Label13.Text in Update 1: C# code, At the front-end system it display till Label13.Text = "Check 3"; then direct gives me Label13.Text = "Bad Output";
Below here are my five tried sql commands. But none of it works hurm =( :
Select Status from db.station where SerialNumber = @SN and StationNumber = @Station and MAX(CAST(Date_Time as DateTime))
or
Select Status from db.station where SerialNumber = @SN and StationNumber = @Station and MAX(CAST(Date_Time as DateTime)) Group By Status
or
Select Top Status from db.station where SerialNumber = @SN and StationNumber = @Station and MAX(CAST(Date_Time as DateTime))
or
Select Status from db.station where SerialNumber = @SN and StationNumber = @Station Oder By Status desc limit 1
or
Select a.Status from db.station INNER JOIN (Select SerialNumber, Status from db.station where SerialNumber = @SN and StationNumber = @Station and MAX(CAST(Date_Time as DateTime))group by SerialNumber) b on a.Status = b.Status

Update 1: C# code on 2021-04-29
if (textbox1.Text != "")
                    {
                        con.Open();
                        Label13.Text = "Check 1";

                        //new command
                        MySqlCommand cmdd = new MySqlCommand("Select SerialNumber, Status from db.station where SerialNumber = @SN  and StationNumber = @Station order by CAST(Date_Time as DateTime) desc limit 1 ", con);

                        Label13.Text = "Check 2";
                        cmdd.Parameters.AddWithValue("@SN", textbox1.Text);
                        cmdd.Parameters.AddWithValue("@Station", "Station 1");

                        Label13.Text = "Check 3";
                        MySqlDataReader read = cmdd.ExecuteReader();
                        Label13.Text = "Check 4";
                        if (read.HasRows)
                        {

                            Label13.Text = "Check 5";
                            while (read.Read())
                            {
                                status = read.GetValue(1).ToString();
                                Label13.Text = status;

                                if (status == "PASS")
                                {
                                    con.Close();
                                    PreChecking.Text = "  Checked : Serial Number passed in previous Station 1";
                                    PreChecking.ForeColor = Color.Green;
                                    YourText1 = "hi";

                                    ////catch WO and CASING SN should be in here
                                    if (textbox1.Text != "")
                                    {
                                        //Auto Capture the Work Order when Entering the serial Number
                                        con.Open();
                                        MySqlCommand cmd = new MySqlCommand("Select WorkOrder from db.workorder where @Text  between coalesce (StartRange, @Text) and Coalesce (EndRange, @Text)", con);
                                        cmd.Parameters.AddWithValue("@Text", textbox1.Text);
                                        MySqlDataReader sdr = cmd.ExecuteReader();
                                        //if the serial number is in the work order range, it will display the work order, else display error message
                                        if (sdr.HasRows)
                                        {
                                            while (sdr.Read())
                                            {
                                                TextBox3.Text = sdr.GetValue(0).ToString();
                                                label12.Text = "  Checked: Valid W/O for Serial Number";
                                                label12.ForeColor = Color.Green;
                                                DropDownList3.Focus();
                                                Button1.Enabled = true;
                                                Button1.Focus();
                                                //**Close pop-up message as requested by Engineers**//
                                                //Page.ClientScript.RegisterStartupScript(this.GetType(), "popupscript", "alert(' Done checking Board Serial Number and validity W/O ');", true);

                                            }
                                        }
                                        else
                                        {
                                            TextBox3.Text = "";
                                            textbox1.Focus();
                                            label12.Text = "Alert: Invalid W/O for Serial Number";
                                            YourText4 = "Hi";
                                            label12.ForeColor = Color.Red;
                                            Button1.Enabled = false;
                                            Page.ClientScript.RegisterStartupScript(this.GetType(), "popupscript", "alert(' 1 Please aware of Invalid W/O for current scan Serial Number');", true);
                                        }
                                        con.Close();
                                    }
                                }
                                else if (status == "FAIL")
                                {

                                    PreChecking.Text = "  Alert: Serial Number not pass in previous Station 1";
                                    PreChecking.ForeColor = Color.Red;
                                    label12.Text = string.Empty;
                                    DropDownList2.Enabled = false;
                                    DropDownList3.Enabled = false;
                                    Button1.Enabled = false;
                                    Page.ClientScript.RegisterStartupScript(this.GetType(), "popupscript", "alert(' Serial NUmber cannot pass this station');", true);
                                }
                            }
                        }
                        else
                        {
                            Label13.Text = "Bad Output";
                        }

                    }

Hope anyone can help and spot the mistake or have a solution. Thank you.

A: You can use order by to get the latest row top and with Limit 1 you can select only the first row.
Select Status from db.station where SerialNumber = @SN and StationNumber = @Station order by CAST(Date_Time as DateTime) desc
limit 1

DB-Fiddle:
Schema and insert statements:
 create table station (SerialNumber varchar(50),    Date varchar(50),   Time varchar(50),   Date_Time varchar(50),  Status  varchar(50),StationNumber varchar(50));

 insert into station values('197601234512345'   ,'2021-04-28','11.53 AM'    ,'2021-04-28 11:53:00'  ,'PASS',    'Station 1');
 insert into station values('197601234512345'   ,'2021-04-28','11.54 AM',   '2021-04-28 11:54:00'   ,'FAIL',    'Station 1');
 insert into station values('197601234512345'   ,'2021-04-28','12.00 PM',   '2021-04-28 12:00:00'   ,'PASS',    'Station 1');
 insert into station values('197601234512345'   ,'2021-04-28','12.05 PM',   '2021-04-28 12:05:00'   ,'FAIL',    'Station 2');
 insert into station values('197601234512345'   ,'2021-04-28','12.10 PM',   '2021-04-28 12:10:00'   ,'PASS',    'Station 2');

Query:
 Select Status from station where SerialNumber ='197601234512345'  and StationNumber = 'Station 1' order by CAST(Date_Time as DateTime) desc
 limit 1

Output:

Status

PASS

db<fiddle here

A: To get last rows for all SerialNumber use:
MySQL 8+
WITH cte AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY SerialNumber ORDER BY Date_Time DESC) rn
              FROM db.station )
SELECT *
FROM cte
WHERE rn = 1;

MySQL 5+
SELECT db.station.*
FROM db.station
NATURAL JOIN ( SELECT SerialNumber, MAX(Date_Time) Date_Time
               FROM db.station
               GROUP BY SerialNumber ) maxdates

If you need these data for particular SerialNumber values only then add according WHERE clause.
If you need the data not for SerialNumber but for (SerialNumber, StationNumber) then modify the queries accordingly.
For single SerialNumber value - according WHERE and ORDER BY Date_Time DESC LIMIT 1 is enough.

A: Solution:
my situation kinda relate to situation that happen in enter link description here
so, my new SQL command
SELECT a.ID, a.Date_Time, a.Status FROM db.station a, (SELECT MAX(ID) as id  FROM db.station WHERE SerialNumber = @SN Group by StationNumber = @Station) b WHERE a.ID = b.id

I test to insert Serial Number 197601234512345 in Station 3
finally, it gets the latest row from the previous Station (Station 2)

ID
SerialNumber
Date
Time
Date_Time
Status
StationNumber

213942
197601234512345
2021-04-28
12.11 PM
2021-04-28 14:31:00
PASS
Station 2


text:
Q: @Embedded annotation in hibernate not working for me Hello Friends I am working on Hibernate Framework.I am trying to use @Embedded Annotation in my application but I don't why its not showing up for me.
This is my code
UserDetails.java
import java.util.Date;

 import javax.persistence.Column;
 import javax.persistence.Embedded;
 import javax.persistence.Entity;
 import javax.persistence.Id;
 import javax.persistence.Temporal;
 import javax.persistence.TemporalType;

 @Entity(name= "USER_DETAILS")
 public class UserDetails {
  @Id
  @Column(name = "USER_NAME")
  private String UserName ;
  @Column(name = "USER_F_NAME")
  private String UserFName ;
  @Column(name = "USER_L_NAME")
  private String UserLName ;
  @Column(name = "USER_CONT_NUMBER")
  private String UserContactNumber ;
  @Column(name = "USER_AGE")
  private int    UserAge ;
  @Column(name = "JOIN_DATE")
  @Temporal(TemporalType.DATE)
  private Date joinDate ;
  @Embedded
  private UserAddress addr ;

  public UserAddress getAddr() {
    return addr;
}
public void setAddr(UserAddress addr) {
    this.addr = addr;
}
public Date getJoinDate() {
    return joinDate;
}
public void setJoinDate(Date joinDate) {
    this.joinDate = joinDate;
}
public String getUserName() {
    return UserName;
}
public void setUserName(String userName) {
    UserName = userName;
}
public String getUserFName() {
    return UserFName;
}
public void setUserFName(String userFName) {
    UserFName = userFName;
}
public String getUserLName() {
    return UserLName;
}
public void setUserLName(String userLName) {
    UserLName = userLName;
}
public String getUserContactNumber() {
    return UserContactNumber;
}
public void setUserContactNumber(String userContactNumber) {
    UserContactNumber = userContactNumber;
}
public int getUserAge() {
    return UserAge;
}
public void setUserAge(int userAge) {
    UserAge = userAge;
}

}

UserAddress.java
    package org.hibernate.model;

import javax.persistence.Embeddable;

@Embeddable
public class UserAddress {
    private String Street ;
    private String City ;
    private String State ;
    private String Country ;
    private String Pincode ;
    public String getStreet() {
        return Street;
    }
    public void setStreet(String street) {
        Street = street;
    }
    public String getCity() {
        return City;
    }
    public void setCity(String city) {
        City = city;
    }
    public String getState() {
        return State;
    }
    public void setState(String state) {
        State = state;
    }
    public String getCountry() {
        return Country;
    }
    public void setCountry(String country) {
        Country = country;
    }
    public String getPincode() {
        return Pincode;
    }
    public void setPincode(String pincode) {
        Pincode = pincode;
    }

}

UserController.java
package org.hibernate.controller;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.model.UserAddress;
import org.hibernate.model.UserDetails;

public class UserController {

    public static void main(String[] args) {
        UserDetails ud = new UserDetails();
        ud.setUserFName("Pritesh");
        ud.setUserLName("Patel");
        ud.setUserName("ppatel123");
        ud.setUserAge(26);
        ud.setUserContactNumber("6479644065");
        ud.setJoinDate(new Date());

        UserAddress addr = new UserAddress();
        addr.setStreet("Stella Drive");
        addr.setCity("Markham");
        addr.setState("Ontario");
        addr.setCountry("Canada");
        addr.setPincode("L6X 5L7");

        ud.setAddr(addr);

        SessionFactory sf = new Configuration().configure().buildSessionFactory();
        System.out.println("Loading done");
        Session session = sf.openSession();
        System.out.println("ransaction begin");
        session.beginTransaction();
        session.save(ud);
        session.getTransaction().commit();
        session.close();

        ud = null ;
        session = sf.openSession();
        session.beginTransaction();
        ud = (UserDetails)session.get(UserDetails.class, "ppatel123");
        System.out.println("User Id " + ud.getUserName());
        System.out.println("User Name " + ud.getUserFName()+ " " + ud.getUserLName() );
        System.out.println("User Age " + ud.getUserAge());
        System.out.println("User Contact Number " + ud.getUserContactNumber());
        System.out.println("User Joining Date " + ud.getJoinDate());
    }

}

Hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/online_store</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root123</property>
         <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
         <!-- Echo all executed SQL to stdout -->
        <property name="hbm2ddl.auto">create</property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Mapping files -->
        <mapping class="org.hibernate.model.UserDetails" />

    </session-factory>
</hibernate-configuration>

output Console
Oct 19, 2016 2:13:41 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.3.Final}
Oct 19, 2016 2:13:41 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Oct 19, 2016 2:13:41 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Oct 19, 2016 2:13:43 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Oct 19, 2016 2:13:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Oct 19, 2016 2:13:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/online_store]
Oct 19, 2016 2:13:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Oct 19, 2016 2:13:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Oct 19, 2016 2:13:43 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Wed Oct 19 14:13:43 EDT 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Oct 19, 2016 2:13:44 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate: drop table if exists USER_DETAILS
Oct 19, 2016 2:13:46 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@517566b] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.

Before It was working fine,but when I start using @Embedded Annotation my out put console only showing this.
Thanks in Advance

A: You copied the same code on your UserDetail and UserAddress classes... So, i'm not sure but probably you forgot to add the @Embeddable tag on your user address class. If you could put the correct code on UserAddress probably would see anything else


text:
Q: Heroku run command does not answer on my network Hi I am running some scripts trough the heroku run command CLI but I am having trouble with this on certain networks. What ports are used for this tool? I thought heroku toolbelt used ssh is it so and is it using standard ports? I can't find this information on herokus forums. Does any one know?
The strange part is I get initial contact with heroku but I then get this error after a long wait.
Error:       Connection timed out - connect(2) (Errno::ETIMEDOUT)

Im not sure if it is a port problem but it seams to only happen on one of my networks which is strictly controlled. So that is why im interested in ports.


text:
Q: Selenium IWebDriver Navigate().GoToUrl() not entering url or navigating to page I'm creating a new test project and can't think of anything else to try to resolve my issue.  I have another Selenium project that works as expected, and have compared the two to find differences.  But first, the main issue I'm running into.
In the setup I call Driver.Navigate().GoToUrl("www.test.com");
No exception is thrown or anything else that would indicate there is a problem, the flow just moves to the next statement, but no Url is entered into the navigation bar, and so obviously the driver never navigates to any page.  The driver does start up a new firefox instance, but it stays blank.
When I compare this new project against an already working project, they seem identical for the most part.  Both projects have ...\packages\Selenium.WebDriver.2.37.0 & ...\packages\Selenium.Support.2.37.0 installed using NuGet package manager.
Both projects have identical references to the project in the .csproj file
--Working project
...

      ....\packages\Selenium.WebDriver.2.37.0\lib\net40\WebDriver.dll

      False
      ....\packages\Selenium.Support.2.37.0\lib\net40\WebDriver.Support.dll

--Unworking project
...

      ..\packages\Selenium.WebDriver.2.37.0\lib\net40\WebDriver.dll

      ..\packages\Selenium.Support.2.37.0\lib\net40\WebDriver.Support.dll

Neither project does anything else.  The constructor for both simply calls:
var WebDriver = new FirefoxDriver();
When I examine the WebDriver object, the only difference I can see is the WindowsHandles property.  The working project has:
WindowsHandles    Count = 1
The non-working project has:
WindowsHandles    {System.Collections.ObjectModel.ReadOnlyCollection}
I have no idea why they're different but as it's the only difference I can find, I'm thinking maybe that's the problem but I have no idea if that's really the case or how I'd fix it.
I've added a try/catch block around the WebDriver.Navigate().GoToUrl() and no exception is being caught.
Both projects target the .NET 4.0 framework.
Any help is greatly appropriated.

A: I figured it out right after I finally broke down and decided to post on StackOverflow. My issue was IWebDrivers insists upon a passed in URL beginning with http. Once I prefixed my URL with that, it worked.

A: Here is a simple example how to do so:

*

*Add NuGet package Selenium.WebDriver

*Download chromedriver (https://sites.google.com/a/chromium.org/chromedriver/) or any other driver from http://www.seleniumhq.org/download/ (section Third Party Browser Drivers NOT DEVELOPED by seleniumhq)

*Copy the file to your project directory in Visual Studio and set the following properties for the file:
Build Action = None;
Copy to Output Directory = Copy if newer
Once installed, try running the following example code:
var driver = new ChromeDriver();
var navigate = driver.Navigate();
navigate.GoToUrl("http://www.microsoft.com"); //works
navigate.GoToUrl("www.microsoft.com"); //does not work

Good luck!

A: Also
navigate.GoToUrl("http:\\www.microsoft.com"); // "\\" instead of "//", wont work
navigate.GoToUrl("http://www.microsoft.com"); // that one works perfectly.

with backslashes instead of forward slashes wont work either... I've just spend about an hour, figuring this out.
URL address, correcly must be with forward slashes.

A: Just concatenate on url "http://" and this problema is solved. o.O
I don't know why this error, but's solved.
Just do it !

A: My issue with Navigate() not working was when driver focus is on the wrong tab (most commonly, if you've already opened another tab by clicking a "_blank" link on the current tab) and you are calling Navigate().GoToUrl().
Then you should be selecting the tab again in which you will change the url, like this:
C# example
var tabs = this.browser.WindowHandles;
this.browser.SwitchTo().Window(tabs[0]);


text:
Q: Android support-v4:22.0.0 Not downloading to correct location? I'm using com.google.android.gms:play-services:7.5.0  which requires: support-v4:22.0.0. Ok no problem right? -- so I download it via SDK Manager:

Now, Android Studio still reports that it cannot find com.android.support:support-v4:22.0.0:
Could not find com.android.support:support-v4:22.0.0.
         Searched in the following locations:
             https://jcenter.bintray.com/com/android/support/support-v4/22.0.0/support-v4-22.0.0.pom
https://jcenter.bintray.com/com/android/support/support-v4/22.0.0/support-v4-22.0.0.aar
             file:/C:/android-sdk/extras/android/m2repository/com/android/support/support-v4/22.0.0/support-v4-22.0.0.pom
             file:/C:/android-sdk/extras/android/m2repository/com/android/support/support-v4/22.0.0/support-v4-22.0.0.aar
             file:/C:/android-sdk/extras/google/m2repository/com/android/support/support-v4/22.0.0/support-v4-22.0.0.pom
             file:/C:/android-sdk/extras/google/m2repository/com/android/support/support-v4/22.0.0/support-v4-22.0.0.aar
So then I go to the location ( C:/android-sdk/extras/google/m2repository/com/android/support  )  to see for myself, and of course its not there. Now I know the download suceeded, so I search my drive for it. Turns out the SDK manager downloaded it to: C:\android-sdk\extras**android**\support\v4  instead. So I tried to import the jar file contained in that folder to my project but that did not work. How do I get around this?

A: The "Android Support Library" entry in the SDK Manager is primarily for Eclipse users. You are using Android Studio, so what matters is the "Android Support Repository", which you have not updated in the SDK Manager.


text:
Q: Realtime auto calculate total value form I'm planning to create a realtime automatic calculating form that gathers the price of products in all (or some) collection and sums up some elements (of course the value is in integer, for example extra fee, modification, ...).
It's Shopify platform, I have created a script that takes the price of a particular product when selected from a dropdown list.
I can't make it do the calculation with some elements also being chosen by the select option.
The idea came from this instruction: http://www.javascript-coder.com/javascript-form/javascript-calculator-script.phtml
Here is the code: the code take price of product works well on my shopify web but when I put it in this code snippet, it doesn't work.

$(function(){
  $('select[name="Menu"]').change(function(){
   var textId= $(this).data('text');
   var price = $( "option:selected" , this).data('price');
   $('#'+textId).val(price);
  });
 });

 $.fn.fonkTopla = function() {
  var total = 0;
  this.each(function() {
   var deger = fonkDeger($(this).val());
   total += deger;
  });
  return total;
 };

 function fonkDeger(veri) {
  return (veri != '') ? parseInt(veri) : 0;
 }

 $(document).ready(function(){
  $('input[name^="inptxt1"]').bind('keyup', function() {
   $('#total').html( $('input[name^="inptxt1"]').fonkTopla());
  });
 });

 function getPrice()
 {
  //Assume form with id="theform"
  var theForm = document.forms["calculate"];
  //Get a reference to the TextBox
  var price = theForm.elements["inptxt1"];
  var howmany =0;
  //If the textbox is not blank
  if(inptxt1.value!="")
  {
   howmany = parseInt(inptxt1.value);
  }
  return howmany;
 }

 var filling_prices= new Array();
 filling_prices["Selection"]=0;
 filling_prices["Fee1"]=3;
 filling_prices["Fee2"]=10;

 //This function finds the filling price based on the
 //drop down selection
 function getFillingPrice()
 {
  var optFillingPrice=0;
  //Get a reference to the form id="calculate"
  var theForm = document.forms["calculate"];
  //Get a reference to the select id="filling"
  var selectedFilling = theForm.elements["filling"];

  //set cakeFilling Price equal to value user chose
  //For example filling_prices["Lemon".value] would be equal to 5
  optFillingPrice = filling_prices[selectedFilling.value];

  //finally we return cakeFillingPrice
  return optFillingPrice;
 }

 function getTotal()
 {
  //Here we get the total price by calling our function
  //Each function returns a number so by calling them we add the values they return together
  var lastPrice = getPrice() + getFillingPrice()

  //display the result
  document.getElementById('totalP').innerHTML =
   "Total Price is: "+lastPrice;

 }
<form action="" id="calculate">
     <select name="Menu" data-text="inptxt1">
      <option value="0" data-price="0">-- Select --</option>
            <option value="10" data-price="10">10$</option>
            <option value="20" data-price="20">20$</option>

     </select>
     <input type="text" name="inptxt1" id="inptxt1" readonly/>
     <select id="filling" name='filling' onchange="calculateTotal()">
      <option value="Selection">-- Select --</option>
      <option value="Fee1">Extra fee 1</option>
      <option value="Fee2">Extra fee 2</option>
     </select>
     Total:

    </form>


text:
Q: yaml generation through java using nested classes Hi I'm trying to create yaml file using java and snakeyaml but i did basic coding on it and wanted to improvise on the creation of hash maps and array list with class objects anyone can help in refactoring this code as I'm new to java.I want help in specifically creating classes for the redundant objects created in createmap function
Sample Code
package com.yaml.writer;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JavaToYamlWithOptions {

    public static void main(String[] args) {
        Map<String,Object> map = createMap();

        DumperOptions options = new DumperOptions();
        options.setIndent(2);
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        options.setPrettyFlow(true);

        Yaml yaml = new Yaml(options);
        String output = yaml.dump(map);
        System.out.println(output);
    }

    private static Map<String,Object> createMap() {

        Map<String,Object> env = new HashMap<>();
        Map<String,String> rpath = new HashMap<>();
        Map<String,String> rtab = new HashMap<>();
        List<Map<String,String>> rlist = new ArrayList<>();
        rpath.put("path","hdfs");
        rtab.put("tabname","tbl");
        rlist.add(rpath);
        rlist.add(rtab);
        Map<String,List<Map<String,String>>> parq = new HashMap<>();
        parq.put("parquet",rlist);
        List<Map<String,List<Map<String,String>>>> readlst = new ArrayList<>();
        readlst.add(parq);
        Map<String,List<Map<String,List<Map<String,String>>>>> readmap = new HashMap<>();
        readmap.put("read", readlst);
        Map<String,String> coltrans = new HashMap<>();
        Map<String,String> colsec = new HashMap<>();
        List<Map<String,String>> collist = new ArrayList<>();
        coltrans.put("coltrans","colxx");
        colsec.put("coal","false");
        collist.add(coltrans);
        collist.add(colsec);
        Map<String,List<Map<String,String>>> trans = new HashMap<>();
        trans.put("transform",collist);
        List<Map<String,List<Map<String,String>>>> trlist = new ArrayList<>();
        trlist.add(trans);
        Map<String,List<Map<String,List<Map<String,String>>>>> trmap = new HashMap<>();
        trmap.put("transform", trlist);
        env.put("environment" ,"kubernetes");
        Map<String,String> wpath = new HashMap<>();
        List<Map<String,String>> wlist = new ArrayList<>();
        wpath.put("path","whdfs");
        wlist.add(wpath);
        Map<String,List<Map<String,String>>> wparq = new HashMap<>();
        wparq.put("parquet",wlist);
        List<Map<String,List<Map<String,String>>>> wrlst = new ArrayList<>();
        wrlst.add(wparq);
        Map<String,List<Map<String,List<Map<String,String>>>>> wmap = new HashMap<>();
        wmap.put("write", wrlst);
        Map<String,Object> action = new HashMap<>();
        trmap.putAll(wmap);
        readmap.putAll(trmap);
        action.put("action1",readmap);
        Map<String,Object> actions = new HashMap<>();
        actions.put("action",action);
        env.putAll(actions);
        return env;

    }
}

expected output
environment: "kubernetes"
action:
  action1:
    transform:
    - transform:
      - colTrans: colxx
      - coal: false
    read:
    - parquet:
      - path: "hdfs"
      - tabname: "tbl"
    write:
    - parquet:
      - path: "whdfs"