Q: C# dependecies aren't being included with publish I'm trying to publish a web API built in .NET Core to a Ubuntu server but am having difficulty with the dependencies. I am new to doing this in C# and haven't found a concise answer to how dependencies are included with the publish command. I was lead to believe that they were complied into a .dll but I am getting this error when running my app
Error:
An assembly specified in the application dependencies manifest (api.deps.json) was not found:
    package: 'Newtonsoft.Json', version: '11.0.2'
    path: 'lib/netstandard2.0/Newtonsoft.Json.dll'

Shouldn't that have been included in the "Release" directory after being published?
I'm using .NET Core on a Mac and then publishing to an Ubuntu sever should that affect anything here.
.csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
    <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  </ItemGroup>

</Project>

A:
Shouldn't that have been included in the "Release" directory after being published?

No.
When you publish a project, you specify a different directory for the publish output when creating the publish profile.

The Release directory is only for assets that are used during debugging. During development, the NuGet dependencies are not in the Release folder, they are in the NuGet cache. So, you cannot always just copy the Release folder and expect it to run.
After publishing, the entire application (including all dependencies) are output to the publish location. Do note that the publish output doesn't necessarily have to be a folder. For example, depending on the type of project it may be published to IIS with web deploy or to an FTP location.


Q: Keep receving segmentation fault when using scanf on an array inside a struct I m kind of new at C and i try to learn data structures by doing exercises. This is the code I've written. I don t understand why it dosen't even enter the for loop.
/*  Define a structure to store the name, an array
marks[] which stores the marks of three different
subjects, and a character grade. Write a program
to display the details of the student whose name
is entered by the user.*/

#include <stdio.h>

int main()
{
    struct stud_info
    {
       char name[20];
       int marks [2][5];
       int char_grade;
    };

    struct stud_info array[20];
    struct stud_info stud1;
    int i,j;
    printf("Enter name of student:\n");
    scanf("%s",stud1.name);
    printf("Enter student char_grade:\n");
    scanf("%d",stud1.char_grade);
    for( i=0;i<=2;i++)
        for( j=0;j<=5;j++)
        {
            printf("Enter grade for [%d]st subject:\n",i);
            scanf("%d",&stud1.marks[i][j]);
        }

    return 0;
}


Q: q.all for angular2 observables is there something like q.all to resolve all http api requests in angular2?
In angular1, I can do something like this:
var promises = [api.getA(),api.getB()];
$q.all(promises).then(function(response){
    // response[0]  --> A
    // response[1]  --> B
})

In angular2, the http module returns Observable,
api.getA().subscribe(A => {A})
api.getB().subscribe(B => {B})

But I want to resolve A and B together, then do something.

A: You will need the .forkJoin operator for that
Observable.forkJoin([observable1,observable2])
       .subscribe((response) => {
          console.log(response[0], response[1]);
       });

You can import the Observable with;
import {Observable} from 'rxjs/Rx';

A: Angular < 6:
import {Observable} from 'rxjs/Observable';
    ...
    return Observable.forkJoin(
        this.http.get('someurl'),
        this.http.get('someotherurl'));

Angular >= 6:
import {forkJoin} from 'rxjs';
...
return forkJoin(
    this.http.get('someurl'),
    this.http.get('someotherurl'));


Q: How to handle jOOQ depreciation warning on procedure that returns a trigger? I use the following stored procedure to maintain the edit time on a few tables via triggers on those tables:
        CREATE OR REPLACE FUNCTION maintain_edit_time()
        RETURNS TRIGGER AS $t_edit_time$
        BEGIN
        NEW.edit_timestamp = NOW();
        RETURN NEW;
        END;
        $t_edit_time$ LANGUAGE plpgsql;

When generating jOOQ objects for the database in question, I get the following generated code:
 /**
 * @deprecated Unknown data type. Please define an explicit {@link org.jooq.Binding} to specify how this type should be handled. Deprecation can be turned off using <deprecationOnUnknownTypes/> in your code generator configuration.
 */
@java.lang.Deprecated
public static Object maintainEditTime(Configuration configuration) {
    MaintainEditTime f = new MaintainEditTime();

    f.execute(configuration);
    return f.getReturnValue();
}

/**
 * @deprecated Unknown data type. Please define an explicit {@link org.jooq.Binding} to specify how this type should be handled. Deprecation can be turned off using <deprecationOnUnknownTypes/> in your code generator configuration.
 */
@java.lang.Deprecated
public static Field<Object> maintainEditTime() {
    MaintainEditTime f = new MaintainEditTime();

    return f.asField();
}

I assume this is because I do not have a jOOQ binding between TRIGGER and a Java object.  However, I do not have a clue what I would define this binding as, nor do I have any need for a binding to exist.
Left alone, though, this generates a compile warning.  What's the cleanest, easiest way to resolve this?
Options seem to include turning off deprecation, using ignoreProcedureReturnValues, or creating a binding.  Ideally, I'd like to simply not generate a Java object for this procedure, but I could not find a way to do that.
Using ignoreProcedureReturnValues globally effects the project just because of this, which is fine for now, I don't have other procedures at all, much less others with a return value.  But, I hate to limit future use.  Also, I'm unclear one what the comment "This feature is deprecated as of jOOQ 3.6.0 and will be removed again in jOOQ 4.0." means on the jOOQ site under this flag.  Is the flag going away, or is support for stored procedure return types going away?  A brief dig through the jOOQ github issues didn't yield me an answer.
Tempted to simply turn off deprecation.  This also seems like a global and not beneficial change, but it would serve the purpose.
If I created a binding, I have no idea what it would do, or how to define it since TRIGGER really isn't a sensible thing to bind a Java object to.  I assume I'd specify  as TRIGGER in the forcedType element, but then the Java binding seems like a waste of time at best and misleading at worst.

A: Well, after noting that an ideal way to do this would be to ignore that procedure, I did find how to ignore the procedure by name in the generally excellent jOOQ website documentation.  Don't know how I missed in on first pass.  If I needed to call this procedure in Java, I'm unclear which of the above options I would have used.
Luckily, there was no need for this procedure to be referenced in code, and I excluded it as shown below in in the jOOQ XML configuration.
<excludes>
    databasechangelog.*
    | maintain_edit_time
</excludes>

A: You've already found the perfect solution, which you documented in your own answer. I'll answer your various other questions here, for completeness' sake

Using ignoreProcedureReturnValues globally effects the project just because of this, which is fine for now, I don't have other procedures at all, much less others with a return value. But, I hate to limit future use. Also, I'm unclear one what the comment "This feature is deprecated as of jOOQ 3.6.0 and will be removed again in jOOQ 4.0." means on the jOOQ site under this flag. Is the flag going away, or is support for stored procedure return types going away? A brief dig through the jOOQ github issues didn't yield me an answer.

That flag has been introduced because of a backwards incompatible change in the code generator that affected only SQL Server: https://github.com/jOOQ/jOOQ/issues/4106
In SQL Server, procedures always return an INT value, just like functions. This change allowed for fetching this INT value using jOOQ generated code. In some cases, it was desireable to not have this feature enabled when upgrading from jOOQ 3.5 to 3.6. Going forward, we'll always generate this INT return type on SQL Server stored procedures.
This is why the flag has been deprecated from the beginning, as we don't encourage its use, except for backwards compatibility usage. It probably won't help you here.
Stored procedure support is definitely not going to be deprecated.

Tempted to simply turn off deprecation. This also seems like a global and not beneficial change, but it would serve the purpose.

Why not. A quick workaround. You don't have to use all the generated code. The deprecation is there to indicate that calling this generated procedure probably won't work out of the box, so its use is discouraged.

If I created a binding, I have no idea what it would do, or how to define it since TRIGGER really isn't a sensible thing to bind a Java object to. I assume I'd specify as TRIGGER in the forcedType element, but then the Java binding seems like a waste of time at best and misleading at worst.

Indeed, that wouldn't really add much value to your use cases as you will never directly call the trigger function in PostgreSQL.
Again, your own solution using <exclude> is the ideal solution here. In the future, we might offer a new code generation configuration flag that allows for turning on/off the generation of trigger functions, with the default being off: https://github.com/jOOQ/jOOQ/issues/9270


Q: HorizontalAlignment not working for Image inside Button (UWP) I have a button with an Image inside it
        <Button BorderThickness="0" Background="Black"  Grid.Column="0" Width="400" >
        <Image HorizontalAlignment="Right" Height="20" Source="ms-appx:///Assets/LockScreenLogo.scale-200.png" Width="20"  />
    </Button>

I want the image to be on the right end of the button so gave HorizontalAlignment="Right". But the Image always comes in the middle of the button. How can I fix this?

A: In the default style of Button, there is a ContentPresenter control to display the content of Button, it uses HorizontalContentAlignment property to control the horizontal alignment of the control's content. The default value is Center. So if you want to put the image in the right of Button, you can change the HorizontalContentAlignment to Right.
<Button HorizontalContentAlignment="Right" BorderThickness="0" Background="Black"  Grid.Column="0" Width="400" >
    <Image Height="20" Source="ms-appx:///Assets/LockScreenLogo.scale-200.png" Width="20"  />
</Button>


Q: Need to build a java file through ANT This is my java file.
package test;

import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class MyTest{
    @Test
    public void startWebDriver(){
            WebDriver driver;
            driver = new FirefoxDriver();
            driver.navigate().to("http://google.com");
            Assert.assertTrue("title should start with google",driver.getTitle().startsWith("Google"));
            driver.close();
            driver.quit();
        }
}

I have stored all the selenium and Junit dependencies in a file named Xjars.
This is my build.xml
<?xml version="1.0"?>
<project name="AntSelenium" default="main" basedir=".">
  <!-- Sets variables which can later be used. -->
  <!-- The value of a property is accessed via ${} -->
  <property name="src.dir" location="src" />

  <property name="build.dir" location="classes" />

  <!-- Variables used for JUnit testin -->
  <property name="test.dir" location="src" />
  <property name="test.report.dir" location="testreport" />
  <property name="jar.dir" location="Xjars"/>
  <path id="classpath">
      <pathelement path="${basedir}"/>
      <fileset dir="${jar.dir}" >
          <include name="**/*.jar"/>
          </fileset>

  </path>

  <!-- Define the classpath which includes the junit.jar and the classes after compiling-->
  <path id="junit.class.path">

    <pathelement location="Xjars/junit-4.8.2.jar" />
    <pathelement location="${build.dir}" />
  </path>

  <!-- Deletes the existing build, docs and dist directory-->
  <target name="clean">
    <delete dir="${build.dir}" />
    <delete dir="${test.report.dir}" />
  </target>

  <!-- Creates the  build, docs and dist directory-->
  <target name="makedir">
    <mkdir dir="${build.dir}" />
    <mkdir dir="${test.report.dir}" />
  </target>

  <!-- Compiles the java code (including the usage of library for JUnit -->
  <target name="compile" depends="clean, makedir">
    <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" includeantruntime="false" />

      <!-- <pathelement path="Xjars/cglib-nodep-2.1_3.jar"/>
        <pathelement path="Xjars/commons-codec-1.10.jar"/>
        <pathelement path="Xjars/commons-collections-3.2.1.jar"/>
        <pathelement path="Xjars/commons-exec-1.3.jar"/>
        <pathelement path="Xjars/commons-io-2.4.jar"/>
        <pathelement path="Xjars/commons-lang3-3.4.jar"/>
        <pathelement path="Xjars/commons-logging-1.2.jar"/>
        <pathelement path="Xjars/cssparser-0.9.16.jar"/>
        <pathelement path="Xjars/gson-2.3.1.jar"/>
        <pathelement path="Xjars/guava-18.0.jar"/>
        <pathelement path="Xjars/htmlunit-2.18.jar"/>
        <pathelement path="Xjars/htmlunit-core-js-2.17.jar"/>
        <pathelement path="Xjars/httpclient-4.5.1.jar"/>
        <pathelement path="Xjars/httpcore-4.4.3.jar"/>
        <pathelement path="Xjars/httpmime-4.5.jar"/>
        <pathelement path="Xjars/jetty-io-9.2.12.v20150709.jar"/>
        <pathelement path="Xjars/jetty-util-9.2.12.v20150709.jar"/>
        <pathelement path="Xjars/jna-4.1.0.jar"/>
        <pathelement path="Xjars/jna-platform-4.1.0.jar"/>
        <pathelement path="Xjars/junit-4.8.2.jar"/>
        <pathelement path="Xjars/junit-4.8.2-sources.jar"/>
        <pathelement path="Xjars/nekohtml-1.9.22.jar"/>
        <pathelement path="Xjars/netty-3.5.2.Final.jar"/>
        <pathelement path="Xjars/sac-1.3.jar"/>
        <pathelement path="Xjars/selenium-api-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-chrome-driver-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-edge-driver-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-firefox-driver-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-htmlunit-driver-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-java-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-leg-rc-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-remote-driver-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-safari-driver-2.48.2.jar"/>
        <pathelement path="Xjars/selenium-support-2.48.2.jar"/>
        <pathelement path="Xjars/serializer-2.7.2.jar"/>
        <pathelement path="Xjars/webbit-0.4.14.jar"/>
        <pathelement path="Xjars/websocket-api-9.2.12.v20150709.jar"/>
        <pathelement path="Xjars/websocket-client-9.2.12.v20150709.jar"/>
        <pathelement path="Xjars/websocket-common-9.2.12.v20150709.jar"/>
        <pathelement path="Xjars/xalan-2.7.2.jar"/>
        <pathelement path="Xjars/xercesImpl-2.11.0.jar"/>
        <pathelement path="Xjars/xml-apis-1.4.01.jar"/> -->

  </target>

  <!-- Run the JUnit Tests -->
  <!-- Output is XML, could also be plain-->
  <target name="junit" depends="compile">
    <junit printsummary="on"  haltonfailure="yes">
      <classpath refid="junit.class.path" />
      <formatter type="plain" usefile="false" />
      <batchtest todir="${test.report.dir}">
        <fileset dir="${src.dir}">
          <include name="**/*Test*.java" />
        </fileset>
      </batchtest>
    </junit>
  </target>

  <target name="main" depends="compile, junit">
    <description>Main target</description>
  </target>

</project>

But finally I'm getting this error Buildfile:
 C:\Users\manish\workspace\AntSelenium\build.xml clean:    [delete]
 Deleting directory C:\Users\manish\workspace\AntSelenium\classes
 [delete] Deleting directory
 C:\Users\manish\workspace\AntSelenium\testreport makedir:
     [mkdir] Created dir: C:\Users\manish\workspace\AntSelenium\classes
     [mkdir] Created dir: C:\Users\manish\workspace\AntSelenium\testreport compile:
     [javac] Compiling 2 source files to C:\Users\manish\workspace\AntSelenium\classes junit:
     [junit] Running test.MyTest
     [junit] Testsuite: test.MyTest
     [junit] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0 sec
     [junit] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0 sec
     [junit]    Caused an ERROR
     [junit] org/openqa/selenium/WebDriver
     [junit] java.lang.NoClassDefFoundError: org/openqa/selenium/WebDriver
     [junit]    at java.lang.Class.forName0(Native Method)
     [junit]    at java.lang.Class.forName(Unknown Source)
     [junit]    at org.eclipse.ant.internal.launching.remote.EclipseDefaultExecutor.executeTargets(EclipseDefaultExecutor.java:36)
     [junit]    at org.eclipse.ant.internal.launching.remote.InternalAntRunner.run(InternalAntRunner.java:452)
     [junit]    at org.eclipse.ant.internal.launching.remote.InternalAntRunner.main(InternalAntRunner.java:139)
     [junit] Caused by: java.lang.ClassNotFoundException: org.openqa.selenium.WebDriver
     [junit]    at java.lang.ClassLoader.loadClass(Unknown Source)

 BUILD FAILED C:\Users\manish\workspace\AntSelenium\build.xml:94: Test
 test.MyTest failed

 Total time: 4 seconds Ant is not able to find the org.openqa.selenium.WebDriver class,

although the jar which I have included is a part of Xjars folder.

A: putting here for clarity but its more a comment than an answer
add this in your ant build file to debug the classpath used
  <target name="compile" depends="clean, makedir">
    <property name="myclasspath" refid="classpath"/>
    <echo message="Classpath = ${myclasspath}"/>

    <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" includeantruntime="false" />
  </target>

It will print out the classpath and help you debug if the jars are correctly picked up


Q: while loop to read from file skips first line i have to read data from a file into a struct array line by line, but it skips the first line. i found somewhere else that because of the fgets and the sscanf combo the 2nd line is the first read, but i dont understand why or how i can fix this. any suggestions or pointing in the right direction would be awesome!
void readData(){
    char line[50];
    char name1[1][50];
    int O, M, R, W;

    input = fopen("input2.dat", "r");

    //count = 0;
    while(fgets(line, 50, input) != NULL){
        hasReadData = 1;
        sscanf_s(line, "%20s %d %d %d %d", name1[0], 50, &O, &M, &R, &W);

        for(i=0; i<200; i++){
            if(strcmp(name1[0], player_arr[i].name) == 0){
                if(O<0 || M<0 || R<0 || W<0){
                    printf_s("%s %d %d %d %d", name1[0], O, M, R, W);
                    printf_s("\tNegative value, data invalid\n");
                    break;
                }
                if(O<M){
                    printf_s("%s %d %d %d %d", name1[0], O, M, R, W);
                    printf_s("\tOvers less than Maidens, data invalid\n");
                    break;
                }
                if(W>10){
                    printf_s("%s %d %d %d %d", name1[0], O, M, R, W);
                    printf_s("\tWickets greater than 10, data invalid\n");
                    break;
                }

                player_arr[i].oversOverall += O;
                player_arr[i].maidensOverall += M;
                player_arr[i].runsOverall += R;
                player_arr[i].wicketsOverall += W;

                player_arr[i].oversLatest = O;
                player_arr[i].maidensLatest = M;
                player_arr[i].runsLatest = R;
                player_arr[i].wicketsLatest = W;
            }
        }
    }
    fclose(input);
}

A: If your while is skipping first line while reading from the file then use this command inside the while loop:
file_pointer.seekg(0,ios::beg);
This file pointer will set your pointer to the beginning of the file.


Q: Converting csv to xls using Data::Table::Excel? How do you use Data::Table::Excel for converting .csv to .xls file format.
I want to do the conversion with the tables2xls subroutine:
my $t = Data::Table::fromFile("testresults-2013-07-01.csv");
my @arr = $t->csv;
Data::Table::Excel::tables2xls("results.xls", $t ,\@arr);

I tried the code above but I was not able get what I expected.

A: Last line must be:
Data::Table::Excel::tables2xls("results.xls", [$t] ,["Sheet name for your Table"]);

And here is colors example like you want:
Data::Table::Excel::tables2xls("results.xls", [$t] ,["Sheet name for your Table"], [["white","silver","gray"]]);


Q: im using ajax but its not executing asynchronously function send(seat_id, seat, seat_name, seat_price, seat_class){

      if(ing_order_yn == "y"){
            alert("결제창 이동 중 입니다. 좌석 변경이 불가능합니다.");

            return false;

        }
        var data1_val = "";
        var data1_val_f = "";
        var e_id    = $('input[name=e_id]').val();  //사용자가 선택한 event_id
        var floor   = $('input[name=floor_value]').val();//층
        var seat_list;

        $.ajax({
            url: '/seat_catch.do?group_id=<%=group_id%>',
            type : 'POST',
            data : { 'event_id' : e_id, 'seat_id' : seat_id },
            datatype : 'html',
            async : true,
            success : function( data1 ){
                    data1_val = data1.trim().substring(0,4);
                    data1_val_f = data1.trim().substring(0,6); //[선택불가]
                    //로그인 세션이없는 경우 ajax 리턴 값은 "session_out" 이다.

                    if(data1.trim() == "session_out"){
                        alert('로그아웃 된 상태입니다.\n로그인 후 사용해 주시기 바랍니다.')

                        document.location.href="/login.do";

                    }else{
                            if(data1_val == "담기성공"){
                            document.getElementById(seat).className  = "sel";

                                //클릭 한 좌석 정보 레이어 보여주기

                                $('#msg_popup2').html(seat_name + "<br>" + seat_price +"원");
                                    $('#msg_popup2').show();
                                    $('#msg_popup2').delay(5000).fadeOut(1000);
                                var e_id = $('input[name=e_id]').val(); //사용자가 선택한 event_id
                                    //좌석 선점 처리 후. 좌석 현행화
                                    orderSeatOp(e_id,'1',floor, function(htmll)
                                        alert(htmll);
                                        $('#seat').html(htmll);
                                    });
                                    <%-- $.ajax({
                                        url : '/seat.do',
                                        type : 'POST',
                                        async : true,
                                        data : { 'event_id' : e_id ,'group_id' : <%=group_id%> , 'floor' : floor },

                                        success : function( res ){
                                        $('#seat').html(res);

                                        return false;
                                    }

                                });

                             --%>

I think it has a problem in code for last section.
I did this two way

*

*one way is ajax code(annotating in last section)

*callback function.

$('#seat').html(res); it takes whole jsp code of layer popup and makes refresh. I want to make it as asynchronously but it still execute for refresh.
I don't know what can I do. please help me.
and sorry for my shortly English.


Q: Serve static files with Node/Express I created a node express app and defined a path for static resources in my express app, app.ts:
app.use(express.static(path.join(__dirname, 'public')));

My static files are well served when I am on a main level, for example localhost:3000/products but I get a 404 return code on secondary paths, for example localhost:3000/products/details with this instruction:

What am I doing wrong?
Thank you in advance for your help.

A: Don't use relative paths for your URLs in the page.  Start them all with a /.  Change this:

to this:

When the path does not start with a /, then the browser adds the path of the containing page URL to the URL before requesting it from the server because ALL requests to the server must be absolute URLs.  That makes things break as soon as you are no longer on a top level page.  But, if your URLS always start with /, then the browser doesn't have to mess with the path of the URL before requesting it.


Q: Docker run: uwsgi gives permission denied This is so weid… I have a docker image that runs a web app. WHen I run it, nothing shows in containers… no error. Nothing under docker ps -a.
I ran docker events& and tried again, and it reported an error 1… which is apparently an app error, Okay.
So, I re-ran as:

docker run -it --entrypoint /bin/bash -p 80:80 --name NAME -d
NAME:latest -s

And then ran each item in the runall.sh
The first three items gave a permission denied:

uwsgi --http-socket 127.0.0.1:3009 --file
/var/www/cgi-bin/tireorder/main.wsgi --processes 1 --uid root
--enable-threads -b 32768 --daemonize /var/www/cgi-bin/tireorder/tireorder.log --pidfile
/var/www/cgi-bin/tireorder/tireorder.pid

Looking this up, and it appears to be a user permission, but all the directories and files are full access to root.
What is really freaky is that, I get it to run in windows and a mint linux VM… but in production(RHEL)) or on my linode VMs(Centos 8, Debian 10, Ubuntu 21) is gives the same permission denied!?
here's the docker file.
FROM lovato/python-2.6.6:latest

WORKDIR /

COPY trotta.tar.gz /

COPY runall.sh /

RUN chmod ugo+x runall.sh

RUN apt-get update

RUN apt-get install haproxy python python-pip python-dev nginx python-paste python-pastewebkit python-babel -y

RUN ["tar", "-xvzf", "trotta.tar.gz"]

RUN ["rm", "/etc/nginx/sites-enabled/default"]

RUN ["cp", "-R", "/usr/lib/python2.6/site-packages/Muntjac-1.1.2-py2.6.egg/muntjac", "/usr/lib/python2.7/dist-packages/"]

COPY uwsgi /usr/local/bin/

COPY /etc/default.conf /etc/nginx/conf.d/

COPY /etc/tireorder.conf /etc/

CMD ./runall.sh

Here is the runall.sh:
uwsgi --http-socket 127.0.0.1:3009 --file /var/www/cgi-bin/tireorder/main.wsgi --processes 1 --uid root --enable-threads -b 32768 --daemonize /var/www/cgi-bin/tireorder/tireorder.log --pidfile /var/www/cgi-bin/tireorder/tireorder.pid
uwsgi --http-socket 127.0.0.1:3310 --file /var/www/cgi-bin/tireorder2/main.wsgi --processes 1 --uid root --enable-threads -b 32768 --daemonize /var/www/cgi-bin/tireorder2/tireorder.log --pidfile /var/www/cgi-bin/tireorder2/tireorder.pid --chdir /var/www/cgi-bin/tireorder2
uwsgi --http-socket 127.0.0.1:3610 --file /var/www/cgi-bin/tireorder3/main.wsgi --processes 1 --uid root --enable-threads -b 32768 --daemonize /var/www/cgi-bin/tireorder3/tireorder.log --pidfile /var/www/cgi-bin/tireorder3/tireorder.pid --chdir /var/www/cgi-bin/tireorder3
service nginx start
/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid
tail -f /var/www/cgi-bin/tireorder/tireorder.log &
tail -f /var/www/cgi-bin/tireorder2/tireorder.log &
tail -f /var/www/cgi-bin/tireorder3/tireorder.log

A: Per Ashok:
Add RUN chmod -R 775  above the CMD command in your dockerfile
This resolved it when applied the folders and the uwsgi.


Q: Add/remove JFXPanel on Swing JFrame I want to add and remove JFXPanel on JFrame container but not able to do that. I am stuck here and get no proper solution on button click I want to add and remove the JFXPanel  control.
What is the wrong in this code?
  public class abc extends JFrame
  {
  JFXPanel fxpanel;
  Container cp;
  public abc()
  {
  cp=this.getContentPane();
  cp.setLayout(null);
  JButton b1= new JButton("Ok");
  JButton b2= new JButton("hide");
  cp.add(b1);
  cp.add(b2);
  b1.setBounds(20,50,50,50);
  b2.setBounds(70,50,50,50);
  b1.addActionListener(this);
  b2.addActionListener(this);
  fxpanel= new JFXPanel();
  cp.add(fxpanel);
  fxpanel.setBounds(600,200,400,500);
 }

  public void actionPerformed(ActionEvent ae)
 {
 if(ae.getActionCommand().equals("OK"))
  {
    fxpanel= new JFXPanel();
    cp.add(fxpanel);
    fxpanel.setBounds(600,200,400,500);

   }
  if(ae.getActionCommand().equals("hide"))
   {
    cp.remove(fxpanel);
    }
   }
    public static void main(String args[])
   {

      abc f1= new abc();
      f1.show();
    }
   }

A: *

*Dont extend JFrame call unnecessarily

*Dont use null/Absolute LayoutManager

*why use show() to set JFrame visible? you should be using setVisible(true)

*Dont forget Swing components should be created a manipulated on  Event Dispatch Thread via SwingUtilities.invokeXXX and JavaFX components via Platform.runLater()
Besides the above the biggest problem you have is that you dont refresh GUI/container after adding/removing components,thus no changes are shown.:
call revalidate() and repaint() on JFrame instance to reflect changes after adding/removing components from a visible container.


Q: How to remove excess whitespace from a string by jQuery and only count the actual number of characters? today I want to design a block text more than 70 characters will hide the extra text and appear show more
But I can't predict if the user will add extra blank lines, which will cause them to be counted as a character. How do I remove the extra white space and count only the parts that actually have words?

$(function(){
    let len = 70
    $('.demo').each(function(){
        if($(this).html().length >len){
            var str=$(this).html().substring(0,len-1)+"...顯示更多";
            $(this).html(str);
        }
    });
});
.content{
  display: flex;
  justify-content:space-between;
  border:1px solid #222;
  padding:10px;
}

.demo{
  overflow:hidden;
  text-overflow:clip;
  display:-webkit-box;
  -webkit-box-orient:vertical;
  -webkit-line-clamp:2;
}

.photo{
  width: 100px;
  height: 100px;
  border:1px;
  border-radius:16px;
  margin-left: 10px;
}

.more{
  text-decoration:none;
  color:blue;
}

    Lorem ipsum dolor sit amet consectetur Lore

A: You can use .trim() as in if ($(this).html().trim().length > len) {
Demo

$(function() {
  let len = 70
  $('.demo').each(function() {
    if ($(this).html().trim().length > len) {
      var str = $(this).html().substring(0, len - 1) + "...顯示更多";
      $(this).html(str);
    }
  });
});
.content {
  display: flex;
  justify-content: space-between;
  border: 1px solid #222;
  padding: 10px;
}

.demo {
  overflow: hidden;
  text-overflow: clip;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.photo {
  width: 100px;
  height: 100px;
  border: 1px;
  border-radius: 16px;
  margin-left: 10px;
}

.more {
  text-decoration: none;
  color: blue;
}

    Lorem ipsum dolor sit amet consectetur Lore


Q: Boost::regex_match isn't firing I have some boost Regex code which I think should fire. I'm new to boost but I know a little bit of Regex. Here's the code that I'm using.
re = boost::basic_regex<TCHAR>(_T("-+\\s+Original\\s+Message\\s+-+"), boost::regex_constants::icase);
boost::match_results<TSTRING::const_iterator> result;
if(boost::regex_match(RawBody, result, re))

and here is the test string I'm using.
this is a test

-------- Original Message --------

everything under here should disappear

My code compiles and runs, it just doesn't trigger the if statement. I tried debugging into the boost code and ... yeah...

A: regex_match

The algorithm regex_match determines whether a given regular
  expression matches all of a given character sequence denoted by a pair
  of bidirectional-iterators, the algorithm is defined as follows, the
  main use of this function is data input validation.

regex_search

The algorithm regex_search will search a range denoted by a pair of
  bidirectional-iterators for a given regular expression. The algorithm
  uses various heuristics to reduce the search time by only checking for
  a match if a match could conceivably start at that position. The
  algorithm is defined as follows:

So, use boost::regex_search. Example.
http://liveworkspace.org/code/fa35778995c4bd1e191c785671ab94b6


Q: How to fix inconvertible types in Android Studio I am trying to start an application based on google maps in Android Studio. I followed the instructions and started an Google Maps activity.
Then I created according to the instructions an API key and enabled the maps SDK android for android and copied the key into the app.
but then when I'm trying to run the app (didnt change a thing) I get this error:
Inconvertible types; cannot cast 'android.support.v4.app.Fragment' to 'com.google.android.gms.maps.SupportMapFragment'

for this line of code:
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
and this error: Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
    is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
    Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:12:5-42:19 to override.
in the event.

Here is the code:
package com.example.android.myfirstmap;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney, Australia, and move the camera.
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

I looked around to see if there is a solution that fixes also my problem but none of what I tried was the right one.
does anyone knows how to fix it? evreything is updated.

A: Support Map Fragment extends androidx.fragment.app.Fragment.
You are importing android.support.v4.app.FragmentActivity which uses android.support.v4.app.Fragment. These are two different classes so they are incompatible.
You need to migrate your app to Android X: https://developer.android.com/jetpack/androidx/migrate
Then, in your build.gradle file, replace com.android.support:support-fragment with androidx.fragment:fragment.
Hope that helps!


Q: drupal 6 - can i use one exposed views filter to search/filter several similar cck fields? i have a decent understanding of configuring drupal and using modules for basic stuff, but just getting into module development and overriding functions and stuff due to my very basic understanding of php and mysql.
i have a custom content type ('books') and a 3 cck field for genres (primary, secondary, tertiary). i'd like a user to be able to filter a view of all books with one exposed multi-selectable 'genre' filter. that's where i'm stuck-- i understand how to have three exposed filters for the 3 genre 'weights' (primary, secondary, tertiary)--i want one filter that would allow users to select any or all of those weights.
is a custom search form my only option?  was there a better way to set things up?  would i have been better off using one cck field for 'genres' with multiple entries? i ruled this out because i thought it would be harder to determine the genre 'weight' (primary, secondary, tertiary).
thanks a million.

A: Think about what the meaning of genres to a book is. Taxonomy is just what you use for this kind of thing. There are several pros using the taxonomy rather than using CCK fields.

*

*Taxonomy is meta data, CCK fields are not. This mean that the way the html is generated for taxonomy terms, it will help SE to understand that these genres are important and it will give you a free SEO

*You can setup how genres should be selected in far more detail than a CCK field. Again since taxonomy is made for exactly this kind of thing. You can setup how users are presentated with the genre selection in various ways. You can predefine genres or let users enter their own as they like. You can make child-parent relation ships and more

*It's easier and more lightweight to use taxonomy than CCK fields.

*If there only is 1 or 2 genre inputted you wont have to have empty CCK fields.

*probably more that I can't think of right now

Using taxonomy you can pretty easily make a search with views, where you make it possible for users to select genres using a multiple select list. You can decide if you require all terms or only one of them. Simply put you should really use taxonomy, it should solve all of your problems, if not, you should still use it and try to solve the problems you could get using taxonomy instead of CCK fields.

A: Jergason has a good point saying that taxonomy would probably be a good fit for your fields. However this wouldn't solve your problem of weighted genres.
A possible (though hacky) solution would be to have a fourth field which combined the values of the other three which is only set when a node is saved. This field could then be used for searching.
The non hacky solution is to write your own views filter but this is very advanced.
There may be a way to do this with views out of the box it is flexible, hopefully someone else knows of an easier non hacky solution.


Q: javascript invalid quantifier breaks my jQuery in asp.net I want to select, Highlight & convert the matching string into a link. So far it works find in jsFiddle.
But same script breaks when i try to use it in asp.net web forms i get following error
SyntaxError: invalid quantifier
[Break On This Error]

var pattern = new RegExp("("+this+")", ["gi"]);

Actual Code
function HighlightKeywords(keywords)
{
var el = $("#article-detail-desc");
$(keywords).each(function()
{
    var pattern = new RegExp("("+this+")", ["gi"]);
    var rs = "<a href='search.aspx?search=$1'$1";
    el.html(el.html().replace(pattern, rs));
});
}

HighlightKeywords(["got", "the","keywords", " tags " ]);

http://jsfiddle.net/LE3sg/6/
i am not sure why i keep getting this error in asp.net webform page

A: When looping an array with jQuery each should always use the arguments in callback to access the array element and use $.each method as opposed to $(selector).each
$.each(keyowrds, function(index, item)
{
    var pattern = new RegExp("("+item+")", ["gi"]);

In code you are using if you log typeof this to console will find it is not actually a string
API reference: http://api.jquery.com/jQuery.each/


Q: Hibernate constraint violation exception hangs sql server I am trying to save a set of records into db like shown below. I have set unique constraint on 2 columns of the table. I have handled the constraint exception. If I insert new set of records I have no issues. If I try to insert duplicate records, exception is handled but ms sql server says

executing query. waiting for response from data source.

Also after this if I try to insert new set of records the http request is not completed and the records are not inserted. How should I handle constraint exception so that ms sql server does not hang?
public void addStepFlow(List<StepFlow> stepFlows) {

        Session session = this.sessionFactory.openSession();
        try {
        Transaction tx = session.beginTransaction();
        for (StepFlow stepFlow : stepFlows) {

            session.save(stepFlow);

            session.flush();
            session.clear();
        }
        tx.commit();
        session.close();
        } catch (JDBCException e) {
            SQLException cause = (SQLException) e.getCause();
            System.out.println(cause.getMessage());
        }
    }

A: Try to rollback on exception.. and also close the session no matter what heppens:
    Session session = this.sessionFactory.openSession();
    Transaction tx = null;
    try {
    tx = session.beginTransaction();
    for (StepFlow stepFlow : stepFlows) {

        session.save(stepFlow);

        session.flush();
        session.clear();
    }
    tx.commit();

    } catch (JDBCException e) {
        SQLException cause = (SQLException) e.getCause();
        System.out.println(cause.getMessage());

        tx.rollback();
    }finally{
        session.close();
    }


Q: stroke-dasharray can't bind with angular 6 I used this Chart with angular 6 , I faced the some conflict on this chart, i try to bind data , but i cant do that, its not working correctly,
This stroke-dasharray="5, 100" to I replaced   this one
stroke-dasharray="{{this.master.locationVsStatusMap.size}}, 100"
stackblitz
anyone know how to do that correctly ?
Thanks in advance!

.single-chart {
  width: 33%;
  justify-content: space-around ;
}

.circular-chart {
  display: block;
  margin: 10px auto;
  max-width: 70%;
  max-height: 150px;
}

.circle-bg {
  fill: none;
  stroke: #3c9ee5;
  stroke-width: 3.8;
}

.circle {
  fill: none;
  stroke-width: 3.8;border-right: 1px solid white; border-left: 1px solid white;
  stroke-linecap:square;
  animation: progress 1s ease-out forwards;
}

@keyframes progress {
  0% {
    stroke-dasharray: 0 100;
  }
}

.circular-chart.orange .circle {
  stroke: #ff9f00;border-right: 1px solid white; border-left: 1px solid white;
}

.circular-chart.green .circle {
  stroke: #4CC790;
}

.circular-chart.blue .circle {
  stroke: #3c9ee5;
}

.percentage {
  fill: #666;
  font-family: sans-serif;
  font-size: 0.3em;
  text-anchor: middle;
}
.flex-wrapper {
  display: flex;
  flex-flow: row nowrap;
}

  <svg viewBox="0 0 36 36" class="circular-chart orange">
    <path class="circle-bg"
          d="M18 2.0845
          a 15.9155 15.9155 0 0 1 0 31.831
          a 15.9155 15.9155 0 0 1 0 -31.831"
    />
    <path class="circle"
          stroke-dasharray="5, 100"
          d="M18 2.0845
          a 15.9155 15.9155 0 0 1 0 31.831
          a 15.9155 15.9155 0 0 1 0 -31.831"
    />
      <text x="18" y="20.35" class="percentage">50%</text>
  </svg>

A: Use style binding - https://coryrylan.com/blog/angular-progress-component-with-svg
style.stroke-dasharray="{{varible}}, 100"

A: Try attribute binding
attr.stroke-dasharray="{{this.master.locationVsStatusMap.size}}, 100"

Forked Example:https://stackblitz.com/edit/angular-wqjlc5
Ref this: https://teropa.info/blog/2016/12/12/graphics-in-angular-2.html


Q: String trend-analysis (suggestions for data structure) I want to keep track of strings from text files over time (reading them in).  What would be the best method to programmatically keep track?  This is the desired end result after 3 entries.
String|frequency|date-Col1|date-Col2|..date-Col N|
==================================================
hello | 2       | 1/1/16  | 3/5/16  |
motto | 1       | 2/3/16

Some ideas I'm kicking around:  using python dictionaries, java arrayLists, R?
Any suggestions, thanks?

A: from collections import defaultdict

words_seen = defaultdict(list)

for word,filedate in get_words():
    words_seen[word].append(filedate)

then frequency is len(words_seen[word]).


Q: Why I cant access pages of my Classic ASP site? I am setting up a classic ASP site on my computer. I have installed all the necessary DLL's, configured the IIS and enabled ASP on my IIS. All the files of the website are in a folder named ClassicASP.This Folder is in wwwroot Folder of IIS.
Now my problem is that I am able to access the Login Page of my site. But when I enter credentials It doesnot redirects to the next page. Its gives
"
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
"
However the file is in the same folder. I can only access Login Page no other page is working it says Resource not Found.
Can some one help. I am new to ClassicASP.


Q: Why doesn't object-fit affect width or height? I have a 240*240px image inside a 100*300px div (demo values, actual values vary and are unknown). I use object-fit: contain to make the image completely visible inside the div and also keep it's aspect ratio. The problem is that object-fit isn't modifying the width of the image, resulting in a weird "padding" (so to say).

How can I make the image take only as much width as required, instead of taking the original width?
Demo: http://codepen.io/alexandernst/pen/ONvqzN

.wrapper {
  height: 100px;
  width: 300px;
  border: 1px solid black;
}
.flex {
  display: flex;
}
img {
  object-fit: contain;
}

A: The object-fit property normally works together with width, height, max-width and max-height. Example:

.wrapper {
  height: 100px;
  width: 300px;
  border: 1px solid black;
}
.flex {
  display: flex;
}
img {
  object-fit: contain;
  height: 100%;
  width: auto;
}

In fact, it works fine too even without object-fit, see this jsFiddle.

A:

.wrapper {
  height: auto;
  width: 100%;
  border: 1px solid black;
  background-image: url(https://unsplash.it/240/240);
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.flex {
  display: flex;
}

img {
  object-fit: contain;
}


Q: Cannot show notification at lock screen Android Studio I'm using NotificationCompat.Builder to show notification music player mini.
I have been show success notfication but without at lock screen. I tried NotificationCompat.Builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC), NotificationCompat.Builder.setPriority(NotificationCompat.PRIORITY_MAX) but all them not worked. My device android version is 9.0.1.
This is my code.
  private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Test";
            String description = "Đây là bản test";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("CHANNEL_ID", name, importance);
            channel.setShowBadge(true);
            channel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager =  getContext().getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

This is function call main.
        createNotificationChannel();
        // Create an explicit intent for an Activity in your app
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        Intent prevIntent = new Intent(this,NotificationReceiver.class).setAction("ActionPrev");
        Intent pauseIntent = new Intent(this,NotificationReceiver.class).setAction("ActionPause");
        Intent nextIntent = new Intent(this,NotificationReceiver.class).setAction("ActionNext");

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        PendingIntent prevpendingIntent = PendingIntent.getBroadcast(this,0,prevIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent pausependingIntent = PendingIntent.getBroadcast(this,0,pauseIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent nextpendingIntent = PendingIntent.getBroadcast(this,0,nextIntent,PendingIntent.FLAG_UPDATE_CURRENT);

        if(mangbaihat.get(position).getFields().getImage_Url().contains("/storage/emulated/0/Download")){
            final BitmapFactory.Options options = new BitmapFactory.Options();
            picture = BitmapFactory.decodeFile(mangbaihat.get(position).getFields().getImage_Url(), options);
        }else{
            picture = getBitmapFromURL(mangbaihat.get(position).getFields().getImage_Url());
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "CHANNEL_ID")
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setSmallIcon(R.drawable.logo)
                .setLargeIcon(picture)
                .setContentTitle(mangbaihat.get(position).getFields().getMusic_Title())
                .setContentText(mangbaihat.get(position).getFields().getComposed())
//                .setDefaults(NotificationCompat.DEFAULT_ALL)
                .addAction(R.drawable.iconpreview_mini,"Previous",prevpendingIntent)
                .addAction(R.drawable.iconpause_mini,"Pause",pausependingIntent)
                .addAction(R.drawable.iconnext_mini,"Next",nextpendingIntent)
                .setStyle(new androidx.media.app.NotificationCompat.MediaStyle().
                    setShowActionsInCompactView(1 /* #1: pause button */).
                    setMediaSession(mediaSession.getSessionToken()))
            .setPriority(NotificationCompat.PRIORITY_MAX)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent)
            .setOnlyAlertOnce(true);

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

    // notificationId is a unique int for each notification that you must define
    notificationManager.notify(0, builder.build());

Pls,Can anyone help me!
Thank you so much!


Q: Applescript for changing filenames I would like to change thousand of filenames with an applescript.
The filenames are all made in this way:
firstPart - secondPart XX.xxx
with the XX a certain number and the .xxx either a jpg or a png extension.
I would like to simply change the parts around so that it would become:
secondPart - firstPart XX.xxx
I have come up with this but my codings skills fail me.
tell application "Finder" to set aList to every file in folder "ImageRename"
set text item delimiters to {" - ", "."}
repeat with i from 1 to number of items in aList
    set aFile to (item i of aList)
    try
        set fileName to name of aFile
        set firstPart to text item 1 of fileName
        set secondPart to text item 2 of fileName
        set thirdPart to text item 3 of fileName
        set newName to secondPart & " - " & firstPart & "." & thirdPart
        set name of aFile to newName
    end try
end repeat

This works only the number sticks to the second part.
So it becomes:
SecondPart XX - firstPart.xxx
How can I make two integers as a text item delimiter?
Please help me out and teach me along the way :-)

A: To answer your question how to use an integer as an text item delimiters is just:
set AppleScript's text item delimiters to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}

You can set multiple text item delimiters at once but the problem is that when using multiple text item delimiters you have actually no idea what was between the two text items. Also the order of how the delimiters appear in the text is not important when using text item delimiters. Therefore I would suggest using regular expressions instead, you define a certain format instead of separating a string and guessing which character was actually the separator.
tell application "Finder" to set aList to every file in folder "ImageRename"
repeat with i from 1 to number of items in aList
   set aFile to item i of aList
   set fileName to name of aFile as string
   set newName to do shell script "perl -pe 's/^(.*) - (.*) ([0-9]{2}\\.(jpeg|png))$/\\2 - \\1 \\3/i' <<<" & quoted form of fileName
   if newName is not fileName then set name of aFile to newName
end repeat

The reason I use perl and not sed is because perl does support the I flag in the substitution which makes the comparison of the expression case insensitive.
edit (requested explanation):
The format of the old string is something like: String can start with any character (^.*) up to the literal string " - " ( - ) then followed by any character (.*) again. The string have to end with a string starting with space and 2 digits ( [0-9]{2}), followed by a literal period (\.) and end with either jpeg or png ((jpeg|png)$). If we put this all together we get a regex like "^.* - .* [0-9]{2}\.(jpeg|png)$". but we want to group the match in different sections and return them in a different order as our new string. Therefore we group the regular expression into 3 different sub matches by placing parentheses:
^(.*) - (.*) ([0-9]{2}\.(jpeg|png))$

The first group will match the firstPart, the second group will match secondPart and the third group (XX.xxx) will match the remaining part. The only thing we need to do is reorder them when we return the new string. A backslash followed by a number in the new string will be replaced by the matching group. In the substitution command this will be notated as /s/search/\2 - \1 \3/flags.
The last part of our substitution are some flags, I place I as a flag for case insensitive matching.
Putting this all together gets me
s/^(.*) - (.*) ([0-9]{2}\.(jpeg|png))$/\2 - \1 \3/I

note: because \ is in applescript a special character we have to write a \ down as \\

A: Just use the space as the delimiter and build the parts.
Edited: to allow for spaces in the text parts.
tell application "Finder" to set aList to every file in folder "ImageRename"
set AppleScript's text item delimiters to " "
repeat with i from 1 to number of items in aList
    set aFile to (item i of aList)
    try
        set fileName to name of aFile
        set lastParts to text item -1 of fileName
        set wordParts to (text items 1 thru -2 of fileName) as string
        set AppleScript's text item delimiters to " - "
        set newName to {text item 2 of wordParts, "-", text item 1 of wordParts, lastParts}
        set AppleScript's text item delimiters to " "
        set name of aFile to (newName as string)
    end try
end repeat
set AppleScript's text item delimiters to ""


Q: Difference between setup.py files If I were to develop and distribute a python package, I know I can probably make a setup.py file like this:
from setuptools import setup, find_packages

setup(name='mypackage',
      version='0.1',
      packages=find_packages()
)

However, when I look at the setup.py in some installed packages on my PC. It is written quite differently. For instance, setup.py in Scipy looks like:
def configuration(parent_package='',top_path=None):
    from scipy._build_utils.system_info import get_info, NotFoundError
    lapack_opt = get_info("lapack_opt")

    from numpy.distutils.misc_util import Configuration
    config = Configuration('scipy',parent_package,top_path)
    config.add_subpackage('cluster')
    config.add_subpackage('constants')
    config.add_subpackage('fft')
    config.add_subpackage('fftpack')
    config.add_subpackage('integrate')
    config.add_subpackage('interpolate')
    config.add_subpackage('io')
    config.add_subpackage('linalg')
    config.add_data_files('*.pxd')
    config.add_subpackage('misc')
    config.add_subpackage('odr')
    config.add_subpackage('optimize')
    config.add_subpackage('signal')
    config.add_subpackage('sparse')
    config.add_subpackage('spatial')
    config.add_subpackage('special')
    config.add_subpackage('stats')
    config.add_subpackage('ndimage')
    config.add_subpackage('_build_utils')
    config.add_subpackage('_lib')
    config.make_config_py()
    return config

if __name__ == '__main__':
    from numpy.distutils.core import setup
    setup(**configuration(top_path='').todict())

Can anyone please explain why and which style I should use when developing my own packages?


Q: Eclipse plugin - creating a new class I'm trying to write an eclipse plugin to auotmatically generate a java class from a text file. How can I do this in JDT?
The name of the class will be derived from the name of the text file, and I will want to generate some methods based on the contents of the text file.
I can probably do this the hard way, just writing to a file, but it seems like the JDT is the best way to go about this.


Q: Adding elements to model space the correct way using .NET API Method One
_AcDb.Line oLine = new _AcDb.Line(ptStart, ptEnd);
AddToModelSpace("PLOT", oLine);

Where AddToModelSpace is:
public static void AddToModelSpace(string strLayer, _AcDb.Entity oEntity)
{
    _AcAp.Document acDoc = _AcAp.Application.DocumentManager.MdiActiveDocument;
    _AcDb.Database acCurDb = acDoc.Database;
    _AcEd.Editor ed = acDoc.Editor;

    using (_AcDb.BlockTable bt = acCurDb.BlockTableId.GetObject(_AcDb.OpenMode.ForRead) as _AcDb.BlockTable)
    using (_AcDb.BlockTableRecord ms = bt[_AcDb.BlockTableRecord.ModelSpace].GetObject(_AcDb.OpenMode.ForWrite) as _AcDb.BlockTableRecord)
        ms.AppendEntity(oEntity);
    oEntity.Layer = strLayer;
    oEntity.Dispose();
}

Method Two
// Get the current document and database
_AcAp.Document docActive = _AcAp.Application.DocumentManager.MdiActiveDocument;
_AcDb.Database docDB = docActive.Database;

// Start a transaction
using (_AcDb.Transaction acTrans = docDB.TransactionManager.StartTransaction())
{
    // Open the Block table for read
    _AcDb.BlockTable acBlkTbl;
    acBlkTbl = acTrans.GetObject(docDB.BlockTableId,
                                    _AcDb.OpenMode.ForRead) as _AcDb.BlockTable;

    // Open the Block table record Model space for write
    _AcDb.BlockTableRecord acBlkTblRec;
    acBlkTblRec = acTrans.GetObject(acBlkTbl[_AcDb.BlockTableRecord.ModelSpace],
                                    _AcDb.OpenMode.ForWrite) as _AcDb.BlockTableRecord;

    // Create line
    using (_AcDb.Line acLine = new _AcDb.Line(ptStart, ptEnd))
    {

        // Add the new object to the block table record and the transaction
        acBlkTblRec.AppendEntity(acLine);
        acTrans.AddNewlyCreatedDBObject(acLine, true);
    }

    // Save the new object to the database
    acTrans.Commit();
}

I have used AddToModelSpace in my project so I hope it is fine!

A: Method Two is the way Autodesk recommends in the developer's documentation (you can read this section).
In Method One, you use the ObjectId.GetObject() method to open the BlockTable and the model space 'BlockTableRecord'. This method uses the top transaction to open object which means that there's an active transaction you should use to add the newly created entity. You can get it with Database.TransactionManager.TopTransaction. If you don't want to use a transaction at all, you have to use the "for advanced use only" ObjectId.Open() method.
A Method Three should be using some extension methods to be called from within a transaction. Here's a simplified (non error checking) extract of the ones I use.
static class ExtensionMethods
{
    public static T GetObject<T>(
        this ObjectId id,
        OpenMode mode = OpenMode.ForRead,
        bool openErased = false,
        bool forceOpenOnLockedLayer = false)
        where T : DBObject
    {
        return (T)id.GetObject(mode, openErased, forceOpenOnLockedLayer);
    }

    public static BlockTableRecord GetModelSpace(this Database db, OpenMode mode = OpenMode.ForRead)
    {
        return SymbolUtilityServices.GetBlockModelSpaceId(db).GetObject<BlockTableRecord>(mode);
    }

    public static ObjectId Add (this BlockTableRecord owner, Entity entity)
    {
        var tr = owner.Database.TransactionManager.TopTransaction;
        var id = owner.AppendEntity(entity);
        tr.AddNewlyCreatedDBObject(entity, true);
        return id;
    }
}

Using example:
using (var tr = db.TransactionManager.StartTransaction())
{
    var line = new Line(startPt, endPt) { Layer = layerName };
    db.GetModelSpace(OpenMode.ForWrite).Add(line);
    tr.Commit();
}


Q: Make X-Axis Lables, value labels and other axis and labels bold in Ggplot2 I work inside a research environment and I can't copy paste the code I used there, but I have previously generated this plot, and have been helped by various people in labelling it with the count number. The problem arises when I screenshot the plot from inside the research environment, and the legends are illegible. I am hoping I can address this by making the labels (including the X-axis label) all bold.
I used some mock-data outside the environment and this is what I have so far.
library(ggplot2)
library(reshape2)
md.df = melt(df, id.vars = c('Group.1'))
tmp = c("virginica","setosa","versicolor")
md.df2 = md.df[order(match(md.df$Group.1, tmp)),]
md.df2$Group.1 = factor(as.character(md.df2$Group.1), levels = unique(md.df2$Group.1))

ggplot(md.df2, aes(x = Group.1, y = value, group = variable, fill = variable)) +
  geom_bar(stat="identity",color='black', position = "dodge") +
  xlab('Species') + ylab('Values') + theme_bw()+
  ylim(0,8)+
  theme(text = element_text(size=16),
        axis.text.x = element_text(angle=0, hjust=.5),
        plot.title = element_text(hjust = 0.5),
        plot.subtitle = element_text(hjust = 0.5))+
  ggtitle("Order variables in barplot")+
  geom_text(aes(label=value), vjust=-0.3, size=4, # adding values
            position = position_dodge(0.9))+ element_text(face="bold")

I need to make the labels onto bold, and the element_text isn't working mainly because I am probably using it in the wrong way. I'd appreciate any help with this.
An example of this plot which I haven't been able to find mock data to re-create outside the environment, have asked a question about in the past, is the one where the axis ticks also need to be made bold. This is because the plot is illegible from the outside.
I've tried addressing the illegibility by saving all my plots using ggsave in 300 resolution but it is very illegible.
I'd appreciate any help with this, and thank you for taking the time to help with this.

A: As I mentioned in my comment to make the value labels bold use geom_text(..., fontface = "bold") and to make the axis labels bold use axis.text.x = element_text(angle=0, hjust=.5, face = "bold").
Using a a minimal reproducible example  based on the ggplot2::mpg dataset:
library(ggplot2)
library(dplyr)

# Create exmaple data
md.df2 <- mpg |>
  count(Group.1 = manufacturer, name = "value") |>
  mutate(
    variable = value >= max(value),
    Group.1 = reorder(Group.1, -value)
  )

ggplot(md.df2, aes(x = Group.1, y = value, group = variable, fill = variable)) +
  geom_col(color = "black", position = "dodge") +
  geom_text(aes(label = value), vjust = -0.3, size = 4, position = position_dodge(0.9), fontface = "bold") +
  labs(x = "Species", y = "Values", title = "Order variables in barplot") +
  theme_bw() +
  theme(
    text = element_text(size = 16),
    axis.text.x = element_text(angle = 90, vjust = .5, face = "bold"),
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5)
  )

A: In addition to @stefan 's answer, you can also set tick length and thickness like so:
## ... plot code +
    theme(## other settings ...,
          axis.ticks = element_line(linewidth = 5),
          axis.ticks.length = unit(10, 'pt'))

However, the example "phenotype conditions" will probably remain hard to appraise, regardless of optimization on the technical level. On the conceptual level it might help to display aggregates, e. g. condition counts per Frequency and supplement a textual list of conditions (sorted alphabetically and by Frequency, or the other way round) for those readers who indeed want to look up any specific condition.


Q: SQL expression in oracle data integrator
I have the following interface in Oracle Data Integrator
http://i44.tinypic.com/2mrsmxt.png
It execute successfully before inserting the following SQL expression
In the mapping I insert the following SQL expression to get the average when the quantity is 0
AVG(
    CASE WHEN TEST.QUN = 0 THEN
        (SELECT TEST.QUN
         FROM TEST
         WHERE TEST1.PRUDU=TEST.PRUDU
         AND TEST1.FLOW=TEST.UNIT
        AND TEST1.UNIT=TEST.UNIT
        AND to_char(TEST.DATEDDD,'MON')= to_char(TEST1.DATEDDD,'MON')
        AND TEST1.DATEDDD !=TEST.DATEDDD
        GROUP BY TEST.QUN )
 ELSE TEST.QUN
END)

When I check this expression in ODI the SQL expression is correct for this RDBMS  but when I executed the interface I get this error
Caused By: java.sql.SQLSyntaxErrorException:
ORA-00937: not a single-group group function

any idea?


Q: Compare numbers in NSMutableArray with indexPath.row I have an NSMutableArray that gets edited quite often as a TableView is edited.  What I want to do is run a check and see if rows in the TableView match up with any numbers in the NSMutableArray, and if they do, perform an action.  So, in the TableView code I have:
if([thearray containsObject:indexPath.row] {
   //perform action here
}

However I keep getting the error:
Incompatible integer to pointer conversion sending 'NSInteger' (aka 'int') to parameter of type 'id';

What am I doing wrong and how can I do this?

A: Use this code...
if([thearray containsObject:[NSNumber numberWithInt:indexPath.row]]) {
   //perform action here
}

A: I think the best you can do here is check if the current count of the array  is greater than indexPath.row the  (since in theory there will be no gaps in the indexes). The method you are currently calling takes an object and tells you if it is a member of the array. There is also objectAtIndex:, but that raises an exception if the integer you pass is out of bounds.
if(thearray.count > indexPath.row) {
  // array has at least indexPath.row + 1 items, so you can get objectAtIndex:indexPath.row
}


Q: Why getting the `This page isn't working... ERR_TOO_MANY_REDIRECTS`? Generated same script file with multiple times in index.html file, I recently upgraded project to angular 8.0.2 version
After upgrading the angular version, am getting this replication problem in index.html file.

This is JavaDemoProject java project, i run the angular application with this javaproject with the help of pom.xml file
I build the project through maven command(mvn clean install -Penv-dev -DskipTests -DbuildNumber=04)

*

*pom.xml file
<plugin>
    <groupId>com.github.testDemo</groupId>
    <artifactId>frontend-maven-plugin</artifactId>
    <version>1.6</version>
    <configuration>
        <workingDirectory>../Angular-Project</workingDirectory>
        <installDirectory>temp</installDirectory>
    </configuration>
    <executions>
       <!-- It will install nodejs and yarn -->
       <execution>
           <id>install node and yarn</id>
           <goals>
               <goal>install-node-and-yarn</goal>
           </goals>
           <configuration>
               <nodeVersion>v11.7.0</nodeVersion>
               <yarnVersion>v1.9.4</yarnVersion>
           </configuration>
       </execution>
       <!-- It will execute command "yarn install" inside "/angular"
            directory -->
       <execution>
          <id>yarn install</id>
          <goals>
             <goal>yarn</goal>
          </goals>
          <configuration>
               <arguments>install</arguments>
          </configuration>
       </execution>
       <!-- It will execute command "yarn build" inside "/angular"
           directory to clean and create "/dist" directory -->
       <execution>
           <id>yarn javaDemoprod </id>
           <goals>
              <goal>yarn</goal>
           </goals>
           <configuration>
               <arguments>javaDemoprod --outputPath=../JavaDemoProject/
                  src/main/resources/templates/dist</arguments>
           </configuration>
       </execution>
    </executions>
</plugin>

*tsconfig.json file:
{
  "compileOnSave": false,
  "compilerOptions": {
      "baseUrl": "./",
      "module": "commonjs",
      "outDir": "./dist/out-tsc",
      "sourceMap": true,
      "declaration": false,
      "moduleResolution": "node",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "target": "es2015",
      "typeRoots": [
         "node_modules/@types"
      ],
      "lib": [
         "es2017",
         "dom"
      ],
      "resolveJsonModule": true,
      "esModuleInterop": true
  }
}

*This is the angular.json file:
"build": {
    "builder": "@angular-devkit/build-angular:browser",
    "options": {
      "outputPath": "dist/Angular-Project",
      "index": "src/index.html",
      "main": "src/main.ts",
      "polyfills": "src/polyfills.ts",
      "tsConfig": "src/tsconfig.app.json",
      "showCircularDependencies": false,
      "assets": [
        "src/favicon.ico",
        "src/eg.ico",
        "src/assets"
      ],
      "styles": [
        "src/styles.scss"
      ],
      "scripts": [],
      "aot": true
    }
  }

*Package.json
"dependencies": {
  "@angular/animations": "^8.0.1",
  "@angular/cdk": "^8.0.1",
  "@angular/common": "^8.0.1",
  "@angular/compiler": "^8.0.1",
  "@angular/core": "^8.0.1",
  "@angular/forms": "^8.0.1",
  "@angular/material": "^8.0.1",
  "@angular/platform-browser": "^8.0.0",
  "@angular/platform-browser-dynamic": "^8.0.1",
  "@angular/router": "^8.0.1",
  "core-js": "^2.5.4",
  "hammerjs": "^2.0.8",
  "ngx-loading": "^3.0.1",
  "node-sass": "^4.10.0",
  "rxjs": "6.5.2",
  "underscore": "^1.9.1",
  "zone.js": "~0.9.1"
},
"devDependencies": {
  "@angular-devkit/build-angular": "~0.800.0",
  "@angular/cli": "~8.0.2",
  "@angular/compiler-cli": "^8.0.1",
  "@angular/language-service": "^8.0.1",
  "@types/jasmine": "~2.8.6",
  "@types/jasminewd2": "~2.0.3",
  "@types/node": "~8.9.4",
  "bootstrap-sass": "^3.3.7",
  "codelyzer": "^5.0.1",
  "jasmine-core": "~2.99.1",
  "jasmine-spec-reporter": "~4.2.1",
  "karma": "~1.7.1",
  "karma-chrome-launcher": "~2.2.0",
  "karma-coverage-istanbul-reporter": "~2.0.0",
  "karma-jasmine": "~1.1.1",
  "karma-jasmine-html-reporter": "^0.2.2",
  "karma-scss-preprocessor": "^3.0.0",
  "protractor": "~5.3.0",
  "ts-node": "~5.0.1",
  "tslint": "~5.9.1",
  "typescript": "~3.4.5"
}

After build the application in index.html path of the
   file JavaDemoProject\src\main\resources\templates\dist\index.html am getting this replication of script files, how can i prevent this replicate script files.

<body>
    <app-root></app-root>
    <script src="runtime-es2015.js" type="module"></script>
    <script src="polyfills-es2015.js" type="module"></script>
    <script src="runtime-es5.js" nomodule></script>
    <script src="polyfills-es5.js" nomodule></script>
    <script src="styles-es2015.js" type="module"></script>
    <script src="styles-es5.js" nomodule></script>
    <script src="vendor-es2015.js" type="module"></script>
    <script src="main-es2015.js" type="module"></script>
    <script src="vendor-es5.js" nomodule></script>
    <script src="main-es5.js" nomodule></script>
</body>

This replications of script file am getting the output of the application showing

This page isn't working...
ERR_TOO_MANY_REDIRECTS

Can anyone help me out to solve this problem.
Thanks in Advance.

A: The scripts which you are able to see is because of the differential loading feature.
Angular 8 has a new feature to generate a separate bundle to the older browser and new browsers.
You can control which browser you want to support, you can read more about this feature on
https://angular.io/guide/deployment#differential-loading


Q: Error message when trying to read an excel file Hi pretty new to angular2 so apologizes if this is something simple - i'm trying to read an excel file using a lib called ts-xlsx and inject the data into the main app root component - The error i'm getting is

zone.js:355Unhandled Promise rejection: Error in ./AppComponent class AppComponent_Host - inline template:0:0 caused by: !CompObj is not a function ; Zone:  ; Task: Promise.then ; Value:
app-service.ts

import { Injectable } from '@angular/core';
import { read, IWorkBook, IWorkSheet, utils } from 'ts-xlsx';

@Injectable()
export class OperationDataService {

    private xbFile = 'test.xlsx';
    private wb: IWorkBook = read(this.xbFile);
    private wbSheet: IWorkSheet = this.wb.Sheets[1];

    objAr: any[];

    constructor() { }

    getData() {

        this.objAr = utils.sheet_to_json(this.wbSheet, { header: 1 });

    }
}

app.component.ts

import { Component, OnInit } from '@angular/core';
import { OperationDataService } from './app.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [OperationDataService]
})
export class AppComponent implements OnInit {

  ObjArray: any[];

  constructor(private _operationDataService: OperationDataService) { }

  ngOnInit() {

    this.ObjArray[1] = this._operationDataService.getData();

  }

}
i can't find much documentation on it so any help would be much appreciated.
Update:
Even-though the information online is small it seems that there are a few problems with the way i grabbed the file above - so i re-wrote the service component to align to original alax example converted to typescript
import { Injectable } from '@angular/core'; import { read, IWorkBook, IWorkSheet, utils } from 'ts-xlsx';

@Injectable() export class OperationDataService {
    url: string;
    oReq: any;
    wb: IWorkBook;
    wbSheet: IWorkSheet;
    arraybuffer: any;
    data: any;
    arr: any;
    bstr: any;
    objAr: any[];

    constructor() {
        this.url = '../assets/data/Operations.xlsx';
        this.oReq = new XMLHttpRequest();
        this.oReq.open('GET', this.url, true);
        this.oReq.responseType = 'arraybuffer';

    }

    getdata() {

        this.oReq.onload = function(): any {

        this.arraybuffer = this.oReq.response;

        /* convert data to binary string */
        this.data = new Uint8Array(this.arraybuffer);
        this.arr = new Array();

        for (let item of this.data) {
            this.arr[item] = String.fromCharCode(this.data[item]);
        }

        this.bstr = this.arr.join('');
        console.log(this.oReq.responseText);

        this.wb = read(this.bstr, {type: 'binary'});
        this.wbSheet = this.wb.Sheets[0];

        this.objAr = utils.sheet_to_json(this.wbSheet, { header: 1 });
        console.log(utils.sheet_to_json(this.wbSheet, { header: 1 }));

        return this.objAr;
        };
    } }

Now i'm not receiving any errors but i can't see the json - any idead what i'm doing wrong?

A: From the code you posted, this looks good in theory, but still has a few errors.

*

*You're using ObjArray in AppComponent without initializing it, so you can't access it with [1]

*The getData method in your service doesn't actually return anything

Here are my proposed changes for the service:
getData() {
    this.objAr = utils.sheet_to_json(this.wbSheet, { header: 1 });
    return this.objAr;
}

and for the component:
export class AppComponent implements OnInit {

  ObjArray: any[] = [];

  constructor(private _operationDataService: OperationDataService) { }

  ngOnInit() {
    let data = this._operationDataService.getData();
    this.ObjArray.push(data);

  }
}

A: this it's work :
Upload() {
    let fileReader = new FileReader();
      fileReader.onload = (e) => {
          this.arrayBuffer = fileReader.result;
          /* convert data to binary string */
          var data = new Uint8Array(this.arrayBuffer);
          var arr = new Array();

          for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
          var bstr = arr.join("");
          var workbook = XLSX.read(bstr, {type:"binary"});
          var first_sheet_name = workbook.SheetNames[0];
          var worksheet = workbook.Sheets[first_sheet_name];
          console.log('excel data:',XLSX.utils.sheet_to_json(worksheet,{raw:true}));
      }
      fileReader.readAsArrayBuffer(this.file);
}


Q: Convert SQL (Left Outer Join's) to LINQ I am having trouble converting a Oracle Sql Query with multiple LEFT OUTER JOIN to LINQ. My attempts don't return the expected results. Could somebody help to convert the SQL Query below to LINQ.
string currentCulture = Culture.GetCulture();
string query = @"SELECT *
               FROM CTGLBL g, CTTGLBL ct, CTLANG lang
               WHERE g.sysctglbl = ct.sysctglbl(+) AND
                     ct.sysctlang = lang.sysctlang (+) AND
                     NVL(lang.activeflag, 1)= 1 AND
                     (ISOCODE LIKE '" + currentCulture + "%' OR ISOCODE IS NULL)";

ISOCODE belongs to CTLANG Table.
ps. I can't use tools like LINQPAD or Linqer.

A: But a better practice for your sql (and here converted to linq) is to use join to join tables and not the where:
string currentCulture = Culture.GetCulture();

var result = from g in CTGLBL
             join ct in CTTGLBL on g.sysctglbl equals ct.sysctglbl into ctj
             from ct in ctj.DefaultIfEmpty()
             join lang in CTLANG on ct.sysctlang equals lang.sysctlang into langj
             from lang in langj.DefaultIfEmpty()
             where (lang == null ?  1 : (lang.activeflag ?? 1)) == 1 &&
                 (lang?.ISOCODE.StartsWith(currentCulture) || lang?.ISOCODE == null)
             select new { g, ct, lang };

You can also have a "nested select" for your CTLANG like this:
string currentCulture = Culture.GetCulture();

var result = from g in CTGLBL
             join ct in CTTGLBL on g.sysctglbl equals ct.sysctglbl into ctj
             from ct in ctj.DefaultIfEmpty()
             join lang in CTTGLBL.Where(lang => lang.activeflag ?? 1 == 1 &&
                                                  (lang.ISOCODE.Contains(currentCulture) ||
                                                   lang.ISOCODE == null))
             on ct.sysctlang equals lang.sysctlang into langj
             from lang in langj.DefaultIfEmpty()
             select new { g, ct, lang };

A: (What I see is a left join, not right)
Assuming you have the proper relations between the tables in your schema, with SQL server (Linq TO SQL) this would work, not sure if it would supported for Oracle:
string currentCulture = Culture.GetCulture();

var data = from g in db.CTGLBL
           from ct in g.CTTGLBL.DefaultIfEmpty()
           from lang in g.CTLANG.DefaultIfEmpty()
           where !g.CTLANG.Any() ||
                 ( lang.activeflag == 1 &&
                   lang.ISOCODE.StartsWith(currentCulture))
           select new {g, ct, lang};


Q: How do exit a while loop with a JOptionPane I am having trouble with my code, I am trying to exit this loop if the user clicks on the CANCEL.OPTION or the CLOSED.OPTION. I handled the exception but can't seem to be able to use the buttons on the window. The program gets the users birthyear from their input of their age. The problem i am having is that I cannot end the loop through the buttons. Thanks in advance!
public Integer getBirthYear() {
    boolean prompt = true;
    while(prompt) {
        String enteredAge = showInputDialog(null,"Enter age:");
        try {
            age = Integer.parseInt(enteredAge);
            if(age == JOptionPane.CANCEL_OPTION || age == JOptionPane.CLOSED_OPTION) {
                System.out.println("MADE IT INTO IF");
            }
            age = year - age;
            prompt = false;
            showMessageDialog(null,age);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
    return age;
}

A: There are several overloaded versions of showInputDialog, with different parameters. Only the javadoc of the last version documents correctly that the return value is null when the user pressed cancel.
public int getBirthYear() {
    boolean prompt = true;
    while (prompt) {
        String enteredAge = showInputDialog(null,"Enter age:");
        if (enteredAge == null) { // Cancel pressed
            age = -1;
            prompt = false;
        } else {
            try {
                age = Integer.parseInt(enteredAge);
                age = year - age;
                prompt = false;
                showMessageDialog(null, age);
            } catch (NumberFormatException e) {
                showMessageDialog(null, "Enter a valid number");
            }
        }
    }
    return age;
}

It might be you want to restructure the program a bit; make age a local variable or whatever. Use int for real integer values. Integer is the Object wrapper class for an int.

A: The most easiest answer to your question is, just put promp = false outside of your try and catch clause and it should work:
public Integer getBirthYear() {
boolean prompt = true;
while(prompt) {
    String enteredAge = showInputDialog(null,"Enter age:");
    try {
        age = Integer.parseInt(enteredAge);
        if(age == JOptionPane.CANCEL_OPTION || age == JOptionPane.CLOSED_OPTION) {
            System.out.println("MADE IT INTO IF");
        }
        age = year - age;
        showMessageDialog(null,age);
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
        prompt = false;
}
return age;
}

A: The problem was in the scope. The entered age wasnt making it into the catch block. I resolved that issue.
    public Integer getBirthYear() {
    boolean prompt = true;
    do {
        try {
            age = year - Integer.parseInt(showInputDialog(null,"Enter age:"));
            prompt = false;
            showMessageDialog(null, age);
        } catch (NumberFormatException e) {
            String ageEntered = showInputDialog(null,"Enter age:");
            e.printStackTrace();
            if(ageEntered == null) { //close the file if Cancel is chosen
                prompt = false;
            }
        }
    } while(prompt);
    return age;
}


Q: how to send form data as csv file or as pdf in email in android studio i have a form from where i have taken user input and it includes checkbox and edittext field; i need to send this through email i tried using itext for pdf and even csv files but none works below is my csv file it sends email but does not send data along with it.
MainActivity:
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import java.io.File;
import java.io.FileOutputStream;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 }

 public void export(View view) {
    //generate data
    StringBuilder data = new StringBuilder();
    data.append("Time,Distance");
    for(int i = 0; i<5; i++){
        data.append("\n"+String.valueOf(i)+","+String.valueOf(i*i));
    }

    try{
        //saving the file into device
        FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
        out.write((data.toString()).getBytes());
        out.close();

        //exporting
        Context context = getApplicationContext();
        File filelocation = new File(getFilesDir(), "data.csv");
        Uri path = FileProvider.getUriForFile
      (context, "com.example.exportcsv.fileprovider", filelocation);
        Intent fileIntent = new Intent(Intent.ACTION_SEND);
        fileIntent.setType("text/csv");
        fileIntent.putExtra(Intent.EXTRA_SUBJECT, "Data");
        fileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        fileIntent.putExtra(Intent.EXTRA_STREAM, path);
        startActivity(Intent.createChooser(fileIntent, "Send mail"));
      }
    catch(Exception e){
        e.printStackTrace();
     }

    }
    }

Provider_paths:
<paths>
<files-path
    name="data"
    path="."/>
</paths>

Activity_main:
<ScrollView
    android:id="@+id/scrollView2"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="1dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#72C8E8"
            android:padding="4sp"
            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:text="@string/name"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30sp"
            android:textStyle="bold" />

        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName" />

        <TextView
            android:id="@+id/textView2"
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#72C8E8"
            android:text="@string/age"
            android:padding="4sp"
            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30sp"
            android:textStyle="bold" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number" />

        <TextView
            android:id="@+id/textView3"
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#72C8E8"
            android:padding="4sp"
            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:text="@string/gender"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30sp"
            android:textStyle="bold" />

        <CheckBox
            android:id="@+id/checkBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:onClick="onCheckboxClicked"
            android:text="@string/m"
            android:textSize="24sp" />

        <CheckBox
            android:id="@+id/checkBox2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:onClick="onCheckboxClicked"
            android:text="@string/f"
            android:textSize="24sp" />

        <TextView
            android:id="@+id/textView4"
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#72C8E8"
            android:padding="4sp"
            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:text="@string/address"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30sp"
            android:textStyle="bold" />

        <EditText
            android:id="@+id/editText3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPostalAddress" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="match_parent"
            android:layout_marginTop="20dp"
            android:layout_height="wrap_content"
            android:background="#72C8E8"
            android:text="@string/phone"
            android:padding="4sp"
            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30sp"
            android:textStyle="bold" />

        <EditText
            android:id="@+id/editText4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number" />

        <Button
            android:id="@+id/button"
            android:layout_marginTop="30dp"
            android:layout_gravity="center_horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="24dp"
            android:textSize="24sp"
            android:onClick="export"
            android:padding="4sp"
            android:background="#72C8E8"

            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:text="@string/export" />

    </LinearLayout>
</ScrollView>

A: Please refer this tutorial to send an email with attachment: https://www.google.com/amp/s/javatutorial.net/send-email-with-attachments-android/amp
You also don't need the "text/csv" mimetype, this is for the email and wrong as you need plain text or html, as you prefer.
In addition to that, do you have the file read permission?


Q: Missing Character For KeyEvent When using the KeyTyped method for the KeyListener, sometimes I get "missing characters". I'll show the code I use to get them, then ask my question.
public class KeyInput implements KeyListener
{
     public void keyTyped(KeyEvent e)
     {
         System.out.println(e.getKeyChar());
     }
}

I left out a few required methods because they are unrelated to my question. If I press a letter, it prints the letter to console. But if I use a key combination, ie. control + g, The character printed to console is just a square with a question mark.

Is there a way to detect if the character is a "missing character"?

A: Maybe you can use the canDisplay(...) method of the Font class.


Q: Ktor modify request on retry not working as expected I have a custom retry policy on receiving 5XX errors from the server. The idea is to retry until I get a non-5XX error with an exponential delay between each retry request also I would like to update the request body on every retry.
Here is my code
import io.ktor.client.*
import io.ktor.client.engine.java.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.request.*
import io.ktor.server.routing.*
import kotlinx.coroutines.*
import kotlin.time.Duration.Companion.seconds

suspend fun main() {
    val serverJob = CoroutineScope(Dispatchers.Default).launch { startServer() }

    val client = HttpClient(Java) {
        install(HttpTimeout) {
            connectTimeoutMillis = 5.seconds.inWholeMilliseconds
        }
        install(HttpRequestRetry)
    }

    client.post {
        url("http://127.0.0.1:8080/")
        setBody("Hello")
        retry {
            retryOnServerErrors(maxRetries = Int.MAX_VALUE)
            exponentialDelay(maxDelayMs = 128.seconds.inWholeMilliseconds)
            modifyRequest { it.setBody("With Different body ...") } // It's not working! if I comment this out then my retry logic works as expected
        }
    }

    client.close()
    serverJob.cancelAndJoin()
}

suspend fun startServer() {
    embeddedServer(Netty, port = 8080) {
        routing {
            post("/") {
                val text = call.receiveText()
                println("Retrying exponentially... $text")
                call.response.status(HttpStatusCode(500, "internal server error"))
            }
        }
    }.start(wait = true)
}

As you can see, if I comment out modifyRequest { it.setBody("With Different body ...") } line from retry logic then everything works fine. If I include that line it only tries once and stuck there, what I'm doing wrong here? how to change the request body for every retry?

A: The problem is that rendering (transformation to an OutgoingContent) of a request body happens during the execution of the HttpRequestPipeline, which takes place only once after making an initial request. The HTTP request retrying happens after in the HttpSendPipeline.
Since you pass a String as a request body it needs to be transformed before the actual sending. To solve this problem, you can manually wrap your String into the TextContent instance and pass it to the setBody method:
retry {
    retryOnServerErrors(maxRetries = Int.MAX_VALUE)
    exponentialDelay(maxDelayMs = 128.seconds.inWholeMilliseconds)
    modifyRequest {
        it.setBody(TextContent("With Different body ...", ContentType.Text.Plain))
    }
}


Q: Affect Second Spinner Choices based on First Spinner So I can see that there are questions about this, but not in the scope of mine. I am buliding an app for Android that has two spinners. The first has an array of choices. However, I am not sure how to affect what choices the second one has based on the first one. I know that you can put in
AdapterView.OnItemSelectedListener

but I'm not sure how to implement this. I've read on this but it's not quite what I'm looking for. I'm also curious as to how I tell the spinner which array to choose, is it in the .xml or in the .java file?

A: Try this,
firstSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub

                    string selectedValue = arg0.getSelectedItem().toString();
                    if(selectedValue.equalsIgnoreCase(string1)
                    {
                        ArrayAdapter<String> firstAdapter = new ArrayAdapter<String>(this,
                            android.R.layout.simple_list_item_1, firstArray);

                        secondSpinner.setAdapter(firstAdapter);//
                    }

                   else if(selectedValue.equalsIgnoreCase(string2)
                   {
                      ArrayAdapter<String> firstAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array2);

                      secondSpinner.setAdapter(firstAdapter);

                   }
            }

Hope it will help you.

A: If it's a String array you could define it in XML then use getResource().getStringArray() or declare it in Java.
In your listener for the first spinner, you could do the following to set the choices for the second spinner.
secondSpinnerAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, newArray);
secondSpinner.setAdapter(secondSpinnerAdapter);

Tested and working

A: update the array list of second spinner in 1st spinner setOnItemSelectedListener
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub

                    string str=spinner1.getSelectedItem().toString();
                    if(str.equals("spinner item"))//spinner item is selected item of spinner1
                    {
                        ArrayAdapter<String>adapter1 = new ArrayAdapter<String>(this,
                            android.R.layout.simple_list_item_1, array1);
                 //adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
                 spinner2.setAdapter(adapter1);//
                    }else if{
                   ArrayAdapter<String>adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array2);
                    //adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
                 spinner2.setAdapter(adapter2);

        }
            }