text:
Q: A way of listing all running heads It would be useful if I could get a list of all the running heads in my document, preferably listed by recto and verso (i.e. right- and left-hand pages), without having to manually go through the output PDF.
Some initial thoughts include:

*

*Temporarily using a different style file to make the Contents list appear differently.

*Just deleting out all body text from the .tex so that I'm just left with chapter and subsection headers.

I'm looking for something of the form:
Chapter # | Verso           | Recto
1         | chapter 1 title | subsection 1 title
1         | chapter 1 title | subsection 2 title
2         | chapter 2 title | subsection 1 title

For other work I might want something of the form: (I include this in case it would use a similar solution!)
Chapter # | Verso           | Recto
1         | book title      | chapter 1 title
2         | book title      | chapter 2 title

If this is an editor-specific question, then for reference I'm using Texmaker.

A: I am not sure if I understand what you want to do. But I think a solution would depend on the class and the package used for page header and footer.
Maybe you can use package scrwfile to clone the ToC in a new list and tocbasic to formate the entries in this new list.
Example:
\documentclass{book}
\usepackage{scrwfile}
\TOCclone[Running heads]{toc}{lorh}
\AtEndDocument{\listoflorh}

\usepackage{tocbasic}
\makeatletter
\AfterTOCHead[lorh]{
  \let\MakeUppercase\relax
  \value{tocdepth}=0
  \pagestyle{plain}
  \DeclareTOCStyleEntry[
    pagenumberbox=\@gobble,
    entryformat=\bfseries\Large
    ]{tocline}{chapter}%
}
\makeatother
\DeclareTOCStyleEntry[
  indent=0pt,
  beforeskip=3pt,
  level=0,
  numwidth=0pt
]{tocline}{rhverso}
\DeclareTOCStyleEntry[
  indent=5.5cm,
  beforeskip=3pt,
  level=0,
  numwidth=0pt
]{tocline}{rhrecto}

\usepackage{fancyhdr}
\pagestyle{fancy}
\renewcommand{\sectionmark}[1]{}
\renewcommand{\subsectionmark}[1]{\markright{\thesubsection. \MakeUppercase{#1}}}
\fancyhead{}
\fancyhead[LE]{\leftmark\addcontentsline{lorh}{rhverso}{\parbox[b]{5cm}{\protect\raggedright\leftmark}}}
\fancyhead[RO]{\rightmark\addcontentsline{lorh}{rhrecto}{\parbox[b]{5cm}{\protect\raggedright\rightmark}}}

\usepackage{blindtext}% only for dummy text
\begin{document}
\tableofcontents
\blinddocument
\blinddocument
\end{document}

or with scrlayer-scrpage instead fancyhdr:
\documentclass{book}
\usepackage{scrwfile}
\TOCclone[Running heads]{toc}{lorh}
\AtEndDocument{\listoflorh}

\usepackage{tocbasic}
\makeatletter
\AfterTOCHead[lorh]{
  \let\MakeUppercase\relax
  \value{tocdepth}=0
  \DeclareTOCStyleEntry[
    pagenumberbox=\@gobble,
    entryformat=\bfseries\Large
    ]{tocline}{chapter}%
}
\makeatother

\DeclareTOCStyleEntry[
  indent=0pt,
  beforeskip=5pt,
  level=0,
  numwidth=0pt
]{tocline}{rhverso}
\DeclareTOCStyleEntry[
  indent=5.5cm,
  beforeskip=5pt,
  level=0,
  numwidth=0pt
]{tocline}{rhrecto}

\usepackage{scrlayer-scrpage}
\automark[subsection]{chapter}
\ihead{%
  \headmark
  \ifodd\value{page}%
    \addcontentsline{lorh}{rhrecto}{\parbox[b]{5cm}{\protect\raggedright\headmark}}%
  \else
    \addcontentsline{lorh}{rhverso}{\parbox[b]{5cm}{\protect\raggedright\headmark}}%
  \fi
}

\usepackage{blindtext}% only for dummy text
\begin{document}
\tableofcontents
\blinddocument
\blinddocument
\end{document}


text:
Q: How to use Delayed Job to execute a method in a specific hour on Ruby on Rails? I have this method:
module ApplicationHelper
  class AtualizarBanco

    require 'open-uri'
    require 'nokogiri'
    require 'net/http'

    def updatetable
      retorno = Net::HTTP.get_response(URI.parse('http://www.olx.com.br/loja/id/174483'))

      if retorno.code == "200"
        site = open ('http://www.olx.com.br/loja/id/174483')
        site_lido = site.read
        site_html = Nokogiri::HTML(site_lido)

        vetor_preco = site_html.at_css('#main-ad-list').css('.item').css('.OLXad-list-price').map{|q| q.text.sub!(" R$ ", "").sub!(".", "").to_f}
        vetor_texto = site_html.at_css('#main-ad-list').css('.item').css('.OLXad-list-title').map{|lista| lista.text.strip}
        vetor_catg = site_html.css('#main-ad-list .OLXad-list-line-2').xpath('p[@class="text detail-category"]').map{|q| q.children.first.text.strip}
        vetor_img = site_html.css('#main-ad-list .OLXad-list-image-box').xpath('span|img[@class="image"]/@src|img[@class="image lazy"]/@data-original').map(&:text)

        i = 0
        if ((vetor_preco.length == vetor_texto.length) && (vetor_preco.length == vetor_catg.length) && (vetor_preco.length == vetor_img.length))
          while i < vetor_preco.length
            @prod = Produto.new(nm_produto: vetor_texto[i], preco: vetor_preco[i], categoria: vetor_catg[i], img_produto: vetor_img[i])
            i += 1
            if (@prod.valid?)
              @prod.save
            end
          end
        end
      end
    end

  end
end

And I want to execute this method everyday at 5:30 am GMT.
I did some searching, and I found out about the Delayed Job gem and the Cron scheduler, but it wasn't clear to me how I use them to do what I need.
Delayed Job works well on Rails 5.0.0.1 ?
on the documentation it talks about versions 3.0+ and 4.2, it wasn't clear to me if it is "4.2 and above" or just 4.2.
I also don't know if I call the Delayed Job gem with just gem 'delayed-job' or if I need to use gem 'delayed_job_active_record', or if I need to change the config.active_job.queue_adapter.
On the documentation, it also doesn't say if the :run_at parameter accept specific time commands, in the examples it has only things like "5 minuts from now" or "2 hours from now".
Any help ?

A: You can use gem whenever, replace your method from application_helper to rake task updatetable.rake e.g.
And your schedule will be as
every 1.day, at: '5:30 am' do
  rake 'atualizar_banco:updatetable'
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nested c-style loops in bash Can anybody explain why the following c-style loop in a bash script doesn't work as expected?
Script:
for ((i=0; i<3; i++))
do
    for ((j==0; j<3; j++))
    do
        echo "Iteration $i $j"
    done
done

Expected output:
Iteration 0 0
Iteration 0 1
Iteration 0 2
Iteration 1 0
Iteration 1 1
Iteration 1 2
Iteration 2 0
Iteration 2 1
Iteration 2 2

Observed output:
Iteration 0
Iteration 0 1
Iteration 0 2

This makes no sense to me. I guess the inner and outer loop "interfere" somwhow (very weirdly) with each other. Non-c-style for loops (with "in") do work as expected...
thanks
m.

A: yes, its because you wrote j==0 . hence only 1 iteration of the inner loop happens, because once j++ makes the value of j equal to 1, the equality j==0 is no longer true.

A: for ((j==0; j<3; j++))

is this a typo just here, or do you really test j for equality to 0? That would maybe explain it...


text:
Q: How to design a rank with flexbox and page controllview I'm trying to put the name's on the left and the rank on the right. I tryed the flexDirection row with a space between or space evenly but it still doesn't work.

Do you have any solution for that ?
Also my function :
 renderRanking = () => {
    return this.state.ranking.map((element) => {
      return (
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-'''',
          }}>
          <View style={{flex: 1}}>
            <Text style={{fontSize: 20, color: 'white'}}>{element.club}</Text>

            <Text style={{fontSize: 20, color: 'white'}}>
              {element.moyenne}
            </Text>
          </View>
        </View>
      );
    });
  };

And my render
render() {
    return (
      <SafeAreaView style={{flex: 1, backgroundColor: 'black'}}>
        <View style={{flex: 1, backgroundColor: 'black'}}>
          <ScrollView>
            <View
              style={{
                flex: 1,
              }}>
              <Text>{this.OpenDecibels()}</Text>
            </View>

            <View style={{paddingBottom: 30}}>
              <PageControlView defaultPage={1}>
                <View>{this.renderRanking()}</View>
              </PageControlView>
            </View>
          </ScrollView>
        </View>
      </SafeAreaView>
    );
  }
}

A: Try this way
<View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-'''',
          }}>
            <Text style={{fontSize: 20, color: 'white'}}>{element.club}</Text>

            <Text style={{fontSize: 20, color: 'white'}}>
              {element.moyenne}
            </Text>
</View>

A: You should try below snippet in your renderRanking function.
renderRanking = () => {
    return this.state.ranking.map((element) => {
      return (
          <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
            <Text style={{fontSize: 20, color: 'white'}}>{element.club}</Text>

            <Text style={{fontSize: 20, color: 'white'}}>
              {element.moyenne}
            </Text>
          </View>
      );
    });
  };

Also change
<PageControlView defaultPage={1}>
    <View>{this.renderRanking()}</View>
</PageControlView>

To
<PageControlView defaultPage={1}>{this.renderRanking()}</PageControlView>


text:
Q: Using jsoup to scrape after Login website I have some problem using Android-Studio jsoup while scrape Website with user login.
While my scraped result have not login successfully.
If successful scrape the website, it would like this.
Picture of Scrape successful
Reference video source:https://youtu.be/59NEPc9Ask4
Web source code of login
PICTURE
This is my code below.
MainActivity.java
public class MainActivity extends AppCompatActivity {
    private Button button;
    private Button button2;
    private TextView textView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.button);
        button2 = findViewById(R.id.button2);
        textView2 = findViewById(R.id.textView2);

        new doInBackground().execute();

    }

    String username = "xxxx@gmail.com";
    String password = "axxxxxx";

    public class doInBackground extends AsyncTask<Void, Void, Void> {
        ProgressDialog dialog;
        String str="";
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                Connection.Response response = Jsoup.connect("https://irs.zuvio.com.tw/irs/login")
                        .data("email",username,"password",password)
                        .method(Connection.Method.POST)
                        .ignoreContentType(true)
                        .execute();
                Map<String,String>coky=response.cookies();

                Document document = Jsoup.connect("https://irs.zuvio.com.tw/student5/irs/index")
                        .cookies(coky)
                        .get();
                str = document.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void unused) {
            super.onPostExecute(unused);
            dialog.dismiss();
            textView2.setText(str);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setTitle("Login...");
            dialog.setMessage("Please Wait");
            dialog.show();
        }
    }

But the result I scraped is empty.
Can anybody tell me how to deal with it?


text:
Q: Why can't I access hosts using command prompt? According to Wikipedia, the path to hosts is:
C:\System32\drivers\etc\hosts

However, when I tried to access the file, this error came up:

The system cannot find the path specified.

A: The hosts file is within your Windows folder: %SYSTEMROOT%\System32\drivers\etc.

A: This is one of the reasons why I do not trust Wikipedia with information involving syntax. Because if you notice the line that you posted the slash after the colon is incorrect (C:/). The correct way is like this: (C:\).
And also you are supposed to put START before the file so it will run. The file path is also incorrect.
The proper syntax is:
start C:\Windows\System32\drivers\etc\hosts

You may also need admin privileges to run this file.


text:
Q: Java object teardown pattern Is there any standard way/pattern to extract piecemeal information from an object ? Say I have a json string which contains few classes which I have to extract. I cannot directly extract it using jackson because there are few transformations that need to be done in order to get the required information (like decryption, uncompression etc..) and I am trying to see if I can hide all of these behind a class.
Here is how I am planning on doing it, is there a better way to achieve this ? just wanted an opinion.
public class ExtractInformation {
    private final Object1 obj1;
    private final Object2 obj2;
          ....
    private final Object3 objn;

    public ExtractInformation(String jsonString) {
        // Extract all the information here and store locally
        obj1 = ...;
        objn = ...;
    }

    public getObect1() {
        return obj1l;
    }

    public getObject2() {
        return obj12;
    }
           ...
    public getObjectn() {
        return obj1n;
    }
}

A: I would more or less agree, just by doing this this way you connect inseparably your domain class (which should not be named ExtractInformation!!!) with the way its data are stored in the json string. You may create 2 separate classes: MyClass (POJO, your domain class) and MyClassJsonExtractor (the class which will serve as a factory for MyClass). And use the Builder pattern for MyClass creation.
public class MyClass {
    private final Object1 obj1;
    private final Object2 obj2;
    private final Object3 obj3;

    private MyClass(MyClassBuilder builder) {
        this.obj1 = builder.obj1;
        this.obj2 = builder.obj2;
        this.obj3 = builder.obj3;
    }

    public getObj1() { return obj1; }
    public getObj2() { return obj2; }
    public getObj3() { return obj3; }

    public static class Builder {
        private final Object1 obj1;
        private final Object2 obj2;
        private final Object3 obj3;

        public Builder() {}

        public Builder setObj1(Object1 obj1) {this.obj1 = obj1; return this; }
        public Builder setObj2(Object2 obj2) {this.obj2 = obj2; return this; }
        public Builder setObj3(Object3 obj3) {this.obj3 = obj3; return this; }

        public MyClass build() {
            return new MyClass(this);
        }
    }

}

public class MyClassJSonExtractor {
    // make the as singleton, either by the old-fashioned way or by Spring
    public MyClass createMyClass(String jsonString) {
         return new MyClass.Builder().
             setObj1(...).
             setObj2(...).
             setObj3(...).
             build();
    }
}


text:
Q: Cómo encuentro donde está el error en un KB de Genexus 17? Parece compilar bien, pero al dar clic en "Reorganizar" arroja el siguiente error (estoy siguiendo el pdf "GeneXus17CoreCourse_PracticalExcercises_sp"):

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe" /nologo /p:Configuration=Release /p:FrameworkPath="C:\Windows\Microsoft.NET\Framework\v4.0.30319" /v:q /m  "C:\KB\Parks\Parks\CSharpModel\build\LastBuild.sln"
"C:\KB\Parks\Parks\CSharpModel\web\bin\reor.exe" -nogui
The last reorganization has failed and you are trying to execute a different reorganization
Unexpected errors may occur if you don't try to finalize previous reorganization before running this one
If you want to run this reorganization anyway, use '-ignoreresume' parameter in the Reorganization Options property of the generator
The reorganization process was not successfully completed.
Failed: Reorganization
error: Error in reorganization
Failed: Run Developer Menu

Lo ultimo que agregué fueron las siguientes reglas:
error("Debe ingresar el Nombre")
if EmployeeName.IsEmpty();
error("Debe ingresar el Apellido")
if EmployeeLastName.IsEmpty();
msg("Está dejando vacío el numero de celular")
if EmployeePhone.IsEmpty();
default(EMPLOYEEAddedDate, today());

A: El error que te está dando ocurre cuando pasa lo siguiente:

*

*Se hicieron cambios en la estructura de la base de datos

*Se mandó a correr la reorganización de la base pero en algún punto ésta falló

*Luego se hicieron más cambios en la estructura de la base de datos (agregar reglas en una trn no modifica la estructura de la base de datos)

*Se impacta y ahi se detecta que ahora hay una nueva reorg pero la anterior no había terminado con éxito

Agregar el argumento  -ignoreresume en las Reorganization Options del generador evita que se haga el chequeo pero la nueva reorg puede fallar pues la anterior no había terminado con éxito.
Si ésta es una KB de pruebas como parece entonces podrías en vez de impactar la base de datos recrearla (Build -> Create Database Tables).

A: Puedes probar agregando el parámetro -ignoreresume a las opciones de reorganización del generador:


text:
Q: Generator printing null before the intended output I've created a random word generator and it seems to work pretty well except for the fact that before the desired output, in the same line, it prints "null".
Here's my code:
import java.util.Random;

public class wordGenerator {

private static String r,s;

public static void randChar(int x) {

    Random rand = new Random();
    x = rand.nextInt((26 - 1) + 1) + 1;

    switch(x) {
    case 1: r = "a"; break;
    case 2: r = "b"; break;
    case 3: r = "c"; break;
    case 4: r = "d"; break;
    case 5: r = "e"; break;
    case 6: r = "f"; break;
    case 7: r = "g"; break;
    case 8: r = "h"; break;
    case 9: r = "i"; break;
    case 10: r = "j"; break;
    case 11: r = "k"; break;
    case 12: r = "l"; break;
    case 13: r = "m"; break;
    case 14: r = "n"; break;
    case 15: r = "o"; break;
    case 16: r = "p"; break;
    case 17: r = "q"; break;
    case 18: r = "r"; break;
    case 19: r = "s"; break;
    case 20: r = "t"; break;
    case 21: r = "u"; break;
    case 22: r = "v"; break;
    case 23: r = "w"; break;
    case 24: r = "x"; break;
    case 25: r = "y"; break;
    case 26: r = "z"; break;
    default: r = "|null|";
    }

    if(x != 1 && x != 5 && x != 9 && x != 15 && x != 21) {
        int h = rand.nextInt(4 - 0);
        if(h == 2) {
            int k = rand.nextInt(6 - 0);
            switch(k) {
            case 1: r = "a"; break;
            case 2: r = "e"; break;
            case 3: r = "i"; break;
            case 4: r = "o"; break;
            case 5: r = "u"; break;
            }
        }
    }

}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Random rand = new Random();
    int y = rand.nextInt((10 - 4) + 1) + 4;

    for(int z = 1; z < y; z++) {
        randChar(0);
        s = s + r;
    }

    System.out.println(s);
}

To me it seems fine, but when I think it should output something like

opfruvme

it prints

nullopfruvme

What's the problem?

A: You didn't initialize s.
private static String r,s="";

When you start your application in the loop the statement s = s + r; takes null value before concatenating with r in the first cycle. Initializing variable with empty string will give you result that you have been expected.

A: You didn't initialize s, so then the first time the s = s + r; line executes the current value of s (null) will be coerced to a String, so you will assign "null" + r to s.


text:
Q: Activity not opening from IntentService I got Push Notification in class GcmIntentService extends IntentService and I am trying to open my ActivityA from here.
It opens the activity when the app is closed, but it cannot open if my app is already running in the background.
Intent intent = new Intent(getApplicationContext(), ActivityA.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
        | Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT
        | Intent.FLAG_ACTIVITY_NEW_TASK
        | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
intent.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
        + WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
        + WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
        + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
        + WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getApplicationContext().startActivity(intent);

How to open ActivityA with interrupting background app?

A: I use BroadcastReceiver for handle message from gcm and start a intent from this class.
Try below code:
Intent notificationIntent = new Intent(context, CustomActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(notificationIntent);

It works fine with me.


text:
Q: What does SQLAlchemy all() return when there are no resuls I think I may be able to simplify this if .all() in SQLAlchemy returns an empty list if no results are found. Please advise:
@classmethod
def list_for(cls, account_id):
    result = list()
    rows = Session.query(UserAbility).filter_by(account_id=account_id)
    for row in rows:
        result.append(row.ability_id)
    return result

A: As the documentation says, all() returns the result of the query as a list. Therefore an empty result is returned as ...
Furthermore since you seem to use the IDs only, you can query UserAbility.ability_id, and do
return [i[0] for i in Session.query(UserAbility.ability_id).filter_by(account_id=account_id).all()]


text:
Q: Cucumber app with gradle runs fine locally but fails on Jenkins When i run my cucumber based project it behaves as though it cannot find the Steps classes - I can tell because the log on Jenkins is offering code snippets for implementation.
I'm using Gradle and I know there are issues with cucumber-jvm.
The relevant part of the build file:
task cucumber(type: JavaExec) {
    dependsOn assemble, compileTestJava
    main = "cucumber.api.cli.Main"
    classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
    args = ['-f', 'pretty', '--glue', 'steps', 'src/test/resources']
    systemProperties = System.getProperties()
}

I can't see why running the same command (./gradlew clean cucumber) via Jenkins fails?
Here's the output from Jenkins:
+ ./gradlew -Dapk=/Users/rakesh/workspace1/AcmeApp_4_10_Tiles/bin/AcmeApp_4_10_Tiles.apk clean cucumber
:clean
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:jar
:assemble
:compileTestJava
:cucumber
Feature: Thrid party request for the Landing page.
  TODO: additional requests for box connection
...

You can implement missing steps with the snippets below:

@Given("^the user chooses not to login$")
...

BUILD SUCCESSFUL

Total time: 8.074 secs
$ /Users/rakesh/Apps/adt-bundle-mac-x86_64-20131030/sdk/platform-tools/adb disconnect emulator-5812
[android] Stopping Android emulator
[android] Archiving emulator log
$ /Users/rakesh/Apps/adt-bundle-mac-x86_64-20131030/sdk/platform-tools/adb kill-server
Finished: SUCCESS

A: I would also like to mention that sometimes this problem occurs,if there are dependencies missing in build.gradle.
In my case,the following statement was missing in main task in build.gradle..
dependsOn assemble, compileTestJava

Adding this,resolved the issue.

A: I solved the problem and it had nothing to do with cucumber, gradle or Jenkins! I had renamed the steps classes (case change) which completely confused subversion and the java step classes were actually missing!!


text:
Q: Gitlab-ci-token user unable to clone repositories I am trying to setup a docker runner and successfully registered the runner with gitlab-ce. However, when the job runs it always fails with the follow:
Running with gitlab-ci-multi-runner 1.10.2 (d171b73)
Using Docker executor with image python:3.4 ...
Starting service postgres:latest ...
Pulling docker image postgres:latest ...
Waiting for services to be up and running...
Pulling docker image python:3.4 ...
Running on runner-b35ff618-project-96-concurrent-0 via toucan...
Cloning repository...
Cloning into '/builds/amrstratus/webportal'...
fatal: unable to access 'https://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx@gitlab.xxxxxxxxx/amrstratus/webportal.git/': Failed to connect to gitlab.xxxxxx port 443: Connection refused
ERROR: Build failed: exit code 1

I tried simply to clone the repository and got a similar error:
root@toucan:/tmp# git clone https://gitlab-ci-token:b35ff618453c702944c736668e1c2c@gitlab.xxxxxxxx/amrstratus/webportal.git/
Cloning into 'webportal'...
remote: HTTP Basic: Access denied
fatal: Authentication failed for 'https://gitlab-ci-token:xxxxxxxxxxx@gitlab.xxxxxxxx/amrstratus/webportal.git/'

Access via https seems to work fine and everything else seems to work.
Any ideas? I am totally stuck.
System Details:
Debian 8 (Jessie)
GitLab 8.16.2
GitLab Shell 4.1.1
GitLab Workhorse v1.3.0
GitLab API v3
Git 2.10.2
Ruby 2.3.3p222
Rails 4.2.7.1
PostgreSQL 9.6.1

A: Note that there might be two issue.
Regarding the token itself (and fatal: Authentication failed ), see this thread

The CI token is now securely generated for each build. It's available in $CI_BUILD_TOKEN.
  If you're cloning a different repository from .gitlab-ci.yml (like we were) your best bet is to use SSH.
Another solution is to use your personal private token:

git clone https://<username>:<private-token>@gitlab.anydomainhere.com/developers/<projectname>.git

(please realize this token gives access to all your projects)

The other issue is related to Docker: fatal: unable to access
You need to be sure you can communicate to your Gitlab instance (as in here or in issue 305).
And check the ownership as in this thread.

A: I know this is old, however, what fixed this issue for me was the adjustments to workhorse as per this comment.
Modified /etc/gitlab/gitlab.rb as follows:
Uncomment this line
gitlab_workhorse['enable'] = true

Add these 2 lines
gitlab_workhorse['listen_network'] = "tcp"
gitlab_workhorse['listen_addr'] = "127.0.0.1:8181"

Then modified the webserver config to point the reverse proxy to this instead of unicorn.

A: Although a solution is already been given for the problem but using the personal token.
As pointed out, it might be failing because if you cloned using the CI_BUILD_TOKEN/CI_JOB_TOKEN, that is only valid for that job run.
So, if you want the pull to work through the runner everytime, you can specify url while pulling :
git pull https://gitlab-ci-token:$CI_JOB_TOKEN@gitlab.anydomainhere.com/developers/<projectname>.git

This way, on every pull request, the new token is used.


text:
Q: OkHttp3 cache seems to be unchecked with Retrofit 2 I'm trying to setup an HTTP cache using Retrofit (2.1.0) and OkHttp (3.3.1). I have seen many posts related to this topic, but none of them helped.
I wrote some unit tests to see how the cache works. It works just fine, but once integrated in my app, the magic ends. I will first show you my implementation and then explain some of my investigation.
First, here is my Retrofit instantiation :
    OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);

    OkHttpClient client = httpBuilder
            .addNetworkInterceptor(INTERCEPTOR_RESPONSE_SET_CACHE)
            .addNetworkInterceptor(INTERCEPTOR_REQUEST_ADD_CHECKSUM)
            .addInterceptor(loggingInterceptor)
            .cache(cacheHttpClient).build();

    Retrofit retrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .baseUrl(BASE_URL)
            .build();

Here is the interceptor adding a header to set cache control:
    private final Interceptor INTERCEPTOR_RESPONSE_SET_CACHE = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            response = response.newBuilder()
                    .header("Cache-Control", "max-age=600") //+ Integer.toString(3600 * 5)
                    .build();
            return response;
        }
    };

The last interceptor adds 2 URL parameters:
 private static final Interceptor INTERCEPTOR_REQUEST_ADD_CHECKSUM = new Interceptor() {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            HttpUrl url = chain.request().url();
            url = url.newBuilder().addQueryParameter("rd", "random1").addQueryParameter("chk","check1").build();
            Request request = chain.request().newBuilder().url(url).build();
            return chain.proceed(request);
        }
    };

Finally, the single method of my service :
 @Headers("Cache-Control: public, max-stale=500")
 @GET("/get_data")
 Call<DataResponse> getData(@Query("year") int year, @Query("month") int month, @Query("day") int day);

About my investigation, I setup an interceptor logger (app side, not network) to see what is happening. I can see lines such as "Cache-Control: public, max-stale=500" in my logs. This means (at least to me) that the header should give an opportunity to the OkHttp client to check the cache.
The cache itself seems to be correctly initialised. When I create it, I force the initialisation and log all the urls present in the cache. Here is how it is implemented:
File httpCacheDirectory = new File(getCacheDir(), "responses");
        httpCacheDirectory.getParentFile().mkdirs();
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache cache = new Cache(httpCacheDirectory, cacheSize);
        try {
            cache.initialize();
            Iterator<String> iterator = cache.urls();
            Log.i(TAG, "URLs in cacheHttpClient : ");
            while (iterator.hasNext()) {
                Log.i(TAG, iterator.next());
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.i(TAG, "CACHE NOT INIT");
        }

When I launch my app with Wifi available, I get the expected responses. Then I kill my app, disable Wifi and relaunch the app. I expect the cache to serve data at this moment. But it fails and I can only see OkHttp printed lines in logs :

HTTP FAILED: java.net.UnknownHostException: Unable to resolve host
  "my-domain.com": No address associated with hostname

Last thing, in RFC 2616, one can read :

max-stale : Indicates that the client is willing to accept a response
  that has exceeded its expiration time. If max-stale is assigned a
  value, then the client is willing to accept a response that has
  exceeded its expiration time by no more than the specified number of
  seconds. If no value is assigned to max-stale, then the client is
  willing to accept a stale response of any age.

When I don't specify an value, it actually works (I get a response even when the Wifi is down). For now this is the only way I found to make it "work". So maybe I just misunderstand the cache-control directive !?
At this point I'm really confused. I really would like to be able to use OkHttp cache system, but somehow I'm missing something.
Thank you for reading all that text !

A: Use this method to create cached okkhttpclient
private OkHttpClient createCachedClient(final Context context) {
        File httpCacheDirectory = new File(context.getCacheDir(), "cache_file");

        Cache cache = new Cache(httpCacheDirectory, 20 * 1024 * 1024);
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setCache(cache);
        okHttpClient.interceptors().add(
                new Interceptor() {
                    @Override
                    public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        String cacheHeaderValue = isOnline(context)
                                ? "public, max-age=2419200"
                                : "public, only-if-cached, max-stale=2419200" ;
                        Request request = originalRequest.newBuilder().build();
                        com.squareup.okhttp.Response response = chain.proceed(request);
                        return response.newBuilder()
                                .removeHeader("Pragma")
                                .removeHeader("Cache-Control")
                                .header("Cache-Control", cacheHeaderValue)
                                .build();
                    }
                }
        );
        okHttpClient.networkInterceptors().add(
                new Interceptor() {
                    @Override
                    public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        String cacheHeaderValue = isOnline(context)
                                ? "public, max-age=2419200"
                                : "public, only-if-cached, max-stale=2419200" ;
                        Request request = originalRequest.newBuilder().build();
                        com.squareup.okhttp.Response response = chain.proceed(request);
                        return response.newBuilder()
                                .removeHeader("Pragma")
                                .removeHeader("Cache-Control")
                                .header("Cache-Control", cacheHeaderValue)
                                .build();
                    }
                }
        );
        return okHttpClient;
    }

    private boolean isOnline(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }
        return false;

        }

Call createCachedClient() method to create OkHttpClient add this client to retrofit
OkHttpClient okHttpClient = createCachedClient(MainActivity.this);
Retrofit retrofit=new Retrofit.Builder()
         .client(okHttpClient)
         .baseUrl(API)
         .addConverterFactory(GsonConverterFactory
         .create()).build();

Add this permission to manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

If internet is available first time it will call the service and cache the request,next time onwards upto 2419200 milliseconds it will use cache to give response.it won't hit server upto 2419200 milliseconds even if device if offline.


text:
Q: Alternative to geom_flag (ggflags) I've noticed that the {ggflags} package is no longer supported in R. Does anybody know if there's an alternative for plotting points as country flags as it could've been done with geom_flag?

A: ggflags has never been officially supported (meaning available on a formal archive like CRAN) - it's a package in github, basically in eternal development.
There are two versions of ggflags around: One with round flags (https://github.com/jimjam-slam/ggflags) and one with rectangle flags (https://github.com/ellisp/ggflags).
Your options: you could fork into that repository in github and update it to work for later versions of R, e.g. with a pull request or you just keep your own version of it. This certainly requires a certain knowledge of how to write packages (I've learned that with Hadley's help: https://r-pkgs.org/). You will do the community a great service, I honestly encourage you to do so:)
Or, if you feel open for some risks, you could download the package and just update the description file by removing unwanted dependencies. Code might fail, but there is a chance that it will work. Don't worry, you won't kill your computer doing that.
https://stackoverflow.com/a/30564896/7941188 tells you how to do this.


text:
Q: How to define an abstract (opaque) interface for a polymorphic object type? ReasonML
module type T = {
  type t('a); // Does not work
  type b; // Works
};

module A: T = {
  type t('a) = {.. b: bool} as 'a;
  type b = bool;
};
module B: T = {
  type t('a) = {.. c: int} as 'a;
  type b = int;
};

Ocaml
module type T  = sig
  type 'a t /* Doesn't work */
  type b /* Works */
end
module A : T = struct type 'a t = < b :bool  ;.. > as 'a
                      type b = bool end
module B : T = struct type 'a t = < c :int  ;.. > as 'a
                      type b = int end

How can I define the module type A t('a) so that it is abstract but compatible with the open polymorphic object types in the implementations?

A: It is not clear if it is really useful but you need to add the constraint explicitly in the module type:
module type TA  = sig
  type 'a t constraint 'a = < b:bool; .. >
end
module A : TA = struct
  type 'a t = < b :bool  ;.. > as 'a
end

A: Types <b : bool; .. > and <c : int; ..> are not compatible much like int and bool are not compatible. In other words, if we will put row polymorphism aside, and focus on simple type constructors, then you're trying to define an interface that matches type int and bool and nothing else, aka bounded polymorphism.
It is also important to understand that subtyping is not inheritance. In your case, you have two classes of objects, the b-class objects that have method b
class virtual b = object
  method virtual b : bool
end

and the c- class of objects that have method c,

class virtual c = object
  method virtual c : int
end

and we can define a class of objects bc that have both methods, naturally via inheritance,
class virtual bc = object
  inherit b
  inherit c
end

Now, let's cooks some objects to play with,
let b : b = object method b = true end
let c : c = object method c = 42 end
let bc : bc = object
  method b = false
  method c = 56
end

We can see that despite that bc class type is defined as inherited from b and c we can't coerce b to c,
# (b : b :> bc);;
Line 1, characters 0-13:
1 | (b : b :> bc);;
    ^^^^^^^^^^^^^
Error: Type b = < b : bool > is not a subtype of bc = < b : bool; c : int >
       The first object type has no method c

and this makes perfect sense since we're trying to downcast an object of the base class to an object of the derived class, which is an illegal operation. Therefore, when you have a hierarchy of class types ordered by inheritance, the base classes are super types and the derived classes are subtypes. E.g., if v inherits from u then v is a subtype of u,
v inherits-from u
-----------------
   u :> v

Once you get a clear understanding of this, you can design a proper interface.


text:
Q: Why is char* not copying into the vector but string is copied? Okay, I'm trying to figure out an issue, when I try this code below:
#include <iostream>
#include <vector>
#include <stdint.h>
#include <string>
#include <Windows.h>
using namespace std;

int main(){
    vector<char*> v;
    char s[10];
    std::cout << "Enter Values :\n";
    for (int i = 0; i<5; i++){
        cin >> s;
        v.push_back(s);
    }

    std::cout << "\n\n\nPrinted Values :\n";
    for (auto ss : v){
        cout << ss << "\n";
        cout << "------------\n";
    }
    system("pause");
    return 0;
}

This is the output I received:
Enter Values :
aaaa
ssss
ddddd
ffff
errrr

Printed Values :
errrr
------------
errrr
------------
errrr
------------
errrr
------------
errrr
------------

But now I changed "char*" to "string":
#include <iostream>
#include <vector>
#include <stdint.h>
#include <string>
#include <Windows.h>
using namespace std;

int main(){
    vector<string> v;
    string s;
    std::cout << "Enter Values :\n";
    for (int i = 0; i<5; i++){
        cin >> s;
        v.push_back(s);
    }

    std::cout << "\n\n\nPrinted Values :\n";
    for (auto ss : v){
        cout << ss << "\n";
        cout << "------------\n";
    }
    system("pause");
    return 0;
}

Now, it stores all of it into the vector:
Enter Values :
aaaa
ssss
ddddd
ffff
errrr

Printed Values :
aaaa
------------
ssss
------------
ddddd
------------
ffff
------------
errrr
------------

My question, is why char* doesn't get stored in the vector but string is being stored in the vector ?

A: Because a vector of char* will store character pointers (memory addresses of the first char of your character array s), not the characters themselves. The only place that stores the chars is your array s itself. But that's continuously overwritten by the <<. Since s is defined only once, it has only one, unique address, and your whole vector will just contain pointers with that same address value.
Note that in C++ the name of an array (also a char array) is converted to a pointer to its first element.


text:
Q: Git grep syntax with square brackets Why does git log --grep=\[92\] match the commit with the following message:
Author: Aston, Ben (Foo-UK) <Ben.Aston@foo.co.uk>
Date:   Wed May 23 12:56:23 2012 +0000

[83] Favourites icon addition for release. <BA>

git-tfs-id: [http://fooppp012v:8080/tfs/TFS2010%20Collection]$/Foo/DnR;C210630

It seems that the correct regular expression format is not what I think?

A: Go with git log --grep=\\[92\\]. Now you get it, right? :)

A: The following worked for us:
git log --grep='\[92\]'


text:
Q: Understanding a proof in Milne's 'Field and Galois Theory' Let $G = \{ \sigma_1, \dots , \sigma_m \} \ (\sigma_1 = e) $ be a finite group of automorphisms of a field $E$, and let $F$ be the fixed field of $G$. Then $[E:F] \leq (G:1)$.
I will omit most of the proof, which I understand. It's just the conclusion that excapes me and I'm sure its something sill that I'm missing.
We choose $\alpha_1, \dots, \alpha_n \in E$, where $n>m$....
After a while we conclude that there are non-trivial $c_1, \dots, c_n \in F$ such that $\alpha_1 c_1 + \dots + \alpha_n c_n = 0$. It's not stated, but this implies that $[E:F] \leq n$, yes? But how does this imply that $[E:F] < m$? I feel like I'm taking crazy pills!
For reference the full proof is Theorem 3.4 on page 36.
http://www.jmilne.org/math/CourseNotes/FT.pdf

A: This shows that for any $n > m$ and any $\alpha_1,\dots,\alpha_n\in E$, the $\alpha_i$ are linearly dependent over $F$. Hence, for a set $\{\alpha_i\mid i = 1,\dots, j\}\subseteq E$ to be linearly independent over $F$ (in particular, if we want the set $\{\alpha_i\}$ to have a chance to be a basis for $E/F$), we must have $j\leq m$, so that $[E : F]\leq m$.

A: The point of this is to show that $(\alpha_1,\dots,\alpha_n)$ is always $F$-linearly independent for any $(\alpha_1,\dots,\alpha_n)\in E^n$ for any $n>m$, I think you agree with me when I say that this is what has been proven.
The implicit conclusion (to show that $n:=[E:F]\leq m$) is to take a base $(\beta_1,\dots,\beta_n)$ of $E$ over $F$. If $n>m$ then $(\beta_1,\dots,\beta_n)$ cannot be linearly independent by what has already been done so it is not a base, whence $n\leq m$.


text:
Q: Get tabledata from webpage into Excel using macro I use a Excel sheet to do some calculation, like assessment of incometax returns. I need to pull data from website into Excel sheet. I successfully did it by using VBA step by step

*

*Create internet explorer application in VBA

*Navigate to website url and login

*Fill a form automatically by a unique id already in my Excel sheet

*Now submit form and result page has data in table form

*Now by using getelementsbyid("tableid") I copied and pasted data in excel sheet.

My question

*

*All tables  don't have id or name

*There is lot of tables

Now I want to pull data from a table without id which is third table from top. How to do this? I tried hard. I don't want  all tables because rows in these tables always changed so when I copy all tables data.

A: Start macro recording, go to Data -> From Web, open the required web page in the import dialog, select the required table, set all import options as needed, and import the data. Then stop recording.
You will get a boiler plate with auto generated macro code, then it will be trivial to fine turn it to your needs.
I did it many times and this is so easy that I haven't stored a snipped to share with you right now.
Update: this is how to import you question from this page
Sub Macro1()
'
' Macro1 Macro
'

'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "URL;http://stackoverflow.com/questions/18158928/get-tabledata-from-webpage-into-excel-using-macro/18160278#18160278" _
        , Destination:=Range("$A$1"))
        .Name = "18160278#18160278"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlOverwriteCells ' adjust this setting to your needs
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .WebSelectionType = xlSpecifiedTables
        .WebFormatting = xlWebFormattingNone
        .WebTables = "1" ' this is the number of the required table on a page
        .WebPreFormattedTextToColumns = True
        .WebConsecutiveDelimitersAsOne = True
        .WebSingleBlockTextImport = False
        .WebDisableDateRecognition = True
        .WebDisableRedirections = False
        .Refresh BackgroundQuery:=False
    End With
End Sub


text:
Q: ZL30251 phase aligned I just want to confirm whether the part zl30251 has phase aligned outputs? If not, can it be aligned?
Also, I can confirm that both the outputs are LVCMOS.
Can you please help me with this?
Also, i searched that the other part dsc2311 also has similar features.
But I cannot confirm from the datasheet that the clock outputs are LVCMOS. But I can see the outputs are phase aligned.
Can you help me?


text:
Q: "String" and "int" type dictionary compare with "Unicode" type dictionary I have three text files.
The one (zoo.txt) looks like this:
{'cow':'113', 'cat':'50', 'dog':'100', 'IDnumber':'113.1.22', 'type':'3'}

And it reads by json function:
file_open = open('zoo.txt', 'r')
zoo_animal = file_open.read()
zoo_animal = json.loads(zoo_animal)

And after the function, the output like this:
{u'cow':u'113', u'cat':u'50', u'dog':u'100', u'IDnumber':u'113.1.22', u'type':u'3'}

The other one is in_range.txt, it means the value of key in zoo.txt must match in this standard range.
The in_range.txt looks like:
cow 1 150
cat 0 25
dog 0 50

And it reads by with function:
with open('in_range.txt', 'r') as g:
for line in g:
    spliteLineR=line.split()
    in_range[str(spliteLineR[0])]=[int(spliteLineR[1]),int(spliteLineR[2])]

The output is:
{'cow':[1,150], 'cat':[0,25], 'dog':[0,50]}

The third text file is single_value.txt, it means the value of key in zoo.txt must equal to standard value.
The single_value.txt looks like:
IDnumber 1.8.70
type 1

And also it reads by with function:
with open('single_value.txt', 'r') as f:
    for line in f:
        spliteLineS=line.split()
        single_value[str(spliteLineS[0])]=str(spliteLineS[1])

The output is:
{'IDnumber':'1.8.70', 'type':'1'}

My question is:

*

*Do I need to transfer all type(str, int and unicode) to unicode or str then compare? because I use mathematical operators(<, ==, >) to compare directly, it can not get right answer.

*If I need to transfer the type, how to do it?

Please give me a hand~ thank you very much~

A: No, you don't need to convert the ASCII strings to Unicode or vice versa, because ASCII is a subset of Unicode, so they behave sensibly when you do equality tests, eg
print('cow' == u'cow')

output
True

That code will work correctly in Python 2 or Python 3.
However, you do have to convert those numeric strings to a numeric type to perform numeric comparisons. Here's a short demo.
from __future__ import print_function

zoo_animal = {
    u'cow':u'113', u'cat':u'50', u'dog':u'100',
    u'IDnumber':u'113.1.22', u'type':u'3',
}
in_range = {'cow':[1, 150], 'cat':[0, 25], 'dog':[0, 50]}

for key in zoo_animal:
    if key in in_range:
        lo, hi = in_range[key]
        val = int(zoo_animal[key])
        print(key, val, lo <= val <= hi)

output
cow 113 True
cat 50 False
dog 100 False

Once again, that code works on both Python 2 and Python 3.


text:
Q: Mac and Windows backup I have a Mac and a PC at home, and I am thinking of getting a NAS like (GoFlex Home Network Storage System or Western Digital My Book Live) to back up both machines.
If I were to use Time Machine to backup on the NAS system, would the Windows be able to backup to the same NAS? If you know of any good ways to backup both PC and Mac, do let me know as well.

A: One easy way to do this would have separate shares: one for Time Machine to back up your Macs and another for another program to back up your PCs.
(The shares could be separate partitions or separate folders on a single partition; it depends on how your NAS is set up.)


text:
Q: Order data inside a geom_tile i have a data frame and i want to generate a geom_tile() plot from it , but I want the graph to be ordered not based on the alphabetic but based on a variable inside this data frame.
structure(list(V1 = c("a", "y", "w", "p", "v", "h", "i"),
    V2 = c("r", "w", "q", "m", "l", "q", "g"), V3 = c(
    "5", "2", "9", "2", "1", "3", "0")), .Names = c("V1", "V2",
"V3"), class = "data.frame", row.names = c(NA, -8L))

I want to order the plot based in the variable V3 , because the normal plotting will order them based on the alphabetic in V1 and V2 .
How this can be done ??

A: I usually try to use levels to fix my data before hand:
x <- structure(list(V1 = c("a", "y", "w", "p", "v", "h", "i"),
    V2 = c("r", "w", "q", "m", "l", "q", "g"), V3 = c(
    "5", "2", "9", "2", "1", "3", "0")), .Names = c("V1", "V2",
"V3"), class = "data.frame", row.names = c(NA, -8L))

x <- x[1:7,]

x$V1 <- factor(x$V1, levels=(x$V1)[order(x$V3)])

# Note it's not an ordered factor, it's a factor in the right order

ggplot(x, aes(V1, V3)) + geom_tile()

UPDATE:
Still not exactly clear on your dimensions, but perhaps something like:
x$V2 <- factor(x$V2, levels=(x$V2)[order(x$V3)])

ggplot(x, aes(V1,V2,fill=V3)) + geom_tile()

A: As an answer to the duplicate question, here's a solution that uses ggplot directly and does not require changing the data.
x <- structure(list(V1 = c("a", "y", "w", "p", "v", "h", "i"),
                    V2 = c("r", "w", "q", "m", "l", "q", "g"),
                    V3 = c( "5", "2", "9", "2", "1", "3", "0")),
               .Names = c("V1", "V2", "V3"), class = "data.frame",
               row.names = c(NA, -8L))

x <- x[1:7,]

ggplot(x, aes(V1, V2, fill=V3)) + geom_tile() +
  scale_x_discrete(limits=(x$V1)[order(x$V3)]) +
  scale_y_discrete(limits=(x$V2)[order(x$V3)])


text:
Q: Compiling C++ programs Should I use Visual C++ Express to write and compile or should I write in Notepad++ and compile it? I like using Notepad++ because of its clean interface and speedy start-up as compared to Visual which is a considerably heavier program.
If I do write in Notepad++ how do I compile it using Visual?

A: Can just compile via the command-line.

A: Visual Studio has intellisense, which makes coding a LOT easier. I mean, there's really no comparison.

A: For successful developing in C++, you need much more than just compiling:

*

*linking

*"solution" management(to a project usually belongs more than 1 file)

*resource  management (for icons, bmp menu etc..)

*debugging

*easy jumping into functions/classes

*intellisense (autocompletion for method/classes)

You will make more errors, produce worse code and will learn slower, if you use a simple texteditor.
Do yourself a favor and start with visual studio (or any other IDE).
Later you can easily switch back to the basics (I doubt you will do that).

A: While it is possible to do all your work from the command line, it is easier to use Visual Studio's UI.  It provide intellisense, easy configuration, integrated source debugging, searching, etc.  Unless you are already an expert, I wouldn't recommend it.
If you are and you really want to use Notepad++, I would suggest using the Windows Platform SDK for a build environment (compiler + linker), and WinDbg for your debugger.

A: You can open up visual studio command prompt and run the command 'cl filename.c' to compile your program. However, this will help you only compile your program. If you want to debug it, you will have to open up a project under Visual Studio.

A: Notepad++ has less sophisticated tools management than some other text editors. For freely available alternatives, consider PSPad or ConTEXT. For paid alternatives, UltraEdit and EditPad Pro are nice.
All of them allow you to easily configure multiple external tools for compiling, building, etc.

A: If you really want to you can use both: you can let any solution item open in Npp: select 'Open With', then select to open the file with Npp and set this as default. This way, you'd use Npp for your editing needs, and still let VS manage the compiling/linking/.. No command line fiddling required.
That said, I use Npp as well, but apart from it's speed it's capabilities are nowhere near what VS offers, nor it's as customizable, and you can easily have VS look as clean as Npp.


text:
Q: What version of texlive is arXiv running? What version of texlive is arxiv running?
I was surprised I could not find a clear statement of this on the website.
I think it is still 2011?

A: As of February 10, 2017, new submissions (and replacements of old submissions) are now compiled with texlive 2016.
(Even current biblatex (3.7) with biber (2.7) is supported, if you upload the bbl file generated by biber. Be aware that bbl is version specific, so this will not work if your biber is not up-to-date or if you update it later on.)

A: At the moment (May 6th, 2022) arxiv is using TeXLive 2020, but this can change every couple of years. You can check which TeXlive version arxiv is using right now here: https://arxiv.org/help/faq/texlive (This website looks as if arxiv is going to keep it up to date in the future, since they have updated it already in the past)


text:
Q: How to increase UIView height which contains UIStackView I have a custom view which contains a label, label can have multiple line text. So i have added that label inside a UIStackView, now my StackView height is increasing but the custom view height doesn't increases. I haven't added bottom constraint on my StackView. What should I do so that my CustomView height also increases with the StackView.
 let myView = Bundle.main.loadNibNamed("TestView", owner: nil, options: nil)![0] as! TestView
    myView.lbl.text = "sdvhjvhsdjkvhsjkdvhsjdvhsdjkvhsdjkvhsdjkvhsjdvhsjdvhsjdvhsjdvhsjdvhsjdvhsjdvhsdjvhsdjvhsdjvhsdjvhsdjvhsjdvhsdjvhsdjvhsjdvhsdjvhsjdvhsdjvhsdjvhsdjvhsjdv"
    myView.lbl.sizeToFit()
    myView.frame = CGRect(x: 10, y: 100, width: UIScreen.main.bounds.width, height: myView.frame.size.height)
    myView.setNeedsLayout()
    myView.layoutIfNeeded()

    self.view.addSubview(myView)

I want to increase my custom view height as per my stackview height.
Please help.

A: Example of stackView constraints with its superview.
Also superview should not have constraints for its height.

A: You should set the top and bottom anchors of your custom view to be constrained to the top and bottom anchors of your stackview.  As your stackView grows, it will push that bottom margin along.  Here's a programmatic example:
//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {

    private lazy var stackView = UIStackView()
    private lazy var addLabelButton = UIButton(type: .system)

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let stackViewContainer = UIView(frame: view.bounds)
       stackViewContainer.backgroundColor = .yellow
        stackViewContainer.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackViewContainer)
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.axis = .vertical

        addLabelButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(addLabelButton)
        stackViewContainer.addSubview(stackView)

        NSLayoutConstraint.activate([
            // Container constrained to three edges of its superview (fourth edge will grow as the stackview grows
            stackViewContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            stackViewContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            stackViewContainer.topAnchor.constraint(equalTo: view.topAnchor),

            // stackView constraints - stackView is constrained to the
            // for corners of its contaier, with margins
            {
                // Stackview has a height of 0 when no arranged subviews have been added.
                let heightConstraint = stackView.heightAnchor.constraint(equalToConstant: 0)
                heightConstraint.priority = .defaultLow
                return heightConstraint
            }(),
            stackView.topAnchor.constraint(equalTo: stackViewContainer.topAnchor, constant: 8),
            stackView.leadingAnchor.constraint(equalTo: stackViewContainer.leadingAnchor, constant: 8),
            stackView.trailingAnchor.constraint(equalTo: stackViewContainer.trailingAnchor, constant: -8),
            stackView.bottomAnchor.constraint(equalTo: stackViewContainer.bottomAnchor, constant: -8),

            // button constraints
            addLabelButton.topAnchor.constraint(equalTo: stackViewContainer.bottomAnchor, constant: 8),
            addLabelButton.centerXAnchor.constraint(equalTo: stackViewContainer.centerXAnchor)
            ])

        addLabelButton.setTitle("New Label", for: .normal)
        addLabelButton.addTarget(self, action: #selector(addLabel(sender:)), for: .touchUpInside)
        self.view = view
    }

    private(set) var labelCount = 0

    @objc func addLabel(sender: AnyObject?) {
        let label = UILabel()
        label.text = "Label #\(labelCount)"
        labelCount += 1
        stackView.addArrangedSubview(label)
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

Note that when the UIStackView is empty, its height is not well defined.  That is why I set its heightAnchor constraint to 0 with a low priority.

A: First of all you should add bottom constraint on your UIStackView. This will help auto layout in determining the run time size of UIStackView.
Now create instance of your custom UIView but do not set it's frame and add it to UIStackView. Make sure you Custom UiView has all the constraints set for auto layout to determine it's run time frame.
This will increase height of both UIView and UIStackView based on content of UIView elements.
For more details you can follow my detailed answer on this at https://stackoverflow.com/a/57954517/3339966


text:
Q: Selenium WebDriver ruby accessing span value What is the best way to to select this element using Selenium WebDriver?
I am trying to access the  element through the class mapResultNumber. This is the actual HTML:

4

A: You could use xpath = //div[@class='mapResultNumber']/span

A: Using a css selector is a more readable way:
element = @driver.find_element(:css => "div.mapResultNumber span")

*

*A dot (period) after a tag indicates the class to select.

*A single space after the first selector (i.e. "div.mapResultNumber") indicates the next tag will be found inside the previous

*You could also use div.mapResultNumber > span to indicate that the span tag is found directly beneath the div


text: Q: Multiple Seek bars for videoJS I am using videojs in my ReactJS application. I am showing markers on seek bar of videojs. Is it possible to have multiple seek bars out side video js so that I can control each seek bar separately and play video from any of them. If yes, then how to show multiple  seekbars? Is there any library already available?


text:
Q: PHP - MySQL - AJAX and Google chrome - Endless loop responses and other errors I'm making a user registration form in PHP - MYSQL, AJAX jQuery and Codeigniter and loading the web page of records, Google chrome console launches a series of unlimited answers every second, the image here.

Note: There are also some slightly unusual behavior in Google Chrome I want to know the reason to solve them.
Selection in yellow: the answers are automatically generated limitless.
Selection in purple: Are the result or answer to that selected answer.
Selection Green: Other errors that I would like to know to be.
Code HTML:

Upload file content ajax

  <form action="" method="POST" id="form_file" name="form_file" enctype="multipart/form-data">

      <input type="file" name="imagex" id="imagex">

    <button type="submit" id="btn_form" class="btn btn-primary">Subir imagen</button>

  </form>

Code AJAX:
$(function() {

    //Empty content alert message
    $('.alert .close').on('click', function(event) {
      event.preventDefault();
      $('.alert .msg').html('');
    });

    $('#form_file')
        .formValidation({
            framework: 'bootstrap',
            icon: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                imagex: {
                    validators: {
                        notEmpty: {
                            message: 'Obligatorio!'
                        },
                        file: {
                            extension: 'jpg,jpeg,png',
                            type: 'image/jpg,image/jpeg,image/png',
                            //maxSize: 9097152,   // 2048 * 1024
                            message: 'imagen no válida ( JPG, JPEG, PNG ) | Max 9MB'
                        }
                    }
                }
            }
        })
        .on('success.form.fv', function (e) {
            // Prevent form submission
            e.preventDefault();

            var $form    = $(e.target),
                fv       = $form.data('formValidation'),
                formData = new FormData(),
                params   = $form.serializeArray(),
                files    = $form.find('[name="imagex"]')[0].files;

            $.each(params, function (i, val) {
                formData.append(val.name, val.value);
            });

            formData.append('imagex', files[0]);
            formData.append('id', Math.random());

            $.ajax({
                //Star preloader
                xhr: function () {
                var xhr = new window.XMLHttpRequest();
                    xhr.upload.addEventListener("progress", function (evt) {
                        if (evt.lengthComputable) {
                            var percentComplete = evt.loaded / evt.total;
                            //Convertimos el porcentaje en valor entero
                            var porcentageRound = percentComplete * 100;
                            //Mostramos la ventana modal
                            $('#modal_progress').modal('show');
                            //Limpiamos el área de mensaje en caso de que tenga información
                            $('#form_file #mensaje_status').html('');
                            //Width bar progress
                            $('.progress-bar').css({
                                width: percentComplete * 100 + '%'
                            });
                            $(".progress-bar").html('
' + Math.round(porcentageRound) +' %
');
                            //Ocultamos el loader
                            if (percentComplete === 1) {
                              //Podemos manipular los elementos del DOM
                              //Ocultamos la barra de progreso
                              $('.progress').addClass('oculto');
                              //Reseteamos la barra de progreso
                              $('.progress-bar').css('width', '0%');
                              //Mostramos un mensaje mientra recibimos respuesta del servidor
                              $('#modal_progress .mensaje').html(' Procesando espere por favor!');
                            }
                        }
                    }, false);

                    return xhr;
                },
                url: '/upload_ajax_full/do_upload/',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function (data) {

                  var data = $.parseJSON(data);

                  if (data.respuesta == true) {
                    //Limpiamos el área de mensaje en caso de que tenga información
                    $('#form_file #mensaje_status').html('');
                    //Cerramos la ventana modal
                    $('#modal_progress').modal('hide');
                    //Habilitamos la barra de progreso
                    $('.progress').removeClass('oculto');
                    //Limpiamos mensaje
                    $('#modal_progress .mensaje').html("");
                    //Limpiamos el campo de imagen
                    $('#imagex').replaceWith($('#imagex').clone( true ));
                    //Mostramos mensaje del servidor
                    $('#form_file #mensaje_status').append(data.mensaje);

                  }

                  if (data.respuesta == false) {
                    //Limpiamos el área de mensaje en caso de que tenga información
                    $('#form_file #mensaje_status').html('');
                    //Cerramos la ventana modal
                    $('#modal_progress').modal('hide');
                    //Habilitamos la barra de progreso
                    $('.progress').removeClass('oculto');
                    //Limpiamos mensaje
                    $('#modal_progress .mensaje').html("");
                    //Limpiamos el campo de imagen
                    $('#imagex').replaceWith($('#imagex').clone( true ));
                    //Mostramos mensaje del servidor
                    $('#form_file #mensaje_status').append(data.mensaje);

                  }

                  // You can reset the form if you want
                  fv.resetForm(true);

                  // You can enable the submit button
                  // to allow the user to add new record
                  fv.disableSubmitButtons(true);
                }
            });
        });

});


text:
Q: Login do Google Sign In não funciona nos navegadores Edge e Opera, mais funciona o Google Chrome e Mozilla Olá pessoal esse é o erro que tenho quando clico no botão de Login do Google nos navegadores Opera e Edge.
O mais estranho que os erros não aparecem no Mozilla e Google Chrome, no Chrome e Mozilla loga de primeira vai normal.

Meu código javascript

function onSignIn(response) {
    console.log("1");
    // Conseguindo as informações do seu usuário:
    var perfil = response.getBasicProfile();

    // Conseguindo o ID do Usuário
    var userID = perfil.getId();

    // Conseguindo o Nome do Usuário
    var userName = perfil.getName();

    // Conseguindo o E-mail do Usuário
    var userEmail = perfil.getEmail();

    if(userEmail != ""){
            botaoDeDeslogar(); //aparece o botao de deslogar
            botaoDeLogar();  //esconde o botao de logar
        }

    if(userEmail == ""){

        }
    // Conseguindo a URL da Foto do Perfil
    var userPicture = perfil.getImageUrl();

    //document.getElementById('user-photo').src = userPicture;
    //document.getElementById('user-name').innerText = userName;
    //document.getElementById('user-email').innerText = userEmail;

    // Recebendo o TOKEN que você usará nas demais requisições à API:
    var LoR = response.getAuthResponse().id_token;
    console.log("Token: " + LoR);

};

$('#google_plus_a').on('click', function (e) {
    console.log("2");
    e.preventDefault();
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
        console.log("3");
        console.log('User signed out.');
    });
});

Tambem ja tentei assim

//---------------------------------------------------------------------------------------------------

// verifica se o usuário está; logado e executa ações
// executa ações se o usuário estiver logado
/*gapi.load('auth2', function () {
    console.log("4");
    gapi.auth2.init({

        client_id: '428001492988-ouocv0d188o1nu3rdhas2dcatahsae1a.apps.googleusercontent.com',

    }).then(function () {
        console.log("5");
        auth2 = gapi.auth2.getAuthInstance();
        console.log(auth2.isSignedIn.get()); // Agora isso sempre retorna corretamente

        if (auth2.isSignedIn.get() == true) {
            botaoDeDeslogar(); //aparece o botao de deslogar
            botaoDeLogar();  //esconde o botao de logar
            console.log("6");
        } else {
            //usuarioDeslogadoGoogle();
            console.log("7");
        }
    });
});*/

//---------------------------------------------------------------------------------------------------------------------------------------------------

//Botao de login do google esta aparencedo display block
function botaoDeLogar() {
    console.log("8");
    console.log("Usuário não esta conectado com o Google deseja logalo BT none!");
    $('#g-signin2').css('display', 'none'); //Botão de login do google desaparece
}

function botaoDeLogar2() {
    console.log("9");
    console.log("Usuário não esta conectado com o Google deseja logalo BT block!");
    $('#g-signin2').css('display', 'block'); //Botão de login do google aparece
}

// Botao de sair se o usuario estiver logado esta aparencendo display none
function botaoDeDeslogar() {
    console.log("10");
    console.log("O usuário está conectado com o Google deseja desconectalo.");
    $('#google_plus_a').css('display', 'block'); //Botao de sair aparece
}

Meu head onde chama a API do Google

<!-- Infomações do google -->
        <script src="https://apis.google.com/js/platform.js" async defer></script>
        <meta name="google-signin-scope" content="profile email">
        <meta name="google-signin-client_id" content="428001492988-97ub0g6ijog4n440anrgm706ijg0dqqt.apps.googleusercontent.com">

Erros que aparecem nos navegadores EDGE e OPERA  -  " No Google
  Chrome e Mozilla funcionan normal ".

Erro que aparece no EDGE e no opera quando clico no Botão de  " Login do Google "

400. That's an error.
Error: redirect_uri_mismatch
The JavaScript origin in the request, https://www.****************.com, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/apis/credentials/oauthclient/428001492988-97ub0g6ijog4n440anrgm706ijg0dqqt.apps.googleusercontent.com?project=428001492988 to update the authorized JavaScript origins.
Learn more
Request Details
redirect_uri=storagerelay://https/www.************.com?id=auth604459
response_type=permission id_token
scope=email profile openid
openid.realm=
client_id=428001492988-97ub0g6ijog4n440anrgm706ijg0dqqt.apps.googleusercontent.com
ss_domain=https://www.*************.com
fetch_basic_profile=true
gsiwebsdk=2
That's all we know.`insira o código aqui`

Erro que aparece nos console no Opera e no Edge

cb=gapi.loaded_0:103 Uncaught

{error: "idpiframe_initialization_failed", details: "Not a valid origin for the client: https://www..…itelist this origin for your project's client ID."}
details: "Not a valid origin for the client: https://www.******.com has not been whitelisted for client ID 428001492988-97ub0g6ijog4n440anrgm706ijg0dqqt.apps.googleusercontent.com. Please go to https://console.developers.google.com/ and whitelist this origin for your project's client ID."
error: "idpiframe_initialization_failed"
__proto__: Object


text:
Q: First and Second order PDF for continuous-time stochastic process Given:
$$ x(t) = \left\{\begin{array}{ll}
\cos \omega_1 t & : P =0.5\\
\cos \omega_2 t & : P=0.5
\end{array}
\right. $$
where $\omega_{1,2}$ are two different known frequencies.
What would the first order and second order PDF's be?
From what I know is that $F(x,t)=P[X(t) \leq x]$ and that the first order PDF is $f(x,t) = \frac{\partial F(x,t)}{\partial x}$. As for the second order PDF $ f(x_1,x_2,t_1,t_2) = \frac{\partial^2 F(x_1,x_2,t_1,t_2)}{\partial x_1 \partial x_2}$.
I doubt that the first and second order PDF end up being $0$ since I am thinking that $F(x,t)=0.5$. What else am I missing?


text:
Q: Getting Access Denied when calling the PutObject operation with bucket-level permission I followed the example on http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_examples.html#iam-policy-example-s3 for how to grant a user access to just one bucket.
I then tested the config using the W3 Total Cache Wordpress plugin. The test failed.
I also tried reproducing the problem using
aws s3 cp --acl=public-read --cache-control='max-age=604800, public' ./test.txt s3://my-bucket/

and that failed with
upload failed: ./test.txt to s3://my-bucket/test.txt A client error (AccessDenied) occurred when calling the PutObject operation: Access Denied

Why can't I upload to my bucket?

A: I was having a similar problem. I was not using the ACL stuff, so I didn't need s3:PutObjectAcl.
In my case, I was doing (in Serverless Framework YML):
- Effect: Allow
  Action:
    - s3:PutObject
  Resource: "arn:aws:s3:::MyBucketName"

Instead of:
- Effect: Allow
  Action:
    - s3:PutObject
  Resource: "arn:aws:s3:::MyBucketName/*"

Which adds a /* to the end of the bucket ARN.
Hope this helps.

A: I encountered the same issue. My bucket was private and had KMS encryption. I was able to resolve this issue by putting in additional KMS permissions in the role. The following list is the bare minimum set of roles needed.
{
  "Version": "2012-10-17",
  "Statement": [
    {
        "Sid": "AllowAttachmentBucketWrite",
        "Effect": "Allow",
        "Action": [
            "s3:PutObject",
            "kms:Decrypt",
            "s3:AbortMultipartUpload",
            "kms:Encrypt",
            "kms:GenerateDataKey"
        ],
        "Resource": [
            "arn:aws:s3:::bucket-name/*",
            "arn:aws:kms:kms-key-arn"
        ]
    }
  ]
}

Reference: https://aws.amazon.com/premiumsupport/knowledge-center/s3-large-file-encryption-kms-key/

A: I was having the same error message for a mistake I made:
Make sure you use a correct s3 uri such as: s3://my-bucket-name/
(If my-bucket-name is at the root of your aws s3 obviously)
I insist on that because when copy pasting the s3 bucket from your browser you get something like https://s3.console.aws.amazon.com/s3/buckets/my-bucket-name/?region=my-aws-regiontab=overview
Thus I made the mistake to use s3://buckets/my-bucket-name which raises:
An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

A: Error :  An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
I solved the issue by passing Extra Args parameter as PutObjectAcl is disabled by company policy.
s3_client.upload_file('./local_file.csv', 'bucket-name', 'path', ExtraArgs={'ServerSideEncryption': 'AES256'})

A: If you have set public access for bucket and if it is still not working, edit bucket policy and paste following:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl",
                "s3:GetObject",
                "s3:GetObjectAcl",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::yourbucketnamehere",
                "arn:aws:s3:::yourbucketnamehere/*"
            ],
            "Effect": "Allow",
            "Principal": "*"
        }
    ]
}

Change yourbucketnamehere in above code with name of your bucket.

A: To answer my own question:
The example policy granted PutObject access, but I also had to grant PutObjectAcl access.
I had to change
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObject"

from the example to:
"s3:PutObject",
"s3:PutObjectAcl",
"s3:GetObject",
"s3:GetObjectAcl",
"s3:DeleteObject"

You also need to make sure your bucket is configured for clients to set a public-accessible ACL by unticking these two boxes:

A: I got this error too: ERROR    AccessDenied: Access Denied
I am working in a NodeJS app that was trying to use the s3.putObject method.  I got clues from reading the many other answers above, so I went to the S3 Bucket, clicked on the Permission tab, then scrolled down to the Bucket Policy section and noticed there was a condition required for access.

So I added a ServerSideEncryption attribute to my params for the putObject call.

This finally worked for me.  No other changes, such as any encryption of the message, are required for the putObject to work.

A: Similar to one post above, (except I was using admin credentials) to get S3 uploads to work with large 50M file.
Initially my error was:
An error occurred (AccessDenied) when calling the CreateMultipartUpload operation: Access Denied

I switched the multipart_threshold to be above the 50M
aws configure set default.s3.multipart_threshold 64MB

and I got:
An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

I checked bucket public access settings and all was allowed.
So I found that public access can be blocked on account level for all S3 buckets:

A: I also solved it by adding the following KMS permissions to my policy to allow the role to put objects in this bucket (and this bucket alone):
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "kms:Decrypt",
                "kms:Encrypt",
                "kms:GenerateDataKey"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::my-bucket",
                "arn:aws:s3:::my-bucket/*"
            ]
        }
    ]
}

You can also test your policy configurations before applying them with the IAM Policy Simulator. This came in handy to me.

A: In my case I had an ECS task with roles attached to it to access S3, but I tried to create a new user for my task to access SES as well. Once I did that I guess I overwrote some permissions somehow.
Basically when I gave SES access to the user my ECS lost access to S3.
My fix was to attach the SES policy to the ECS role together with the S3 policy and get rid of the new user.
What I learned is that ECS needs permissions in 2 different stages, when spinning up the task and for the task's everyday needs. If you want to give the containers in the task access to other AWS resources you need to make sure to attach those permissions to the ECS task.
My code fix in terraform:
data "aws_iam_policy" "AmazonSESFullAccess" {
  arn = "arn:aws:iam::aws:policy/AmazonSESFullAccess"
}

resource "aws_iam_role_policy_attachment" "ecs_ses_access" {
  role       = aws_iam_role.app_iam_role.name
  policy_arn = data.aws_iam_policy.AmazonSESFullAccess.arn
}

A: In case this help out anyone else, in my case, I was using a CMK (it worked fine using the default aws/s3 key)
I had to go into my encryption key definition in IAM and add the programmatic user logged into boto3 to the list of users that "can use this key to encrypt and decrypt data from within applications and when using AWS services integrated with KMS.".

A: I was just banging my head against a wall just trying to get S3 uploads to work with large files. Initially my error was:
An error occurred (AccessDenied) when calling the CreateMultipartUpload operation: Access Denied

Then I tried copying a smaller file and got:
An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

I could list objects fine but I couldn't do anything else even though I had s3:* permissions in my Role policy. I ended up reworking the policy to this:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:DeleteObject"
            ],
            "Resource": "arn:aws:s3:::my-bucket/*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucketMultipartUploads",
                "s3:AbortMultipartUpload",
                "s3:ListMultipartUploadParts"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket",
                "arn:aws:s3:::my-bucket/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "s3:ListBucket",
            "Resource": "*"
        }
    ]
}

Now I'm able to upload any file. Replace my-bucket with your bucket name. I hope this helps somebody else that's going thru this.

A: In my case the problem was that I was uploading the files with "--acl=public-read" in the command line.
However that bucket has public access blocked and is accessed only through CloudFront.

A: I had a similar issue uploading to an S3 bucket protected with KWS encryption.
I have a minimal policy that allows the addition of objects under a specific s3 key.
I needed to add the following KMS permissions to my policy to allow the role to put objects in the bucket. (Might be slightly more than are strictly required)
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "kms:ListKeys",
                "kms:GenerateRandom",
                "kms:ListAliases",
                "s3:PutAccountPublicAccessBlock",
                "s3:GetAccountPublicAccessBlock",
                "s3:ListAllMyBuckets",
                "s3:HeadBucket"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "kms:ImportKeyMaterial",
                "kms:ListKeyPolicies",
                "kms:ListRetirableGrants",
                "kms:GetKeyPolicy",
                "kms:GenerateDataKeyWithoutPlaintext",
                "kms:ListResourceTags",
                "kms:ReEncryptFrom",
                "kms:ListGrants",
                "kms:GetParametersForImport",
                "kms:TagResource",
                "kms:Encrypt",
                "kms:GetKeyRotationStatus",
                "kms:GenerateDataKey",
                "kms:ReEncryptTo",
                "kms:DescribeKey"
            ],
            "Resource": "arn:aws:kms:<MY-REGION>:<MY-ACCOUNT>:key/<MY-KEY-GUID>"
        },
        {
            "Sid": "VisualEditor2",
            "Effect": "Allow",
            "Action": [
            <The S3 actions>
            ],
            "Resource": [
                "arn:aws:s3:::<MY-BUCKET-NAME>",
                "arn:aws:s3:::<MY-BUCKET-NAME>/<MY-BUCKET-KEY>/*"
            ]
        }
    ]
}

A: For me I was using expired auth keys. Generated new ones and boom.

A: My problem was that my source (an ec2 instance) had an IAM role attached that didn't allow any write actions, so even though the bucket policy was correct, I couldn't write anything to anywhere from it. I solved it by adding this policy to the IAM role:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": [
                "arn:aws:s3:::destination-bucket/destination-path/*"
            ]
        }
    ]
}

A: I was facing the similar issue so checked the permission tab in the AWS bucket. The public access was blocked which was causing the issue in my case so I unchecked the option and it worked.
enter image description here

A: If you have specified your own customer managed KMS key for S3 encryption you also need to provide the flag --server-side-encryption aws:kms, for example:
aws s3api put-object --bucket bucket --key objectKey --body /path/to/file --server-side-encryption aws:kms
If you do not add the flag --server-side-encryption aws:kms the cli displays an AccessDenied error

A: I was able to solve the issue by granting complete s3 access to Lambda from policies. Make a new role for Lambda and attach the policy with complete S3 Access to it.
Hope this will help.

A: In addition, I have set the permission for the group to which the user belongs to.


text:
Q: My scroll handler JavaScript doesn't work in Internet Explorer I have a script on my site that works in every browser, except Internet Explorer. Can someone explain why this doesn't work?

var header = document.getElementById('header');
var picturebg = document.getElementsByClassName('picturebg')[0];
var arrow = document.getElementsByClassName('toTop-transparent')[0];
var supportPageOffset = window.pageXOffset !== undefined;

window.onscroll = function() {
  "use strict";
  var y = window.scrollY;

  if (y > 7) {
    header.className = 'header-colored';
    arrow.className = 'toTop';
    picturebg.className = 'picturebgns';
  } else {
    header.className = 'header-transparent';
    arrow.className = 'toTop-transparent';
    picturebg.className = 'picturebg';
  }
};

The console doesn't give any errors, it just doesn't work. I have another jQuery script that runs just fine.
I've seen the other question here about the same thing, but it didn't help in any way.

A: Certain properties used in your snippet are not supported by IE.
From the MDN page on scrollY:

For cross-browser compatibility, use window.pageYOffset instead of window.scrollY. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties.1

It appears you already have found the check for pageOffset support, so also check if non-standard properties are supported (e.g. CSS1 is compatible):
var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");

var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;

Try this sample, using addEventListener() instead of onscroll.

var header = document.getElementById('header');
var picturebg = document.getElementsByClassName('picturebg')[0];
var arrow = document.getElementsByClassName('toTop-transparent')[0];
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");

header.addEventListener('scroll', function(event) {
  "use strict";
  var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
console.log('y: ',y);
  if (y > 7) {
    header.className = 'header-colored';
    arrow.className = 'toTop';
    picturebg.className = 'picturebgns';
  } else {
    header.className = 'header-transparent';
    arrow.className = 'toTop-transparent';
    picturebg.className = 'picturebg';
  }
});

↓

1https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY#Notes


text:
Q: Android ImageView refresh in Loop I am new to Android and I need to create an Image Map i.e. I have a custom map in a bitmap and I need to display and move a cursor (Location Indicator) over the Image Map. I have used Image View to display the image and canvas to draw the cursor over that image and this works fine in below code:
WalMap = BitmapFactory.decodeResource(getResources(), R.drawable.map);
bMap = Bitmap.createBitmap(WalMap.getWidth(), WalMap.getHeight(), Bitmap.Config.RGB_565);
canvas = new Canvas(bMap);
canvas.drawBitmap(WalMap, 0, 0, null);
icon = BitmapFactory.decodeResource(getResources(), R.drawable.cursor);
icon = Bitmap.createScaledBitmap(icon, 30, 30, false);
canvas.drawBitmap(icon, 90, 100, paint);
image.setImageDrawable(new BitmapDrawable(getResources(), bMap));

Now, I need to refresh the position of cursor after say every X seconds. When I try to do this in a loop or in a thread the app gets force close on my phone. Here is the attempt on using threads:
    Thread thread = new Thread() {
    @Override
    public void run() {
        try {
            doMySearch(width,height,move,canvas);
            while (true) {
                sleep(1000);
                break;
            }
            move=100;
            doMySearch(width,height,move,canvas);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } };    public void doMySearch(int xaxis, int yaxis, int ymove,Canvas canvas) {

            canvas.drawBitmap(icon, xaxis / 2 + 90, yaxis / 3 + ymove + i, paint);
            image.setImageDrawable(new BitmapDrawable(getResources(), bMap));
    }

Also, if I try this in a loop, the canvas still keeps previous position of cursor on the display and doesn't refresh upon redraw. Will appreciate any help. Thanks.

A: TO UPDATE UI ON THREAD
Thread t = new Thread() {

@Override
public void run() {
try {
  while (!isInterrupted()) {
    Thread.sleep(1000);
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        doMySearch();
      }
    });
  }
} catch (InterruptedException e) {
}
}
};

t.start();

TO UPDATE YOUR LOCATION
//Create a new image bitmap and attach a brand new canvas to it
drawBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),     Bitmap.Config.RGB_565);
uLocationCanvas = new Canvas(drawBitmap);

uLocationCanvas.drawBitmap(bitmap, 0, 0, null);

uLocationPaint = new Paint();
uLocationPaint.setColor(Color.BLUE);

bitmapDrawable = new BitmapDrawable(getResources(), drawBitmap);

//Draw the image bitmap into the cavas
uLocationCanvas.drawBitmap(bitmap, 0, 0, null);

uLocationPaint = new Paint();
uLocationPaint.setColor(Color.BLUE);
//Draw everything else you want into the canvas, in this example a rectangle  with rounded edges
uLocationCanvas.drawCircle(x, y, 10, uLocationPaint);

//Attach the canvas to the ImageView
floorImage.setImageDrawable(new BitmapDrawable(getResources(), drawBitmap));

hope this will help


text:
Q: Convolution implementation does not work as expected I spent the whole day trying to implement the "convolution algorithm" in Java, but this last does not seem to work properly with all kernels, it works great with the blur kernel with a factor of 1/9, but not with the other ones.
For example, if I use the {{0.1.0},{0,0,0},{0,0,0}} matrix which is supposed to shift the image up by 1 pixel, surprisingly, it stretches the image all the way down.
Example of what I get:

And here is the code:
public class ConvolutionTest {

    static BufferedImage bfimg;
    static BufferedImage outputimg;
    static File output = new File("/home/bz/Pictures/Selection_003_mod");
    static File input = new File("/home/bz/Pictures/Selection_003.png");
    static WritableRaster wr;
    static int tempColor;
    static double [] newColor = {0,0,0};
    static double red=0, green=0, blue=0;
    static double sumR=0, sumG=0, sumB=0;

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

        int tempIcoor;
        int tempJcoor;
        double[][] matConv = {
                                {0d, 1d, 0d},
                                {0d, 0d, 0d},
                                {0d, 0d, 0d}
                              };

         bfimg = ImageIO.read(input);
         outputimg = bfimg;
         wr = outputimg.getRaster();

         for (int i = 1; i < bfimg.getHeight()-1; i++) {
            for (int j = 1; j < bfimg.getWidth()-1; j++) {

                tempIcoor = i - 1;
                tempJcoor = j - 1;

                for (int tempI = 0; tempI < 3; tempI++) {
                    for (int tempJ = 0; tempJ < 3; tempJ++) {

                        tempColor = bfimg.getRGB(tempJcoor, tempIcoor);

                        red = tempColor >> 16 & 0xff;
                        red = red * matConv[tempI][tempJ];

                        green = tempColor >> 8  & 0xff;
                        green = green * matConv[tempI][tempJ];

                        blue = tempColor      & 0xff;
                        blue = blue * matConv[tempI][tempJ];;

                        sumR = red + sumR;

                        sumG = green + sumG;

                        sumB = blue + sumB;

                        tempJcoor++;

                    }

                    newColor[0] = sumR;
                    newColor[1] = sumG;
                    newColor[2] = sumB;

                    tempIcoor++;
                    tempJcoor=j-1;
                }

                wr.setPixel(j, i, newColor);

                sumR=0;
                sumG=0;
                sumB=0;
            }
        }

        ImageIO.write(sortie, "png", output);

    }

}

A: With
outputimg = bfimg;

you are setting the output image to be the same as the input image. When you perform the convolution of the first row, then (as you said) the first row of pixels from the input image will be written into the the second row of the output image. But they are identical - so you end up with all rows of the output image being copies of the first row of the input image.
Just replace this line with
outputimg = new BufferedImage(
    bfimg.getWidth(), bfimg.getHeight(),
    BufferedImage.TYPE_INT_ARGB);

to create a new output image to write to.
By the way: All this is already available in the standard API. You might want to have a look at the classes related to http://docs.oracle.com/javase/7/docs/api/java/awt/image/ConvolveOp.html


text:
Q: Felix with PostgreSQL I want to work in java OSGI bundle (Felix) with PostgreSQL database. I have this dependency in the pom:
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.4.1207</version>
</dependency>
And this class is in PostgreSQL bundle.
`public class PostgreSQLDBDAOFactory extends DAOFactory {
Connection conn = null;
private static final Logger LOG = Logger.getLogger(PostgreSQLDBDAOFactory.class.getName());

public PostgreSQLDBDAOFactory() throws ClassNotFoundException {
    try {
        Class.forName("org.postgresql.Driver");
        String url = "jdbc:postgresql://localhost:5432/CarsAPJ";
        String user  = "petr";
        String password = "pass";
        conn = DriverManager.getConnection(url, user, password);
        ...}
    ...
    }
...

}`
Building of OSGI bundle is OK, but after starting app in Felix, I have this error. I have this bundle in modules and in felix configuration script.
Jan 18, 2016 1:13:02 AM org.lib.postgresqldb.PostgreSQLDBDAOFactory <init>
SEVERE: java.lang.ClassNotFoundException: org.postgresql.Driver not found by org.lib.postgresqlDB [4]
Do you know anybody, how to resolve it, please?

A: When you load the DriverManager class in your bundle then this is delegated to the classloader of the system bundle (felix framework). So the DriverManager will only see the packages that are visible to the system bundle. The DB drivers are not visible there of course.
To make it short. You should not rely on the DriverManager to make a DB connection. Instead use a DataSource.
The best way to get a DataBase connection is to use pax-jdbc. It provides a way to create and publish DataSources as OSGi services.
So you can just refer to the service from your bundle and create a Connection from it. This makes sure your bundle does not depend on the specific database and allows the admin to easily change the DataSource config.
I also got some tutorials for Apache Karaf that show how to cleanly build database based applications on top of OSGi.


text:
Q: method not suitable for an entry point I get the error Program does not contain a static Main method suitable for an entry point.
I want to use the method UploadFileToBlobStorage in the main method.
Here is my main method:
 public static void Main(string[] args,BlobContainerClient containerClient)
{
    _ = CreateBlobClientContainerAsync();

    _ = UploadFileToBlobStorage(containerClient);

    Console.WriteLine("Press any key to exit.");
    Console.ReadLine();
}

and here is the UploadFileToBlobStorage method:
public static async Task<int> UploadFileToBlobStorage(BlobContainerClient containerClient)
{
    // Create a local file in the ./data/ directory for uploading and downloading
    string localPath = "./data/";
    string fileName = "perfblob" + Guid.NewGuid().ToString() + ".txt";
    string localFilePath = Path.Combine(localPath, fileName);

    // Write text to the file
    await File.WriteAllTextAsync(localFilePath, "Blob Upload!");

    // Get a reference to a blob
    BlobClient blobClient = containerClient.GetBlobClient(fileName);

    Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

    // Upload data from the local file
    await blobClient.UploadAsync(localFilePath, true);

    return 200;
}

A: your Main method doesn't have a valid code signature, you have to remove this argument "BlobContainerClient containerClient"


text:
Q: Combining multiple OpenAPI Specifications, that do not reference each other, during maven generate sources step A Backend Java Project has rest endpoints that are defined in multiple different locations, each with their own generated openapi-yaml.
In order to use this project together with an api gateway, I need to combine these yamls into 1, before stuffing the file into my war file.
These specifications are generated in the generate-sources phase. I have tried using the swagger-codege-maven-plugin, but this plugin only seems to combine references. My specs do not reference each other, they just define different endpoints.
Is there a way to combine the specs during compilation with maven? Does anyone know of a plugin that does this?
Essentially, I need to put all the components from 1 file into the component section of another file and all the paths of 1 file into the paths of another file
I appreciate the help and thank you for your time!

A: After searching around further I have found this small plugin
https://github.com/randomnoun/swagger-combine-maven-plugin
which after playing around with the settings for a bit, I have achieved the functionality I needed in my original post.