text:
Q: shell command (involving sed) works in bash but not in rake task on mac os I have a rake task that performs a shell command. When I run it from bash, the substitution worked, but when I run the rake task, the substitution did not take place.
My rake file:
require 'rake'
namespace 'performance_tests' do
  task :test_guests_generation do

    %x{sed -e 's/NO_OF_GUESTS = \[.*]/NO_OF_GUESTS = \[400, 10]/' -i '' db/seeds.rb}
  end
end

Trying the command in Mac OS Terminal does perform the substitution:
$ sed -e 's/NO_OF_GUESTS = \[.*]/NO_OF_GUESTS = \[400, 10]/' -i '' db/seeds.rb

A: Um... not sure to be honest. Have you tried escaping the spaces? Can you paste the line you are working on and the desired result?


text:
Q: OpenJPA with Oracle - NullPointerException while creating the EntityManager I am new to OpenJPA. When I tried to write a sample program with OpenJPA and Oracle, I am getting a NullPointerException while creating the EntityManager.
Sample program is
    public static void main(String[] args) {
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("testjpa");
        EntityManager em = entityManagerFactory.createEntityManager();
        EntityTransaction userTransaction = em.getTransaction();

        userTransaction.begin();
        Customer customer = new Customer();
        customer.setFirstName("Charles");
        customer.setLastName("Dickens");
        customer.setCustType("RETAIL");
        customer.setStreet("10 Downing Street");
        customer.setAppt("1");
        customer.setCity("NewYork");
        customer.setZipCode("12345");
        em.persist(customer);
        userTransaction.commit();
        em.close();
        entityManagerFactory.close();
}

persistence.xml is
<persistence-unit name="testjpa">
    <provider>
        org.apache.openjpa.persistence.PersistenceProviderImpl
    </provider>
    <class>sample.jpa.entity.Customer</class>
    <properties>
        <property name="openjpa.jdbc.DBDictionary" value="oracle(DriverVendor=oracle)" />
        <property name="openjpa.ConnectionURL" value="jdbc:oracle:thin:@localhost:1521:xe" />
        <property name="openjpa.ConnectionDriverName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="openjpa.ConnectionUserName" value="xxxxx" />
        <property name="openjpa.ConnectionPassword" value="xxxxx" />
        <property name="openjpa.Log" value="SQL=TRACE" />
    </properties>
</persistence-unit>

Stacktrace is
Exception in thread "main" java.lang.NullPointerException
at sample.jpa.main.TestJPA.main(TestJPA.java:16)

This is happening at
EntityManager em = entityManagerFactory.createEntityManager();

Can anyone help me to resolve this?

A: Like Eelke told you already: You have to post the exact stack trace. There is no chance to start debugging this without the stack.
I also hope that his whitespace behind "Persistence" in your code snippet is just a typo:
EntityManagerFactory entityManagerFactory = Persistence .createEntityManagerFactory("testjpa");

Sebastian

redpajama_set_name: RedPajamaStackExchange


text:
Q: removeEventListener for object data load I have added an event listener to catch the loading of an SVG after a user action.
HTML
<object id="mySVG" type="image/svg+xml" data="default.svg"></object>

JS
mySVG = document.getElementById('mySVG');
mySVG.addEventListener('load', function () {
  // work with SVG contentDocument
});
mySVG.setAttribute('data', 'new.svg');

After another user action, I am clearing out the SVG by loading a blank inline SVG
var svgUrl = URL.createObjectURL(new Blob(['<svg xmlns="http://www.w3.org/2000/svg" width="700" height="700"/>'], {'type':'image/svg+xml'}));
mySVG.setAttribute('data', svgUrl);

I looks like setting this blank SVG is also triggering the load event, which is undesirable. So I tried
mySVG.removeEventListener('load');

This gives me the error

TypeError: Not enough arguments to EventTarget.removeEventListener.

What is the correct syntax for removeEventListener in this context?
edit: method to set the blank SVG was incorrect, corrected after reading this.

A: You should name your function and then pass it as the second argument both to addEventListener and removeEventListener, like so:

mySVG = document.getElementById('mySVG');

function loadFunction() {
  // work with SVG contentDocument
}

mySVG.addEventListener('load', loadFunction);
mySVG.setAttribute('data', 'new.svg');

mySVG.setAttribute('data', 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22700%22%20height%3D%22700%22%2F%3E');

mySVG.removeEventListener('load', loadFunction);
<object id="mySVG" type="image/svg+xml" data="default.svg"></object>

removeEventListener requires at least two arguments, the event type ('load') and the listener to remove, so you have to reference the listener that was added previously for it to ve removed.

A: mySVG.removeEventListener('load'); should have a target as second parameter on which it listens events


text:
Q: Is it a good idea to deploy a GraphQL server on Google Cloud Functions or AWS Lambda? Otherwise what are the alternatives? This morning, I asked me "What are the different tech stacks to deploy a GraphQL server in the cloud (AWS, GCP, etc.)?
And after some research, I found some tutorials which are using AWS Lambda. But is it a good idea to deploy a GraphQL server on Google Cloud Functions or AWS Lambda? Otherwise what are the alternatives?
Some tutorials that I have found which are using AWS Lambda :

*

*https://serverless.com/blog/running-scalable-reliable-graphql-endpoint-with-serverless/

*https://hackernoon.com/create-a-serverless-graphql-server-using-express-apollo-server-and-aws-lambda-c3850a2092b5

*https://medium.com/@cody.taft/serverless-graphql-with-aws-f7b6da9d2162


text:
Q: how to link custom ng2-charts plugin to one chart only? We created a plugin for a barchart using ng2-charts.
Component.ts:
 barChartPlugins: ChartComponentLike[] = [
    {
      id: 'SOME_ID',
      afterDatasetDraw: (chart, args, options) => {
           // do some stuff using component property this.params
      }
    },
];

and template:
  <canvas
    #canvas
    baseChart
    [options]="barChartOptions"
    [data]="barChartData"
    [legend]="barChartLegend"
    [plugins]="barChartPlugins"
  ></canvas>

The issue is that anytime another barchart is instanciated in the application, the plugin is applied AND the the values in this.params come from the first barchart.
How can we link the plugin to some chart only and/or pass some parameters?
So far, the only ugly solution we found is to pass parameters through the canvas id and we really don't want to do that.


text:
Q: Fragment Navigation Inside a Tabbed Action Bar The Problem
Before I describe my current setup I will describe my problem. I need to have hierarchal navigation between fragments inside separate tabs. Say I drill down on level in a tab, I then switch tabs and then go back to the first, original tab, I need it to be on the drilled down level and then have the ability to go back up to the top level of that tab.
Now onto my setup.
I have an application with one activity called MainActivity. This activity is what controls my tabbed action bar. I have followed many different tutorials to handle the switching of Fragments when a tab is selected and here is the code below that works drawing your attention to the onTabSelected and onTabUnselected methods.
MainActivity -- Tab Listener
public static class MyTabListener<T extends Fragment> implements ActionBar.TabListener {
    private final Activity mActivity;
    private final String mTag;
    private final Class<T> mClass;
    private final Bundle mArgs;
    private Fragment mFragment;

    public MyTabListener(Activity activity, String tag, Class<T> clz) {
        this(activity, tag, clz, null);
    }

    public MyTabListener(Activity activity, String tag, Class<T> clz, Bundle args) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
        mArgs = args;

        // Check to see if we already have a fragment for this tab, probably
        // from a previously saved state.  If so, deactivate it, because our
        // initial state is that a tab isn't shown.
        mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
        if (mFragment != null && !mFragment.isDetached()) {
            FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
            ft.detach(mFragment);
            ft.commit();
        }
    }

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        Log.e("FRAGMENT","Selected Fragment With Tag " + mTag);
        if (mFragment == null) {
            mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
            ft.add(android.R.id.content, mFragment, mTag);
        } else {
            ft.attach(mFragment);
        }
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        if (mFragment != null) {
            ft.detach(mFragment);
        }
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show();
    }

}

When I am on Tab1 viewing Fragment1', when a button is pressed I then show anotherFragmentcalledFragment2` which I need the ability to go back from. The code below works if I just stay on that tab however when navigating away from the tab and back to it, everything messes up.
MainActivity -- Showing second fragment
Fragment tdFrag = Fragment.instantiate(this, SecondFragment.class.getName());
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(android.R.id.content, tdFrag, "secondfrag");
    ft.addToBackStack(null);
    ft.commit();

My Thoughts
I think it must be the way I detach the fragments and handle the switching over when a new tab is pressed. Maybe I need to implement some way of storing each individual backstack for each tab and loading the fragments from that instead of the system back stack?
Any help would be great. I have tried to explain it as thoroughly and simply as possible.
Thanks in advance.

A: Ok so after a bit of experimentation I decided to implement a custom backstack using enumerated types.
I have two types of enumerated types: a ViewType and CurrentTab type. The CurrentTab type tells me what tab I'm currently viewing and the ViewType tells me what view is being viewed in these tabs. I have an instance of a ViewType for each tab I have to store where I am in the hieerarchy.
To implement a backstack I override the method thats called when the back button is pressed.
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {

             return true;
        }
     return super.onKeyDone(keyCode,event);
}

So in where it checks for the back button I put my code to check the current tab and the separate view types. That way I know where I am and if I push back I know where I need to go.
I hope this helps any questions just post a comment.


text:
Q: Downloading file using java (Showing invalid characters in downloaded file) I'm trying to download a file using java, file is downloading but showing invalid characters in a file as shown in below.
Same thing with the images too, Showing invalid image.
Everything looks fine, Did i missed something? or Anybody having better solution than this?
index.jsp

     Click on the link to download:
     Download Link

download.jsp
<%
try {
    String filename = "C:/slcmimages/StudentDetails.xls"; // jpg, png, doc etc
    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition", "attachment; filename=" + filename);

    // transfer the file byte-by-byte to the response object
    File fileToDownload = new File(filename);
    response.setContentLength((int) fileToDownload.length());
    FileInputStream fileInputStream = new FileInputStream(fileToDownload);
    int i = 0;
    while ((i = fileInputStream.read()) != -1) {
        out.write(i);
    }
    fileInputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}
%>

Actual File:

File after downloading:


text:
Q: launchctl gives permission error I have a user named 'tv' (OS X 10.11.5) and I have these files in /Users/tv/Library/LaunchAgents/
# ls -lsa /Users/tv/Library/LaunchAgents/
total 16
0 drwxr-xr-x   4 tv  staff   136 Jun 24 20:46 .
0 drwx------@ 50 tv  staff  1700 May 19 11:05 ..
8 -rw-r--r--@  1 tv  staff   487 Dec 24  2015 com.bittorrent.uTorrent.plist
8 -rw-r--r--   1 tv  staff   559 Jun 24 20:46 com.drzoidberg33.plexpy.plist

I get Path had bad ownership/permissions when I try to load either file. I've rebooted, changed the group to wheel, tried to manually load them repeatedly, but I always get the same error. The permissions look exactly the same as on my normal user account:
$ ls -lsa Library/LaunchAgents/
total 8
0 drwxr-xr-x   8 lbutlr  staff   272 Oct  8  2015 .
0 drwx------@ 63 lbutlr  staff  2142 Apr  2 02:11 ..
8 -rw-r--r--   1 lbutlr  staff   452 Mar 30  2015 com.kreme.home.randsig.plist
$ launchctl load /Users/lbutlr/Library/LaunchAgents/com.kreme.home.randsig.plist
/Users/lbutlr/Library/LaunchAgents/com.kreme.home.randsig.plist: service already loaded`

This link is similar, but is dealing with root permissions inside the /Library folder

A: The issue turned out to be that the executable referenced in the ProgramArguments inside the plist was not executable. Doh!


text:
Q: Why is there no call to repository's update method for this request (Entity Framework, automapper, repository pattern)? I am trying to understand the code in following screenshot. After map operation, the object is not written back to the repository. What is this concept called? How does SaveChangesAsync make call to the update method on the repository?

A:
How does SaveChangesAsync make call to the update method on the repository?

The DbContext is the repository, and it's tracking the oldCamp object.  When SaveChagnes() is called it will detect changes to any tracked entities and take the appropriate action (insert,update or delete).

A: Under the hood SaveChangesAsync() will automatically call DetectChanges() to discover any changes to entity instances before saving to the underlying database. This can be disabled via AutoDetectChangesEnabled.


text:
Q: C++ append to second line of file I would like to append entries in a simple csv file at the second line.  The first line contains my column headers and the newest entry has to be on top.
My thought is to read in the first line until the '\n', then move to the next line and write there, but i don't know if that is the most efficient solution.  Can someone provide an example?

A: Since you have stated in the comments that this file will not be very large I would suggest you read in the header into some sort of container.  Then insert after the header the newest data that needs to be inserted into the file.  Then read in the rest of the file.  After you do that then you can write the contents of the container back into the file.  Here is a simple demonstration:
std::ifstream fin("somefilename");
std::vector<std::string> file;
file.reserve(30); // grow the capacity to save on allocations
std::string reader;

std::string new_data = "some new data";
getline(fin, reader);
file.push_back(reader);  //add header
file.push_back(new_data);  // add new line

while(getline(fin, reader))  // get rest of file
    file.push_back(reader);

std::ofstream fout("somefilename");
for (const auto & e : file)
    fout << e << "\n";


text:
Q: Bad smoothness webkitRequestAnimationFrame vs setInterval With regard to a previous question of mine, I tried out Chromium's support of webkitRequestAnimationFrame. Although it would have a bunch of advantages, it turned out to be much worse for me than using plain setInterval / setTimeout for generating an animation.
I tried the example stated on http://paulirish.com/2011/requestanimationframe-for-smart-animating/, both with webkitRequestAnimationFrame and with setTimeout:

*

*webkitRequestAnimationFrame: http://jsfiddle.net/hnQYt/

*setTimeout: http://jsfiddle.net/hnQYt/2/
Am I the only person having issues with the smoothness of the first method? If not, how come this specially designed method fails miserably?

A: The latest nightly build solved this issue - I guess it was a bug which is now fixed.


text:
Q: Autoloading constants in PHP? I was hoping that if I were to define constants in a separate namespace, like:
namespace config\database\mysql;

const HOST = 'localhost';
const USER = 'testusr';
const PASSWORD = 'testpwd';
const NAME = 'testdb';

That I would be able to use __autoload to automatically include them:
function __autoload($className)
{
    echo "Autoload: {$className}\n";
    $class_file = str_replace('\\', '/', $className) . ".php";
    if(file_exists($class_file)) {
        include $class_file;
    }
}

echo config\database\mysql\HOST;

This, however, does not work. The __autoload is not called for the constant as it is with classes, leaving me with a Undefined constant error.
Some way that I can simulate the class __autoload for constants?

A: Try this (worked on my server):
<?php
namespace config\database\mysql;

class Mysql
{
    const HOST = 'localhost';
    const USER = 'testusr';
    const PASSWORD = 'testpwd';
    const NAME = 'testdb';
}
?>

<?php
function __autoload($className)
{
    echo "Autoload: {$className}\n";
    $class_file = str_replace('\\', '/', $className) . ".php";
    if(file_exists($class_file)) {
        include $class_file;
    }
}

echo config\database\mysql\Mysql::HOST;
?>

Basically you need to create a class to act as a wrapper for the constants but by doing so it allows __autoload() to work as you intended.

A: Using an undefined constant will throw a PHP warning.
You can write a custom error handler to catch the warning and load in the appropriate constants file.


text:
Q: Is it possible to send an email when a checkbox is checked 'true' in Google Sheets to the email address listed on the same row as the checkbox? I'm trying to figure out how to automatically send out an email to the email address on the same row as the checkbox as soon as the checkbox is checked and marked as 'true'.
Then be able to have the email send something like: "Your ad is live."
Here's a link to my sample spreadsheet.

A: Yes you can do it by making List of Selected email address from the List where checkbox is selected .
for this you have to create an ArrayList of String and when you click on send button you can add all email address from row where checkbox was selected and you can send email to those email address.


text:
Q: clojure - best way to increase date by x days I need to read in a date string in yyyyMMdd format and increase it by x amount of days - at the minute I am doing it by converting to millis and adding 1 day in mills then converting back to yyyyMMdd.
(.print
 (.withZone
  (DateTimeFormat/forPattern "yyyymmdd") (DateTimeZone/forID "EST"))
 (+ 86400000 (.parseMillis
  (.withZone (DateTimeFormat/forPattern "yyyymmdd")
  (DateTimeZone/forID "EST")) "20150401")))

Is there a cleaner way to do this? clj-time library is not available to me, and I am using clojure 1.2

A: Since you cant't use clj-time, which is the best option in this case, I can't think of anything better than using org.joda.time as you did.
However, I would suggest rewriting your code a little bit:

*

*there is no need for time zones here;

*you could create DateTimeFormat object once and reuse it.

Here is how your function could look:

(defn add [date pattern days]
  (let [fmt (DateTimeFormat/forPattern pattern)
        add (* 86400000 days)]
    (->>  date
          (.parseMillis fmt)
          (+ add)
          (.print fmt))))

(add "20150401" "yyyymmdd" 1) ; => "20150402"

If you don't want to work with milliseconds, you could use .parseDateTime instead of .parseMillis and .plusDays method do add days to the parsed date:

(defn add [date pattern days]
  (let [fmt (DateTimeFormat/forPattern pattern)
        dt  (.parseDateTime fmt date)]
    (.print fmt (.plusDays dt days))))


text:
Q: Remote mysql Database access error using spark Accessing Table from remote mysql database, which works fine locally from eclipse but throwing error while trying from spark-submit.
ERROR SparkContext: Error initializing SparkContext.java.lang.IllegalArgumentException: java.net.UnknownHostException: namenode
at org.apache.hadoop.security.SecurityUtil.buildTokenService(SecurityUtil.java:378)

Spark-submit below:
spark-submit \
--jars /home/hduser/.ivy2/cache/com.typesafe/config/bundles/config-1.3.1.jar \
--class "retail.stack" --master local[2] \
--driver-memory 2g --executor-memory 2g --executor-cores 2 \
sample-spark-180417_2.11-1.0.jar \
/home/hduser/spark-training/workspace/demos/output/extra_in_src \
/home/hduser/spark-training/workspace/demos/output/extradest \
/home/hduser/spark-training/workspace/demos/output/bestMatch

Code Below:
  val spark = SparkSession.builder().master("local").appName("Database")
  .getOrCreate()

val jdbcUsername = "root"
val jdbcPassword = "root"
val url = "jdbc:mysql://192.168.175.35:3306/sample?useSSL=false"

val connectionProperties = new java.util.Properties()
connectionProperties.put("user", jdbcUsername)
connectionProperties.put("password", jdbcPassword)

 val querySource = "(select * from source1) as src"
val queryDestination = "(select * from destination1) as dest"

val source = spark.read.jdbc(url, querySource, connectionProperties).rdd.map(_.mkString(","))
val destination = spark.read.jdbc(url, queryDestination, connectionProperties).rdd.map(_.mkString(","))

Thank you

A: I resolved it by reconfiguring the Connection string. It worked fine.!


text:
Q: How to install hwloc-dev package on Docker alpine container The hwloc-dev package missing on the Docker Alpine Linux container.
 # apk add hwloc-dev hwloc-tools
ERROR: unsatisfiable constraints:
  hwloc-dev (missing):
    required by: world[hwloc-dev]
  hwloc-tools (missing):

A: As indicated by the package explorer, this package is in the alpine edge community repository.
You need to add it to your /etc/apk/repositories:
echo 'https://dl-cdn.alpinelinux.org/alpine/edge/community' >> /etc/apk/repositories


text:
Q: How to use progress dialog with AsyncTask and fragment? I want to use a ProgressDialog within a Fragment for an AsyncTask. With Activity the following code works perfectly, but with Fragment no.
public class ResultTask extends AsyncTask<String, Void, Report> {

    private ProgressDialog pDialog;
    private Context context;

    public ResultTask(Context context) {
        super();
        this.context = context;

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(context);
        pDialog.setMessage("Loading...");

        pDialog.show();
    }

    @Override
    protected Report doInBackground(String... params) {
      //myLong operation

    }

    @Override
    protected void onPostExecute(Report report) {
        pDialog.dismiss();
        super.onPostExecute(report);
    }

}

How Can I fix in a very simple way ? The idea of the ProgressBar, is just to let understand the user, that a long operation is processed.
UPDATE
Here is the code of the Fragment, where I execute the AsyncTask:
ResultTask task = new ResultTask(getActivity());
Report report = task.execute("paramenters").get();

And this is the code of the Activity, where I select the Fragment:
private void changeActivity(Button button, final Fragment fragment) {
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.container, fragment).commit();
            }
        });

    }

A: If you use .get() for an AsyncTask than it is going to WAIT there until the result not arriving, which case the UI thread to be blokced, while task is running.
USE .execute and use handlers to communicate with the task.
In this case, you don`t need a handler, because the onPre and onPost methods are related the UI, but the doInBackGround not :)
http://developer.android.com/reference/android/os/AsyncTask.html#get()
article:
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html


text:
Q: Cypress: contains().click() with or statement the problem is that the Docker image from Cypress sets the browser language to english and some elements on the page are translated to english. It looks like it's a bug in Cypress because the browser in the Docker image, regardless of the set language, translates certain texts into English. even if the set browser language is different.
my local browser language is different than the one in the docker image so some texts are different for me locally than in the dockerimage (english). now i have to build a workaround until cypress manages to fix the bug.
i want cypress to select an element which is selected by a logical or ( || ). However it doesn't work because cypress.contains() doesn't support this.
For a better illustration here is a simple example of what I mean. Do you have an idea how to implement this?
const value1 = data.text_local_language
const value2 = data.text_english

         cy.get("element")
          .contains(value1 || value2)
          .click();

A: There is the oneOf assertion if an exact match is is acceptable.
cy.get('element')
  .should('satisfy', ($el) => {
    expect($el.text()).to.be.oneOf([value1,value2])
  })
  .click()

A: You can check the text contains either text inside a .then() command and assert it.
const thisText = 'this'
const thatText = 'that'

cy.get('element')
  .then($el => {
    const text =  $el.text()
    const thisOrThat = text.includes(thisText) || text.includes(thatText)
    expect(thisOrThat, `text contains ${thisText} or ${thatText}`).to.be.true
    cy.wrap($el).click()
  })

A: You can use a regular expression in contains()
const value1 = data.text_local_language
const value2 = data.text_english

const regex = new RegExp(`${value1}|${value2}`)  // build regex from variables

cy.get("element")
  .contains(regex)
  .click();

The regular expression (inside the slashes) value1|value2 matches either value1 or value2 (or is denoted by the pipe-symbol |).

A: To assert that an element contains alternative parts you can use a regular expression (RegExp) inside contains().
Assert Contains RegExp
To build a regex pattern from variables use the constructor new RegExp with a string expression.
const value1 = 'Hello'
const value2 = 'World'

// simple with plus operator
cy.get("element").contains(new RegExp(value1 + '|' + value2))

// short and expressive with ES6 template literals
cy.get("element").contains(new RegExp(`${value1}|${value2}`))

// for multiple elements use Array.join()
const elements = ['Fire', 'Air', 'Water'];
cy.get("element").contains(new RegExp(elements.join('|'))

See also the Cypress Assertions guide on Text Content:
// use cy.contains to find an element with its text
// matching the given regular expression
cy.contains('[data-testid="greeting"]', /^Hello/)

Configure browser language in your containerized Cypress
If you want to configure the language used for testing, you could:

*

*set the LANG environment variable in your docker container, which can then be picked by the browser as system/default locale

*set the browser preferences in Cypress's Browser Launch API, which will then be used in the accept-language request header

See Setting the browser language in Cypress


text:
Q: Using Koma-script for defining ToC for each chapter I try to use solution suggested by @esddd in the question "Replacement minitoc package style by KOMA-script possibilities", but unfortunately I came across the following problem:

As you can see above, in the Toc defined for chapter, is added also entry for following Part. How the above entry for Part can be suppressed in the MNWE code? See MNWE:
MNWE
 \documentclass[fontsize=10pt,open=any,twocolumn]{scrbook}[2019/10/12]% needs version 3.27 or newer
\usepackage{blindtext}
\usepackage{scrwfile}% avoid trouble with the limited number of write handles
\usepackage{xpatch}

% https://tex.stackexchange.com/a/359758
% https://tex.stackexchange.com/a/502077
\makeatletter
\newif\ifuseparttoc
\newcommand*{\parttoc}[1][\thepart]{% new command to generate and show a chapter toc
\useparttoctrue% switch on part-toc-entries
\edef\ext@parttoc{tcp#1}% extension of the part-toc-file, e.g., tcpI
\DeclareNewTOC[
    listname=My Content,
    %unset=onecolumn% if the part toc should use twocolumn
]{\ext@parttoc}% declare a new toc file
\begingroup
    \value{tocdepth}=\chaptertocdepth% we want entries down to chapter
    \listoftoc{\ext@parttoc}% show the toc with header
\endgroup
}
\xapptocmd\addtocentrydefault{% patch the KOMA-Script's generic toc entry generator
\ifuseparttoc% if part toc entries should be generated
    \expandafter\tocbasic@addxcontentsline\expandafter{\ext@parttoc}{#1}{#2}{#3}% do it
\fi
}{}{}
\xpretocmd\part{\useparttocfalse}{}{}% automatically switch of part toc entries at start of every \part

\newif\ifusechaptertoc% Switch to tell \addtocentrydefault to not only make entries to the toc-file but also to the current section-toc-file
\newcommand*{\chaptertoc}[2][\thechapter]{% new command to generate and show a chapter toc
\usechaptertoctrue% switch on chapter-toc-entries
\edef\ext@chaptoc{tcc#1}% extension of the chapter-toc-file, e.g., tcc1
\DeclareNewTOC{\ext@chaptoc}% declare a new toc file
%\addsec*{Contents}% header of the chaptertoc
\setchapterpreamble{%
    \begin{minipage}{\linewidth}
    \hrulefill\par
    \value{tocdepth}=\subsectiontocdepth% we want entries down to subsection
    \listoftoc*{\ext@chaptoc}% show the toc without header
    \end{minipage}%
    \par\bigskip\nobreak\noindent\hrulefill\par
    \bigskip\noindent\ignorespaces% add some vertical space after the toc and do not indent the following text
}%
}
% \xpretocmd{⟨command⟩}{⟨prepend⟩}{⟨success⟩}{⟨failure⟩}
% \xapptocmd{⟨command⟩}{⟨append⟩}{⟨success⟩}{⟨failure⟩}
\xapptocmd\addtocentrydefault{% patch the KOMA-Script's generic toc entry generator
\ifusechaptertoc% if chapter toc entries should be generated
    \ifstr{#1}{chapter}{}
    {\expandafter\tocbasic@addxcontentsline\expandafter{\ext@chaptoc}{#1}{#2}{#3}}% do it
\fi
}{}{}
\xpretocmd\chapter{\usechaptertocfalse}{}{}% automatically switch of chapter toc entries at start of every \chapter
\makeatother

\newcommand\setchaptertoc[1][]{%
\ifstr{#1}{}
    {\AddtoOneTimeDoHook{heading/preinit/chapter}{\chaptertoc}}
    {\AddtoOneTimeDoHook{heading/preinit/chapter}{\chaptertoc[#1]}}%
}

\setcounter{tocdepth}{\partnumdepth}% depth of TOC
\begin{document}
\tableofcontents

\part{My Part I}
\parttoc
\setchaptertoc
    \chapter{My chapter I}
        \section{My first section}
            \blindtext
        \subsection{My first subsection}
            \blindtext
        \section{My second section}
            \blindtext

\part{My Part II}
\parttoc
\setchaptertoc
    \chapter{My chapter II}
        \section{My first section}
            \blindtext
            \subsection{My first subsection}
                \blindtext
        \section{My second section}
            \blindtext
\end{document}

Code is well documented, but I still don't understand why it's working like that.

A: There was \xpretocmd\part{\usechaptertocfalse}{}{} missing in the other answer.
\documentclass[fontsize=10pt,open=any,twocolumn]{scrbook}[2019/10/12]% needs version 3.27 or newer
\providecommand*{\Ifstr}{\ifstr}% added because of changes in upcoming KOMA-Script version 3.28 and \ifstr replaced by \Ifstr in the code (see https://komascript.de/faq_deprecatedif)
\usepackage{blindtext}
\usepackage{scrwfile}% avoid trouble with the limited number of write handles
\usepackage{xpatch}

% https://tex.stackexchange.com/a/359758
% https://tex.stackexchange.com/a/502077
\makeatletter
\newif\ifuseparttoc
\newcommand*{\parttoc}[1][\thepart]{% new command to generate and show a chapter toc
\useparttoctrue% switch on part-toc-entries
\edef\ext@parttoc{tcp#1}% extension of the part-toc-file, e.g., tcpI
\DeclareNewTOC[
    listname=My Content,
    %unset=onecolumn% if the part toc should use twocolumn
]{\ext@parttoc}% declare a new toc file
\begingroup
    \value{tocdepth}=\chaptertocdepth% we want entries down to chapter
    \listoftoc{\ext@parttoc}% show the toc with header
\endgroup
}
\xapptocmd\addtocentrydefault{% patch the KOMA-Script's generic toc entry generator
\ifuseparttoc% if part toc entries should be generated
    \expandafter\tocbasic@addxcontentsline\expandafter{\ext@parttoc}{#1}{#2}{#3}% do it
\fi
}{}{}
\xpretocmd\part{\useparttocfalse}{}{}% automatically switch of part toc entries at start of every \part

\newif\ifusechaptertoc% Switch to tell \addtocentrydefault to not only make entries to the toc-file but also to the current section-toc-file
\newcommand*{\chaptertoc}[2][\thechapter]{% new command to generate and show a chapter toc
\usechaptertoctrue% switch on chapter-toc-entries
\edef\ext@chaptoc{tcc#1}% extension of the chapter-toc-file, e.g., tcc1
\DeclareNewTOC{\ext@chaptoc}% declare a new toc file
%\addsec*{Contents}% header of the chaptertoc
\setchapterpreamble{%
    \begin{minipage}{\linewidth}
    \hrulefill\par
    \value{tocdepth}=\subsectiontocdepth% we want entries down to subsection
    \listoftoc*{\ext@chaptoc}% show the toc without header
    \end{minipage}%
    \par\bigskip\nobreak\noindent\hrulefill\par
    \bigskip\noindent\ignorespaces% add some vertical space after the toc and do not indent the following text
}%
}
% \xpretocmd{command)}{(prepend⟩}{⟨success⟩}{⟨failure⟩}
% \xapptocmd{⟨command⟩}{⟨append⟩}{⟨success⟩}{⟨failure⟩}
\xapptocmd\addtocentrydefault{% patch the KOMA-Script's generic toc entry generator
\ifusechaptertoc% if chapter toc entries should be generated
    \Ifstr{#1}{chapter}{}
    {\expandafter\tocbasic@addxcontentsline\expandafter{\ext@chaptoc}{#1}{#2}{#3}}% do it
\fi
}{}{}
\xpretocmd\chapter{\usechaptertocfalse}{}{}% entries in chapter toc are automatically switched off at start of \chapter
\xpretocmd\part{\usechaptertocfalse}{}{}% entries in chapter toc are automatically switched off at start of \part
\makeatother

\newcommand\setchaptertoc[1][]{%
  \Ifstr{#1}{}
    {\AddtoOneTimeDoHook{heading/preinit/chapter}{\chaptertoc}}
    {\AddtoOneTimeDoHook{heading/preinit/chapter}{\chaptertoc[#1]}}%
}

\setcounter{tocdepth}{\partnumdepth}% depth of TOC
\begin{document}
\tableofcontents

\part{My Part I}
\parttoc
\setchaptertoc
\chapter{My chapter I}
\section{My first section}
\blindtext
\subsection{My first subsection}
\blindtext
\section{My second section}
\blindtext

\part{My Part II}
\parttoc
\setchaptertoc
\chapter{My chapter II}
\section{My first section}
\blindtext
\subsection{My first subsection}
\blindtext
\section{My second section}
\blindtext
\end{document}


text:
Q: jQuery menu item selected I all!
I have this menu:

Home

Entidad

With jQuery I'm tring to apply the class .active when a menu item is clicked, as:
  $(document).ready(function(){
      $("li a").click(function(){
           $(this).parent().find("li").addClass('active');
      });
  });

It doesn't work, could you help me?

A: The parent of a is li it self so you do not need to find li.
Live Demo
$(document).ready(function(){
      $("li a").click(function(){
           $(this).parent().addClass('active');
      });
});

Edit To remove the class from previous elements and add to current
Live Demo
$(document).ready(function(){
      $("li a").click(function(event){
           $('#navigation li').removeClass();
           $(this).parent().addClass('active');
      });
});

A: When handling the click of a, li is the parent item, so just do:
$(this).parent().addClass('active');

Are you sure of this, though, as I would have thought it sensible to make the link the active thing? Just an observation.

A: Your page will get refreshed once the hyperlink is clicked so this code $(this).parent().addClass('active') will not going to work.
Try this instead:
$(function() {
                var page = getParameterByName('page');
                $("#navigation a:contains('" + page + "')").parent().addClass('active');
            });

            function getParameterByName(name)
            {
              name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
              var regexS = "[\\?&]" + name + "=([^&#]*)";
              var regex = new RegExp(regexS);
              var results = regex.exec(window.location.search);
              if(results == null)
                return "Home";
              else
                return decodeURIComponent(results[1].replace(/\+/g, " "));
            }

A: Its just
$(this).parent().addClass('active'); //  $(this).parent() selects list element

No need to find again li element there.


text:
Q: How to perform a LIKE query using multiple keywords from search field using mysqli prepared statement This question is similar to this previously asked question except that I am using mysqli instead of PDO.
I perform the query as such:
$word=preg_split('/[\s]+/',$terms);
$totalwords=count($word);

$terms is obtained further up from a GET
$sql="SELECT title,content FROM articles WHERE (title LIKE CONCAT('%',?,'%') OR (content LIKE CONCAT('%',?,'%'))";

for(i=1;$i<$totalwords;$i++){
  $sql.=" OR (title LIKE CONCAT('%',?,'%') OR (content LIKE CONCAT('%',?,'%'))";
}

$stmt=$conn->prepare($sql);
foreach($word as $key => $keyword){
  $term=$keyword;
  $stmt->bind_param('ss',$term,$term);
}
$stmt->execute;
$stmt->store_result;

If I enter one word in the search form, I get the right results, however, if I enter more than one word, I get no results at all.
So I included a print_r($sql); to see what was being sent to the database and this is what I get for one term (which works fine):
SELECT title,content FROM articles WHERE (title LIKE CONCAT('%',?,'%') OR content LIKE CONCAT('%',?,'%'));

and this is what I get for multiple words (which returns no results even though it should):
SELECT title,content FROM articles WHERE (title LIKE CONCAT('%',?,'%') OR content LIKE CONCAT('%',?,'%')) OR (title LIKE CONCAT('%',?,'%') OR content LIKE CONCAT('%',?,'%'));

which seems like everything is working fine, so I turned on my mysql logs and discovered that the single word queries show up but the multi-word queries are non-existent.
So I added print_r($stmt); and I get Commands out of sync; you can't run this command now for multi-word queries.
What am I doing wrong?

A: As user3783243 states in the comments above, my placeholders and parameters where not matching.  So in order to solve that, I did the following (this will be sloppy as I'm new to PHP but if someone can clean it up for me I'll award the answer to that).
First you have to create a string for the type parameter (mine are all strings so this was easy, you could run a conditional statement if you have different types).  Since I use two placeholders for each entry in my SQL, each iteration will include two s's.
$typeparam='';
foreach($word as $key => $value){
  $typeparam.='ss';
}

Then create a new array to put the types and the values all together (again, since there are two placeholders for each parameter, I just add the $word twice to the array):
$bindpars=array();

$bindpars[]=&$typeparam;
foreach($word as $key => $value){
  $bindpars[]=&$word[$key];
  $bindpars[]=&$word[$key];
}

Finally, bind the parameters using call_user_func_array:
call_user_func_array(array($stmt,'bind_param'),$bindpars);

So the code in my question now looks like this:
$word=preg_split('/[\s]+/',$terms);
$totalwords=count($word);

$sql="SELECT title,content FROM articles WHERE (title LIKE CONCAT('%',?,'%') OR (content LIKE CONCAT('%',?,'%'))";

for(i=1;$i<$totalwords;$i++){
  $sql.=" AND (title LIKE CONCAT('%',?,'%') OR (content LIKE CONCAT('%',?,'%'))";
}

$stmt=$conn->prepare($sql);

$typeparam='';
foreach($word as $key => $value){
  $typeparam.='ss';
}

$bindpars=array();

$bindpars[]=&$typeparam;
foreach($word as $key => $value){
  $bindpars[]=&$word[$key];
  $bindpars[]=&$word[$key];
}

call_user_func_array(array($stmt,'bind_param'),$bindpars);

$stmt->execute;
$stmt->store_result;


text:
Q: Advance Custom Field unable to show values in custom page template wordpress Custom "single.php" unable to show Advance Custom Field value.
this is the function for getting the page id of custom "page template" using custom "single.php"
enter code here

<?php
  function lang_page_id($id){
    if(function_exists('icl_object_id'))
    {
      return icl_object_id($id,'page', false,ICL_LANGUAGE_CODE);
    } else
    {
     return $id;
    }
   }
?>

this for showing the acf value
enter code here

<?php the_field('smr_header',
lang_page_id(355));?>

A: Remove the following:
<?php
    function lang_page_id($id){
       if(function_exists('icl_object_id'))
       {
           return icl_object_id($id,'page', false,ICL_LANGUAGE_CODE);
       } else
       {
           return $id;
       }
    }
?>

In your code:

<?php the_field('smr_header', 355);?>

Or:
<?php $h4_feature_title = get_field('smr_header', 355);?>

<?php echo $h4_feature_title;?>

ACF already has post specific values, simply put the id of the post that you want to get the field from. I am not sure why you would want to use this for the current page since then you should just use the_field('smr_header'); as this gets it from the current page.
If you do want to get the ID of the page, inside the loop:
$postid = get_the_ID();
echo $postid;

And only include on the custom page template.
If you do want to get the ID of the page, outside the loop, make a function with the following in:
global $wp_query;
echo $wp_query->post->ID;


text:
Q: Why wont my if statement accept my condition python Beginner here,
whenever I try to run the code with sum as 20 for example, it only returns [2,10], rather than the intended [2,10,4,5,5,4,10,2]
def Factors(num):
    factor1=2
    factors=[]
    while factor1<num:
        while num%factor1 == 0:
            factors.append(factor1)
            factors.append(num/factor1)
            factor1+=1
            continue
        if num%factor1 != 0:
            factor1+=1

        return factors

A: I rewrote some of this code and this is what I came up with.
factors = []

def Factor(num):
    first_factor = 1
    while first_factor <= num:
        if num % first_factor == 0:
            factors.append(first_factor)
            first_factor += 1
        else:
            first_factor += 1

    return(factors)

print(Factor(20))


text:
Q: Send Auto messages from whatsapp I have More than 1000 Numbers in a data base.i need to send happy birthday message to the number if the user is using whatsapp. Is this possible?i don't mind if i need to be pay or what..is it possible?

A: [deprecated]
the best way is using : https://github.com/rquiroz/WhatsAPINet
that´s a sample code
   WhatsApp wa = new WhatsApp("your number", "your password", "pankaj", false, false);
wa.OnConnectSuccess += () =>
{
    Response.Write("connect");
    wa.OnLoginSuccess += (phno,data) =>
    {
        wa.SendMessage("to", "msg");
    };

    wa.OnLoginFailed += (data) =>
    {
        Response.Write("login failed"+data);
    };
    wa.Login();
};
wa.OnConnectFailed+= (ex)=>
{
    Response.Write("connection failed");
}

A: Do you need an mobile application that should do it? If so i don't think there is any application like that in the market. Until now Whatsapp has not exposed any of their apis for developers to take advantages of its functionality.


text:
Q: How can I send a VueJS object to store in Laravel controller? I have this methods, but the information does not reach the database, please help me,I do not know why the information is not sent to the controlle.
When I send the correctly completed data they are not loading to the database, but it does pass through the controller, since it returns to the previous route. The data object can be viewed in the console.

It's the Controller. The controller is fine, because I call it in another section and the information is added correctly.

public function store($data){
        $billing=new OSbilling();
        $billing->order_id=$data['order_id'];
        $billing->billing_number=$data['billing_number'];
        $billing->billed_timene=$data['billed_timene'];
        $billing->billed_travel=$data['billed_travel'];
        $billing->billed_hours=$data['billed_hours'];
        $billing->price=$data['price'];
        $billing->type=$data['type'];
        $billing->created_at=strtotime(Kusher::GetActualDate());
        if(isset($data['created_at'])){
            $billing->created_at=$data['created_at'];
        }
        if($billing->save()){
            return '200';
        }
        return '500';
}

When I send the correctly completed data they are not loading to the database, but it does pass through the controller, since it returns to the previous route. The data object can be viewed in the console.

public function postStorefast($obj){

        $array=Input::all();

        $this->store($array);

        $order=OrderService::find(Input::get('order_id'));
        $billings=OSbilling::whereRaw('order_id='.$order->id)->get();
        $total_hours=0;
        foreach ($billings as $key => $billing) {
            $total_hours=$total_hours+$billing->billed_hours;;
        }
        $possible_hours=$order->execute_hours-$total_hours;

        if($possible_hours<=0 && $possible_hours >= 0 ){
            $OL=new OSorderLogsController();
            $log=array(
                "order_id"=>$order->id,
                "status_id"=>"6",
                "user_id"=>Auth::id(),
                "notes"=>"");
            $OL->postSave($log);
             $order->status = 6;
            $order->save();
        }

        return Redirect::back();
    }

Here is the HTML

Creación de facturas

            Buscar orden (por OS u OSI)
          <input type="text" v-model="term" @keyup.enter="search">
          <button v-on:click="search">Buscar</button>

 0">

            En esta tabla puedes agregar las ordenes que se van a facturar

                  OSI
                  OS
                  Profesional
                  Actividad
                  Desplazamiento real
                  Valor ARL real
                  Valor ARL
             Horas/Unidades posibles
                  Selección

                  {[{of.id}]}
                  {[{of.order_number}]}
                  {[{of.profesional}]}
                  {[{of.activity}]}
                  {[{of.travel_price}]}
                  {[{of.real_arl_price}]}
                  {[{of.arl_value_timene}]}
             {[{ of.possible_hours}]}

                  <button class="btn btn-success" @click="add(of)">Agregar</button>

 0">

            Ordenes a facturar

            En esta tabla puedes modificar los valores de las ordenes

               Fecha factura
              <input type="date" v-model="fechaFactura">

               Número factura
              <input type="text" v-model="numeroFactura">

                  OSI
                  OS
                  Profesional
                  Actividad
                  Desplazamiento Real
                  Valor ARL real
                  Valor ARL tiempo no efectivo
                  Cantidad Desplazamiento
                  Número de horas
/ Unidades
                  Valor a facturar

                  Selección

                  {[{os.id}]}
                  {[{os.order_number}]}
                  {[{os.profesional}]}
                  {[{os.activity}]}
                  {[{os.travel_price}]}
                  {[{os.real_arl_price}]}
                  {[{os.arl_value_timene}]}
                  {[{os.travel_quantity}]}
                    {{Form::open(array('action'=>'OSbillingsController@postStore'))}}
                  <input  class="form-control" type="number" :max="os.possible_hours" min="1" v-model="os.input_hours">

                     {[{(os.input_hours * os.real_arl_price) +(os.arl_value_timene*os.hours_not_efective) +(os.travel_quantity*os.travel_price) }]}
                    <input
                      class="form-control"
                      type="hidden"  min="0" v-model="os.input_price">

                  <input type="checkbox" v-model="os.selected">

                    <button class="btn btn-default" @click="bill">Crear facturas</button>

            {{Form::close()}}

And here is vue js

A: You can just in your request add the json which is your v-model in the body request, but the request have to be POST, PUT, PATCH.
in axios you do something like this
axios.post('/users', this.user).then(response => response);

In your controller, you will receive it like an array because laravel parses the object.
and you can get it like this
$request->user['name'] //for example


text:
Q: Form validation in conjunction with hidden fields Good day. Thanks to great assistance from Derek and Ross I have managed to put together a form with a validation option. The specific thing about this is that the page contains 3 forms which from only one is displayed depending of the drop-down list. Everything seems to be working perfectly apart from one thing. I can't submit the form because on the other 2 hidden forms there contain unfilled fields. How can I overcome this issue? I think it's a matter of adding to jquery a part which will ignore the hidden elements during validation process. But unfortunately I don't know how to do this.The code below:
HTML:
    <select id='selector'>
    <option value='opt1' id="opt1">Quote Request</option>
    <option value='opt2' id="opt2">General Enquiry</option>
    <option value='opt3' id="opt3">Feedback</option>
</select>

<form action="" method="post" id="form1" class="form" action="scripts/form-quote.php">

                Name
                <input id="name" name="name" type="text" placeholder="Name" class="required"/>

                E-mail
                <input id="email" name="email" type="text" placeholder="E-mail" class="required"/>

                Message
                <textarea id="msg" name="msg" cols="43" rows="8" placeholder="Please specify your requirements" class="required"></textarea>

                Referrer
                <input id="ad" name="ad" type="text" placeholder="Where did you hear about us?" />

        <button type="submit" class="submit">Request a quote</button>

</form>

<form action="" method="post" id="form2" class="form" action="scripts/form-general.php">

                Name
                <input id="name" name="name" type="text" placeholder="Name" class="required"/>

                E-mail
                <input id="email" name="email" type="text" placeholder="E-mail" class="required"/>

                Message
                <textarea id="msg" name="msg" cols="43" rows="8" placeholder="Please enter your message" class="required"></textarea>

                Referrer
                <input id="ad" name="ad" type="text" placeholder="Where did you hear about us?" />

        <button type="submit" class="submit">Send your message</button>

</form>

<form action="" method="post" id="form3" class="form" action="scripts/form-feedback.php">

        <select>
            <option value='General feedback'>General feedback</option>
            <option value='Website feedback'>Website feedback </option>
            <option value='Services feedback'>Provided services feedback</option>
        </select>

                Name
                <input id="name" name="name" type="text" placeholder="Name" class="required"/>

                E-mail
                <input id="email" name="email" type="text" placeholder="E-mail" class="required"/>

                Message
                <textarea id="msg" name="msg" cols="43" rows="8" placeholder="Your feedback" class="required"></textarea>

                Referrer
                <input id="ad" name="ad" type="text" placeholder="Where did you hear about us?" />

        <button type="submit" class="submit">Send your feedback</button>

</form>

jQuery:
 $(function () {
var addErrorMessage = function (field) {
        var err = $(document.createElement('p')).addClass('validation-error').text('Required field');
        field.addClass('err').after(err);
    },
    clearError = function () {
        var t = $(this);
        if (t.hasClass('err')) {
            t.removeClass('err');
            t.next('p').empty().remove();
        }
    },
    isEmpty = function (str) {
        return str.trim().length < 1;
    },
    isValidEmail = function (str) {
        var regexp = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        return regexp.test(str);
    },
    validateForm = function () {
        var requiredFields = $(this).find('.required'),
            email = $('#email'),
            fieldsValidate = true;

        // check that required fields are not empty
        requiredFields.each(function () {
            var t = $(this);
            if (isEmpty(t.val())) {
                fieldsValidate = false;
                if (!t.hasClass('err')) {
                    addErrorMessage(t);
                }
            }
        });

        // check that email is valid
        if (!isValidEmail(email.val().trim())) {
            fieldsValidate = false;
            if (!email.hasClass('err')) {
                addErrorMessage(email);
            }
        }
        return fieldsValidate;
    };

$('input, textarea').keyup(clearError);
$('#form1').submit(validateForm);

var $select = $("#selector");
$select.change(function () {
    if ($('#selector option:selected').attr("id") == "opt1") {
        if ($('#form1').is(":hidden")) {
            $('#form1').fadeIn(500);
        }
        $('#form2').hide();
        $('#form3').hide();
    }
    if ($('#selector option:selected').attr("id") == "opt2") {
        if ($('#form2').is(":hidden")) {
            $('#form2').fadeIn(500);
        }
        $('#form1').hide();
        $('#form3').hide();
    }
    if ($('#selector option:selected').attr("id") == "opt3") {
        if ($('#form3').is(":hidden")) {
            $('#form3').fadeIn(500);
        }
        $('#form1').hide();
        $('#form2').hide();
    }
});
});

And the jsFiddle here

A: Fiddle
This took me some time to fix. Your code had some problems. You had same id for fields in different forms, so when you submit a form he always gets the fields from the first form, even if you are writing on the 2nd or 3rd.
I added a parameter in your function and added a click function on the submit buttons. There were some more small things, which I corrected but forgot what was along the way. I changed the keyup to blur. In case people use autocomplete it's more user friendly, change back if you don't like.
It might be some more small things to fix. But what you wanted is here, I think.
I added some console.log(); this is a good idea for your future debugging :)
HTML:
<select id='selector'>
    <option value='opt1' id="opt1">Quote Request</option>
    <option value='opt2' id="opt2">General Enquiry</option>
    <option value='opt3' id="opt3">Feedback</option>
</select>
<form method="post" id="form1" class="form" action="scripts/form-quote.php">

            Name
            <input id="namef1" name="name" type="text" placeholder="Name" class="required" />

            E-mail
            <input id="emailf1" name="email" type="text" placeholder="E-mail" class="required" />

            Message
            <textarea id="msgf1" name="msg" cols="43" rows="8" placeholder="Please specify your requirements" class="required"></textarea>

            Referrer
            <input id="adf1" name="ad" type="text" placeholder="Where did you hear about us?" />

    <button type="submit" class="submit">Request a quote</button>
</form>
<form method="post" id="form2" class="form" action="scripts/form-general.php">

            Name
            <input id="namef2" name="name" type="text" placeholder="Name" class="required" />

            E-mail
            <input id="emailf2" name="email" type="text" placeholder="E-mail" class="required" />

            Message
            <textarea id="msgf2" name="msg" cols="43" rows="8" placeholder="Please enter your message" class="required"></textarea>

            Referrer
            <input id="adf2" name="ad" type="text" placeholder="Where did you hear about us?" />

    <button type="submit" class="submit">Send your message</button>
</form>
<form method="post" id="form3" class="form" action="scripts/form-feedback.php">
    <select>
        <option value='General feedback'>General feedback</option>
        <option value='Website feedback'>Website feedback</option>
        <option value='Services feedback'>Provided services feedback</option>
    </select>

            Name
            <input id="namef3" name="name" type="text" placeholder="Name" class="required" />

            E-mail
            <input id="emailf3" name="email" type="text" placeholder="E-mail" class="required" />

            Message
            <textarea id="msgf3" name="msg" cols="43" rows="8" placeholder="Your feedback" class="required"></textarea>

            Referrer
            <input id="adf3" name="ad" type="text" placeholder="Where did you hear about us?" />

    <button type="submit" class="submit">Send your feedback</button>
</form>

JS:
var addErrorMessage = function (field) {
    var err = $(document.createElement('p')).addClass('validation-error').text('Required field');
    field.addClass('err').after(err);
},
clearError = function () {
    var t = $(this);
    if (t.hasClass('err')) {
        t.removeClass('err');
        t.next('p').empty().remove();
    }
},
isEmpty = function (str) {
    return str.trim().length < 1;
},
isValidEmail = function (str) {
    var regexp = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regexp.test(str);
},
fieldsValidate = false;

function validateForm(e) {
    console.log('validate start');
    var requiredFields = jQuery(e).find('.required');
    var email = jQuery(e).find('input[name="email"]');
    var emailValue = email.val();
    console.log(emailValue+' mail val');
    fieldsValidate = true;
    // check that required fields are not empty
    requiredFields.each(function () {
        var t = $(this);
        if (isEmpty(t.val())) {
            fieldsValidate = false;
            if (!t.hasClass('err')) {
                addErrorMessage(t);
            }
        }
    });

    // check that email is valid
    console.log(isValidEmail(emailValue) + ' valid?');

    if (!isValidEmail(emailValue)) {
        fieldsValidate = false;
        if (!email.hasClass('err')) {
            addErrorMessage(email);
            console.log('mail NOT ok');
        }
    }
    console.log(fieldsValidate + ' before return');
    return fieldsValidate;
};

$('input, textarea').blur(clearError);

$(".submit").click(function() { return validateForm(this.form) });

var $select = $("#selector");
$select.change(function () {

    if ($('#selector option:selected').attr("id") == "opt1") {
        if ($('#form1').is(":hidden")) {
            $('#form1').fadeIn(500);
        }
        $('#form2').hide();
        $('#form3').hide();
    }
    if ($('#selector option:selected').attr("id") == "opt2") {
        if ($('#form2').is(":hidden")) {
            $('#form2').fadeIn(500);
        }
        $('#form1').hide();
        $('#form3').hide();
    }
    if ($('#selector option:selected').attr("id") == "opt3") {
        if ($('#form3').is(":hidden")) {
            $('#form3').fadeIn(500);
        }
        $('#form1').hide();
        $('#form2').hide();
    }
});

A: If the form is not dynamic, you can just check the id and deny any matching hidden elements that should be empty.


text:
Q: Rendering problem with React app inside Docker container The React app described below is built in VS Code with React v18.0.0, node v.14.15.4 and npm v8.4.1.  It also imports modules from a 3rd party mapping API called the ArcGIS JavaScript API and I'm running v4.18 of that.
I've used this mapping API to create many vanilla JS web apps over the years.  I reference its JS and CSS via CDN.  The current need is to leverage it within a React app that's deployed in a Docker container running NGINX.
I can launch the app from VS Code using 'npm start'.  It runs at localhost:3000 and everything works as expected.  The map renders within the correct div and it shows the gray canvas basemap tiles.  The CSS is also loading correctly and the zoom +/- buttons render correctly.  All of this correct behavior happens when the app is launched locally.  I can deploy it IIS or I can just run 'npm start' in VS Code and it runs without issues.  This is how it displays:

Code within the React app that creates the map and map view:
import logo from './logo.svg';
import './App.css';
import { useEffect, useState, useRef } from "react";
import esriConfig from "@arcgis/core/config";
import Map from "@arcgis/core/Map";
import MapView from "@arcgis/core/views/MapView";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";

function App() {
  const mapRef = useRef();

  esriConfig.apiKey = "REMOVED";

  const initMap = () => {
    const map = new Map({
      basemap: "arcgis-light-gray",
      layers: []
    });

    const view = new MapView({
      map: map,
      center: [-82.354, 27.895],
      zoom: 9,
      container: mapRef.current,
    });
  };

  useEffect(() => {
    initMap();
  }, []);

  return (

  );
}

export default App;

All of the above works when hosted locally or builT and deployed to IIS.
But the ultimate goal is to deploy this app within a Docker container running NGINX.  The docker image builds successfully and also runs successfully, but when I browse the app running inside the container the basemap tiles don't render.  CSS and JS are both being loaded, I get 200 responses for both.  The 3rd party content is loading but for some reason the images tiles in the map don't render and all I get is a map with a blank background.

I get the same result in Chrome and Edge.  There are no errors or exception thrown in the browser's console.  It's as if the JS API is loading successfully but somehow the image tiles aren't rendering and I can't see any reason why this would fail only inside a Docker container.
Dockerfile
FROM node:latest as build

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

RUN npm run build

FROM nginx:latest

COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/build/ /usr/share/nginx/html/

.dockerignore file
node_modules
Dockerfile
.git

default.conf for NGINX
server {
    listen 80;
    listen [::]:80;

    root /usr/share/nginx/html;
    index index.html index.htm index.nginx-debian.html;

    server_name localhost;

    location / {
        try_files $uri $uri/ =404;
    }
}

Because I have other React apps with ArcGIS JS maps working perfectly, I believe the problem has to have something to do with Docker and/or NGINXand how it is failing to handle the image tiles correctly.
I also noticed some differences in the requests being made by each version of this app.  In the network tab of Chrome's developer tools it looks like the app makes an extra call when running locally that is not made when it's running in a docker container.
Locally it makes two calls to LightGray:Base and LightGray:Labels, and also World_Basemap_v2 further down.

I see fewer calls for the light gray basemap resource in the Docker container and no request for World_Basemap_v2 at all.

Unfortunately I don't know if the above differences are significant at all.
Has anyone else had any issues along these lines?  I've already called for help on the ArcGIS forum but I sense that almost nobody is trying to run this API within Docker.
Thanks
Update & Work-Around
Uninstalling @arcgis/core and installing esri-loader instead resulted in correct rendering of the basemap I'm using.
import logo from "./logo.svg";
import "./App.css";
import { loadModules } from "esri-loader";

function App() {

  loadModules(['esri/config', 'esri/views/MapView', 'esri/Map']).then(([esriConfig, MapView, Map]) => {
    esriConfig.apiKey = "REMOVED";

    const map = new Map({
      basemap: 'arcgis-light-gray'
    });

    const mapView = new MapView({
      map: map,
      zoom: 10,
      center: [-82.5, 28],
      container: "map-div"
    });
  });

  return (

  );
}

export default App;

A: I found two work-arounds.
The problem seems to be with the esriConfig module, specifically defining an API key within a React app.  A key is required to use the premium set of basemaps which includes the one I'm using, "arcgis-light-gray".  I have always defined my developer API key in my ArcGIS JS apps and I've done so in this React app as well.  But this module appears to be broken in React.  Either that or I need to reference the module differently than I currently am.  If so, it's not covered in any documentation I could find.
Work-around #1 - use a non-premium basemap like "gray" or "gray-vector".  These basemaps lack the same level of detail at higher zoom levels, making this approach unacceptable if you want to zoom in to larger scales and see detail on individual parcels.
Work-around #2 - uninstall @arcgis/core and install esri-loader instead.  This set of modules appears to be the better way to use the ArcGIS JS API in React.  With esri-loader the modules are imported with the loadModules function instead of require or import.  After refactoring the app to use esri-loader I am now able to define my API key and the premium "arcgis-light-gray" basemap renders correctly.  I'll put updated code in the original post.


text:
Q: Buffered writer writes memory trash on text file My buffered writer is writting some randomly trash in my txt file. I use int  nodes = Integer.valueOf(NODES_TEXT_FIELD.getText()); to store the value of one TextField that should only accept ints.
this is my writer:
 private static void writeOnFile(BufferedWriter writer, int nodes){

           try {
               System.out.println(nodes);
               System.out.println("Last check before write");
                writer.write(nodes);
                System.out.println(nodes);
        } catch (IOException e) {

            JOptionPane.showMessageDialog(null, "Failed to write data on file");
                e.printStackTrace();
        }
       }

My output:
2
Last check before write
2

and in the text file I found: '?' (which changes to another memory trash depending on what number you input
Anybody has any Idea of what might be wrong? I stuck here for 5 hours until now..

A: Because write() writes a character .

Writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.
Parameters:
c - int specifying a character to be written

You can use Writer#write(String):
writer.write(String.valueOf(nodes));

A: Try this:
Writer wr = new FileWriter("thefileToWriteTo.txt");
wr.write( String.valueOf(nodes) );
wr.close();

you can always extract the writing into a loop if that is what you are doing with your nodes or some kind of escaping, it would be more helpful if you explain what is it that you are actually trying to achieve by writing this to a file, as we might advise you on that.


text:
Q: Angular async function call from template I try to build an image-cache service for my Ionic application.
<ion-col [routerLink]="['/category-detail',cat.objectId,i]" class="category-item"
      *ngFor="let cat of categories;index as i" size="3">
      <ion-img class="cat-image" [src]="getImage(cat.image.url) | async">
      </ion-img>
      <p class="cat-name">
        {{cat.name}}
      </p>
    </ion-col>

I am calling the function from src tag in ion-image
async getImage(fileUrl: any) {
    return await this.cacheService.checkFile(fileUrl);
  }

This functions checking a file if its there it returns URL of file else it returns URL in parameter
public async checkFile(fileUrl) {
    let stringURL = String(fileUrl);
    let fileName = stringURL.split('//')[1].replace(/\//g, '-');
    return this.file.checkFile(this.file.tempDirectory, fileName)
      .then(
        async result => {
          if (result) {
            return this.file.tempDirectory + fileName;
          } else {
            return fileUrl;
          }
        }
      )
      .catch(
        async err => {
          //FileError.NOT_FOUND_ERR
          if (err.code == 1) {
            let fileTransfer: FileTransferObject = this.transfer.create();
            return fileTransfer.download(fileUrl, this.file.tempDirectory + fileName, true)
              .then(
                result => {
                  console.log(result);
                  return result;
                }
              )
              .catch(
                error => {
                  throw error;
                }
              )

          } else {
            throw err;
          }

        }
      )
  }

I searched various of questions and examples but none of them worked for me.
My goal is try to return a dynamic URL with a promise chain.
I am so confused with async,promise and observable keywords in Angular.
My project config :
Ionic:

   Ionic CLI                     : 6.9.1 (/Users/suatkarabacak/npm/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 5.1.1
   @angular-devkit/build-angular : 0.803.26
   @angular-devkit/schematics    : 8.3.26
   @angular/cli                  : 8.3.26
   @ionic/angular-toolkit        : 2.2.0

Cordova:

   Cordova CLI       : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms : android 8.1.0, ios 5.1.1
   Cordova Plugins   : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.2.1, (and 7 other plugins)

Utility:

   cordova-res : 0.14.0
   native-run  : 1.0.0

System:

   ios-deploy : 1.9.4
   ios-sim    : 8.0.2
   NodeJS     : v10.16.3 (/usr/local/bin/node)
   npm        : 6.9.0
   OS         : macOS Catalina
   Xcode      : Xcode 11.3 Build version 11C29

A: I would use a custom pipe in this case to implement your requirement.
so basically you have something like the following in your template:
<ion-col ... *ngFor="let cat of categories ..." ...>
   <ion-img ... [src]="cat | catImageUrl | async"></ion-img>
</ion-col>

Then you'll implement a custom Angular pipe getting cat image URL from a cat object asynchronously:
@Pipe({name: 'catImageUrl'})
export class CatImageUrlPipe implements PipeTransform {
  constructor(/* inject your cache service */) {}

  transform(cat: Category): Promise<string> {
    return this.cacheService.checkFile(cat.image.url);
  }
}

And that's all you need. Basically you compose 2 pipes together to make a Category -> Promise<string> -> string transformation to get the image url.

A: Ignoring your checkFile method, but you can use the async pipe:
image : Promise<any>;

ngOnInit(): void {
  if (this.cat) {
    this.image = this.cacheService.checkFile(this.cat.image.url);
  }
}

<ion-img class="cat-image" [src]="image | async"></ion-img>

basically, you only need to use async/await if you really want to wait for a Promise. When you are actually returning the promise, there is no use of it. Just clutters your code


text:
Q: Wait for a method to return true I have two methods A and B. A calls the B method from inside. B method returns true or false whether a file is having content or not. Here is the code:
    public static void A()
    {
        var isValid = B();
        // Wait until "isValid" comes true
        var xx = "test";
    }

    public static bool B()
    {
        // This will check for a file content
        // Say C://test.txt
        // If the file has some content this method will return true else false
    }

I want the A method to wait and do not execute the "var xx = "test";" line unless the B method returns true. Can you help me by giving some pointers how to do that?
EDIT: I cant use if loop simply i.e if(isValid) because the file for which the content is to be checked is written by some other thread so I need to continuously check that B method from inside the A. I can't let this piece of code "var xx = "test";" to be executed unless B returns true and if it is returning false the code should wait there (at var isValid = B();) unless B returns true i.e the code should continuously check the B status.

A: You should use a while loop
while (!B ()) { }
var x = "test";

This will execute B until it returns true. A better approach is probably to implement an event which will trigger when a condition turns true.
Considering you're using files,  you could look into FileSystemWatcher,  which can trigger a method if a file changes.

A: Use a FileSystemWatcher object with the Changed event handler pointed to a method that will be executed when the file content changes (and has content after the change).
See the example here.

A: Try this:
if(B())
    var xx = "test";

A: Try this
public static void A()
    {
       while(!B())
        {
       var isValid = B(); //whatever the code
        }
     var xx = "test";
    }


text:
Q: Eliminate temp file usage from shell script that extracts patterns from a file I have an input text file:
EL.EEX.FRANCE.DELMONTHS.JAN2016.SPOT.VOL      15JAN2016
EL.EEX.GERMANY.DELMONTHS.JAN2016.SPOT.L       15JAN2016
EL.EEX.GERMANY.DELMONTHS.JAN2016.SPOT.H       15JAN2016
EL.EEX.GERMANY.DELMONTHS.JAN2016.SPOT.S       15JAN2016
EL.EEX.ITALY.DELMONTHS.JAN2016.FWD            15JAN2016
EL.EEX.ITALY.DELMONTHS.JAN2016.FWD            15JAN2016

Given the sample data upto the max level of dot(.) we need unique type of 1 representative sample(complete line) without dates. So the output will be
EL.EEX.FRANCE.DELMONTHS.JAN2016.SPOT.VOL
EL.EEX.GERMANY.DELMONTHS.JAN2016.SPOT.L
EL.EEX.ITALY.DELMONTHS.JAN2016.FWD

(The order of the lines in the output doesn't matter.)
Below program works fine but it generates many intermediate temp files. How could we do without that in shell?
#input file name and path assumed in current directory
file="./osc.txt"
resultfilepath="./OSCoutput.txt"
tmpfilepath="./OSCtempoutput.txt"
tmp1filepath="./OSCtemp1output.txt"
tmp2filepath="./OSCtemp2output.txt"

rm $resultfilepath
rm $tmpfilepath
#using awk to filter only series data without dates
awk -F' ' '{print $1}' $file >> $tmpfilepath

#getting all the unique dataclass_names at column 1
DATACLASSNAME=(`cut -f 1 -d'.' $tmpfilepath | sort | uniq`)
for i in "${DATACLASSNAME[@]}"; do
rm $tmp1filepath
#we are filtering the file with that dataclass
awk -F'.' -v awk_dataclassname="$i" '$1==awk_dataclassname' $tmpfilepath >> $tmp1filepath
#also we are calculating the number of delimeter in filtered record and sorting it
COLCOUNT=(`awk -F'.' '{print NF}' $tmp1filepath | uniq | sort`)
for j in "${COLCOUNT[@]}"; do
rm $tmp2filepath
#in the filtered data we are taking series of a particular dimension length and dumping data
awk -F '.' -v awk_colcount="$j" '(NF==awk_colcount){print}' $tmp1filepath >> $tmp2filepath
#reducing column no by 1
newj=$(echo $((j - 1)))
#removing last column(generally observation dimension) by cut column
GREPSAMPLE=(`cut -f -$newj -d'.' $tmp2filepath | uniq`)
SAMPLELENGTH=(`wc -l $tmp2filepath`)
#we are now taking unique series sample
for k in "${GREPSAMPLE[@]}"; do
#doing grep of unique sample but taking the whole line
echo `grep $k $tmp1filepath | head -1` >> $resultfilepath

done
done
done
cat $resultfilepath
echo "processing finish"

A: The whole thing can be accomplished with just this awk invocation.
awk '{
    key = $0;
    sub("\\.[^.]*$", "", key);      # Let key be everything up to the last dot

    if (!seen[key]) { print $1 }    # If key has not been seen, print 1st col
    seen[key] = 1;                  # Mark the key as seen
}' "$file" > "$resultfilepath"

In general, when you have a script that involves lots of awking and grepping, chances are that you can just write an awk script.


text:
Q: PythonAnywhere JSONDecodeError I am attempting Codecademy's DjangoVet final module and am getting the below error in the error.log when I try and deploy via PythonAnywhere
2023-02-11 07:01:19,598: Error running WSGI application
2023-02-11 07:01:19,599: json.decoder.JSONDecodeError: Expecting ':' delimiter: line 2 column 18 (char 19)
2023-02-11 07:01:19,599:   File "/var/www/dollarbi11_pythonanywhere_com_wsgi.py", line 17, in <module>
2023-02-11 07:01:19,600:     application = get_wsgi_application()
2023-02-11 07:01:19,600:
2023-02-11 07:01:19,600:   File "/home/DollarBi11/.virtualenvs/vet/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
2023-02-11 07:01:19,600:     django.setup(set_prefix=False)
2023-02-11 07:01:19,600:
2023-02-11 07:01:19,601:   File "/home/DollarBi11/.virtualenvs/vet/lib/python3.10/site-packages/django/__init__.py", line 19, in setup
2023-02-11 07:01:19,601:     configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
2023-02-11 07:01:19,601:
2023-02-11 07:01:19,602:   File "/home/DollarBi11/.virtualenvs/vet/lib/python3.10/site-packages/django/conf/__init__.py", line 82, in __getattr__
2023-02-11 07:01:19,602:     self._setup(name)
2023-02-11 07:01:19,602:
2023-02-11 07:01:19,602:   File "/home/DollarBi11/.virtualenvs/vet/lib/python3.10/site-packages/django/conf/__init__.py", line 69, in _setup
2023-02-11 07:01:19,603:     self._wrapped = Settings(settings_module)
2023-02-11 07:01:19,603:
2023-02-11 07:01:19,603:   File "/home/DollarBi11/.virtualenvs/vet/lib/python3.10/site-packages/django/conf/__init__.py", line 170, in __init__
2023-02-11 07:01:19,603:     mod = importlib.import_module(self.SETTINGS_MODULE)
2023-02-11 07:01:19,603:
2023-02-11 07:01:19,603:   File "/home/DollarBi11/djangovet/djangovet/settings.py", line 29, in <module>
2023-02-11 07:01:19,604:     project_keys = json.loads(k.read())
2023-02-11 07:01:19,604:
2023-02-11 07:01:19,604:   File "/usr/local/lib/python3.10/json/__init__.py", line 346, in loads
2023-02-11 07:01:19,604:     return _default_decoder.decode(s)
2023-02-11 07:01:19,604:
2023-02-11 07:01:19,605:   File "/usr/local/lib/python3.10/json/decoder.py", line 337, in decode
2023-02-11 07:01:19,605:     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
2023-02-11 07:01:19,605:
2023-02-11 07:01:19,605:   File "/usr/local/lib/python3.10/json/decoder.py", line 353, in raw_decode
2023-02-11 07:01:19,605:     obj, end = self.scan_once(s, idx)

Here is the code for the dollarbi11_pythonanywhere_com_wsgi.py file, which I copied from the project tutorial
# +++++++++++ DJANGO +++++++++++
import os
import sys
#
## assuming your django settings file is at '/home/yourname/mysite/mysite/settings.py'
## and your manage.py is is at '/home/yourname/mysite/manage.py'
path = '/home/DollarBi11/djangovet'
if path not in sys.path:
    sys.path.append(path)
#
os.environ['DJANGO_SETTINGS_MODULE'] = 'djangovet.settings'
#
## then:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Lines 26 to 29 of settings.py
KEYSDIR = str(BASE_DIR)+"/keys.json"

with open(KEYSDIR) as k:
    project_keys = json.loads(k.read())

keys.json
{
    "SECRET_KEY" = "XXXX"
}

A: It looks like the problem is in your keys.json file; you should use colons rather than equals signs to separate keys and values, so it should be this:
{
    "SECRET_KEY": "XXXX"
}


text:
Q: const корректность для указателей class InnerTest
{
public:
    InnerTest() {};
    ~InnerTest() {};

    void some_non_const_method() { std::cout << ++m_data << std::endl; }

private:
    int m_data{ 0 };
};

class Test
{
public:
    Test() {};
    ~Test() {};

    // error C2662: 'void InnerTest::some_non_const_method(void)': cannot convert 'this' pointer from 'const InnerTest' to 'InnerTest &'
    void foo() const { m_test.some_non_const_method(); };

    void bar() const { m_ptest->some_non_const_method(); };

private:
    InnerTest m_test;
    std::unique_ptr<InnerTest> m_ptest{ std::make_unique<InnerTest>() };
};

int main()
{
    Test t1;

    t1.foo();
    t1.bar();

    return 0;
}

Итак есть примерно такой код, как можно добиться const корректности при использовании указателей для константных методов?

A: Компилятор прав - у вас член имеет тип
unique_ptr<InnerTest>

и его значение вы не меняете. Если вы хотите явно указать, что там у вас константный указатель - то скажите об этом прямо:
unique_ptr<const InnerTest>

Все, вообще-то корректно - const в функции-члене относится к объекту класса, так что m_test, входящий в объект класса, действительно не может вызывать неконстантный метод. Но какой-то левый, не пойми где находящийся объект InnerTest - с какой стати ему запрещать вызывать неконстантный метод?...

A: В С++ const корректность не подразумевает транзитивности, т.е. const применяется только к самому объекту (указателю), но не распространяется на объекты, на которые тот указывает. А умные указатели из стандартной библиотеки просто мимикрируют поведением обычных указателей. Однако несложно реализовать обертку, имитирующую транзитивное поведение, для этого следует лишь добавить соотв. const перегрузки:
online compiler
template< typename x_Value > class
t_TransitivePtr
{
    private: x_Value * m_p_value;

    public: explicit t_TransitivePtr(x_Value * p_value): m_p_value{p_value} {}

    public: x_Value & operator * (void) { return *m_p_value; }

    public: x_Value const & operator * (void) const { return *m_p_value; }

    public: x_Value * operator -> (void) { return m_p_value; }

    public: x_Value const * operator -> (void) const { return m_p_value; }
};

#include <string>

class
t_Test
{
    private: t_TransitivePtr<::std::string> m_ptr;

    public: explicit t_Test(::std::string & value): m_ptr{&value} {}

    public: void Method(void) { m_ptr->clear(); } // OK

    public: void ConstMethod(void) const { m_ptr->clear(); } // Error
};

В разных других языках может быть реализовано другое поведением. Например в языке D const полностью транзитивный; это подразумевает, что const указатель в принципе не может указывать на не const объект.


text:
Q: HTML tag for text on single row  vs  vs  I have two text fields which I want to show side by side

My Poems

If I use  for the
, they remain side by side. Any other tag I use (
,
, ) all puts in the next row.
I have changed the css width of the navbar-brand, navbar-header so it doesn't wrap around. Am I missing something... do I need to give float or some other way to make it stand side by side

A: Add display:inline or display:inline-block to your h4 tag like this

My Poems

or give your element a classname and add define its style to display inline-block like this

My Poems

.myTitle{display:inline-block;}


text:
Q: Simple Backbone.JS in CoffeeScript Errors I have a very simple Backbone.JS app developed, for learning CoffeeScript + Backbone.JS:
class Todo extends Backbone.Model
    defaults:
        title: ''
        priority: 0
        done: false

class Todo extends Backbone.Collection
    model: Todo
    localStorage: new Backbone.LocalStorage("Todos")

t = new Todo({ title: 'todo 1' })
console.log t

But I am getting (looks very much like an infinite loop)
<error>
b.extend
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel
f.extend.add
f.extend.reset
g.Collection
Todo
f.extend._prepareModel

With normal JS I define class and inheritance like
Todo = Backbone.Model.extend({})

But in CoffeeScript its
class Todo extends Backbone.Model

are they the same? I dont think so, is this the cause of the problem?

A: You have a typo in your collection, you want to call it Todos, not Todo:
class Todos extends Backbone.Collection
    model: Todo
    localStorage: new Backbone.LocalStorage("Todos")

If I do this:
class Todo extends Backbone.Model
class Todo extends Backbone.Collection
    model: Todo

t = new Todo(title: 'todo 1')
console.log t

I get a "Maximum call stack size exceeded." error: http://jsfiddle.net/ambiguous/FTCr2/
But if the collection is called Todos, things work: http://jsfiddle.net/ambiguous/RrA2D/
Your problem seems to be that your collection's model property is the collection itself so you end up with infinite recursion as the collection tries to create a model which is actually the collection ...


text:
Q: Pylibnet installation error ubuntu 14 I've been looking in the internet for a solution of this issue when i try to install pylibnet , i would like to know if you guys were be able to install pylibnet succesfully and how.
Thanks
root@root:/home/core2# pip install ./pylibnet-3.0-beta-rc1.tar.gz
Unpacking ./pylibnet-3.0-beta-rc1.tar.gz
  Running setup.py (path:/tmp/pip-LSMFJM-build/setup.py) egg_info for package from file:///home/core/pylibnet-3.0-beta-rc1.tar.gz
    Searching for libnet...
    Could not locate the static library "libnet.a"
    Complete output from command python setup.py egg_info:
    Searching for libnet...

Could not locate the static library "libnet.a"

----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 255 in /tmp/pip-LSMFJM-build
Storing debug log for failure in /root/.pip/pip.log

A: Try runnning
$ find / | grep libnet.a

or
$ locate libnet.a

and if it is found somewhere then move it to /usr/lib/libnet.a because this is where pip looks for it when it trys to install pylibnet e.g.
$ sudo cp /usr/lib/i386-linux-gnu/libnet.a /usr/lib/libnet.a

this worked for me :-)


text:
Q: How to make the indentifier "tortuga" not to be undefined? I want to create this function:
void drawSquare(int x) {
    tortuga.forward(x);
    tortuga.right(90);
    tortuga.forward(x);
    tortuga.right(90);
    tortuga.forward(x);
    tortuga.right(90);
}

However, I get that the identifier "tortuga" is undefined.
I tried to modify the function like this:
void drawSquare(int x) {
    ct::TurtleScreen scr;
    scr.bgcolor({ "white" });
    ct::Turtle tortuga(scr);
    Home(tortuga);
    tortuga.forward(x);
    tortuga.right(90);
    tortuga.forward(x);
    tortuga.right(90);
    tortuga.forward(x);
    tortuga.right(90);
    tortuga.pencolor({ "red" });
    tortuga.speed(ct::TS_FASTEST);
    scr.exitonclick();
}

I get that the identifier "tortuga" is defined now, which seems to work.However, 20ish windows appeared where in each window, the turtle only drew three sides of a square like the following image:
image
I expected a spiral to be drawn.
Here is all the program:
#include"CTurtle.hpp"
#include <iostream>
using namespace std;
#define Home(x) x.left(90)

namespace ct = cturtle;
int shellSize;
int initialShellSize;

void drawSquare(int x) {
    ct::TurtleScreen scr;
    scr.bgcolor({ "white" });
    ct::Turtle tortuga(scr);
    Home(tortuga);
    tortuga.forward(x);
    tortuga.right(90);
    tortuga.forward(x);
    tortuga.right(90);
    tortuga.forward(x);
    tortuga.right(90);
    tortuga.pencolor({ "red" });
    tortuga.speed(ct::TS_FASTEST);
    scr.exitonclick();
}

int main(int argc, char** argv) {
    std::cout << "Type the size of the outershell of the spiral: "; // Type a number and press enter
    std::cin >> shellSize; // Get user input from the keyboard
    initialShellSize = shellSize;

    for (int i = 10; i <= initialShellSize; i = i + 10)
    {
        shellSize = initialShellSize - (initialShellSize/i);
        drawSquare(shellSize);
    }

    return 0;
}

A: I've never used this library before, but it seems all you need to do is add a turtle parameter to your function and pass the turtle object to the function. This is not dissimilar to what you've already done with the x parameter. Parameter passing is a basic technique of the C++ language (and pretty much any programming language).
void drawSquare(ct::Turtle& tortuga, int x) {
    Home(tortuga);
    tortuga.forward(x);
    tortuga.right(90);
    tortuga.forward(x);
    tortuga.right(90);
    tortuga.forward(x);
    tortuga.right(90);
    tortuga.forward(x);
}

int main(int argc, char** argv) {
    std::cout << "Type the size of the outershell of the spiral: "; // Type a number and press enter
    std::cin >> shellSize; // Get user input from the keyboard
    initialShellSize = shellSize;

    ct::TurtleScreen scr;
    scr.bgcolor({ "white" });
    ct::Turtle tortuga(scr);
    for (int i = 10; i <= initialShellSize; i = i + 10)
    {
        shellSize = initialShellSize - (initialShellSize/i);
        drawSquare(tortuga, shellSize);
    }

    return 0;
}

I've used a reference ct::Turtle& tortuga instead of ct::Turtle tortuga. I'm guessing that is right, but as I said I've never used this library before.
And as already mentioned to get a square I'm guessing you need to call forward four times.
I've also put the call to Home inside the function, you might disagree.


text:
Q: Адаптер для картинок [Вопрос закрыт] В JSON списке имеется ссылки на картинки.
Объясните, пожалуйста, как сделать так, что бы при выводе отображались картинки.
Json файл имеет следующий вид:
{"list" : [{ "title" : "350.png", "description" : "1", "imageURL" : "URL" },{ "title" : "Dom.jpg", "description" : "2", "imageURL" : "URL" }.... и тп

A: *

*
Добавляем uses_permission для доступа вашего приложения в интернет:
<uses-permission android:name="android.permission.INTERNET"/>

*
Создаем класс с сеттерами и геттерами для заполнения Вашего списка:
То есть в Вашем случае должно быть три функции для установки значений:
title, description, imageURL и три соответственно для возврата  их значений.
Создадим такой класс:
public class MySetGetClass
    {

    String title;
    String description;
    String imageURL;
    public MySetGetClass(String title, String description, String imageURL) {
            this.title = title;
            this.description = description;
            this.imageURL = imageURL;
    }

// ГЕТТЕРЫ – жрицы любви
    public String getTitle() {
            return title;
    }
    public String getDescription() {
            return description;
    }
    public String getImageUrl() {
            return imageURL;
    }

// СЕТТЕРЫ
    public void setTitle(String title) {
            this.title = title;
    }

    public void setName(String description) {

            this. description = description;
    }

    public void setImageUrl(String imageURL) {
            this. imageURL = imageURL;
    }
  }

С этим классом вроде разобрались, идем дальше!

*

*
Создаем свой кастомный адаптер для наполнения нашего списка.
Т.к. стоит цель загрузки изображений из сети, а заморачиваться с этим самому большого желания нет, поэтому скачиваем библиотеку https://github.com/nostra13/Android-Universal-Image-Loader и добавляем .jar файл библиотек в наш проект.
Далее сам класс нашего адаптера.
public class MyAdapter extends ArrayAdapter< MySetGetClass > {
private final Activity activity;
private final ArrayList< MySetGetClass > entries;
public MyAdapter (final Activity a, final int textViewResourceId, final ArrayList< MySetGetClass > entries) {
        super(a, textViewResourceId, entries);
        this.entries = entries;
        activity = a;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        ViewHolder holder;
        if (v == null) {
                LayoutInflater inflater = (LayoutInflater) activity
                                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = inflater.inflate(R.layout.ваш_лайоут_с_ImageView и двумя TextView, parent, false);
                holder = new ViewHolder();
                // инициализируем нашу разметку
                holder.text1 = (TextView) v.findViewById(R.id.textView1);
                holder.text2 = (TextView) v.findViewById(R.id.textView2);
                holder.imageView = (ImageView) v.findViewById(R.id.imageView1);
                v.setTag(holder);
        } else {
                holder = (ViewHolder) v.getTag();
        }
        MySetGetClass mySetGet = entries.get(position);
        if (mySetGet != null) {
                holder.text1.setText(mySetGet.getTitle());
                holder.text1.setText(mySetGet.getDescrition());
                ImageLoader imageLoader = ImageLoader.getInstance();
                imageLoader.init(ImageLoaderConfiguration.createDefault(getContext()));
                imageLoader.displayImage(mySetGet.getImageUrl(), holder.imageView);
        }
        return v;
}
   private static class ViewHolder {
        public TextView text1;
        public TextView text2;
        public ImageView imageView;
      }

}
Адаптер готов, пора передавать ему значения.

*

*
Заполнение адаптера
В основной активности, во время парсинга, Вы убираете HashMap (он Вам больше не нужен) и делаете следующее:
public class MainActivity extends Activity {
private MyAdapter adapter;
private final ArrayList<MySetGetClass> nutro= new ArrayList< MySetGetClass >();
private ListView list;

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

        nutro.removeAll(nutro);
        for(int i =0; i < ja.length(); i++) {
        JSONObject my_obj = ja.getJSONObject(i);
        title = my_obj.getString("title");
        description = my_obj.getString("description");
        imageURL = my_obj.getString("imageURL");
        MySetGetClass struct = new MySetGetClass (title,description,imageURL);
        nutro.add(struct);
        }

        list = (ListView) findViewById(R.id.listView1);
        adapter = new FriendsAdapter(MainActivity.this, R.id.listView1, nutro);
        lv.setAdapter(adapter);
}

}
Запускаем и проверяем! Вроде все.


text:
Q: generating a list with php, depending on button id and value I'm new to web development and don't quite know everything I need. So I'm trying to generate a list with php from an xml file, when a button is clicked. The generation is dependant on the button's id and value.
Here is the php generating the list:
<?php

$art_c=$_REQUEST["art"];
$an_c=$_REQUEST["an"];
$fisier="arh.xml";
$xml=simplexml_load_file($fisier) or die("Unable to load XML file!");

foreach($xml->an as $an)
{
    if($an['anid']==$an_c)
    {
        foreach($an->nr as $nr)
        {
            if($nr['nrid']==$nr_c)
            {
                foreach($xml->articol as $art)
                {
                    $univ = array();
                    $aut = array('','','','','','','','','','');
                    $articol=trim($art).".xml";
                    $xmlart=simplexml_load_file($articol) or die("Unable to load XML file!");

                    echo '
Title:&nbsp
';
                    echo "";
                    $tit=$xmlart->titlu;
                    echo "$tit";
                    echo "
";
                    echo '
Autori:&nbsp
';

                    foreach($xmlart->autor as $autor)
                    {
                        $idx=$autor['univ'];
                        for($i=0;$i<sizeof($univ);$i++)
                        {
                            if(strcmp($univ[$i],$idx)==0)break;
                        }
                        if($i>=sizeof($univ))
                        {
                            $univ[$i]=$idx;
                        }
                        if(strlen($aut[$i])==0)$aut[$i]=$autor;
                        else $aut[$i]=$aut[$i].', '.$autor;
                    }

                    for($i=0;$i<sizeof($univ);$i++)
                    {
                        echo $aut[$i].' - '.$univ[$i];
                        echo "
";
                        echo "           &nbsp";
                    }

                }
            }
        }
    }

}

echo "
";

I tried dending the id adn value with ajax, but the php does not get the variables I send with ajax.
A model of the xml file is here:
<?xml version="1.0" encoding="UTF-8" ?>
<rev>
  <an anid="2014">
    <nr nrid="1" data="27 martie">
      <articol>
        <titlu>titlu1</titlu>
        <autor univ="UAIC">Ionescu</autor>
        <autor univ="UMF">Cata</autor>
        <autor univ="UMF">Stan</autor>
        <autor univ="UAIC">Alex</autor>
        <autor univ="UAIC">Dan</autor>
        <tag>tag1,tag2,tag3</tag>
        <id>2014_1_1</id>
      </articol>

Any idea how could I do this?

A: Your ajax request is not correct, you didn't set the values for "art" and "an", it should be something like "cuprins.php?art=xxx&an=yyy"


text:
Q: how do to hide that " user is typing " message in pidgin? how do to hide  that " user is typing " message  in pidgin?

A: If you don't want others to know you are typing, you should uncheck the "Notify buddies that you are typing to them" in the "Conversation" tab in the "Preferences" window.