text:
Q: Kitchen converge fails with Access Denied when copying password secret I've been running through the basic chef tutorials and have set up a WinServer2012 vm and successfully deployed my kitchen with the basic awesome customers cookbook using vagrant.
However, I've hit a brick wall when trying to enable security for sql. I've followed the tutorial to create an encrypted sql password file along with the encrypted_data_bag_secret. When running kitchen converge, I get to the 'Transferring files to MACHINE_NAME' stage and then get this access denied error
>>>>>> ------Exception-------
>>>>>> Class: Kitchen::ActionFailed
>>>>>> Message: Failed to complete #converge action: [[WinRM::FS::Core::FileTransporter] Upload failed (exitcode: 1)
sc : Access to the path 'C:\Users\vagrant\AppData\Local\Temp\kitchen' is
denied.
At line:2 char:66
+ function Decode-Base64File($src, $dst) {folder (split-path $dst);sc -force
-Enco ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
    + CategoryInfo          : NotSpecified: (:) [Set-Content], UnauthorizedAcc
   essException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.Pow
   erShell.Commands.SetContentCommand

]
>>>>>> ----------------------
>>>>>> Please see .kitchen/logs/kitchen.log for more details
>>>>>> Also try running `kitchen diagnose --all` for configuration

I have traced the issue to this line in the .kitchen.yml file:
provisioner:
  encrypted_data_bag_secret_key_path: "../../.chef/encrypted_data_bag_secret"

I can see no issue in the vm with permissions, 'C:\Users\vagrant\AppData\Local\Temp\kitchen' exists and is accessible to the vagrant user. It doesn't seem related to the recipes I'm running as I can remove them all and still get the same issue. My colleague with this same setup has the same issue.
Does anyone have any ideas or pointers on what might be going on? I'm on Windows 7, using VirtualBox and vagrant. My Kitchen.yml file is below (although pretty much identical to the tutorial)
    ---
driver:
  name: vagrant
  network:
    - ["private_network", {ip: "192.168.35.35"}]

provisioner:
  name: chef_zero_scheduled_task

platforms:
  - name: windows-2012r2
    driver:
      customize:
        memory: 2048

suites:
  - name: default
    data_bags_path: "../../data_bags"
    run_list:
      - recipe[mock_emr::default]
    provisioner:
      encrypted_data_bag_secret_key_path: "../../.chef/encrypted_data_bag_secret"
    attributes:
      mock_emr:
        secret_file: 'C:/Users/vagrant/AppData/Local/Temp/kitchen/encrypted_data_bag_secret'
      sql_server:
        sysadmins: ['Administrator', 'vagrant']

A: It is a known bug (https://learn.chef.io/manage-a-web-app/windows/configure-sql-server/)
Update your test-kitchen to the last version:
$ chef gem install appbundle-updater
$ appbundle-updater chefdk test-kitchen v1.7.3

Then Converge again, it should be fixed.


text:
Q: How to delete all the triggers and procedures from a single table? I am working on a problem where I need to rename the table name. The table has few triggers and procedures attach to it.
My steps to do that:

*

*Delete all the triggers and procedures of the table name employee.

*Rename table name(employee) to user using ALTER command.

*Then create all the triggers and procedures according to the new table.

Database I am using is postgresql.
Below query is used to delete the single trigger on a table.
DROP TRIGGER IF EXISTS update_employee_changes on employee;

But I want to delete all the triggers and procedures related to the given table in a single query.

A: You don't have to drop the triggers and functions. Just use a transaction:
BEGIN;

ALTER TABLE ... RENAME TO ...;

CREATE OR REPLACE FUNCTION /* function that uses the new name */
...

COMMIT;

You only have to replace the trigger functions and other functions. Triggers, views etc. don't have to be modified.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need similar function of strtotime( "next monday" ) in SQL Server I need similar function of strtotime( "next monday" ) in SQL Server.

A: DateAdd(d, (8+@@DateFirst+DatePart(dw,GetDate()))%7, GetDate())

This gives you next Monday, at the current time-of-day; i.e. if you use it at 11:49 AM Wednesday, you'll get next Monday at 11:49 AM. If that's not what you want, look up functions DatePart, DateAdd, and DateDiff - you should be able to adjust it.


text:
Q: Using put and proc format to create a new column in SAS I have a following code:
  visitnum = put(visitn,visitnumber.);

which is directed to
  proc format;
   value visitnumber
  'Screening Assessment' = 1
  'Treatment Visit - Day 1' = 2
  'Treatment Visit - Day 7' = 3
  'Treatment Visit - Day 14/15' = 4
  'Follow-Up Visit - Day 28' = 5
 run;

However when I output the 'visitnum' variable, it gives the 'Treatmen' as the output for the matching columns.

A: If this is character to numeric, you need to use an informat rather than a format.
proc format;
   invalue visitnumber
      'Screening Assessment'        = 1
      'Treatment Visit - Day 1'     = 2
      'Treatment Visit - Day 7'     = 3
      'Treatment Visit - Day 14/15' = 4
      'Follow-Up Visit - Day 28'    = 5
  ;
 run;

Example:
data foo;
    length visitn $27.;

    do visitn = 'Screening Assessment'
              , 'Treatment Visit - Day 1'
              , 'Treatment Visit - Day 7'
              , 'Treatment Visit - Day 14/15'
              , 'Follow-Up Visit - Day 28'
    ;
        visitnum = input(visitn, visitnumber.);
        output;
    end;
run;

Output:
visitn                        visitnum
Screening Assessment          1
Treatment Visit - Day 1       2
Treatment Visit - Day 7       3
Treatment Visit - Day 14/15   4
Follow-Up Visit - Day 28      5

A: Your description of the result appears to indicate that the input string did not match any of the values the format knows about.   In that case the PUT() function will just echo the input.  Truncation could occur if the width of the format specification used in the PUT() function call is shorter than the length of the input string.  Or truncation could happen if the target variable VISITNUM is defined shorter than the string returned by the PUT() function.
So either the value of VISITN does not match any of the values the FORMAT knows about or the format was not found.


text:
Q: Why does asp.net core's URL Rewriting middle ware does not match following regex? I am trying to rewrite simple url to other url in asp.net core 3 application. I have used the re-writer as follows
app.UseRewriter(new RewriteOptions().AddRewrite(@"^(?i)quote_request.aspx\?id=(.*)", "quote/revise/$1", skipRemainingRules: true));

But this is not matching and rewriting (mysite)/quote_request.aspx?id=123 to (mysite)/quote/revise/123
Am I missing something? Regex matches perfectly at https://dotnetfiddle.net/vk0ZVn though.
also,
app.UseRewriter(new RewriteOptions().AddRewrite(@"^(?i)quote_request.aspx(.*)", "quote/revise$1", skipRemainingRules: true));

is correctly rewriting (mysite)/quote_request.aspx?id=123 to (mysite)/quote/revise?id=123.

A: I had to look into code of RewriteRule in order to find answer. Here is fragment of ApplyRule method:
PathString path1 = context.HttpContext.Request.Path;
Match match = path1 != PathString.Empty ? this.InitialMatch.Match(path1.ToString().Substring(1)) : this.InitialMatch.Match(path1.ToString());
if (!match.Success)
    return;

context.HttpContext.Request.Path returns only /quote_request.aspx for request to quote_request.aspx?id=123 while missing part is in context.HttpContext.Request.QueryString! So it just ignores part of url after ? and doesn't apply rule even if passed regex is correct. So in order to do avoid skipping query you have to write custom IRule based on existing RewriteRule class, here is simplified example:
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;

public class CustomRewriteRule : IRule
{
    public Regex InitialMatch { get; }

    public string Replacement { get; }

    public bool StopProcessing { get; }

    public CustomRewriteRule(string regex, string replacement, bool stopProcessing)
    {
        InitialMatch = new Regex(regex, RegexOptions.Compiled | RegexOptions.CultureInvariant);
        Replacement = replacement;
        StopProcessing = stopProcessing;
    }

    public virtual void ApplyRule(RewriteContext context)
    {
        var fullPath = context.HttpContext.Request.Path + context.HttpContext.Request.QueryString;
        var match = fullPath != string.Empty ? InitialMatch.Match(fullPath.Substring(1)) : InitialMatch.Match(fullPath);
        if (!match.Success)
            return;

        var str = match.Result(this.Replacement);
        var request = context.HttpContext.Request;
        if (StopProcessing)
            context.Result = RuleResult.SkipRemainingRules;

        request.Path = str[0] != '/' ? PathString.FromUriComponent("/" + str) : PathString.FromUriComponent(str);
        request.QueryString = QueryString.Empty;
    }
}

Usage:
var options = new RewriteOptions().Add(new CustomRewriteRule(@"^(?i)quote_request.aspx\?id=(.*)", "quote/revise/$1", true));
app.UseRewriter(options);


text:
Q: New WP installation due to language issues My current WP installation is in English, I dowloaded the theme (So cute by YIT)
My objective is to set up a store in swedish. I've been struggeling to translate strings etc, I've tried the WPML plugin and I also tried creating new .mo and .po files with Poedit according to general recommendations.
I have now decided to use the Swedish WP installation and my question before I do this is if I simply can overwrite current English files via FTP? There is a wp-config-sample.php in the new installation file but I guess this serves no function as I have the original wp-config.php with the correct "define" settings plus database settings etc? Thank you!

A: There isn't really a Swedish version of WordPress although they do provide a convenient package that has the language files already loaded. The only differences from the core (English) distribution are the folder wp-content/languages, the variable $wp_local_package = 'sv_SE'; set in wp-includes/version.php, the localized readme.html file and the wp-config-sample.php file.
So yes, you should be safe uploading directly on top of your current install as long as you upload the same version number (3.9.2 to 3.9.2 or 3.9.1 to 3.9.1).
The file wp-config-sample.php has PHP comments localized to your language so you can either update the variables in that file from your current wp-config.php and just rename it or you can just set define('WPLANG', 'sv_SE'); in your current config file if your fine with comments in English.


text:
Q: How to update variables in a class from an activity I have ImageAnalyzer class for image analysis using cameraX. I need to update variables in class from camera activity.
Code for camera activity:
class CustomCameraActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewBinding.currencyHistoryButton.setOnClickListener {
           val intent = Intent(context, CountryPickerActivity::class.java)
           startActivityForResult(intent, 112)
       }
    }

// Code to receive data from activity result which i need to pass to the class for updation

   override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
       super.onActivityResult(requestCode, resultCode, data)
       if (requestCode == 112) {
           if (resultCode == Activity.RESULT_OK) {
               val result = data?.getStringExtra("COUNTRY")
               Log.e(TAG, "COUNTRY:$result")
           }
           if (resultCode == Activity.RESULT_CANCELED) {
               // Write your code if there's no result
           }
       }
   }

}

code for imageAnalysis class:
class ImageAnalyzer(listener: ImageAnalyzerListener? = null) : ImageAnalysis.Analyzer, ViewModel() {

    private val listeners = ArrayList<ImageAnalyzerListener>().apply { listener?.let { add(it) } }

    //value I need to update
    private val country = MutableLiveData<String>("Canada")

}

A: Your ImageAnalyzer class is a ViewModel, so assuming you have access to its instance, you would create another read-only live data and observe changes made to it.
class ImageAnalyzer(listener: ImageAnalyzerListener? = null) : ImageAnalysis.Analyzer, ViewModel() {

        ...

        //value I need to update
        private val _country = MutableLiveData<String>("Canada")

        // only expose a readable state
        val country : LiveData<String> = _country

        fun updateCountry(newValue: String) {
            country.value = newValue
        }
    }

Then somewhere in your CustomCameraActivity, assuming you already have an instance of ImageAnalyzer ViewModel
fun someActivityFunction() {
    imageAnalysisVM.updateCountry("Thailand")
}

Now if you want to listen to its changes
fun listenToCountryChanges() {

    imageAnalysisVM.country.observe(viewLifecycleOwner) {
            // react to changes made to the country
    }

}


text:
Q: How to use virtual function with enum? Update the question,
I'm trying to using enum passing the parameter to virtual function.
I want to  practice the Strategy mode of design pattern.
Here is my code(example) ,which should print "Hello".(C++),
I ran but error,
Error message:
 undefined reference to `test(Enum)'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
compiler exit status 1

please help tell me where wrong.
    class Base
{
  public:
  virtual void show() = 0;
};

class child1 : public Base
{
  public:
  void show(){
      cout<<"Hello"<<endl;
  };
};

enum Enum {
    child1,child2,
};

int main() {
    Base* test(Enum);
auto the_test =test(child1);
the_test->show();
    return 0;
}

I have no idea where wrong.please help to tell me.
thanks


text:
Q: Creating small screenshots in js using the bmp-js package In my JS code, I need to save canvas screenshots. I do it with a package bmp-js (https://www.npmjs.com/package/bmp-js)
  data_GUI = await utilities.get_canvas(canvas_selector)
  arr_of_data_GUI = Object.values(data_GUI)
  arr_of_data_GUI = new Uint8Array(arr_of_data_GUI)
  temp = bmp.encode(
    {
      data: arr_of_data_GUI,
      width: canvas_width,
      height: canvas_height
    }
  )
  return fs.createWriteStream(file_path).write(temp.data)

My screenshots are about 3mb in size. I want to take smaller screenshots. The documentation for bmp-js has this code:
var bmp = require("bmp-js");
var rawData = bmp.encode(bmpData);//default no compression,write rawData to .bmp file

The comment to the code says "default no compression", but I can't find how to call this code with compression.
Please help me!


text:
Q: try to use LabVIEW func in visual c++ I try to include LabVIEW function into my visual C++ project via DLL. In the dll there is just one function: void __cdecl imgpro(uintptr_t *ImageOut3, LVBoolean *BL, LVBoolean *R,
   LVBoolean *L, LVBoolean *BR);
This function process frames from a camera in LabVIEW.
in visual C++ . I take img,a,b,c,d out from the function.
but there is 1 error at void __cdecl imgpro(&img,&a,&b,&c,&d); "error: incomplete type is not allowed" although I think I have provided the function with all parameters and the syntax is ok.
#include "SharedLib.h"
#include <extcode.h>
#include <iostream>
using namespace std;
int main(){
LVBoolean a,b,c,d;
uintptr_t img;
void __cdecl imgpro(&img,&a,&b,&c,&d);

system("pause");
}


text:
Q: Почему не обновляется defaultValue? Не обновляется defaultValue у input.
Как можно обновить значение по умолчанию?
import React, {useEffect, useState} from 'react';

const DifficultyComponent = () => {

    const DifficultyGetServer = () => {
        fetch('/getDifficulty').then(response => response.json()).then(data => {
                console.log(data);
                setDifficulty(data['difficulty'])
            }
        );
    }

    const [maxNumber, setMaxNumber] = useState(5);
    const [difficulty, setDifficulty] = useState(0);

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

    return (

            Сложность игры (Максимальное число: {maxNumber})
            <input type="number" className="form-control" id="difficulty" min="1" defaultValue={difficulty} onChange={(e) => setMaxNumber(e.target.value * 5)}/>

    );
};

export default DifficultyComponent;


text: Q: Why doesn't the device token field get set sometimes with Parse installation Noticed that sometimes the deviceToken field doesn't get set on android or ios even though we give permissions on the client.  Is there a built in delay or know use cases where the deviceToken doesn't get set with push permissions in parse?


text:
Q: Modx Revolution Installation Fails I am trying to install Modx Revolution on an Nginx server I have, but the installation fails and results in an empty screen after I select the "Install" button during setup. The installation itself runs without any problems until it reaches this point, so I'm really scratching my head here. I've ran through the Modx forums numerous times to no avail.
A few things to note:
The SQL database fills up with the tables generated by Modx but without anything in the users table.
I've tried adding write permissions to ALL files recursively in the Modx directory, as well as setting 777 permissions and changing user/group ownership of every file.
I've ensured the nginx configuration script is identical to one that is being used on another box that is running properly.
The empty screen appears when the URL reads "index.php?action=install" at the end.
If anybody knows of anything I haven't tried or am blindly ignoring, I would greatly appreciate it.
Thanks!
EDIT: I ran the setup in Chrome, and I am actually getting an HTTP 500, unable to handle the request error.
EDIT #2: In the error log for nginx I receive the following lines:
"directory index of "[directory]" is forbidden, client: [client], server: [server], request: "GET / HTTP/1.1", host: "[hostname]"
"FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream"
"connect() failed (111: Connection refused) while connecting to upstream, client [client], server [server], request: "GET /setup/index.php?action=summary HTTP/1.1"

A: I just figured it out actually. Turns out that ModX Revolution requires that SimpleXML is enabled, even though the installer just shows a warning if it is not. The installer continued as normal after I installed, and then enabled the SimpleXML extension for PHP.


text:
Q: FacesContext.getCurrentInstance() returns null within request handled by FacesServlet(?) I have a Facelet that has two <h:forms>.  The command link in one form executes without a problem.  The command link in the other form does not work: a NullPointerException is thrown because FacesContext.getCurrentInstance() is returning null.  It appears to me that the request goes through FacesServlet so it doesn't make sense that FacesContext.getCurrentInstance() would return null.
Here's the XHTML:
<h:form>
    <h:commandLink action="#{localeManager.setLanguage('en')}">English</h:commandLink>
</h:form>

The resulting HTML is here:
<form id="j_idt20" name="j_idt20" method="post" action="/Patrac/faces/academicyear.xhtml" enctype="application/x-www-form-urlencoded">
    <input type="hidden" name="j_idt20" value="j_idt20" />

    English
    <input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="-3103232499387158697:-8681635922139458233" autocomplete="off" />
</form>

Here is the LocaleManager:
@Named
@SessionScoped
public class LocaleManager implements Serializable
{
...
    public void setLanguage(String language)
    {
        this.locale = new Locale(language);
        FacesContext fc = FacesContext.getCurrentInstance();

        UIViewRoot uivr = fc.getViewRoot(); <===== NullPointerException

        uivr.setLocale(locale);
    }
}

And here's the stack trace:
16:35:31,697 WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle] (http--127.0.0.1-8443-4) #{localeManager.setLanguage('en')}: java.lang.NullPointerException: javax.faces.FacesException: #{localeManager.setLanguage('en')}: java.lang.NullPointerException
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118) [jsf-impl-2.1.5-jbossorg-1.jar:2.1.5-SNAPSHOT]
    at javax.faces.component.UICommand.broadcast(UICommand.java:315) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) [jsf-impl-2.1.5-jbossorg-1.jar:2.1.5-SNAPSHOT]
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.5-jbossorg-1.jar:2.1.5-SNAPSHOT]
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.5-jbossorg-1.jar:2.1.5-SNAPSHOT]
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.7.Final.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.7.Final.jar:]
    at org.jboss.weld.servlet.ConversationPropagationFilter.doFilter(ConversationPropagationFilter.java:62) [weld-core-1.1.4.Final.jar:2011-11-22 20:01]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.7.Final.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.7.Final.jar:]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.7.Final.jar:]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.7.Final.jar:]
    at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.0.CR1b.jar:7.1.0.CR1b]
    at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:151) [jboss-as-web-7.1.0.CR1b.jar:7.1.0.CR1b]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.7.Final.jar:]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.7.Final.jar:]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.7.Final.jar:]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:362) [jbossweb-7.0.7.Final.jar:]
    at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:897) [jbossweb-7.0.7.Final.jar:]
    at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:626) [jbossweb-7.0.7.Final.jar:]
    at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:2033) [jbossweb-7.0.7.Final.jar:]
    at java.lang.Thread.run(Thread.java:722) [:1.7.0_02]
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) [jsf-impl-2.1.5-jbossorg-1.jar:2.1.5-SNAPSHOT]
    ... 24 more
Caused by: java.lang.NullPointerException
    at com.patrac.controller.LocaleManager.setLanguage(LocaleManager.java:38) [Patrac-ejb-1.0-SNAPSHOT.jar:]
    at com.patrac.controller.LocaleManager$Proxy$_$$_WeldClientProxy.setLanguage(LocaleManager$Proxy$_$$_WeldClientProxy.java) [Patrac-ejb-1.0-SNAPSHOT.jar:]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [:1.7.0_02]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [:1.7.0_02]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [:1.7.0_02]
    at java.lang.reflect.Method.invoke(Method.java:601) [:1.7.0_02]
    at org.apache.el.parser.AstValue.invoke(AstValue.java:262) [jbossweb-7.0.7.Final.jar:]
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278) [jbossweb-7.0.7.Final.jar:]
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39) [weld-core-1.1.4.Final.jar:2011-11-22 20:01]
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) [weld-core-1.1.4.Final.jar:2011-11-22 20:01]
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) [jsf-impl-2.1.5-jbossorg-1.jar:2.1.5-SNAPSHOT]
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    ... 25 more

Taking a look at this answer to a similar question my first thought was that the request was not going through FacesServlet.  But looking at form action field in the generated HTML and the stack trace, above, it looks to me like the request is going through FacesServlet.
Any ideas on this?  What am I not getting?

A: The problem was that I was invoking FacesContext.getCurrentInstance() from the EJB tier.  This is why it worked when deployed as a WAR, but not as an EAR.  I was very low on the Java EE learning curve at the time :-)

A: The @SessionScoped annotation is it imported from javax.faces.bean package or javax.enterprise.context? You should never use the javax.faces.bean package annotations since it will give you a different container other than CDI, and only stick to javax.enterprise.context.


text:
Q: Ubuntu20.04 libhdf5.so.8 and libH5Part.so.0 not found I compiled hdf5 and h5part in ubuntu 20.04, linked them inside makefile and \etc\profile. But when I run mpirun -np 4 lapine lapine.inp, error appears as below
proxy:0:0@ubuntu] HYDU_create_process (utils/launch/launch.c:74): execvp error on file lapine (No such file or directory)

Then I typed ldd lapine, the message is
linux-vdso.so.1 (0x00007fff62411000)
libhdf5.so.8 => not found
libH5Part.so.0 => not found
libmpi.so.12 => /opt/mpich3/lib/libmpi.so.12 (0x00007f55ab5b9000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f55ab3d7000)
libm.so.6 => /usr/lib/x86_64-linux-gnu/libm.so.6 (0x00007f55ab288000)
libgcc_s.so.1 => /usr/lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f55ab26d000)
libc.so.6 => /usr/lib/x86_64-linux-gnu/libc.so.6 (0x00007f55ab079000)
libpthread.so.0 => /usr/lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f55ab056000)
librt.so.1 => /usr/lib/x86_64-linux-gnu/librt.so.1 (0x00007f55ab04c000)
/lib64/ld-linux-x86-64.so.2 (0x00007f55aba69000)

it seems that hdf5 and h5part are not linked correctly. After checking several times, I still could not fix it. Could any one help me out? Thx.
hdf5 configure parameters
./configure --prefix=/opt/hdf5 --enable-parallel --with-pic --enable-linux-lfs --enable-shared --enable-build-mode=production --disable-sharedlib-rpath --enable-static --with-szlib=/opt/szip --with-zlib=/opt/zlib CC=/opt/mpich3/bin/mpicc CXX=/opt/mpich3/bin/mpicxx

h5part configure parameters
./configure --prefix=/opt/H5part --enable-parallel --with-pic --enable-shared --enable-build-mode=production --disable-sharedlib-rpath --enable-static --with-hdf5=/opt/hdf5 CC=/opt/mpich3/bin/mpicc CXX=/opt/mpich3/bin/mpicxx

\etc\profile:
export PATH=/opt/mpich3/bin:$PATH
export PATH=/opt/hdf5/bin:$PATH
export LD_LIBRARY_PATH=/opt/hdf5/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/H5part/lib

\lapine\src\makefile:
 CXX = /opt/mpich3/bin/mpicxx
 ....

 MPIHOME=/opt/mpich3
 HDF5HOME= /opt/hdf5
 H5PARTHOME= /opt/H5part
 BLITZHOME= /usr/local/include/blitz
 SZIPHOME= /opt/szip
 ZLIBHOME= /opt/zlib

 INCS = -I$(HDF5HOME)/include    -I$(BLITZHOME)/include
 -I$(SZIPHOME)/include   -I$(ZLIBHOME)/include  -I$(H5PARTHOME)/include

 LIBS = -L$(BLITZHOME)/lib -lblitz -L$(SZIPHOME)/lib -lsz
 -L$(ZLIBHOME)/lib -lz  -L$(HDF5HOME)/lib -lhdf5 -lz -lsz
 -L$(H5PARTHOME)/lib -lH5Part -lz -ldl

 OBJECTS = main.o readfile.o oerror.o sobol.o parameter.o network.o \
      field.o domain.o fieldsolver.o boundaryEB.o boundaryP.o  \

sixpenny


text:
Q: How can I get tormysql to do inserts? I think my understanding of the control flow here is flawed. What I want is to scrape a bunch of URLs, and as I encounter them, spin up a connection from the pool to insert the URL to my database.
I think the issue here is my understanding of yield. How can I make tormysql accept a parameter and use a connection asynchronously to write that parameter to a database?
Basically, I just want insert_to_db() to insert, asynchronously, a URL to my database. But insert_to_db() is not actually running.
from lxml import html
import tormysql
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
import time
import sys
import csv
from shutil import copyfile

import requests
from bs4 import BeautifulSoup

pool = tormysql.ConnectionPool(
    max_connections = 20, #max open connections
    idle_seconds = 7200, #conntion idle timeout time, 0 is not timeout
    wait_connection_timeout = 3, #wait connection timeout
    host = "unidb.cfavdkskfrrc.us-west-2.rds.amazonaws.com",
    user = "#",
    passwd = "#",
    db = "diplomacy_data",
    charset = "utf8"
)

def insert_to_db(game_url):
    print(game_url)
    with (yield pool.Connection()) as conn:
        try:
            with conn.cursor() as cursor:
                yield cursor.execute("INSERT INTO FvA_urls(URL) VALUES('%s')" % game_url)
        except:
            yield conn.rollback()
        else:
            print('committed', game_url)
            yield conn.commit()

username = "#"
password = "#"
login_url = "https://webdiplomacy.net/logon.php"

driver = webdriver.Chrome()
driver.get(login_url)
driver.find_element_by_css_selector('body > div.content.content-follow-on > form > ul > li:nth-child(2) > input[type="text"]').send_keys(username)
driver.find_element_by_css_selector('body > div.content.content-follow-on > form > ul > li:nth-child(5) > input[type="password"]').send_keys(password)
driver.find_element_by_css_selector('body > div.content.content-follow-on > form > ul > li:nth-child(10) > input').click()

url = "https://webdiplomacy.net/gamelistings.php?"
params = "page-games=1&gamelistType=Finished&searchOn=on"
driver.get(url + params)
driver.find_element_by_css_selector('body > div:nth-child(5) > div:nth-child(2) > form > li:nth-child(5) > input[type="radio"]:nth-child(6)').click()
driver.find_element_by_css_selector('body > div:nth-child(5) > div:nth-child(2) > form > input').click()
# Get all the URLS
page_num = 0
while True:
    page_num += 1
    if page_num % 20 == 0:
        print(page_num)
    a = driver.find_elements(By.XPATH, '/html/body/div[5]/div[3]/div[*]/div[6]/div[2]/a')
    if len(a) < 1:
        pool.close()
        exit()
    else:
        for button in a:
            game_url = button.get_attribute('href')
            insert_to_db(game_url)
        driver.find_element_by_css_selector('body > div:nth-child(6) > div:nth-child(4) > div:nth-child(1) > div:nth-child(2) > a:nth-child(3) > img').click()

All of the examples of TorMySQL usage I can find anywhere are just repeated asynchronous inserts of 1 to a table. So obviously completely useless.
Is it impossible to have each connection do something independently? Like is this library exclusively only useful for doing precisely the same thing many times asynchronously?

A: I believe the '%' syntax for string interpolation is a pattern demonstrated to be vulnerable to SQL Injection. Any potentially unsafe values incorporated into the SQL text must be properly escaped.
I also think that including the single quotes is causing invalid SQL syntax to be generated, and the execution of the statement is failing with a syntax error
 cursor.execute("INSERT INTO FvA_urls(URL) VALUES('%s')" % game_url)
                                                  ^  ^   ^

(It's possible that I'm barking up the wrong tree. I haven't verified this with testing. Maybe the single quotes are required or tolerated, and maybe the value is being properly escaped.)
I think a better pattern is to use a comma in place of the percent sign, and pass a tuple as an argument, like this:
 cursor.execute("INSERT INTO FvA_urls(URL) VALUES( %s )", (game_url,))
                                                  ^  ^  ^ ^        ^^

For comparison, take a look at this line of code in example/pool.py
    cur = yield POOL.execute("SELECT SLEEP(%s)", (t,))
                                               ^ ^ ^^

My bet is this where the problem is.
But in the spirit of StackOverflow as a question / answer site, I recognize that these questions were also asked:
Q: Is it impossible to have each connection do something independently?
Q: Like is this library exclusively only useful for doing precisely the same thing many times asynchronously?
Does the code in example/pool.py answer your question? The same SQL statement is being executed with different values, which is what it seems like you are attempting to accomplish.


text:
Q: PayPal sandbox API don't allow buyers to log in i am working on android studio developing mobile application. i have a payment feature and i integrated PayPal sandbox and when user clicks check out the PayPal page appears. however, when any buyers tries to log in using the appeared page it "incorrect username/password. please try again" although i am sure it is correct and tried multiple accounts and one of them has a valid real credit card but same output. I wonder why this happens? please can someone help me as soon as possible.
this what appears when user tries to log in:
screen shot of PayPal error message
three java classes are related to payment part are provided:
confirmOrder.java:
package com.example.my1stapplication;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.content.Intent;
import com.example.my1stapplication.config.Config;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;

import android.text.TextUtils;
import android.widget.Toast;

import org.json.JSONException;

import java.io.Serializable;

import java.util.HashMap;
import java.math.BigDecimal;

public class confirmOrder extends AppCompatActivity {

    EditText district, streetName, houseNo, phoneNo;
    Button checkout;

    DatabaseReference ordersref= FirebaseDatabase.getInstance().getReference("Orders");
    final HashMap<String, Object> ordersMap=new HashMap<>();
public static final int PAYPAL_REQUEST_CODE=7171;

private static PayPalConfiguration config = new PayPalConfiguration().environment(PayPalConfiguration.ENVIRONMENT_SANDBOX).clientId(Config.PAYPAL_CLIENT_ID);
 //Double totalPrice=getIntent().getDoubleExtra("totalPrice",0);

    @Override
    protected void onDestroy() {
        stopService(new Intent(this, PayPalService.class));
        super.onDestroy();
    }

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

        Double totalPrice=getIntent().getDoubleExtra("totalPrice",0);

        Intent intent = new Intent(this, PayPalService.class);
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION,config);
        startService(intent);

        district = (EditText) findViewById(R.id.district);
        streetName = (EditText) findViewById(R.id.streetName);
        houseNo = (EditText) findViewById(R.id.houseNo);
        phoneNo = (EditText) findViewById(R.id.phoneNo);
        checkout = (Button) findViewById(R.id.checkout);
        String buyerID = getIntent().getStringExtra("buyerID");
        // Double totalPrice=getIntent().getDoubleExtra("totalPrice",0);
        //HashMap cart=(HashMap) getIntent().getSerializableExtra("cart");

        checkout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String district1 = district.getText().toString();
                String streetName1 = district.getText().toString();
                String houseNo1 = district.getText().toString();
                String phoneNo1 = district.getText().toString();

                if (!TextUtils.isEmpty(district1) && !TextUtils.isEmpty(district1)
                        && !TextUtils.isEmpty(district1) && !TextUtils.isEmpty(district1)) {

                    Double totalPrice = getIntent().getDoubleExtra("totalPrice", 0);
                    HashMap<String, Object> cart = (HashMap<String, Object>) getIntent().getSerializableExtra("cart");
                    String Orderid = ordersref.push().getKey();
                    ordersMap.put("orderID", Orderid);
                    ordersMap.put("totalPrice", (totalPrice));
                    ordersMap.put("buyerID", FirebaseAuth.getInstance().getCurrentUser().getUid());
                    ordersMap.put("district", district1);
                    ordersMap.put("streetName", streetName1);
                    ordersMap.put("houseNo", houseNo1);
                    ordersMap.put("phoneNo", phoneNo1);
                    ordersMap.put("paied", false);
                    ordersMap.put("shipped", false);
                    ordersMap.put("takenFromOwner", false);
                    //ordersMap.put("inCart", adapter);
                    ordersref.child(Orderid).updateChildren(ordersMap);
                    ordersref.child(Orderid).child("cart").updateChildren(cart);

                    processPayment();

                } else {
                    Toast.makeText(getApplicationContext(), "please enter all fields", Toast.LENGTH_LONG).show();
                }
            }

        });

    }

    private void processPayment(){

        Double totalPrice=getIntent().getDoubleExtra("totalPrice",0);
        PayPalPayment payPalPayment =new PayPalPayment(new BigDecimal(totalPrice),"USD", "Pay for the material/s" , PayPalPayment.PAYMENT_INTENT_SALE);

        Intent intent = new Intent(this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION,config);
    intent.putExtra(PaymentActivity.EXTRA_PAYMENT,payPalPayment);
    startActivityForResult(intent,PAYPAL_REQUEST_CODE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Double totalPrice=getIntent().getDoubleExtra("totalPrice",0);

        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PAYPAL_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                PaymentConfirmation confirmation = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
                if (confirmation != null) {

                    try {

                        String paymentDetails = confirmation.toJSONObject().toString(4);
                        startActivity(new Intent(this, PaymentDetails.class).putExtra("PaymentDetails", paymentDetails).putExtra("PaymentAmount", totalPrice));
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                } else if (resultCode == Activity.RESULT_CANCELED) {
                    Toast.makeText(this, "Cancel", Toast.LENGTH_SHORT).show();
                }

            } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
                Toast.makeText(this, "Invalid Payment", Toast.LENGTH_SHORT).show();

            }

        }

    }
}

PaymentDetails.java:

package com.example.my1stapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONObject;
import android.content.Intent;
import org.json.JSONException;
public class PaymentDetails extends AppCompatActivity {

    TextView txtId,txtAmount,txtStatus;

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

        txtId = (TextView)findViewById(R.id.txtId);
        txtStatus = (TextView)findViewById(R.id.txtStatus);
        txtAmount = (TextView)findViewById(R.id.txtAmount);

        Intent intent=getIntent();

        try{

            JSONObject jsonObject = new JSONObject(intent.getStringExtra("PaymentDetails"));
        showDetails(jsonObject.getJSONObject("response"),intent.getStringExtra("PaymentAmount"));

        }
        catch (JSONException e){
e.printStackTrace();

        }
    }

    private void showDetails(JSONObject response , String paymentAmount) throws JSONException {

try {
    txtId.setText(response.getString("id"));
    txtStatus.setText(response.getString("status"));
    txtAmount.setText("SR"+paymentAmount);
}

catch(JSONException e){
    e.printStackTrace();
}
    }

}

Config.java:

package com.example.my1stapplication.config;

public class Config {
    public static final String PAYPAL_CLIENT_ID = "AR1bLXBzCYYWa4BCkEyTTcbijrtWPh9u15b3sxQbHQZ-ymhEonDq9zwMo1CqqM95fwHPp-pNjbRF99Am";
}

A: In order to log into a PayPal Sandbox page, you must use a PayPal Sandbox ( www.sandbox.paypal.com ) account , not a live ( www.paypal.com ) account.
You can create as many PayPal Sandbox accounts as you need within https://www.paypal.com/signin?returnUri=https%3A%2F%2Fdeveloper.paypal.com%2Fdeveloper%2Faccounts
Their email identifiers are fictitious and can be anything not previously used in sandbox. No real emails are ever sent to those addresses; instead, there is a Notifications tab on the left of developer.paypal.com


text:
Q: A question on Euler Phi Function Let $p$ be a fixed odd prime. If $n$ is an integer such that $p | \phi(n)$, how much could be said about $n$? Can you think of any relations between $p$ and $n$? Any input would be appreciated!

A: The formula for Euler's function gives most of the answers:
$$n=p^aq^br^c...$$ $$\phi(n)=p^{a-1}(p-1)q^{b-1}(q-1)r^{c-1}(r-1)=n(1-\frac1 p)(1-\frac1 q)(1-\frac1 r)$$
If p|$\phi(n)$ then we must have:
(a) p must be one of the prime factors of n, and
(b) The index "a" of p in $n=p^aq^br^c...$, must be greater than 1.

A: 3 is obviously NOT a factor of 14 but if you look at the formula for $\phi(14)$ the index of each prime factor, 2 and 7, is only 1.  So, condition (b) does not apply.


text:
Q: El script sólo se añade en la primer elemento de un forEach Hola estoy queriendo utilizar la librería dotdotdot.
Estoy imprimiendo unas descripciones y no quiero que salga todo el mensaje , bueno el primer elemento que imprime lo hace, pero el resto ya no agrega la función de dotdotdot.
<?php foreach($listadoOfertas as $listadoOfertas){ ?>

<?php  echo $listadoOfertas['titulo'];?>

 Empresa: <?php  echo $listadoOfertas['empresa'];?>

Localidad: <?php  echo $listadoOfertas['localidad'];?>      Fecha:
                <?php  echo $listadoOfertas['fecha_publicacion'];?>

<?php  echo $listadoOfertas['descripcion_oferta'];?>

            </script>

        <?php };?>

A: En vez de id se puede utilizar una clase común a todos los elementos descripción.

<?php  echo $listadoOfertas['descripcion_oferta'];?>

Y en el script utilizar la clase para recorrer los elementos:
$(".descripcion").each(function() {
    id_des = this.id;
    $("#"+id_des).dotdotdot();
});

Debería aplicarse a todos los elementos con la clase 'descripcion';


text:
Q: Multiple VC compile errors I'm using VC++ to write a 128-bit integer "class" in C (wrapped the header in extern "C" block), however, during routine builds to check for errors, I encountered many after adding this function:
/* Negate (2s compliment NOT) a 128-bit integer */
INT128_INLINE void int128_neg(int128_t *ret, int128_t arg)
{
    /* 2s compliment negation is equivalent to ((~value) + 1) */

    int128_t one;
    int128_from_i8(&one, 1);

    int128_t inv;
    int128_inv(&inv, arg);

    int128_add(ret, one, inv);
}

Essentially, if it's not clear enough, it finds the negative (-x) of a given int128_t. Here is the int128_t structure:
/* Work at the byte level to work around endianess crap */
/* (speaking of which, this is big endian, at least is should be) */
#pragma pack(1)
struct _int128_t
{
    /* SIGN BIT: 0xxxxxxx = positive; 1xxxxxxx = negative */
    uint8_t byte01; /* MSB */
    uint8_t byte02;
    uint8_t byte03;
    uint8_t byte04;
    uint8_t byte05;
    uint8_t byte06;
    uint8_t byte07;
    uint8_t byte08;
    uint8_t byte09;
    uint8_t byte10;
    uint8_t byte11;
    uint8_t byte12;
    uint8_t byte13;
    uint8_t byte14;
    uint8_t byte15;
    uint8_t byte16; /* LSB */
};

/* A 128-bit integer structure and functions written in pure C99 code :) */
typedef struct _int128_t int128_t;

and the function prototypes:
/* Invert (~) a 128-bit integer */
INT128_INLINE void int128_inv(int128_t *ret, int128_t arg) { ... }

/* Add two 128-bit integers together */
INT128_INLINE void int128_add(int128_t *ret, int128_t lhs, int128_t rhs) { ... }

and INT128_INLINE (obviously the one that sets it to __inline is used):
/* MC++ requires `__inline`*/
#ifdef _MSC_VER
#  define INT128_INLINE __inline
#else
   /* use standard inline */
#  define INT128_INLINE inline
#endif

Now, the errors I am receiving with the function are:
Error   24  error C2275: 'int128_t' : illegal use of this type as an expression d:\libplist\libplist\include\int128.h   313 1   libplist
Error   25  error C2146: syntax error : missing ';' before identifier 'inv' d:\libplist\libplist\include\int128.h   313 1   libplist
Error   26  error C2065: 'inv' : undeclared identifier  d:\libplist\libplist\include\int128.h   313 1   libplist
Error   28  error C2065: 'inv' : undeclared identifier  d:\libplist\libplist\include\int128.h   314 1   libplist
Error   29  error C2065: 'inv' : undeclared identifier  d:\libplist\libplist\include\int128.h   316 1   libplist
Error   30  error C2440: 'function' : cannot convert from 'int' to 'int128_t'   d:\libplist\libplist\include\int128.h   316 1   libplist
Error   32  error C2371: 'int128_inv' : redefinition; different basic types d:\libplist\libplist\include\int128.h   324 1   libplist

and before you ask, line 313 is the int128_t inv;. And also, libplist is an Apple PList library I am working on to work that uses libxml2 with the iTunes database (C:\Users\{YOU}\My Music\iTunes\iTunes Library.xml)
I tried rewriting the function to be sure it wasn't some weird Unicode crap (like people do to troll with the R2L char), but it didn't help. I tried doing int128_t inv = *ret;, but that just gives:
Error   27  error C2440: '=' : cannot convert from 'int128_t' to 'int'  d:\libplist\libplist\include\int128.h   313 1   libplist

A: int128_t one;
int128_from_i8(&one, 1);

int128_t inv;
int128_inv(&inv, arg);

This is not valid C89 code because C89 requires that all variables are declared at the top of a function, and Visual C only supports C89. Declarations must appear before statements in a function. So, if you're truly using the C compiler (and not the C++ compiler), this would cause errors. What you should be doing instead is:
int128_t one;
int128_t inv;

int128_from_i8(&one, 1);
int128_inv(&inv, arg);

Also, this comment is incorrect:
/* A 128-bit integer structure and functions written in pure C99 code :) */

If you're using Visual C, it's C89, not C99, for the aforementioned reason. Microsoft's said that they will never support any C standard later than C89 because they don't feel it's worth the effort and that everyone should be using C++ or C# instead. I don't like it, but I can't do anything about it; so, whatever.


text:
Q: What is the solution when a user want to register with a previously authenticated phone number using Firebase Authentication for Android? I am confused about which firebase authentication method should I use for my app. I know it's easy to implement and also easy for users to register using their phone numbers. The issue I see, using the phone number is that these days users are changing their mobile numbers and the mobile operators are giving the same number to a new customer. So, as you know, it's not safe only to rely on phone authentication. So, what I have been thinking is to let the user register with their phone number and then create a username of their choice and use the username as the login credentials.
But, again, what to do if a new user wants to register with a mobile number that was previously used by one of my users? Is it possible for the new user to register with a previously used mobile number for phone authentication?
And what to do if the user wants to change his number? Suppose a user register with mobile number 123 and created an account, he then wants to change his number to 567. Is it possible to change?
My question might sound stupid or silly, but the reason I am asking this is that I don't see any option to edit it here manually.

What is the best way to handle it?
Thanks in advance for the help.


text:
Q: Looping through two sets of data to conditionally append to CSV file I'm writing a script that should: 1) open a CSV file 2) loop through some eBay results data 3) write details from this data to the same file if it matches a search term and if it's not already present, but it has a few issues:

*

*The headers are not written if not present, so I'm manually adding them. I was previously using DictWriter() with writeheader(), but fieldnames was required, so they were written each time

*The if result_id != existing_result_id: condition doesn't work in a nested loop, so the rows aren't written. if any(x in result_title.upper() for x in search_terms): does currently work, but I'm not sure how to combine them before writing the rows

import csv
import smtplib
from requests_html import HTMLSession

SEARCH_TERMS = ['one', 'two']

session = HTMLSession()
response = session.get('https://www.ebay.com/sch/i.html?_from=R40&_nkw=blink+182&_sacat=0&_sop=10&rt=nc&LH_PrefLoc=2')
results = response.html.find('ul.srp-results li.s-item')

with open('ebay-results.csv', 'r') as csv_file:
  csv_reader = csv.reader(csv_file)
  next(csv_reader) # Skip headers

  with open('ebay-results.csv', 'a') as csv_file_updated:
    # field_names = ['Title', 'Link', 'ID']
    csv_writer = csv.writer(csv_file_updated)
    search_terms = [x.upper() for x in SEARCH_TERMS]

    for result in results:
      result_title = result.find('h3.s-item__title', first=True).text.replace('New Listing', '')
      result_link = result.find('a.s-item__link', first=True).attrs['href'].split('?')[0]
      result_id = result_link.split('/')[4].split('?')[0]
      result_info = [result_title, result_link, result_id]

      if any(x in result_title.upper() for x in search_terms):
        for line in csv_reader:
          existing_result_id = line[2]

          if result_id != existing_result_id:
            csv_writer.writerow(result_info)

            send_email(search_terms, result_link)

A: There's a few issues with your code:

*

*you create a file handle to read a file and then another file handle to append to the same file; that's dodgy at best, do you expect the reader to read lines you've appended? What's the purpose?

*you exhaust the reader with for line in csv_reader: for every result, which will only work once, since you don't seek the start of the file before rereading; however, why reread the file over and over anyway?

*standard Python indentation is 4 deep, you would do well to follow convention, as not doing so just makes your code harder to read, maintain and reuse.

It appears you simply want to write results for identifiers you haven't written results for previously to the file. Why not do this:

*

*read the results once, keeping the identifiers for a quick lookup

*then loop over the results, writing results with new identifiers

This is likely what you were after:
import csv
from requests_html import HTMLSession

SEARCH_TERMS = ['one', 'two']

session = HTMLSession()
response = session.get('https://www.ebay.com/sch/i.html?_from=R40&_nkw=blink+182&_sacat=0&_sop=10&rt=nc&LH_PrefLoc=2')
results = response.html.find('ul.srp-results li.s-item')

with open('ebay-results.csv', 'r+', newline='') as csv_file:
    csv_reader = csv.reader(csv_file)
    next(csv_reader)  # Skip headers
    existing_ids = [rec[2] for rec in csv_reader]

    # field_names = ['Title', 'Link', 'ID']
    csv_writer = csv.writer(csv_file)
    search_terms = [x.upper() for x in SEARCH_TERMS]

    for result in results:
        result_title = result.find('h3.s-item__title', first=True).text.replace('New Listing', '')
        result_link = result.find('a.s-item__link', first=True).attrs['href'].split('?')[0]
        result_id = result_link.split('/')[4].split('?')[0]
        result_info = [result_title, result_link, result_id]

        if any(x in result_title.upper() for x in search_terms):
            if result_id not in existing_ids:
                csv_writer.writerow(result_info)

                # not implemented, but not relevant to the question
                # send_email(search_terms, result_link)

You asked how to deal with the headers, another issue might be that the .csv doesn't exist when first running. Something like this would solve both:
from pathlib import Path

# create file if it doesn't exist, write header to it
if not Path('ebay-results.csv').is_file():
    with open('ebay-results.csv', 'w') as csv_file:
        csv_file.write('Title,Link,ID\n')

# reopen the file for reading, which now must exist, and has a header
with open('ebay-results.csv', 'r+', newline='') as csv_file:
    csv_reader = csv.reader(csv_file)
    field_names = next(csv_reader)


text:
Q: Webpage returns blank when imported JavaScript function I'm implementing a JavaScript function that displays a schedule block on a calendar view, given its starting time and end time.
Here's the function that calculates the length of the block to be placed, given the two time parameters:
function calculateBlockLength(startTime, endTime) {
  const start = stringTimetoDate(startTime);
  const end = stringTimetoDate(endTime);
  const startHour = start.getHours();
  const endHour = end.getHours();
  const startMinutes = start.getMinutes();
  const endMinutes = end.getMinutes();
  let startBlock = 1;
  let length = 1;

  if (startHour > 10) {
    for (let i = 10; i < startHour; i++) {
      startBlock += 12;
    }
  }

  if (startHour >= 10 && endHour <= 22) {
    for (let i = startHour; i < endHour; i++) {
      length += 12;
    }
    if (Math.abs(endMinutes - startMinutes) === 30) {
      length += 6;
    }
  }

  return [startTime, startBlock, length];
}

Now I imported the function on another JavaScript file which returns the calendar view.
import calculateBlockLength from './utilities.js';

let [testStart, testSB, testLength] = calculateBlockLength('11:00AM', '3:00PM');
console.log(testStart);
console.log(testSB);
console.log(testLength);

When the webpage is locally run, it returns a blank page, while there are no ongoing errors. The page is written using TailwindCSS, and uses the values returned from the function calculateBlockLength().
export default function WeeklyView() {
    return (
        <ol
        className="col-start-1 col-end-2 row-start-1 grid grid-cols-1 sm:grid-cols-7 sm:pr-8"
        style={{gridTemplateRows: '1.75rem repeat(288, minmax(0, 1fr)) auto',}}>

            <SessionBlock
             dayIndex={3}
             start={testSB}
             end={testLength}
             textColor={'text-blue-500'}
             sessionName={'Test 1'}
             sessionStartTime={'10:00AM'}/>
        </ol>
    )
}

Do note the other unnecessary TailwindCSS components are removed from this code for simplicity.


text:
Q: Chrome not autoplaying video I'm using autoplay video sporadically throughout a client's site, however the below code is (for some reason), not autoplaying in Chrome(63.0.3239.132). Works fine in Safari and FF.
I am not getting any console errors either?
<video src="https://player.vimeo.com/external/247833422.hd.mp4?s=8d872a36d3dbe7f74e9613ab144d088b5bab6649&profile_id=174" poster="" preload autoplay loop muted></video>

A: Quick fix for Chrome:
<video src="https://player.vimeo.com/external/247833422.hd.mp4?s=8d872a36d3dbe7f74e9613ab144d088b5bab6649&profile_id=174" id="video1" poster="" preload autoplay loop muted></video>

<script>
    document.getElementById('video1').play();
</script>

A: In addition to this, set the video to muted <video autoplay loop muted><source...

A: According to google chrome's policy  unmuted videos will not auto play or programmatically play. To auto play video just mute your video by add muted attribute like below :
<video autoplay loop muted="muted"></video>


text:
Q: PHP SQL Table Entry hyperlinking Below is my Php code. Would anyone be able to tell me how to remove the hyperlinking of every single SQL entry in this code?
As I don't want my users to click into any of the entries and then directed to another web page. I just want a static table with entries from my sql database.
Thanks very much!
<?
 #Get the event id from $_GET
    $int_event_id = $_GET["EventID"];
    if((int)$int_event_id)
    {
        $pdo = new PDO('mysql:host=localhost;dbname=clubresults', 'root', '12345678');
    #Set Error Mode to ERRMODE_EXCEPTION.
    $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $pdo->query("SELECT EventName, Score, Place from results WHERE EventID ='$int_event_id' ORDER By EventID ASC");
$rowset = array();

if ($query) {
  while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    // Build array of rows
    $rowset[] = $row;
  }

  // Output header first
  $headrow = $rowset[0];
  print("
\n
\n");
  // Use $rowset[0] to write the table heading
  foreach ($headrow as $col => $val) {
    printf("%s	\n", $col);
  }
  print("
");

  // Then output table rows.
  // Outer loop iterates over row
  foreach ($rowset as $row) {
     print("
");
     // Inner loop iterates over columns using $col => $val
     foreach ($row as $col => $val) {
        // We don't know your column names, but substitute the first column (the ID) for FIRSTCOL here
        printf("%s	\n", $row['EventID'],$val);
     }
     print("
");
  }
}}
print("
");
?>

A: If you change this line:
printf("%s	\n", $row['EventID'],$val);

To this you should be fine:
printf("%s	\n", $val);


text:
Q: java.lang.ExceptionInInitializerError Exception in JasperReports I have installed iReports plugin to NetBeans IDE 8.0.2 and I have tried this code:
package Frames;

import java.io.InputStream;
import java.util.*;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.design.*;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.view.*;
public class reports {

    public reports() {
        try {
            Class.forName("oracle.jdbc.OracleDriver");
            java.sql.Connection con = java.sql.DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ora10g", "employees", "manager");
            InputStream stream = getClass().getClassLoader().getResourceAsStream("/Reports/report1.jrxml");
            JasperDesign jasperDesign = JRXmlLoader.load(stream);
            Map<String, Object> params = new HashMap<String, Object>();
            JasperReport report = JasperCompileManager.compileReport(jasperDesign);
            JasperPrint jasperPrint = JasperFillManager.fillReport(report, params, con);
            JasperViewer.viewReport(jasperPrint, false);
        } catch (Exception x) {
            x.printStackTrace();
        }
    }

    public static void main(String... args) {
        new reports();
    }
}

But I am having an exception like this:
run:
Exception in thread "main" java.lang.ExceptionInInitializerError
    at net.sf.jasperreports.engine.JRPropertiesUtil.loadProperties(JRPropertiesUtil.java:99)    at net.sf.jasperreports.engine.JRPropertiesUtil.loadProperties(JRPropertiesUtil.java:99)
    at net.sf.jasperreports.engine.DefaultJasperReportsContext.initProperties(DefaultJasperReportsContext.java:94)
    at net.sf.jasperreports.engine.DefaultJasperReportsContext.<init>(DefaultJasperReportsContext.java:71)
    at net.sf.jasperreports.engine.DefaultJasperReportsContext.<clinit>(DefaultJasperReportsContext.java:59)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:239)
    at Frames.reports.<init>(reports.java:16)
    at Frames.reports.main(reports.java:27)
Caused by: java.lang.SecurityException: class "org.slf4j.ILoggerFactory"'s signer information does not match signer information of other classes in the same package
    at java.lang.ClassLoader.checkCerts(ClassLoader.java:895)
    at java.lang.ClassLoader.preDefineClass(ClassLoader.java:665)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:758)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.apache.commons.logging.impl.SLF4JLogFactory.getInstance(SLF4JLogFactory.java:155)
    at org.apache.commons.logging.impl.SLF4JLogFactory.getInstance(SLF4JLogFactory.java:131)
    at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:272)
    at net.sf.jasperreports.engine.util.JRLoader.<clinit>(JRLoader.java:68)
    ... 7 more


text:
Q: Facebook passport auth, exporting passport.authenticate method I'm trying to authenticate user through passport-facebook, and there is 1 really odd thing happening which im really unsure of. When defining my routes i have this line of code
app.get('/login/facebook',
        IsAuth.facebookEnter ),

//passport.authenticate('facebook')

    app.get('/login/facebook/return',
        IsAuth.facebookComeBack)

And in my IsAuth file i have the following
const passport = require('passport')

const FacebookStrategy = require('../passport/facebook_passport')

module.exports = {

    facebookEnter(){
       passport.authenticate('facebook')
    },
    facebookComeBack(){
        passport.authenticate('facebook', { failureRedirect: '/login' }),
            function(req, res) {
                res.redirect('/');
            }
    }

}
and the strategy itself here

const passport = require('passport')
const User = require('../models/User')
const FacebookStrategy = require('passport-facebook')

passport.use(new FacebookStrategy({
    clientID: "ALMOST POSTED IT",
    clientSecret: "Ntest test",
    //call baack to one of our routes to valiate the auth request
    //is called when the user pressed on OK to login with facebook
    callbackURL: "http://localhost:8888/login/facebook/return"
  },
  function(accessToken, refreshToken, profile, cb) {
        console.log(profile, accessToken, refreshToken)

  }
))

The question is

Why when i write
app.get('/login/facebook',
        IsAuth.facebookEnter ),
it doesnt work but if i write this code

app.get('/login/facebook',
            passport.authenticate('facebook') ),

then it works, so why? My JWT passport authnetication works good as expected even though using the same folder structure How can i make it work and keep passport.authenticate in a seperate file?

A: I'm not sure.. but mine works with this!
Might as well just divide the module.exports?
module.exports.fbAuth = passport.authenticate("facebook");

module.exports.fbAuthCB = function(req, res, next) {
  passport.authenticate("facebook", (err, user, info) =>
    generateTokenAndRedirect(err, user, info, req, res, next)
  )(req, res);
};

router.get("/auth/facebook", authCtrl.fbAuth);
router.get("/auth/facebook/callback", authCtrl.fbAuthCB);


text:
Q: the JS code stop working while ajax load
*

*The code 1: When I click on the "click here" it's supposed to hide the div with "id=adiv", and when I click again its show it again.

*The code 2 and 3: the ajax code (code 2) belongs to code 3. but there not belong to code 1! this codes just refresh php page every 1 second.
Why after the ajax code (code 2&3) loads in the page, the 'code 1' stops working? When I click on "click here", its doing nothing.
But before the ajax load, the code 1 works good.
the codes 2 and 3 works good, i have no problem with them. the only problem is with code 1.
edit: when i debug this page its show me for the line: "hideshow(document.getElementById('adiv'))" (in code 1), this eror: "Uncaught ReferenceError: hideshow is not defined (anonymous function)".
but i dont really understand why i have this problem? and what i need to do to solve this?
1) The script:
Click here

Now you see me

2) The ajax code:

3) The code that play the ajax code:


text:
Q: make a glossary with ConTeXt is there a simple way to make a glossary in ConTeXt?
just like with the glossaries package in latex
example : https://en.wikibooks.org/wiki/LaTeX/Glossary

A: It is possible to use the synonym system to make a glossary.
Define:
\definesynonyms[definition][definitions][\deffull]

Create a new definition :
\definition[CONTEXT]{ConTeXt}{The best way to write texts}

Use :
\CONTEXT
\deffull{CONTEXT}

List all definitions:
\completelistofdefinitions[criterium=all]

More information in : http://wiki.contextgarden.net/Command/definesynonyms
and in the ConTeXt manual
Thank you for your help @Aditya


text:
Q: How to create a Restore Point using command line in Windows 7? I have installed Windows 7 64 bit, however it's behaving erratic. Sometimes network icon goes missing or sometimes USB driver stops working and so on. So far System Restore has saved me every time.
So I am thinking to auto create System Restore every two days at logon.  I can write a BAT script that runs every two days but I am not aware if there's any way to create a Restore Point using command line.
If there's any command that can work I would be glad to know.
Thanks in advance.

A: You seem to have an XY problem.

How to create a Restore Point using command line in Windows 7?

Windows PowerShell has the command you need: Checkpoint-Computer. You need to supply a description to it. Like this:
Checkpoint-Computer "Some description"

You read the full documentation here: https://msdn.microsoft.com/powershell/reference/5.1/Microsoft.PowerShell.Management/Checkpoint-Computer

So I am thinking to auto create System Restore every two days at logon

Then you asked the wrong question: You want to know how to create a restore point on a schedule, not from a command prompt. (You probably don't even care if don't see a command prompt.)
Use Windows Scheduled Tasks for that. To do this:

*

*Right-click on Computer and select "Manage..."

*Open the following tree path: Computer Management (Local) -> System Tools -> Task Scheduler -> Task Scheduler Library -> Microsoft -> Windows -> SystemRestore

*Find the task called "SR". (Since there is only that one task, you should have problem finding it.) Double-click on it, or right-click on it and select "Properties".

*In the "Trigger" tab, define a "Daily" trigger for it that recurs every 2 days. Set an starting hour for it. And don't worry, if your computer was not on when this hour comes, the task will start next time your turn on your computer.


text:
Q: I wrote a python script to dedupe a csv and I think it's 90% working. Could really use some help troubleshooting one issue The code is supposed to find duplicates by comparing FirstName, LastName, and Email. All Duplicates should be written to the Dupes.csv file, and all Uniques should be written to Deduplicated.csv, but this is currently not happening..
Example:
If row A shows up in Orginal.csv 10 times, the code writes A1 to deduplicated.csv, and it writes A2 - A10 to dupes.csv.
This is incorrect. A1-A10 should ALL be written to the dupes.csv file, leaving only unique rows in deduplicated.csv.
Another strange behavior is that A2-A10 are all getting written to dupes.csv TWICE!
I would really appreciate any and all feedback as this is my first professional python script and I'm feeling pretty disheartened.
Here is my code:
import csv

def read_csv(filename):
    the_file = open(filename, 'r', encoding='latin1')
    the_reader = csv.reader(the_file, dialect='excel')
    table = []
    #As long as the table row has values we will add it to the table
    for row in the_reader:
        if len(row) > 0:
            table.append(tuple(row))
    the_file.close()
    return table

def create_file(table, filename):
    join_file = open(filename, 'w+', encoding='latin1')
    for row in table:
        line = ""
        #build up the new row - don't comma on last item so add last item separate
        for i in range(len(row)-1):
            line += row[i] + ","
        line += row[-1]
        #adds the string to the new file
        join_file.write(line+'\n')
    join_file.close()

def main():
    original = read_csv('Contact.csv')

    print('finished read')
    #hold duplicate values
    dupes = []
    #holds all of the values without duplicates
    dedup = set()
    #pairs to know if we have seen a match before
    pairs = set()
    for row in original:
        #if row in dupes:
            #dupes.append(row)
        if (row[4],row[5],row[19]) in pairs:
            dupes.append(row)
        else:
            pairs.add((row[4],row[5],row[19]))
            dedup.add(row)

    print('finished first parse')
    #go through and add in one more of each duplicate
    seen = set()
    for row in dupes:
        if row in seen:
            continue
        else:
            dupes.append(row)
            seen.add(row)

    print ('writing files')
    create_file(dupes, 'duplicate_leads.csv')
    create_file(dedup, 'deduplicated_leads.csv')

if __name__ == '__main__':
    main()

A: You should look into the pandas module for this, it will be extremely fast, and much easier than rolling your own.
import pandas as pd

x = pd.read_csv('Contact.csv')

duplicates = x.duplicated(['row4', 'row5', 'row19'], keep = False)
#use the names of the columns you want to check

x[duplicates].to_csv('duplicates.csv') #write duplicates

x[~duplicates].to_csv('uniques.csv') #write uniques


text:
Q: How to check if a Cell contains a dropdown list with vba I'm working on a VBA Scribt, that automatlically fills a large Excle with dummy data for testing reasons.
Therefore i traverse all used cells and check theyr NumberFormat.
The Excel also contains dropdown lists.
Is there any function that can find/ identify such a list and automatically select a random value?
Thanks!

A: Here is one way to check a cell for DataValidation
Sub IsIt()
    On Error GoTo trap
    MsgBox ActiveCell.Validation.Formula1
    On Error GoTo 0
    Exit Sub
trap:
    MsgBox "no data validation"
    On Error GoTo 0
End Sub


text:
Q: Responsive Embed Youtube Video as banner I'm placing an embed youtube video on my website. It's responsive and resizing correctly however I don't want the video to have a height of 100%. I want it to have a max height of 450px and then resize down.
//html

//css
#video-wrapper {
  width: 100%;
  max-height: 450px;
}
.video-container {
        position:relative;
        padding-bottom:56.25%;
        padding-top:30px;
        height:0;
        overflow:hidden;
}

.video-container iframe, .video-container object, .video-container embed {
        position:absolute;
        top:0;
        left:0;
        width:100%;
        height:100%;
}

When i give video-wrapper a width of lets say 80% or 400px it works but I can't do the same with the height. When I change the embed class to 450px it crops the video.
Here's the JSFiddle i created: http://jsfiddle.net/c34phqgo/1/

A: I hope I'm understanding you right, but I think this is what you mean. Set the max-height of the iframe to 450px. Scales with the screen.
#video-wrapper {
  width: 100%;
  height 100%;
}

.video-container iframe,
.video-container object,
.video-container embed {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  max-height: 450px;
}


text:
Q: @NonNull annotation allows null values in validation I have the following method in my controller:
@PostMapping("/register")
    public String registerNewUser(@Valid User user, BindingResult result, Model model, RedirectAttributes redirectAttributes) {
        System.out.println(result);
        System.out.println(user);
        if(result.hasErrors()) {
            System.out.println("***ERROR***");
            System.out.println(result.getAllErrors());
            return result.getAllErrors().toString();
        } else {
            //userRepository.save(user);
            System.out.println("user saved!");
            return "user saved!";
        }
    }

And my user entity specifies:
@NonNull
@Column(nullable = false, unique = true)
@Valid
public String alias;

Now if I make a simple post request (I use the Advanced REST client for chrome extension)  I get:
org.springframework.validation.BeanPropertyBindingResult: 0 errors
User(id=null, email=null, password=null, enabled=false, firstName=null, lastName=null, fullName=null null, alias=null, roles=[], links=[])
user saved!

Where it seems to validate despite @NonNull alias being null.
If I change @NonNull to @NotEmpty
Then validation works as expected:
[Field error in object 'user' on field 'alias': rejected value [null]; codes [NotEmpty.user.alias,NotEmpty.alias,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.alias,alias]; arguments []; default message [alias]]; default message [must not be empty]]

BUT what I don't understand is why @NonNull allows Nulls?

A: There's no @NonNull annotation in the JSR-303 validation API. The annotation is called @NotNull. Make sure you actually use the javax.validation.constraints.NotNull annotation to mark the field.

A: You should use NotNull from javax.validation package and not from lombok (those are to be deleted, when java starts supporting validation - see here). It validates the beans. More info here. You can also use hibernate's @NotNull from org.hibernate.validator. This also does validation.

A:
javax.validation.constraints

@NotNull: The annotated element must not be null.Accepts any type
@NotEmpty: The annotated element must not be null nor empty. Supported types are:

*

*CharSequence (length of character sequence is evaluated)

*Collection (collection size is evaluated)

*Map (map size is evaluated)

*Array (array length is evaluated)

@NotBlank:The annotated element must not be null and must contain at least one non-whitespace character. Accepts CharSequence

@NonNull refer to Lombok

Here are the Great Details which you may like Click Here


text:
Q: Using Clipboard.js to change button text by a class I found this
change button text after click w/ clipboard.js
but it causes an error: $ is not a function, see screenshot below
https://www.awesomescreenshot.com/image/8535357?key=55d48e1db3b3e996966454c551958fac
How can I change the button text with Clipboard.js after someoen have clicked it by a class instead of an ID?
For example, the button text will be changed to 'copied' and after some time it will automatically change back to the original text.
Below is my code:

<button
  class="copyElement"
  data-clipboard-text="123"
>
  Take Me There
</button>

A: Using success event without jQuery
https://clipboardjs.com/#events

var clipboard = new ClipboardJS('.copyElement')

clipboard.on('success', function(e) {
    let oldtext = e.trigger.textContent
    e.trigger.textContent = 'Copied!'
    setTimeout(() => e.trigger.textContent = oldtext, 2000)
});

<button class="copyElement" data-clipboard-text="123">
  Take Me There 1
</button>

<button class="copyElement" data-clipboard-text="456">
  Take Me There 2
</button>


text:
Q: ubuntu ftp 500 OOPS: prctl PR_SET_SECCOMP failed I have just installed vsftp in my ubuntu 14 server. I have installed vsftp also using sudo apt-get install command. then restarted ftp server but it refuse all connection for this error 500 OOPS: prctl PR_SET_SECCOMP failed
please take a look here .
aysael@srv:~$ sudo ftp
ftp> open 127.0.0.1
Connected to 127.0.0.1.
500 OOPS: prctl PR_SET_SECCOMP failed

Here is my config file /etc/vsftpd.conf
seccomp_sandbox=no
listen=YES
# Allow anonymous FTP? (Disabled by default)
anonymous_enable=NO
#
# Uncomment this to allow local users to log in.
local_enable=YES
#
# Uncomment this to enable any form of FTP write command.
write_enable=YES
#
dirmessage_enable=YES
#
# If enabled, vsftpd will display directory listings with the time
# in  your  local  time  zone.  The default is to display GMT. The
# times returned by the MDTM FTP command are also affected by this
# option.
use_localtime=YES
#
# Activate logging of uploads/downloads.
xferlog_enable=YES
#
# Make sure PORT transfer connections originate from port 20 (ftp-data).
connect_from_port_20=YES
ftpd_banner=Welcome to blah FTP service.

secure_chroot_dir=/var/run/vsftpd/empty
#
# This string is the name of the PAM service vsftpd will use.
pam_service_name=vsftpd
#
# This option specifies the location of the RSA certificate to use for SSL
# encrypted connections.
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
# This option specifies the location of the RSA key to use for SSL
# encrypted connections.
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key

A: The message indicates that the prctl(PR_SET_SECCOMP, ...) call failed.
if (!tunable_seccomp_sandbox)
{
  return;
}

...

ret = prctl(PR_SET_SECCOMP, 2, &prog, 0, 0);
if (ret != 0)
{
  die("prctl PR_SET_SECCOMP failed");
}

It can happen when your kernel does not have the CONFIG_SECCOMP_FILTER enabled.
Quote from the prctl man page:

PR_SET_SECCOMP (since Linux 2.6.23)
Set the secure computing (seccomp) mode for the calling thread, to limit the available system calls. The seccomp mode is selected via arg2. (The seccomp constants are defined in <linux/seccomp.h>
...
With arg2 set to SECCOMP_MODE_FILTER (since Linux 3.5) the system calls allowed are defined by a pointer to a Berkeley Packet Filter passed in arg3. This argument is a pointer to struct sock_fprog; it can be designed to filter arbitrary system calls and system call arguments. This mode is available only if the kernel is configured with CONFIG_SECCOMP_FILTER enabled.

You should be able to workaround that by configuring vsftpd not to enable the seccomp mode.
Use the seccomp_sandbox=no option in the vsftpd.conf.
The option does not seem to be documented.
But you seem to have that set already. That might indicate that your vsftpd.conf is not being used actually. Or that you did not restart vsftpd since your set the option.
If you have the option really set, you should never get the error message, as you can see in the code snippet above (code of your vsftpd 3.0.2).


text:
Q: How to make a slingshot? enter image description here
enter image description here
I made this slingshot with objects in Unity3D. I know im suppose to add components but I dont know exactly which ones. The two yellows would represent as my elastics. Keep in note i have a robot arm made on the side. My claw hand will grab the object holder and pull it back so it can shoot. I need help in

*

*what component should i add to them to make them like rubberband or elastic

*how attach them to my objectHolder

*how to make it shoot
please help and be patient with me :( Any advice I would appreciate it. Thank you :)

private Animation anim;
  Rigidbody rb;
  void Start()
  {
      anim = gameObject.GetComponent<Animation>();

  }
  void Update()
  {
      //********************Open pincher ********************
      if (Input.GetKey(KeyCode.X))
      {
          anim.Play("clawopen");
          //rb.AddTorque(Vector3.up * speed);
      }
      //*******************Close pincher ********************
      if (Input.GetKey(KeyCode.Y))
      {
          anim.Play("clawclose");
          // rb.AddTorque(Vector3.down * speed);
      }
      //*******************if not both ********************
      else
      {
          rb.angularVelocity = Vector3.zero;

      }
  }
}

A: There is no magic component that will achieve what you want. You should break it down into smaller chunks.
Start with the movement of the object holder. There are different ways to achieve this. If you want to manipulate it via mouse, you can write a script that makes the objectHolder follow mouse movement while a mouse button is pressed. Once you release the mouse button you can let the object holder smoothly go back to it's start position.
For the elastic parts, I would replace the objects with LineRenderers. But also here are different ways to achieve this.
Maybe this tutorial helps you.

A: attach a spring component to the dark orange round shape and set connectedAnchor to the position of where it should stretch from. You can play around with soeing and damoer to make it more or less stretchy.
I would reccomend a very high spring (spring should be about 100-1000) and mass (mass should be about 5-10) on this. The ball should have a mass of 1 or less.
You can set the Rigidbody.position to the claw's position (while it is closed) Then when it opens' it will release and launch.
For example SlingShot.cs (on the dark orange object.
[HideInInspector] public bool closedClaw = false;
[HideInInspector] public Vector3 clawPos;
Rigidbody rb;
void Start()
{
     rb = GetComponent<Rigidbody>();
}
void Update()
{
    if (closedClaw)
    {
         rb.positon = clawPos;
    }
}

And then somewhere in the script that closes the claw
SlingShot ss;
GameObject slingShot;
void Start()
{
    ss = slingShot.GetComponent<SlingShot>();
}

...

if (right claw.localEulerAngles.z /*or whatever axis it rotates on*/
> 90f /*or whatever threshHold*/)
{
    ss.closedClaw = true;
}
else
{
    ss.closedClaw = false;
}
ss.clawPos = rightClaw.transform.position +
leftClaw.transform.position;
ss.clawPos /= 2f;

All of this is untested and may have errors.
If this all works,I will come back later and do the stretchy yellow rubber bands.
Requested by comment Open closing arm
public float speed;
public Transform rightClaw;
public Transform leftClaw;
public Vector3 axis;
public Vector2 minMaxRotation;
void Update()
{
    if (Input.GetKey(KeyCode.X))
    {
         Press(1);
    }
    if (Input.GetKey(KeyCode.Y))
    {
         Press(-1);
    }
}
void Press(int open)
{
    float r = rightClaw.transform.localEulerAngles * axis;
    rightClaw.transform.localEulerAngles =
axis * Mathf.Clamp(r + speed * open, minMaxRotation.x, minMaxRotation.y);
    float l = leftClaw.transform.localEulerAngles * axis;
    leftClaw.transform.localEulerAngles =
axis * Mathf.Clamp(l - speed * open, 180f - minMaxRotation.x, 180f - minMaxRotation.y);
}


text:
Q: Splunk integration with Hadoop How to integrate splunk with Hadoop (MapR distribution)?

A: Yes, there are a number of Splunk documents available on the subject.  The first hits in a Google search will serve you well or go to docs.splunk.com and search for "Hadoop".


text:
Q: How to Delete Facebook Messages via Facebook API? Is there a way to retrieve all Facebook Message ids with the read mailbox permission and then delete them all one by one? Everyone is crying about how it's difficult to delete your chat/message history. I wondered if there was an easy way to write an app to do this.
Facebook API - Message

A: Normally you would issue an HTTP DELETE call to https://graph.facebook.com/messageID?access_token=...  But it appears that this is an API call that either require special whitelisting from Facebook or isn't currently supported because it does not work right now and returns "Unsupported delete request."

A: Install https://chrome.google.com/webstore/detail/jquerify/gbmifchmngifmadobkcpijhhldeeelkc
Open the facebook using
https://mbasic.facebook.com/messages/?_rdr
Enable jQuery using jQueryify extension you installed.
Then go to your chrome developer tools> sources > snippet and create a new snippet and paste the following code and run it.
// Code snippet for facebook messages removing:

var WHITELISTED_USERS_X = [];
function removeElement(elementId) {
    // Removes an element from the document
    var element = document.getElementById(elementId);
    if (element) {
        element.parentNode.removeChild(element);
    }
}

function addElement(parentId, elementTag, elementId, html) {
    // Adds an element to the document
    //     removeElement
    removeElement(elementId);
    var p = document.getElementById(parentId);
    var newElement = document.createElement(elementTag);
    newElement.setAttribute('id', elementId);
    newElement.innerHTML = html;
    if (p) {
        p.appendChild(newElement);
    } else {
        var body = document.getElementsByTagName("body")[0]
        body.appendChild(newElement);
    }

}
addElement("body", "div", "123x", "hello World23");
console.log(`getOlderMessagesLink()`);
console.log(getOlderMessagesLink());
var aLinks = document.querySelectorAll('h3 a'), i;

for (i = 0; i < aLinks.length; ++i) {
    let currentLink = aLinks[i];
    currentLink.style.color = currentLink.style.color == "black" ? "red" : "green";

    $.get( currentLink.href, function( data ) {

    getPayload1(currentLink.href).then(payLoad=>{
    let abLink = currentLink.href;
    let deleteApiLink = abLink.split('?').pop().split('&');
    deleteApiLink.splice(1 , 0, `tids=${deleteApiLink[0].split('=').pop()}`)
    deleteApiLink = deleteApiLink.join("&").split("#").shift();
    const apiLink = `https://mbasic.facebook.com/messages/action_redirect?` + deleteApiLink;

    $.post(apiLink, payLoad ).done(function( data ) {
    let mydeletehref = findInParsed(data, "a:contains('Delete')");
    const username = currentLink.innerText;
    const deleteLink = mydeletehref.href;
    if(WHITELISTED_USERS_X.indexOf(username) == -1){
        // console.log(`${username}: ${deleteLink}`);
        insertDeleteLinkInUser(username, deleteLink);
    }

  });

    });
      })

}
function getPayload1(link){
    return new Promise(resp=>{
        $.get(link, function( html1 ) {
        let fbDtsg = findInParsed(html1, "input[name='fb_dtsg']");
        let jazoest = findInParsed(html1, "input[name='jazoest']");
        resp ({
            "fb_dtsg": fbDtsg.value,
            "jazoest": jazoest.value,
            "delete": "Delete"
        })
    });
    })
}
function findInParsed(html, selector){
    return $(selector, html).get(0) || $(html).filter(selector).get(0);
}
function getOlderMessagesLink(html = false){
    if(html){
        return $("#see_older_threads").find("a").get(0).href;
    }
    let selector = "#see_older_threads";
    return $(selector, html).find("a").get(0).href || $(html).filter(selector).find("a").get(0).href;
}
function insertDeleteLinkInUser(username, link){
    $("a:contains('" + username + "')").parent().parent().parent().prepend('DELETE ME');
}


text:
Q: Java PostMethod with xml I am trying to post XML data as a body to a REST api.
I have a method that creates the request called doREST.
String url = null;
        HttpMethod method;
        LOG.info("QUERY: " + query);
        if (StringUtil.isEmpty(query)) {
            url = BuildRequestURL("/issues.ashx/issues/mywork");
            method = doREST(url, false);
        } else {
            url = BuildRequestURL("/issues.ashx/issues/filters");
            //method = doREST(url, true);
            method = doREST(url, true);
            String xml = "<IssuesFilterEN>" +
                    "<IssueID>" + query + "</IssueID>" +
                    "</IssuesFilterEN>";
            RequestEntity entity = new StringRequestEntity(xml,"text/xml; charset=iso-8859-1", null);

method.setRequestEntity(entity);
    }

and the doREST method
private HttpMethod doREST(String request, boolean post) throws Exception {
        String uri = request;
        HttpMethod method = post ? new PostMethod(uri) : new GetMethod(uri);
        configureHttpMethod(method);
        HttpClient client = getHttpClient();
        client.getParams().setParameter(HttpClientParams.SO_TIMEOUT, timeoutLength);
        client.executeMethod(method);
        return method;
    }

My issue is the method.setRequestEntity is saying that the method could not be found.
I have
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.*;

If i set method = PostMethod instead of method = doREST it works but I don't want to have to do that in all my other methods just to create queries.
Is there something I am missing as to why the method.setRequestEntity is not working the way it is right now?
EDIT:
I got my information for using setRequestEntity from PostMethod setRequestBody(String) deprecated - why?
EDIT 2:
Here is what I ended up doing.
private HttpMethod doREST(String request, RequestEntity entity) throws Exception {
        String uri = request;
        HttpMethod method;
        if ( entity != null ){
            method = new PostMethod(uri);
            ((PostMethod) method).setRequestEntity(entity);

        } else {
            method = new GetMethod(uri);
        }
        configureHttpMethod(method);
        HttpClient client = getHttpClient();
        client.getParams().setParameter(HttpClientParams.SO_TIMEOUT, timeoutLength);
        client.executeMethod(method);
        return method;
    }

A: You should modify doREST to accept the RequestEntity instead of a boolean. Pass in null for a GET and a value for POST. Use that as the check to see if you need a PostMethod or a GetMethod. Then you can have the specific type so you can call the PostMethod only setRequestEntity().
EDIT:
You can avoid the cast like this:
private HttpMethod doREST(String request, RequestEntity entity) throws Exception {
    String uri = request;
    HttpMethod method;
    if ( entity != null ){
        PostMethod postMethod = new PostMethod(uri);
        postMethod.setRequestEntity(entity);
        method = postMethod;
    } else {
        method = new GetMethod(uri);
    }
    configureHttpMethod(method);
    HttpClient client = getHttpClient();
    client.getParams().setParameter(HttpClientParams.SO_TIMEOUT, timeoutLength);
    client.executeMethod(method);
    return method;
}

A: The method you should be calling is setEntity, not setRequestEntity.  Also, your body should be wrapped in a StringEntity, not a StringRequestEntity, imported from org.apache.http.entity.


text:
Q: Ubuntu 18.04 Not entire RAM is used but 2/4GB of swap is used, So I have been working hard to optimize my Ubuntu Server 18.04 runing LEMP with everything up-to-date, including latest kernel updates and I have noticed some small delays in SSH responsiveness.
My idea is pointed towards RAM and SWAP usage
https://imgur.com/a/cRbnv8r
In the link above there are screenshots of free -m, htop and vmstat.
I am not entirely sure what is going on here, not the entire RAM is used, but over 2GB of SWAP is used?...
I see 2 possibilities here:

*

*I am actually running out of ram and ubuntu is using a lot of this 2GB swap and keeps a small amount of free memory for impotant tasks.

*I am actually not using a lot of ram and ubuntu is just using SWAP to make the performance better.

I have doubts though and I would prefer if somebody could point me in the right understanding here.
I have also set swappiness to 5 and vfs_cache_pressure to 50, to use as little SWAP as possible, quite a while ago now.
Could this situation be the cause of my SSH being slow?
ex:
entering password on my local PC in terminal - I can type as fast as I possibly can and it will work
entering password on the remote server via SSH - I can not type the password as fast as I can as it will tell me invalid password.
I am using shift while entering the password, but it shouldn't cause me to enter invalid password when the SSH is slow.

A: It looks like in your case that most of the memory is used, just not for programs.  In general, Linux will prefer to swap out parts of a program in order to leave some memory for buffers and page cache.
Although this may seem counter-intuitive, it actually makes performance a lot better.  Talking to the disk tends to be a couple of orders of magnitude slower than talking to memory, so keeping some disk cache in memory can improve performance very significantly.  This is normal and you should not need to adjust the swappiness or cache pressure in any way, and you should undo any changes you've made to those settings.
The reason you're seeing delays when typing over SSH is likely due to network issues.  When you're using SSH interactively, you want low latency: that is, the most important thing is to have the packets sent as quickly as possible, even if that means the amount of data you can send is much lower.  Somewhere along the line, your packets are taking longer to make the round-trip than they should.
There are a bunch of reasons this could be the case, but a lot of it depends where your server is located.  If it's far away, latency will be higher.  Also, if the network is congested somewhere along the way, you'll also see some lag.
The tool one typically uses to troubleshoot these kinds of problems is mtr.  You can run mtr -t YOUR_SERVER and see if there's any latency problems.
If there's no latency problems, then it is possible that your server being low on memory is the problem, but in that case your solution needs to be to add memory, not to tinker with kernel parameters.  It's obvious from your image that you're well exceeding the memory capacity of the server and you either need to add more or use less.


text:
Q: cronjob in codeigniter using cpanel My website hosting server is hostmonster.com.
My application uses codeigniter framework.
I have a code which sends emails to my users and I want to make it automatic.
I have used the cpanel of the hosting service and I tried to give the command as
php -q www.mysite.com/admin admin sendDailyEmail

my controller is admin and the method is sendDailyEmail and the controller is present inside the application/controllers/admin folder.
I have also set a reminder email to me whenever the cronjob is run.
The email subject reads

Cron  php -q /home1/username/public_html/admin admin sendDailyEmail

and the body says

No input file specified

Where do I go wrong.
I have never run cronjobs and this is my first time.
I am no good in giving command line instuctions too.
My admin sendDailyEmail code is as follows
function sendDailyEmail() {
    $data = $this->admin_model->getDailyData();
    foreach ($data as $u) {
    if($u->Daily){
     //if(!$u->Amount){
       if ($u->Email=='myemail@gmail.com') {

                $user['user_data']['FirstName'] = $u->FirstName;
                $user['user_data']['LastName'] = $u->LastName;
                $user['user_data']['Id']=$u->Id;

                $this->email->clear();
                $this->email->to($u->Email);
                $this->email->from('alerts@mysite.com', 'MySite');
                $this->email->subject("My Subject");
                $msg = $this->load->view('emails/daily_view', $user, true);
                $this->email->message($msg);
                if ($this->email->send())
                    $data['message'] = "Daily Emails has been sent successfully";
                else
                    $data['message'] = "Daily Emails Sending Failed";
            }
        }
    }
    $data['main_content']['next_view'] = 'admin_home_view';
    $this->load->view('includes/admin_template', $data);
}

A: Codeigniter sets up command line differently for running crons, etc.
Read:
http://www.codeigniter.com/user_guide/general/cli.html
So you should run:
php index.php admin admin sendDailyEmail

(that may need adjusted; based on your code above)
Have a look at an article I just wrote that goes a little deeper into it all:
http://codebyjeff.com/blog/2013/10/setting-environment-vars-for-codeigniter-commandline

A: You can use wget and set the time for whatever you like:
wget http://www.mysite.com/admin/sendDailyEmail

You can also use curl:
curl --silent http://www.mysite.com/admin/sendDailyEmail

A: For CodeIgniter 2.2.0
You can try this:
 php-cli /home/username/public_html/index.php controller method

or at your case
 php-cli /home/username/public_html/index.php admin sendDailyEmail

It works fine with me..
Cheers!

A: i have facing same issue while, but following work for me
wget http://www.yoursite.com/controller/function