text:
Q: New VBAproject open prevention I have a excel report that has VBA code written.When i try to view code, alongwith my code that is under display a new project VBAproject(Book 1) opens.Using this new workbook code can be written that changes my values in excel.I cannot set Userinterfaceonly to false as this doesnt allow the internal VBA to run.
Can the VBAproject(book 1) that opens alongwith my code under display be prevented/locked so that no new code can be written?

A: You can set a password on VBA associated with a workbook.
Open the VBA editor for the workbook you want to protect. Select the project, and go to the Tools Menu, then the VBAProject Properties option. Clicki the Protection tab, and set the password, confirm it, click OK. Save the workbook.
Now if you try to open the VBA for that workbook you'll be prompted for the password, but the VBA can still be called.
PS Don't forget the password!


text:
Q: Holidays and sundays: database or function validation? I have a web application up and running, and right now my bosses wanted me to do some updates, but also they wanted to be able to use some information using a mobile device.
I am in charge of the web application for desktop and they hired a third party developers to get the mobile app done, I thought they were going to program it in Android, but they are using xamarin or apache cordova, which for me is the same, because I know eventually I will have to change or update that application.
The matter here is that the mobile app developers are asking me to save the sundays in the same table I am storing the holidays,because according to them using functions to calculate mondays is degrading the app's performance a lot.
I am not expert, but if they are using something like apache cordova or ionic, they are making an hybrid application, which basically is a web page, so, this past weekend I made a quick test, listing all the main info and showing all the data related to that item in another view.  It was my first time programming a sort of optimized web page for mobiles, using basics of responsive web desing, you it is worth noticing that being my first time, I could have not done any kind of real optimization that professional programmers in that particular area do, and it seemed to me that it was pretty decent.
I forgot to mention, the holidays and sundays are not showing anywhere, they are part of calculations to get some fees' amount a customer must pay, and as you should know, being mobile, they do not show all at once, but one by one because the main list shows the name of the customer, his/her account number, and the total amount to pay, then you click it and go to the detailed view.
So, long story short, according to your experience, would you save the sundays info in the database or use javascript/php functions to operate with them?
Thank you for your help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to trigger a Jenkins build on a Perforce submit I am using Jenkins with Perforce. I have downloaded the P4 Plugin, and I have read over the documentation but I am still a bit confused. In my Jenkins project, I have the build trigger set to "Perforce triggered build". I'm assuming that means I need to add a trigger to Perforce that tells Jenkins to run a build, but I have no idea on how to do that.
I have not been able to find any documentation on how to implement a trigger from Perforce to notify Jenkins it needs to run. I can find documentation from Perforce on how to setup basic triggers, but I can not find anything from Jenkins on how to set up the actual connection to trigger builds on Perforce submits.
On the "Changes" tab in Jenkins, I am able to see the what was submitted to Perforce, so I know that Perforce and Jenkins are at least communicating. Initially, I thought that Jenkins would just automatically run the build on a Perforce submit, if I had "Perforce triggered build" checked, but that doesn't seem to be the case.
So my questions are:
Am I correct in assuming that I need to manually create a trigger to be added to Perforce?
If so, does anyone know of any documentation or examples that I can look to as a guide?

A: Yes, you need to add a trigger to Perforce. It's well documented here.


text:
Q: set EditText line itself length I want to have something like this :
the ___ is the EditText, the () is the button, the --- is the rest of the screen
___________()
how can i make the line to always take the place until the button?
when i rotate the screen the edittext line should get until the button as well.
but this is what i get:
_______()-----
This is what i have right now and dont know what to change:
    <LinearLayout
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:weightSum="2"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

    <EditText
        android:maxLength="15"
        android:layout_weight="1"
        android:layout_width=""
        android:layout_height="wrap_content"
        android:id="@+id/word" />

    <Button
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit"
        android:id="@+id/submit"
        android:layout_gravity="right" />
</LinearLayout>

A: Try with RelativeLayout:
<RelativeLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content" >

    <EditText
        android:maxLength="15"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/word"
        android:layout_toLeftOf="@+id/submit"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit"
        android:id="@+id/submit"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true" />
</RelativeLayout>

A: Your button should have weight=0, so the EditText always gets all the unused screen space. É voila.
<LinearLayout
    android:layout_weight="1"
    android:layout_width="wrap_content"
    android:weightSum="2"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

<EditText
    android:maxLength="15"
    android:layout_weight="1"
    android:layout_width=""
    android:layout_height="wrap_content"
    android:id="@+id/word" />

<Button
    android:layout_weight="0"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Submit"
    android:id="@+id/submit"
    android:layout_gravity="right" />
</LinearLayout>


text:
Q: Flask not serving static files My static files are all returning a 404 error.
below is the structure:
-root
   -web
      -static
        -css
          -main.css
      -templates
         base.html
         home.html

      app.py

I have a static and templates folder in the same directory as the app. Below is the code for app.py:
class FrontEnd(Flask):
    jinja_options = Flask.jinja_options.copy()
    jinja_options.update(dict(
        block_start_string='{%',
        block_end_string='%}',
        variable_start_string='[[',
        variable_end_string=']]',
        comment_start_string='{#',
        comment_end_string='#}',
    ))

app = FrontEnd(__name__)

@app.route('/')
def index_page():
    details = {"name" : "mark", "surname" : "boleigha", "occupation" : "programmer"}
    view_data = { "page_name" : "this is the homepage", "title" : "Home", "details" : details }
    return render_template("home.html", **view_data)

below is the code for base.html:

   <head>
       <title>[[title]] | Recruitr</title>

       <link rel="stylesheet" href="[[ url_for('static', filename='css/bootstrap.min.css') ]]"  />
   </head>
   <body>
      {% block content %}

      {% endblock content %}
   </body>
</html>

below is the code for home.html:
{% extends "base.html" %}

{% block content %}
  #body here
{% endblock content %}

please note that i use [[ in the jinja templates to avoid confusions with curly braces as i intend to use a javascript framework.
All CSS files are in static folder. Template render but without styling as  static files are suddenly returning 404 error.
everything was working fine until i rebooted. below is screenshot of my terminal and file tree:
screenshot
file_tree


text:
Q: Check duplicate record for multiple child list using java generic where duplicate key is abstract for each child DTO types in list I have a base DTO class.
    public abstract class Parent
   {
      String applicationNumber;
   }

In addition to that, I can have multiple child classes based on this parent class
child class 1:
public class childOneDTO extends Parent
    {
      String applicationStatus;
      String admissionStatus;

      public(String applicationNumer, String appStatus, String admStatus)
      {
         supper(appliationNumber)
         this.verificationStatus  = vStatus;
         this.admissionStatus = admStatus;
      }
   }

child class 2:
public class childTwoDTO extends Parent
{
  String verificationStatus;
  String documenataionStatus;

  public(String applicationNumber, String vStatus, String dStatus)
  {
    supper(appliationNumber)
    this.verificationStatus  = vStatus;
    this.documentationStatus = dStatus;
  }
}

Like this, I can have multiple child classes..
There is an operation that contained List of child objects to verify whether there are duplicate objects included in a list based on the application number.
For Example:
sample data populated lists ->
List<ChildOneDTO> listOne = new ArrayList<>();
listOne.add(new ChildOne("123", "app1", "adm1");
listOne.add(new ChildOne("234", "app2", "adm2");
listOne.add(new ChildOne("345", "app3", "adm3");
listOne.add(new ChildOne("345", "app4", "adm4");

Same way...
List<ChildTwoDTO> listTwo = new ArrayList<>();
listTwo.add(new ChildTwo("123", "app1", "adm1");
listTwo.add(new ChildTwo("234", "app2", "adm2");
listTwo.add(new ChildTwo("345", "app3", "adm3");
listTwo.add(new ChildTwo("345", "app4", "adm4");

There is a validator class.
public class Validator
{
  public void validateChildOne(List<CHildOneDTO> childOneList)
  {

    validateApplicationStatus(childOneList)
    validateAdmissionStatus(childOneList)
    validateForDuplicateApplicationNumber(childOneList)
  }

  public void validateChildTwo(List<CHildTwoDTO> childTwoList)
  {

    validateDocumentationStatus(childTwoList)
    validateVerificationStatus(childTwoList)
    validateForDuplicateApplicationNumber(childTwoList)
  }
}

In that manner, though I have a separate validator method for each child Datos, I need to write a common method to validate the application number to check whether there are duplicate values available since application number is common for each and every child classes.
How can achieve this?


text:
Q: Compact Disc Optics - Why use a linear polariser and a quarter wave plate? I just came across this website about the application of a quarter wave plate. Link: Compact Disc Optics.
My question is why does the beam need to be linearly and then circularly polarised before sending to the compact disc? And the returned beam undergoes the same before reaching the detector? Is it related to power loss?

A: What you may not realize from that website is that the same optical element is shown on the left and on the right. Laser emission and detection happen simultaneously, but for clarity they are drawn separately.
See how circular polarization changed after the reflection from the CD. Now, when it comes through the quater-wave plate it has polarization perpendicular to the incoming laser beam and gets reflected towards the detector. Neat!

A: A quarter wave plate together with a polarizing beam splitter is a standard way of building an optical isolator.  In an optical isolator the light traveling in one direction is transmitted but the light travelling in the reverse direction is reflected.  This is important when reading compact discs because the reflected light carries the signal that you want to read.
As for how it separates the forward travelling and backward travelling light.  The initial pass through the linear polarizer leaves the light linear polarized in one direction.  The first pass through the quarter wave plate converts it to circular polarization, and the reflection off of the CD converts it to the opposite handedness circular polarization.  Finally, the quarter wave plate converts it to the opposite linear polarization from the input beam which is then reflected by the polarizing beamsplitter.


text:
Q: Let $p$ be an odd prime and $P(x)$ a polynomial of degree $p-2$. If $p\mid P(n)+P(n+1)+...+P(n+p-1) \forall n$, must $P$ have integer coefficients? I am stuck on this question from Zeit's book The Art and Craft of Problem Solving.
Question
Let $p$ be an odd prime and $P(x)$ a polynomial of degree at most $p-2$.
If $P(n)+P(n+1)+...+P(n+p-1)$ is an integer divisible by $p$ for every integer $n$, must $P$ have integer coefficients?
Attempt
I think $P$ must have integer coefficients. Suppose $P(x)=\sum_{k=0}^{p-2} a_k \cdot x^k$. Define $H(n)=P(n)+P(n+1)+...+P(n+p-1)$. Then we can expand $H(n)$ into a polynomial $H(n)=\sum_{k=0}^{p-2} c_k \cdot n^k$, where each of the coefficients $c_k$ are some linear combination of $a_k$.
If $c_i$ is not an integer for some $i$, then I think by choosing some suitable $n_i$, we can cancel all denominators of $c_j$ where $j \neq i$, while leaving $c_i$ still a fraction. Then $H(n_i)$ will be non-integer. But I don't know how to prove this properly. The $c_i$ are already very complicated to express.
However, if $c_i$ is integer for all $i$, then I am stuck.
I also don't know where to use the fact that $p\mid H(n)$ for all $n$.
Thanks for the help!

A: The answer is no.  For example, $$P(x):=\frac{x\,(x+1)\,(x+5)}{6}$$
is not in $\mathbb{Z}[x]$.  However, for $p=5$, we see that $P(x)$ satisfies the required conditions.  To see this, we observe that
$$\sum_{r=0}^4\,P(n+r)=5\,\left(\frac{n(n-1)(n+1)}{6}+2n^2+8n+11\right)$$
for all $n\in\mathbb{Z}$.


text:
Q: The LDO on my STM32 circuit heats too much after long hours of operation I have an STM32F0 based circuit to control two AC loads (a compressor unit and an MD40 pump). A 12V supply feeds the circuit. On the PCB there is an LM2576T to step the voltage down to 5V. This is further regulated to 3.3V (for powering the STM32) using an LM3940.
My modules seems to be working fine. But once in a while (for two days it was working fine), when the loads are operating on the relays, the LM3940 heats up to 80 degree Celsius and my circuit temporarily turns off (as indicated by the 7 segments dimming and turning off eventually). The design of the circuits looks okay to me and the 12V power supply has been tested with other circuits and can provide a current of up to 5A. This was not a one time issue. This problem was recurring. At one point, the main circuit stopped working because the LDO got burned.
I've attached the power supply circuit diagrams. Also attached is the circuit for the relay boards which control the loads. There is a Darlington pair of BC847s on the board for driving the relay. The relay circuit is not optocoupled. The relays are powered by the main 12V supply.

C18 - 10uF Tantalam

I've been unable to figure this out so far, so any help is appreciated.

Other components on my circuit:

*

*4 seven segments

*An MAX485 on UART for MODBUS communication

*Some tactile switches

*Some NTC thermistors read by the STM ADC

A: There are no series resistors for the 7 segment display LEDs, so the LEDs draw too much current.


text:
Q: Highlight the Menu Item found in Search Result of Android Settings App Inside Android core Settings App, when we search anything in the search bar, then the result of that search is highlighted automatically.
For e.g. please see below image where I highlighted my application name in the Notification Access section.

I achieved this by following code:
val intent = Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS").apply {
    val app = "${application.packageName}/${NotificationListener::class.java.name}" //Here NotificationListener is a service name
    val fragmentKey = ":settings:fragment_args_key"
    val showFragmentKey = ":settings:show_fragment_args"
    putExtra(fragmentKey, app)
    putExtra(showFragmentKey, Bundle().apply { putString(fragmentKey, app) })
}

I referred to the Solution on this LINK
However, I want to highlight my application name in the Usage Access Setting.
i.e. when I open the intent for Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS) then inside the list of apps, my app name must be highlighted.
However the above logic/approach is not working for Usage Access Screen.
My application opens the intent but does not highlight my app name there.
I did a detailed research but I am still facing challenge.
Hence, I request you all to please assist.

A: For ACTION_USAGE_ACCESS_SETTINGS , I can't find one. Have you seen it anywhere? If so, please show me on which app. I've requested about this here:

*

*https://issuetracker.google.com/issues/165311852

*https://issuetracker.google.com/issues/160303945
And one in general, for all settings:

*

*https://issuetracker.google.com/issues/163176781
As for notification-access, check here: stackoverflow.com/a/63914445/878126


text:
Q: FakeItEasy deep nested types faking I have a complex object that I'm trying to fake.
interface IContext
{
    User User { get; }
}

A.CallTo(
    () => _fakeContext.User.Subscription.Attributes)
    .Returns(new List<Attribute>());

But I get the next exception:
The current proxy generator can not intercept the specified method for the following reasons: - Non virtual methods can not be intercepted
All nested types are properties, and they are simple anemic types with get; set; property modifiers. And when I look into the debugger they all are fakes.
Is there any way to setup the last property of the chain and avoid setuping all previous ones?

A: If your objects are anemic enough, you might want to give AutoFixture a go:
var fake = A.Fake<>();
var fixture = new Fixture();
// If it's possible [1], AutoFixture will generate entire object graph
var user = fixture.CreateAnonymous<User>();
// Since data will be random [2], you can overwrite properties as you like
user.User.Subscription.Attributes = new List<Attributes>();
A.CallTo(() => fake.User).Returns(user);

*

*In order for it to work, your custom objects need to have public constructor and preferably avoid using interfaces (but that can be mitigated with auto-mocking extensions, like AutoFakeItEasy).

*The .Build method provides fluent API to customize objects autogeneration, so the randomness can be controlled


text:
Q: How to display a list of arrays based on a value within array? So I have an array like below:
Array
(
[0] => Array
    (
        [model] => COROLLA
        [trim] => L
        [msrp] => 16,800
        [type] => car
    )

[1] => Array
    (
        [model] => COROLLA
        [trim] => LE
        [msrp] => 18,300
        [type] => car
    )

I need to be able to call all unique values of type and iterate through them to return them as if the type is a category.  So I need to make a list of all the vehicles with 'car' as a type and another list for all vehicles with 'van' as a type etc.  I have this to get unique values:
$type = array();
  foreach($cars as $car){
    $type[] = $car['type'];
  }
$type = array_unique($type);

I am really running into a wall on how to search for their values and return the top level array.  i know this is basic but I am struggling.

A: The code below will result in an array that groups vehicles by type:
$vbt = array();
foreach ( $cars as $car )
{
    $vbt[ $car['type'] ][] = $car;
}

So now you have an array that looks like this:
/*
$vbt ==  Array
(
    [car] => Array
    (
        [0] => Array
        (
            [model] => COROLLA
            [trim] => L
            [msrp] => 16,800
            [type] => car
        )

        [1] => Array
        (
            [model] => COROLLA
            [trim] => LE
            [msrp] => 18,300
            [type] => car
        )
    )

    [van] => Array
    (
        [0] => Array
        (
            [model] => ODYSSEY
            [trim] => L
            [msrp] => 16,800
            [type] => van
        )
    )
)
*/

From that structure you can access any list of vehicles if you have the type, for instance, to get an array of all type == van you'll do:
$vans = $vbt['van'];

/*
$vans == Array
(
    [0] => Array
    (
        [model] => ODYSSEY
        [trim] => L
        [msrp] => 16,800
        [type] => van
    )
)
*/

If you know already the type and you just want to get the list of vehicles of that type:
$vehicles = array();
$searchType = 'car';
foreach ( $cars as $car )
{
    if ( $car['type'] == $searchType )
    {
        $vehicles[] = $car;
    }
}

/*
$vehicles == Array
    (
        [0] => Array
        (
            [model] => COROLLA
            [trim] => L
            [msrp] => 16,800
            [type] => car
        )

        [1] => Array
        (
            [model] => COROLLA
            [trim] => LE
            [msrp] => 18,300
            [type] => car
        )
    )
*/

A: If you have PHP >= 5.5.0 you can get the type associated with their keys like this:
$cars_types = array_column($cars, 'type');

Then you could sort on the type and loop it to access the $cars array:
asort($cars_types);

foreach($cars_types as $key => $type) {
    echo $type; // or $cars[$key]['type']
    echo $cars[$key]['model'];
    //etc
}


text:
Q: Como chamar um Interstitial clicando em um item da lista que passa por um Adapter? Preciso chamar um Interstitial nesta Activity clicando em um item da lista que vem do meu Adapter:
public class ListOfTemplates extends AppCompatActivity {
    private Template template;
    private ViewHolder view;

    private InterstitialAd mInterstitialAd;

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

        final RecyclerView rclTemplates = findViewById(R.id.rclTemplates);
        final TextView txtNome = findViewById(R.id.txtNome);
        final Button btn = findViewById(R.id.btnAdmod);

        MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");

        //Toast.makeText(getApplicationContext(), "Desliguei", Toast.LENGTH_LONG).show();
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
        LoadInterstitial();

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                LoadInterstitial();
            }
        });

        rclTemplates.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mInterstitialAd.isLoaded()) {
                    mInterstitialAd.show();
                } else {
                    Log.d("TAG", "The interstitial wasn't loaded yet.");
                }
                //mInterstitialAd.show();
            }
        });

        if (ListaTemplates.getTamanhoListaTemplates() > 0){
            ListaTemplates.getListaTemplates().clear();
        }

        TemplateDAO dao = new TemplateDAO(getApplicationContext());
        dao.selectTemplates();

        ListaTemplates.carregarTemplates();

        Adapter tempAdapter = new Adapter(ListaTemplates.getListaTemplates(), getApplicationContext());

        rclTemplates.setAdapter(tempAdapter);

        RecyclerView.LayoutManager meuLayout = new LinearLayoutManager(
                getApplicationContext(),
                LinearLayoutManager.VERTICAL,
                false
        );

        rclTemplates.setLayoutManager(meuLayout);

    }

    private void LoadInterstitial(){
        //mInterstitialAd.loadAd(new AdRequest.Builder().build());
        AdRequest interAdRequest = new AdRequest.Builder().build();
        mInterstitialAd.loadAd(interAdRequest);
        Toast.makeText(getApplicationContext(), "Estou aqui", Toast.LENGTH_LONG).show();
    }

}

Meu Adapter:
public class Adapter extends RecyclerView.Adapter {

    private ArrayList<Template> listaTemplates;
    private Context context;

    public Adapter(ArrayList<Template> listaTemplates, Context context) {
        this.listaTemplates = listaTemplates;
        this.context = context;
    }
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.minha_celula, parent, false);

        //
        RecyclerView.ViewHolder holder = new ViewHolder(view);
        return  holder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {

        final ViewHolder holderArm = (ViewHolder)holder;

        holderArm.txtNome.setText(listaTemplates.get(position).getNome());

        if (ListaTemplates.getTemplate(position).getPhoto().equals("classic")){
            holderArm.imgCelula.setImageResource(R.drawable.on);
        }else if (ListaTemplates.getTemplate(position).getPhoto().equals("spark"){
            holderArm.imgCelula.setImageResource(R.drawable.power_on2);
        }
        final String nome = holderArm.txtNome.getText().toString();
        holderArm.txtNome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(context, MainActivity.class);
                intent.putExtra("index", position);
                intent.putExtra("nome", nome);

                Bundle bundle = new Bundle();
                intent.putExtra("keyNome", nome);
                intent.putExtra("keyNome", nome);

                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);

            }
        });

    }

    @Override
    public int getItemCount() {
        return listaTemplates.size();
    }
}

A: Eu fiquei dias tentando implementar este Interstitial (pode parecer simples, mas sou iniciante em Desenvolvimento Android), então resolvi pedir ajuda aqui, mas é incrível, só foi eu postar a dúvida, minutos depois eu consegui a solução esperada. Vou deixar a resolução aqui caso alguém tenha essa dúvida um dia.
public class Adapter extends RecyclerView.Adapter {

    private ArrayList<Template> listaTemplates;
    private Context context;
    private InterstitialAd mInterstitialAd;

    public Adapter(ArrayList<Template> listaTemplates, Context context) {
        this.listaTemplates = listaTemplates;
        this.context = context;
    }
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.minha_celula, parent, false);

        RecyclerView.ViewHolder holder = new ViewHolder(view);
        return  holder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {

        final ViewHolder holderArm = (ViewHolder)holder;

        holderArm.txtNome.setText(listaTemplates.get(position).getNome());

        if (ListaTemplates.getTemplate(position).getPhoto().equals("classic")){
            holderArm.imgCelula.setImageResource(R.drawable.on);
        }else if (ListaTemplates.getTemplate(position).getPhoto().equals("spark")){
            holderArm.imgCelula.setImageResource(R.drawable.power_on2);
        }
        //holderArm.txtNome.setText("Ver Detalhes");
        final String nome = holderArm.txtNome.getText().toString();
        holderArm.txtNome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Posição na lisa e não no Banco de Dados
                Intent intent = new Intent(context, MainActivity.class);
                intent.putExtra("index", position);
                intent.putExtra("nome", nome);

                //Toast.makeText(context, "Nome printado: " + nome, Toast.LENGTH_SHORT).show();

                Bundle bundle = new Bundle();
                intent.putExtra("keyNome", nome);
                //bundle.putString("keyNome", nome);
                intent.putExtra("keyNome", nome);

                //intent.putExtra("nome", holderArm.txtNome);
                //holderArm.txtNome.toString();

                /** Código da resolução
                    Toda vez que selecionar um item da lista que passar pelo Adapter será chamado um Interstitial
                **/
                AdRequest adRequest = new AdRequest.Builder().build();
                mInterstitialAd = new InterstitialAd(context);
                mInterstitialAd.setAdUnitId("ca-app-pub-1714562797049244/5381799713");
                mInterstitialAd.loadAd(adRequest);
                mInterstitialAd.setAdListener(new AdListener() {
                    @Override
                    public void onAdLoaded() {
                        displayInterstirial();
                    }
                });

                //Resolvendo o problema de "Calling startActivity() from outside of an Activity"
                //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);

            }
        });
    }

    private void displayInterstirial(){
        if (mInterstitialAd.isLoaded()){
            mInterstitialAd.show();
        }
    }

    @Override
    public int getItemCount() {
        return listaTemplates.size();
    }
}


text:
Q: Connecting 2 classes I have a student object class and I have to create an arraylist of these students.
Im trying to create the program that inputs information into the student object then store it into an arraylist.
The first command to this array is to add a student object to the array the next command would be to remove a student from the array.
How would I get a user to input a command then go to another method that leads to storing information if everytime i try to complie i get static errors.
import java.util.Scanner;
import java.util.ArrayList;

public class CollegeTester
{
Scanner input = new Scanner(System.in);
ArrayList<Student> array = new ArrayList<Student>();
CollegeTester collegeTester = new CollegeTester();;

public static void  main(String[] args)
{
    new CollegeTester().getCommand();
}

public void getCommand()
{
    System.out.println("Enter a command: ");
    String command = input.nextLine();
    if(command.equals("add"))
        collegeTester.addCommand();
}

public void addCommand()
{
    System.out.println("Enter a Name: ");
    String name = input.nextLine();
}

}

A: There is another loophole. Your main method is not static. Your program will not run without it. Change it to
public static void main(String[] args)
{

}

Also then you cannot access non-static methods directly from static method.
Either you should instantiate class and then call methods or make methods static.
 public static void main(String[] args){
 CollegeTester collegeTester = new CollegeTester();
 collegeTester.addCommand();
 }

If you want to call specific method on specific options, then you should use switch case.

A: You  are trying to access to not static method from static method. At first make an instance of CollegeTester class, than call it. For example:
import java.util.ArrayList;
import java.util.Scanner;

public class CollegeTester {
    private Scanner input = new Scanner(System.in);
    private ArrayList<Student> array = new ArrayList<Student>();

    public static void main(String[] args) {
        new CollegeTester().getCommand();
    }

    public void getCommand() {
        System.out.println("Enter a command: ");
        String command = input.nextLine();
        if (command.equals("add"))
            this.addCommand();
    }

    public void addCommand() {
        System.out.println("Enter a Name: ");
        String name = input.nextLine();
    }
}

public class Student {
    // Some properties and fty.
}


text:
Q: Pullback of maps out of a connected & locally path connected space I'm reading Peter May's "Concise Course in Algebraic Topology", and I'm having trouble interpreting this yellow-highlighted line.
When I've seen the expression "pullback of $f$ along $g$" previously, $g$ and $f$ have had shared codomains. So I have two questions:

*

*Diagrammatically, what does the setup look like here? (i.e. what is May saying?)

*Why does $D$ cover $A$ in this situation?

A: In the chapter "Covering spaces" May makes the assumption

Throughout this chapter, we assume that all given spaces are connected and locally path connected.

You can of course introduce the concept of covering spaces in a more general setting by omitting this assumption. Most authors do so.
In this general setting one can easily prove that the pullback of a covering map $p : E \to B$ along a map $f :A  \to B$ is again a covering map. This pullback is of course a map $p' : E' \to A$:
$\require{AMScd}$
\begin{CD}
E'  @>{f'}>> E \\
@V{p'}VV @V{p}VV \\
A @>{f}>> B\end{CD}
May's statement (which I modified a little bit to adjust it to our general setting) is this:

The pullback of a map $f :A  \to B$ along a covering map $E \to B$ is a covering map $p : D \to A$.

I think the pullback of $f$ along $E \to B$ is a map $D \to E$ which is not what we want. But perhaps that is only a question of notational conventions.
May's statement includes the assumption "where $A$ is connected and locally path
connected". This is due to his basic assumption on spaces. Moreover, he adds "and $D$ is a component of the pullback". This is due to the fact that our above $E'$ is not necessarily connected. But restricting $p' : E' \to A$ to such $D$ yields again a covering map - which now fits into his framework. An example for this phenomenon is the covering map $p : \mathbb R \to  S^1$. Pulliing back along the inclusion of a one-point space $P$ into $S^1$ yields the covering map $\mathbb Z \to P$.


text:
Q: Operating System becomes unstable after prolonged use My setup

*

*uname -a prints:
Darwin Jutsu.local 11.2.0 Darwin Kernel Version 11.2.0: Tue Aug  9 20:54:00 PDT 2011;
root:xnu-1699.24.8~1/RELEASE_X86_64 x86_64

*Mac OS X Version: 10.7.3 as of this post

*Processor: 2.66 GHz Intel Core i7

*Memory: 8 GB 1067 MHz DDR3

Problem
Google chrome starts to time out in an odd way: I'll open a new tab and try to load gmail. It's taking longer then it should, so I try to right click or open the console but nothing happens.
I am able to close the tab and try again - but the page loads and I am unable to do anything on the page.
Troubleshooting

*

*This is what things start to look like when life sucks...
Processes: 97 total, 3 running, 2 stuck, 92 sleeping, 489 threads                                                                                11:59:12
Load Avg: 3.35, 2.46, 1.58  CPU usage: 3.28% user, 27.93% sys, 68.77% idle   SharedLibs: 13M resident, 6744K data, 0B linkedit. MemRegions: 19003 total, 1363M resident, 65M private, 663M shared.
PhysMem: 1037M wired, 2255M active, 272M inactive, 3563M used, 4626M free. VM: 198G vsize, 1118M framework vsize, 1886103(0) pageins, 0(0) pageouts. Networks: packets: 287068/334M in, 164599/24M out.
Disks: 28824/1238M read, 56041/935M written.

*I've tried to kill the processes -9 and -15.
The processes end up as such: "(Google Chrome)" - which seems very odd to me.
I'm used to seeing "Google Chrome He" or something like this:
/Applications/Google Chrome.app/Contents/Versions/17.0.963.46/Google Chrome Helper.app/Contents/MacOS/Google Chrome Helper --type=renderer --lang=en-US --force-fieldtest=ConnCountImpact/conn_count_6/ConnnectBackupJobs/ConnectBackupJobsEnabled/DnsImpact/default_enabled_prefetch/DnsParallelism/parallel_default/GlobalSdch/global_enable_sdch/IdleSktToImpact/idle_timeout_10/Instant/SilentExperimentA/Prefetch/ContentPrefetchPrerender1/PrerenderFromOmnibox/OmniboxPrerenderEnabled/PrerenderFromOmniboxHeuristic/ExactFullAlgorithm/ProxyConnectionImpact/proxy_connections_32/SpdyCwnd/cwndMin16/SpdyImpact/npn_with_spdy/WarmSocketImpact/warm_socket/ --extension-process --enable-print-preview --channel=313.0x33f8c00.1296777368

At this point I figure I should just restart or shutdown. But the system becomes unwilling to, stating that it can't shut down any of the current processes. I try to terminate Adium or the Terminal itself and those won't close as well.
This leads me to holding down the power button.    When the system boots back up, everything works as it should, even the kill commands.
Does anyone have a guess as to what might be causing this?
Syslog: (220 was the parent Google Chrome process)
Feb 10 15:06:35 Jutsu Dock[222] <Error>: kCGErrorIllegalArgument: CGSSetWindowTransformsAtPlacement: Failed

Feb 10 15:06:35 Jutsu Dock[222] <Error>: kCGErrorIllegalArgument: CGSSetWindowTransformAtPlacement: Failed

--- last message repeated 1 time ---

Feb 10 15:06:35 Jutsu Dock[222] <Error>: kCGErrorIllegalArgument: CGSSetWindowListGlobalClipShape: Invalid window 0x72

Feb 10 15:06:31 Jutsu Dock[222] <Warning>: trying to take pid 220 out of fullscreen but it is not the current space

Update

*

*This problem is not exclusive to Google Chrome, it happens with iTunes and other applications as well.

*"killing" the processes doesn't produce the desired results, but going to Apple Icon -> Force Quit does indeed completely stop the process as it should.
But the system still begins to degrade in stability, for instance, iTunes reports:
"The iTunes Library file is locked, on a locked disk,
or you do not have write permission for this file."

*When I tried to exit the Terminal that process became stuck as well (see report @ github).
Rebooting still remains the only viable option.

A: While your issue may go beyond this, there is one piece of behavior I've noticed with Google Chrome;
When you open a new window / tab, wait for the content to load. Wait for the Top Sites and everything else to appear. If you browse to a site while that's still loading, Chrome rarely allows me to browse to anything else. Wherein if I start having this problem and let the Top Sites content load, and THEN browse somewhere, it works pretty much perfectly and without any problems.
Whenever I'm "stuck" loading content, killing the tab takes time, at least a handful of seconds, but it does eventually happen.
However, I have never had massive computer instability as a result of Chrome, shutdown / restart has never failed to work.


text:
Q: How to make transparency in emgu cv? I have a requirement of making the black color background of a image as transparent. Any ideas on how to do this using EmguCV ?
Below is the image which I'm using for this process.

A: First keep in mind that some image types do not support transparency, for example jpeg,
What you're describing is easy to implement; just iterate through the pixels and when you encounter a black pixel (all rgb values are less then 10), replace it with a new pixel (or MCvScalar in emgucv) with an alpha value set to zero.

(255, 255, 255, 0)


text:
Q: How to declare a nullable enum by default null in postgreSQL using Knew migration? I'm new on Knex, and I have to resolve a migration that adds a column with a value of type enum which should be null by default. I can't find a clear example of how to do it. My guess is this:
const NEW_ENUM= [
  "",
  "FAILED",
  "SUCCESS",
  "WAITING"
]
export async function up(knex: Knex): Promise<void> {
  await knex.schema.alterTable(TABLE_NAME, (table: Knex.TableBuilder) => {
    table
      .enum(NEW_COLUMN_NAME, NEW_ENUM, {
        useNative: true,
        enumName: NEW_ENUM_NAME,
      })
      .nullable()
      .defaultTo(null);
  });
}


text:
Q: Given a band of $m$ opaque squares arranged in a circle, can we find a viewpoint from which we see exactly $m/2-1$ squares?
Given a band of $m\ge 3$ opaque squares arranged in a circle, can we find a viewpoint (i.e. a point on a sphere centered at the midpoint of the circle with a radius large enough to see the whole band from any viewpoint; the viewing direction is the vector from the viewpoint to the center of the sphere) from which we see exactly $\lfloor m/2\rfloor$ squares? Moreover, can we find a viewpoint from which we see exactly $\lfloor m/2\rfloor-1$ squares?

I assume that this is an easy to answer question, but I've got problems in arguing. Clearly, each square contributes $2\pi/m\text{ rad}$ to the angle sum of the circle. I don't know how I need to phrase this, but it's also clear that we can see any square whose normal $n$ takes an angle in $(-\pi/2,\pi/2)$ with $-v$, where $v$ is the viewing direction. So, I guess the answer has something to do with $$\frac{2\pi\text{ rad}}m\stackrel!=\frac{\pi\text{ rad}}k\Leftrightarrow k=\frac m2\tag 1\;.$$
But as I said before, I need help to find a rigorous argumentation.

A: The outward normal vectors point in directions $\frac{2\pi k}{m}$ ($k = 0, \ldots, m-1$), as you observe. Let's assume that the face-centers are at locations
$$
P_k = (\cos(2\pi k/m), \sin (2 \pi k / m))
$$
as well, i.e., on a unit circle.
Letting $\alpha = \frac{2\pi}{m}$, we have
$$
P_k = (\cos k\alpha, \sin k \alpha) \\
n_k = [\cos k\alpha, \sin k \alpha]
$$
where $n_k$ is the normal to the $k$th face.
Consider a view from a point far along the ray in direction $\beta = \frac{\pi}{2} + \frac{\alpha}{2}$, i.e.
$$
Q = (s \cos \beta, s \sin \beta)
$$
Now face $k$ is visible from $Q$ if $ (Q - P_k) \cdot n_k > 0$, which simplifies to
$$
Q \cdot n_k > P_k \cdot n_k.
$$
Since $P_k$ and $n_k$ are the same (in coordinates) and are points of the unit circle, this condition becomes
$$
Q \cdot n_k > 1.
$$
And then
$$
Q \cdot n_k  = [s \cos \beta , s \sin \beta] \cdot  [\cos k\alpha, \sin k \alpha]\\
=  s \cos \beta \cos k \alpha + s \sin \beta \sin k \alpha.
$$
Letting $u = k \alpha$ for a moment, this is
$$
Q\cdot n_k  =   s(\cos \beta \cos u +  \sin \beta \sin u)\\
= s \cos (\beta - u)
$$
As long as $\beta - u$ has positive cosine, we can choose $s$ large enough to make this number $> 1$. Let's look at $\beta - u = \beta - k \alpha$.
For the cosine to be positive, we need
\begin{align}
-\pi/2 &< \beta - k \alpha < \pi/2 \\
-\pi &< \pi + \alpha - 2k \alpha < \pi \\
-\pi &< \pi + (1-2k)\alpha  < \pi \\
-\pi &< \pi + (1-2k)\frac{2\pi}{m}  < \pi \\
-1 &< 1 + (1-2k)\frac{2}{m}  < 1 \\
-m &< m + 2(1-2k)  < m \\
-2m &< 2(1-2k)  < 0 \\
0 &< 2(2k-1)  < 2m \\
0 &< 2k-1  < m
\end{align}
which has the $\frac{m}{2} - 1$ solutions $k = 1, 2, \ldots, \lfloor \frac{m}{2} \rfloor$.

A: Adapting the idea of John Hughes, I came up with the following solution: Identifying $\mathbb C\cong\mathbb R^2$, we can assume that the centers of the squares are at the locations $$c_k:=e^{k\alpha\rm i}\;\;\;\text{for }k\in\left\{0,\ldots,m-1\right\}$$ with $\alpha:=2\pi/m$, i.e. the centers of the squares are the $m$th roots of unity lying on the unit circle. The corresponding outward unit normals are $n_k:=c_k\color{blue}{-0}$. Let $v$ be a view point at angle $\beta:=\pi/2$, i.e. $$v:=ce^{\frac\pi2{\rm i}}$$ for some $c>0$ large enough to see the entire band (but since that's not important, we will assume $c=1$). Notice that the viewing direction corresponding to $v$ is $0-v$ (again, that's not important, but nice to know). We can see the $k$th square from $v$ iff $$\sphericalangle(c_k,v)\in\left(-\frac\pi2,\frac\pi2\right)\;,$$ i.e. iff $$0<\cos\sphericalangle(c_k,v)=\langle c_k,v\rangle=\cos(k\alpha)\cos\frac\pi2+\sin(k\alpha)\sin\frac\pi2=\sin(k\alpha)\;,$$ i.e. iff $$k\alpha\in(0,\pi)\Leftrightarrow k\in\left(0,\frac m2\right)\;.$$

So, there's a viewpoint from which we see exactly $\lfloor\frac m2\rfloor-1$ squares. Replacing $\beta$ by $(\alpha+\pi)/2$, the same argumentation yields that there's a viewpoint from which we see exactly $\lfloor\frac m2\rfloor$ squares (see John Hughes' answer).


text:
Q: delete entity in onetomany relationship jpa i have 3 tables: customer, rent, and edition. where customer have one or more rents, and edition have one or more rents. rent have 2 foreign keys (customerId, editionId) and one primary key (rentId), i am trying to delete one customer, but i have an error that the fk of customerId are still in the rent table. i first delete all rents from the customer's listRent. Here is the delete method (email is the customerId from rent´s table):
    public boolean delete(String email){
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("tutorial");
        EntityManager entityManager = entityManagerFactory.createEntityManager();

        Customer customer= entityManager.find(Customer.class, email);
        if(customer!=null){
            entityManager.getTransaction().begin();
            for (Rent rent :customer.getRentList()) {
                entityManager.remove(rent);
            }
            entityManager.remove(customer);
            entityManager.getTransaction().commit();
            entityManager.close();
            entityManagerFactory.close();
            return true;
        }
        entityManager.close();
        entityManagerFactory.close();
        return false;
    }

but still have the error:
javax.persistence.RollbackException: Error while committing the transaction (...)
Caused by: org.postgresql.util.PSQLException: ERROR: update o delete in «customer» violates the foreign key «fkgft5yuturjnobc97u2x1464b» in the table «rent»

here is the customer entity:
@Entity
@Table(name="Customer")
public class Customer {

    @Id
    @Column(name="email")
    private String email;

    @Column(name="firstName")
    private String firstName;

    @Column(name="lastName")
    private String lastName;

    @Column(name="Gender")
    private String gender;

    @Column(name="age")
    private Integer age;

    @OneToMany(mappedBy = "customer", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private List<Rent> rentList = new ArrayList<>();

    public Customer(){
    }

    public Customer(String email, String firstName, String lastName, String gender, Integer age) {
        this.email = email;
        this.firstName = firstName;
        this.lastName = lastName;
        this.gender = gender;
        this.age = age;
    }

and rent entity:
@Entity
@Table(name = "Rent")
public class Rent {

    @Id
    @GeneratedValue
    @Column(name="rent_id")
    private Integer rentId;

    @ManyToOne
    @JoinColumn(name="email")
    private Customer customer;

    @ManyToOne
    @JoinColumn(name="edition_id")
    private Edition edition;

    @Column(name="renting_date")
    private String rentingDate;

    public Rent(){
    }

    public Rent(String rentingDate) {
        this.rentingDate = rentingDate;
    }

I'm skipping the edit table just because is the same that customer with other attributes, and the owner of both tables is rent. i try delete directly in postgresql and works when i delete the rent table and then customer table, but for some reason, i cant not delete with jpa
i am ussing postgresql 13, wildfly 23 and hibernate.

A: There are tests in Hibernate(https://github.com/hibernate/hibernate-orm/blob/main/hibernate-core/src/test/java/org/hibernate/test/bytecode/enhancement/cascade/CascadeDeleteCollectionTest.java) that exercise exactly this scenario so there must be something wrong with your setup. It's a bit fishy that you build up the EntityManagerFactory manually since you run on Wildfly. My guess, you are packaging a custom old version of Hibernate into your WAR which is then used which might be buggy. Try using <scope>provided</scope> for the Hibernate dependency.


text:
Q: Probability Question involving dices Two fair dice are thrown. Given that the total score obtained is even, find the probability of throwing a double.
So I got that the sample space is all the possible outcomes and, |S|= 21.
A = Event that total score obtained is even.
|A| = 12
B = Event that double is thrown
, |B| = 6
How should i continue thereafter?
I took $\frac{\frac{6}{21}}{\frac{12}{21}}=\frac{1}{2}$
but the given answer is $\frac{1}{3}$
Am i approaching the qn the right way?
Thanks in advanced!

A: As you realised, there are $36$ outcomes, $\{(1,1), (1,2),\ldots,(1,6),(2,1),(2,2),\ldots,(2,6), \ldots, (6,1),\ldots,(6,6)\}$ (of the form first die-result, second die-result).
Of these, half ($18$) have even sum, and of these $6$ have a double. So indeed the right answer should be $\frac{6}{18} = \frac{1}{3}$.


text:
Q: Setting a maximum response time in a spring 3.0 application I have a web application that our product owner has stated must respond within 2.5 seconds and be usable within 3 seconds.
Right now it's mostly POJOs on top of a thinly sliced Spring MVC layer which is being used for dependency injection and directing requests to controllers.
The webapp is a very thin slice of meat between a stack of APIs which are being built to provide cohesion to a disparate set of very old, irregular APIs. Some of which can take longer than 3 seconds (though not too often)
What I want is a way to tell spring or tomcat that if it isn't loading the JSP by  within 2500ms I want to load the jsp that tells our user that "Dude, we're crawlin' through molasses here! Give us a second and try again. If you get this page multiple times; then you're really boned!"
Right now it appears I could do this several ways (ordered by my desire)

*

*In spring I may be able to set up a timeout and load a different jsp

*In the load balancer I may be able to set up a timeout with a redirect

*In tomcat I may be able to set up a timeout and load a different jsp

*In apache I may be able to set up a tomcat iwth a redirect

*in the app I split the architecture to run inside a thread that is polled every 100ms to see if it had stopped running, and after 2500ms it throws an exception

A: If I remember correctly, all requests to Spring MVC go via a single filter. You can probably override it and program your timeout settings (e.g. have a configurable XML with timeout-enforced URLs or paths). Guava's TimeLimiter would be a good tool to implement the timeout enforcement itself.
<general-rant>
I don't know the industry you're in, but generally in the web world it is a bit too self-demanding to panic if a response doesn't come back in 2-3s, especially if long taking responses are just a minority (as you say). I have experience with large heaps (Xmx=10g) where just a GC can take several minutes to accomplish. OK, maybe this is an overrated example, but one-two second taking GCs are pretty reasonable.
Even Tomcat manual says that very small timeouts will likely be counterproductive. Your product owner must be choleric :)
</general-rant>
Ah, there's more. Don't forget you can't just redirect if you have already posted something back to your servlet response. So you probably need to delay your response until the last bit of computation is done and flush everything at the end. This means you have to wrap your HttpServletResponse with a decorator which has some sort of a latch which delays response output until the full response is generated, or if timeout occurs - redirects to "ouch" page.


text:
Q: ANOVA on multiple models stored in a tibble It is possible to use anova on multible models stored in a tibble without listing them manually.
An example prediction of wage from age in Wage dataset from the ISLR2 library. I have a tibble a column for polynomial degrees in one column, GLM models in another and CV errors in the third column.
I can use anova through do.call but it does not show p-values without passing test = 'F' as an argument.
library(ISLR2)
library(tidyverse)
library(boot)
GLM <- function(n) {
  result <- glm(wage ~ poly(age, n), data = Wage)
  return(result)
}
CV <- function(n) {
  glm_fit <- glm(wage ~ poly(age, n), data = Wage)
  result <- cv.glm(Wage, glm_fit, K = 10)$delta[1]
  return(result)
}

set.seed(1)
models <- tibble(polynom_degrees = 1:10) %>%
  mutate(linear_model = map(polynom_degrees, GLM)) %>%
  mutate(CV_error = map(polynom_degrees, CV)) %>%
  mutate(CV_error = unlist(CV_error))

do.call(anova, models$linear_model)


text:
Q: Loading JS functions on dynamically loaded pages I am using CSS-Tricks dynamic page script found here.
http://css-tricks.com/dynamic-page-replacing-content/
$(function() {

var newHash      = "",
    $mainContent = $("#main-content"),
    $pageWrap    = $("#page-wrap"),
    baseHeight   = 0,
    $el;

$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $mainContent.height();

$("nav").delegate("a", "click", function() {
    window.location.hash = $(this).attr("href");
    return false;
});

$(window).bind('hashchange', function(){

    newHash = window.location.hash.substring(1);

    if (newHash) {
        $mainContent
            .find("#guts")
            .fadeOut(200, function() {
                $mainContent.hide().load(newHash + " #guts", function() {
                    $mainContent.fadeIn(200, function() {
                        /*
                        $pageWrap.animate({
                            height: baseHeight + $mainContent.height() + "px"
                        });
                        */
                    });
                    $("nav a").removeClass("current");
                    $("nav a[href="+newHash+"]").addClass("current");
                });
            });
    };

});

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

});

Body
<body onload="onLoad()">

I am using a number generating script (below) on one of my pages, but I am having trouble getting it to only show on one, single page. When placed in the head of the document or my includes/scripts.php that is loaded on every page, it shows on every page. When only included on the page I want, it does not work.
<script>

function counter() {
var num = 0;
    for (num = 0; num < 500; num++) {
      document.write(num + '   ');
    }
}
counter();

</script>

I have tried a few different things but can't seem to get it to only appear on a single page. Is there any way around this without ditching the CSS-Tricks Dynamic Page?

A: What if you insert your code into dynamicpage.js like this?
$(window).bind('hashchange', function(){

    newHash = window.location.hash.substring(1);

    if(newHash === 'somePage') { // the page you want to implement the effect
      // your code
    }
    /*
      ....
    */
});

A: You might try adding a class to your <body> tag (or other near-to-top level wrapper if you're just dynamically loading to the HTML attribute of your body tag in the first place) that lets the script distinguish between pages that ought to use the function and those that don't, something like:
$(document).ready( function() {
    $(`body.usesCounter`).on(eventToBeCounted, counterFuncAsCallback);
    }

But the fact that it's not working when only loaded on a single page does suggest you've got something else going on. Can you give us the header for the single page, the script block (and where it is on the page), and some sense of how/when it's called?
Are you loading the single page dynamically? If you are, the script tags won't be accessible unless you reload the DOM somehow or else do some funky binding via jQuery's $.on() or something similar that listens for changes to the DOM.

UPDATE
Looking at the tutorial you are trying to emulate, the general problem you're facing is that the JS on that page you're loading isn't going to be registered with the DOM. I've had to write code that can read dynamically lodaded JS like this, and if  you want to do it both effectively and securely, it's quite a lot of effort. The point of JS-based page loading is to be fetching "view-like" content; assets, html, etc.. In a single-page environment, any required logic should—generally—exist on that page.
I highly recommend you include the code in your initial page, and then conditionally call it when the appropriate page arrives. There are lots and lots of ways to do that, basically find some distinguishing feature of the page(s) where your counter should be run, and, after having loaded the page, look for said features and, if found, allow your code to run. You might have something as simple as a variable, isCounterPage set, by default, to false. Then, after a dynamic page load occurs, if the inspection fires and this var remains false, don't execute code associated with the counter. Otherwise, let it do its thing.


text:
Q: Gujarati OCR software How would one go about creating an ocr software for indic languages?
How can one analyze the character's?
How to manipulate them into font data?
I believe that I would need to use some form of tracing the line patterns and analyzing those patterns to a font character.

A: OCR (Optical Character Recognition) is not an ordinary programming task. Indeed it not just about your programming skills and demands a good understanding of a chunk of scientific issues. Here I draw a general picture of the steps required to accomplish such a task and mention the skills required, so you can follow them if you insisted yet;

*

*Preprocessing: An OCR program almost always performs a pre-processing on the image to improve it's quality as an input to its Recognition part. (Skill:Image Processing)

*Character Recognition: After applying the required changes to the input image (like removing some parts, scaling, applying some filters, ...) the program should recognize the character using a tool from the vast number of tools that exist (like Neural Networks, SVM, KNN ...).(Skill: Machine Learning-at least enough knowledge about one of the pre-mentioned tools)

*Postprocessing: The accuracy of the output from the previous step can further improve most of the time specially if you inject a domain knowledge into the problem, like forcing the output to an existing lexicon. (skill: ML again- KNN, CBR, ...)
I hope this general explanation guides you well. And believe that I tried to keep it as simple as possible.

A: Gujarati script could be tricky for many existing OCR libraries. A few questions:

*

*Do you want to read machine-printed text, or handwriting? These are two separate problem domains.

*Do you intend to develop/apply the OCR algorithm to a specific set of images/texts? If so, could you post some sample images?

*What is your end goal? Do you want to scan handwritten texts for machine processing, or read text for industrial applications, or scan forms?

*What read rate (accuracy) would be acceptable?

I'd suggest that textbooks are still a better starting point than reading a smattering of posts, articles, and papers online. There are two books I recommend for anyone interested in OCR:
Reading in the Brain by Stanislas Dehaene
Character Recognition Systems by Cheriet et al.
The Dehaene book is quite readable, and when reading it you will develop certain notions about how OCR might be developed for your particular application. I think it's typically best, no matter your level of experience, to try to solve a problem with whatever skills you have before you spend too much time reading the work of others. Spend a few days or a few weeks writing a bit of code or at least writing down ideas.
The Cheriet book gives a relatively current overview of work in the field. Even if the math isn't familiar to you, you'll get some idea of what research has been done.
Try first to get a broad overview of what has been done in the field, and what techniques have been tested for scripts similar to Gujarati. Stroke extraction techniques tested for Japanese, Chinese, and related scripts would likely be relevant to Gujarati. To my knowledge the number of existing OCR solutions for scripts such as Gujarati is relatively limited. However, some neural network-based methods could be used to train software on Gujarati characters (or any arbitrary symbols) and then recognize them, assuming the characters to be read are machine printed.
See if you can find a set of sample images for Gujarati. For a number of languages there are standard image sets or at least common image sets used to test the accuracy of OCR algorithms. If possible, get the original, raw, color or 8-bit grayscale images rather than images that have already been binarized to black and white (0 and 1).

As a start, I'd recommend finding at least one software package that at least partly solves your problem. Some OCR algorithms recognize outlines, others use neural networks to recognize grayscale patterns, and so on. Once you find a software package that has an algorithm that is somewhat successful with your image samples, you can identify what type of algorithm is used and proceed from there.
Tesseract is mentioned frequently. Free's a good price, so you might want to give it a try.
https://code.google.com/p/tesseract-ocr/
It's been a few years since I looked at the following, but one of these may have a user-trainable font that you could try on machine-printed Gujarati:

*

*FineReader by ABBYY.

*OmniPage by Nuance.

Companies in industrial image processing (a.k.a. "machine vision") offer software packages that implement a variety of OCR algorithms. Although these software packages are typically designed to read a few lines of text on silicon wafers, product packaging, or the like, they may be useful to you because (a) the simple user interfaces may help you test ideas quickly, (b) the packages include many additional image processing tools, (c) there are few limitations on the characters, symbols, or image features you can train, and (d) you may be able to download trial versions that have fully functional OCR tools.

*

*Cognex

*Microscan

*MvTec (product: HALCON)

*National Instruments LabVIEW

For machine-printed text, image capture is also important. A good optical system can help improve read accuracy: that could mean selecting a good camera + lens + light, or perhaps choosing a high-quality flatbed scanner.


text:
Q: Modify Asp gridview boundfield I want to add some text to a boundfield build in the code behind without writing any code in the code behind.
example
I receive "overflow" in a specific field, and i'd like to display "stack overflow" and if i receive "house" i want to display "stack house"
is there a property to put text behind or after whatever comes in the boundfield ?

A: Use a custom column.
  <asp:TemplateField HeaderText="MyColumn">
    <ItemTemplate>
         stack <asp:Literal runat="server" Text="<%#Eval("myField")%>" />
    </ItemTemplate>
  </asp:TemplateField>

A: notice
HtmlEncode=false
<asp:BoundField DataField="yourColumn" HeaderText="Your Header" DataFormatString="{0} overflow" HtmlEncode="false" SortExpression="GenCommission" />

A: Why not just use item template?
// instead of
<asP:BoundField DataField="FieldName" />

// use
<asp:TemplateField>
<ItemTemplate>
    prefix <%# Eval("FieldName") %> suffix
</ItemTemplate>
</asp:TemplateField>


text:
Q: Timeout exception from BulkCursorToCursorAdaptor Here is the crash dump i've got from playstore.
Fatal Exception: java.util.concurrent.TimeoutException: android.database.BulkCursorToCursorAdaptor.finalize() timed out after 10 seconds
       at android.os.BinderProxy.transactNative(Binder.java)
       at android.os.BinderProxy.transact(Binder.java:503)
       at android.database.BulkCursorProxy.close(BulkCursorNative.java:214)
       at android.database.BulkCursorToCursorAdaptor.close(BulkCursorToCursorAdaptor.java:121)
       at android.database.AbstractCursor.finalize(AbstractCursor.java:470)
       at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:202)
       at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:185)
       at java.lang.Thread.run(Thread.java:818)

Device details:
Lenovo P1a42
Android 6.0.1
Any help on why this crash happens?


text:
Q: IAsyncAction OnCompleted event handler called prematurely Something weird happening in my application and I cannot comprehend it. I create a background task for network communication using the ThreadPool class. In this task I call some methods asynchronously. The reason is that sometimes synchronous methods are not provided by Microsoft (for example there is not method DatagramSocket.Connect so I must use method DatagramSocket.ConnectAsync). But because I need to call these methods synchronously, I must use keyword "await" and mark the method as "async". When I do this, event handler for background task created in Button_Click event handler start is called prematurely. When the background task really finishes its job (for example by breaking the execution in debugger in manually moving execution pointer to the end of UdpSend method), OnCompleted event handler is not called. Is this normal ? Am I missing something important ?
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
   IAsyncAction work;

   public MainPage()
   {
      this.InitializeComponent();
   }

   private void Button_Click(object sender, RoutedEventArgs e)
   {
      if (work == null)
      {
         ButtonStart.Content = "Stop UDP test";
         work = ThreadPool.RunAsync(UdpSend);
         work.Completed = OnUdpSendFinish;
      }
      else
      {
         work.Cancel();
      }
   }

   private async void UdpSend(IAsyncAction work)
   {
      DatagramSocket socket = new DatagramSocket();
      socket.MessageReceived += Socket_MessageReceived;
      HostName host_name = new HostName("10.0.0.2");
      await socket.ConnectAsync(host_name, "1234");
      DataWriter writer = new DataWriter(socket.OutputStream);
      uint data = 0;
      int payload_size = 512;
      int payload_len = payload_size / sizeof(uint);
      while (work.Status != AsyncStatus.Canceled)
      {
         for (int i = 0; i < payload_len; i++)
         {
            writer.WriteUInt32(data++);
         }

         await writer.StoreAsync();
      }
   }

   private void Socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
   {
      throw new System.NotImplementedException();
   }

   private async void OnUdpSendFinish(IAsyncAction asyncInfo, AsyncStatus asyncStatus)
   {
      await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
          () =>
          {
             ButtonStart.Content = "Start UDP test";
          });
      work = null;
   }
}

A: That's because of how the await keyword works. It allows you to write all the code in the same method for readability, but in truth the method is split in two. Let's take a simple example:
private async void Example()
{
    DoSomething();
    await AsyncCall();
    DoSomethingElse();
}

After compilation, the method is rewritten to something like (it's much more complicated):
private void Example()
{
    DoSomething();
    AsyncCall();
}

private void ExampleContinuation()
{
    DoSomethingElse();
}

How the method is executed depends on what context it runs on. In your case, since you've used the thread pool, Example is run in the task you created (your IAsyncAction). After AsyncCall, the Example method returns, and so your Completed event is triggered. And only then, the runtime spins a new thread from the threadpool and uses it to run ExampleContinuation.
I workaround could be to use Task.Run instead of directly the threadpool. Task.Run will also use the threadpool under the cover, but with all the plumber y to handle those corner cases:
private Task work;

private void Button_Click(object sender, RoutedEventArgs e)
{
   if (work == null)
   {
      ButtonStart.Content = "Stop UDP test";
      work = Task.Run(UdpSend);
      work.ContinueWith(_ => OnUdpSendFinish());
   }
   else
   {
      work.Cancel();
   }
}

Then change the return type of your "UdpSend" method (it should have no incidence on the contents of the method, but it indicates the task that your call should be awaited):
private async Task UdpSend(IAsyncAction work)

Lastly, change the signature of your Completed handler:
private async void OnUdpSendFinish()

And you're done ;)


text:
Q: pyparsing lineno issue (bug?) I am using pyparsing to parse a language called pig. I found some unexpected result when used the function 'lineno' when the input text have some '\t' in it.
For easy to ask, I simplified the code to address the problem:
#/usr/bin/env python
from pyparsing import *

ident = Word(alphas)
statement1 = ident + Literal('=')+ Keyword('GENERATE', caseless = True) + SkipTo(Literal(';'),ignore = nestedExpr())+ Literal(';').suppress()
statement2 = Keyword('STORE',caseless = True) + ident + Literal(';').suppress()
statement = statement1|statement2

text = """
fact = GENERATE
('Exp' :(a
                )
)  ;

STORE fact ;

"""

all_statements = statement.scanString(text)
for tokens,startloc,endloc in all_statements:
        print 'startloc:' + str(startloc) , 'lineno:' + str(lineno(startloc,text))
        print 'endloc:' + str(endloc), 'lineno:' + str(lineno(endloc,text))
        print tokens

Notice that in the input text, there is more than 3 '\t' in the beginning of the third line
When I run this , the output is :
startloc:1 lineno:2
endloc:66 lineno:10
['fact', '=', 'GENERATE', "('Exp' :(a\n                                )\n)  "]
startloc:68 lineno:10
endloc:80 lineno:10
['STORE', 'fact']

this should be wrong, as there is total 9 line, it said the first statement is from line 2 to line 10.
I happened to found that when I delete those '\t', the input text is :
text = """
fact = GENERATE
('Exp' :(a
)
)  ;

STORE fact ;

"""

and I run it again, the result is :
startloc:1 lineno:2
endloc:34 lineno:5
['fact', '=', 'GENERATE', "('Exp' :(a\n)\n)  "]
startloc:36 lineno:7
endloc:48 lineno:7
['STORE', 'fact']

And this result seems correct, the first statement is from line 2 to line 5, the second statemenet is from line 7 to line 7 .This is what I expected.
So I think there maybe something wrong in the lineno() function, or maybe scanString.
Or maybe there is something wrong in my code?

A: Use parseWithTabs before calling scanString.


text:
Q: iOS: OverlayView. Which is the right view to put it? I have an application which saves some values on a bluetooth device. This of course takes some time.
When I exit a settings screen, the new settings get saved to this device. During the save process I'm putting an overlay view containing an activity indicator over the screen to block any inputs. When the save process is finished, the view gets a callback to remove the pop to the previous view and remove the overlay view. I tried to implement this idea in different ways, but always having an unwelcome side effect.
First implementation:
I put the overlayview over the keyWindow of the application.
Everything is block as wished. But when receiving the callback the overlay view gets removed first and with a little delay the transition back to the previous view gets executed, even the [overlay removeFromSuperView] is in the "viewDidDisappear" method.
-(void)putOverlayView{
    overlayView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];

    overlayView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] init];
    activity.center =overlayView.center;
    activity.transform = CGAffineTransformMakeScale(2, 2);
    [activity startAnimating];
    [overlayView addSubview:activity];
    [[UIApplication sharedApplication].keyWindow addSubview:overlayView];

}
-(void)savingDone{

    [self.navigationController popViewControllerAnimated:YES];

}
-(void)viewDidDisappear:(BOOL)animated{
[overlayView removeFromSuperview];

}

Second implementation:
I put the overlay view on the navigationControllers's view.
The screen gets blocked as wished, even this weird delayed transition effect, which i had in the first implementation idea is gone. But when I'm back at the previous view, the whole input is blocked. Even the overlayview is gone.
-(void)putOverlayView{
    overlayView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];

    overlayView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] init];
    activity.center =overlayView.center;
    activity.transform = CGAffineTransformMakeScale(2, 2);
    [activity startAnimating];
    [overlayView addSubview:activity];
    [self.navigationController view] addSubview:overlayView];

}
-(void)savingDone{

    [self.navigationController popViewControllerAnimated:YES];

}
-(void)viewDidDisappear:(BOOL)animated{
[overlayView removeFromSuperview];

}

Finally the third implementation:
I put the overlayview on the [self view].
With this option, I don't have any of the above mentioned effect. Although the NavigationController Title with the back button isn't block, as it is above the [self view]
-(void)putOverlayView{
    overlayView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];

    overlayView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] init];
    activity.center =overlayView.center;
    activity.transform = CGAffineTransformMakeScale(2, 2);
    [activity startAnimating];
    [overlayView addSubview:activity];
    [self view] addSubview:overlayView];

}
-(void)savingDone{

    [self.navigationController popViewControllerAnimated:YES];

}
-(void)viewDidDisappear:(BOOL)animated{
[overlayView removeFromSuperview];

}

I tried three different ideas, all not working as wished, but always in a different way.
On wich view do I have to put my overlay view to not have any of those unwished effects?
I kind of have the feeling that it would be the right way to put it on the navigationController's view, but how do I have to handle it, that the screen is unlocked for input afterwards?
I hope I gave enough informations, otherwise I will add them to the post of course.
Thanks for any help.


text:
Q: Como salvar os valores de uma String em uma variável Double? Tenho uma String com o valor x dentro dela
(String valor = "x")
Preciso passar esse valor para uma Variável Double, como faço para passar o valor de x da String para a variável? Sendo que se eu converter de String para Double o valor da variável Double fica nulo.
saldo = Double.parseDouble(valor);  <--- Após a conversão o valor fica nulo
Existe uma maneira para coletar esse valor e salvar em uma variável Double?

A: O método parseDouble é o mais usado para fazer esse tipo de conversão.
public class ConvertStringToDouble {
  public static void main(String[] args) {
    String aString = "700";
    double aDouble = Double.parseDouble(aString);

    System.out.println(aDouble);
  }
}

Você pode também fazer o CAST para converter para o seu tipo.

double aDouble = (Double)aString;

Usar o Double.valueOf

O método estático Double.valueOf () irá retornar um objeto Double mantendo o valor da seqüência especificada .
Sintaxe
String numberAsString = "153.25";
double number = Double.valueOf(numberAsString);
System.out.println("The number is: " + number);

Converter usando new Double(String).doubleValue()

String numberAsString = "153.25";
Double doubleObject = new Double(numberAsString);
double number = doubleObject.doubleValue();

Podemos encurtar para:
String numberAsString = "153.25";
double number = new Double(numberAsString).doubleValue();

Ou;
double number = new Double("153.25").doubleValue();

Converte usando DecimalFormat

O java.text.DecimalFormat classe é uma classe que pode ser usado para converter um número para a sua representação de String . Ele também pode ser usado no sentido inverso - ele pode analisar um String em sua representação numérica.
Exemplo
String numberAsString = "153.25";
DecimalFormat decimalFormat = new DecimalFormat("#");
try {
   double number = decimalFormat.parse(numberAsString).doubleValue();
   System.out.println("The number is: " + number);
} catch (ParseException e) {
   System.out.println(numberAsString + " is not a valid number.");
}

Obs:  se sua string contive , no lugar do . , o ideal e fazer um  replace antes de tenta converte.
String number = "123,321";
double value = Double.parseDouble(number.replace(",",".") );

Veja funcionado aqui.


text:
Q: Callback function in user mode vs kernel mode Why is it advisable to run callback functions in user mode vs kernel mode?

A: The only code that should execute in kernel mode is that which has been loaded into pages that are protected to restrict kernel mode access.
If you could execute a kernel mode callback function, that would open the door to all kinds of security holes.


text:
Q: Chart.js show tooltips on page load I am using http://www.chartjs.org/ to display a pie chart but can't seem to figure out how to display the tooltips on page load.
$(document).on('ready page:load', function() {

    Chart.defaults.global.tooltipEvents = ['click', 'mousemove', 'window.onload'];
    Chart.defaults.global.customTooltips = function(tooltip) {
        var text = tooltip.text;
        var tooltipEl = $('#chartjs-tooltip');

        if(!tooltip) {
            tooltipEl.css({
                opacity: 0
            });
            return;
        }

        if(text) {
            var id = text.split(":")[0].replace(/ /g, '-').toLowerCase();
            $('.tip-text').addClass('hide');
            $('#'+id+'-tip').removeClass('hide').show();
        }

        // Set caret Position
        tooltipEl.removeClass('above below');
        tooltipEl.addClass(tooltip.yAlign);
        // Set Text
        tooltipEl.html(tooltip.text.split(":")[0]);
        // Find Y Location on page
        var top;
        if (tooltip.yAlign == 'above') {
            top = tooltip.y - tooltip.caretHeight - tooltip.caretPadding;
        } else {
            top = tooltip.y + tooltip.caretHeight + tooltip.caretPadding;
        }
        // Display, position, and set styles for font
        tooltipEl.css({
            opacity: 1,
            left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
            top: tooltip.chart.canvas.offsetTop + top + 'px',
            fontFamily: tooltip.fontFamily,
            fontSize: tooltip.fontSize,
            fontStyle: tooltip.fontStyle,
        });
    }

    var body = $('body');

    if(body.is(".home")) {
        var ctx1 = $("#custom-research-chart").get(0).getContext("2d");
        var data = [
            {
                value: 250,
                color:"#7ad3f7",
                highlight: "#7ad3f7",
                label: "GROWTH OVER TIME",
                labelColor: "white",
                labelFontSize: "16"
            },
            {
                value: 250,
                color:"#9e062e",
                highlight: "#9e062e",
                label: "INNOVATION",
                labelColor: "white",
                labelFontSize: "16"
            },
            {
                value: 250,
                color:"#577e7e",
                highlight: "#577e7e",
                label: "DEVELOPMENT",
                labelColor: "white",
                labelFontSize: "16"
            },
            {
                value: 250,
                color:"#f28d1e",
                highlight: "#f28d1e",
                label: "MARKET RESEARCH",
                labelColor: "white",
                labelFontSize: "16"
            },
        ];
        var customResearch = new Chart(ctx1).Doughnut(data);

        $('.various').fancybox({
            maxWidth    : 800,
            maxHeight   : 600,
            width       : '70%',
            height      : '70%',
            openEffect  : 'none'
        });

        $.force_appear();

        $(document.body).on('appear', '#alicia', function(e, $affected) {
            console.log("HEY")
        });
    }

});

A: A quick way to do this is to turn tooltips off (so that the chart does not redraw when the mouse is over it) and turn animation off (so that again the chart does not wipe the tool tips off the chart when being redrawn). Then you can manually call the showTooltip method of the chart passing it the segments.
If you want to keep animations you would need to have a listener for the end of the animation but i can;t seem to find any documentation on that event being fired (it may not exist)

var data = [{
    value: 300,
    color: "#F7464A",
    highlight: "#FF5A5E",
    label: "Red"
}, {
    value: 100,
    color: "#FDB45C",
    highlight: "#FFC870",
    label: "Yellow"
}]

//canvases
var chart = document.getElementById("chart").getContext("2d");

//charts
var myChart = new Chart(chart).Doughnut(data, {
    animation:false,
    showTooltips: false,
});
myChart.showTooltip(myChart.segments);
<script src="http://www.quincewebdesign.com/cdn/Chart.js"></script>
<canvas id="chart"></canvas>

This is a quick way as it doesn't give much control on the position of the tool tips and if you have a lot of data in your pie they may overlap.


text:
Q: How to get the Client-IP, even if a Proxy / VPN is used? How do I get the clientIP from users in my regisrtationforms? It's easy to get the IP with the user isn't using a Proxy, Proxycacade or VPN. But if he uses one of those its difficult. X-Fowarded-For isn't reliable and fails within cascads.
But there are possibilities, because JavaApplets and Flash aren't using the Proxy-Services. How can I archieve to get the clientIP with those technics? I prever to use a small Flash-Code to get the IP from the client, but how to implement?
Another way should be a counterpixel which is using IPv6. Most of the proxyservices only support IPv4, can I tell an image only to use IPv6?
Maybe there are better solutions for my problem, so I look forward to you suggestions. Cheers.

A: Why do you want to know the IP address of the client? If they hide it then it's probably none of your business.
If you want to use it for limiting the number of connections, votes, etc. then think again. IPv4 addresses are running out so one IPv4 address will be used by many users, and even the IPv4 addresses between the ISP and the user and the IPv4 addresses inside a user's network will overlap. You will see the following situation more and more: You get a connection from a 'normal' IPv4 address, say 192.0.2.42. That will be a NAT box with i.e. 10.0.0.0/8 on the inside. On one of those addresses the user will connect a NAT box which NATs it to 192.168.1.0/24. Neither 192.0.2.42, the address in 10.0.0.0/8 nor the address in 192.168.1.0/24 will identify a user.
With IPv6 a user has an almost unlimited amount of IP addresses. An IPv6 address can only be used to see which /64 network the connection comes from, but not for tracking users or devices.
Giving meaning to IP addresses is pointless, unless you can go to law enforcement and get the NAT logs of all boxes involved...


text:
Q: How to create Yii2 Breadcrumbs I am looking for yii2 beadcrumb code
I have layout page in twig want to add breadcrumb there and want to update it according to pages for example
Dashboard/Employees/Add Employee
Dashboard/Employee/Edit Employee
Dashboard and employee will be clickable
I got very less information on yii2 breadcrumbs on internet.

A: In your main layout use:
<?=
   Breadcrumbs::widget([
      'homeLink' => [
                      'label' => Yii::t('yii', 'Dashboard'),
                      'url' => Yii::$app->homeUrl,
                 ],
      'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
   ])
?>

And in your view:
$this->title = 'Add Employee';
$this->params['breadcrumbs'][] = ['label' => 'Employees', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;

This will generate the following breadcrumbs:
Dashboard / Employees / Add Employee

A: In your layout-
//use yii\widgets\Breadcrumbs;

<?=
   Breadcrumbs::widget([
        'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
   ])
?>

In your view-
$this->title = 'Example';
$this->params['breadcrumbs'][] = $this->title;

Hope it will work.

A: My Code looks like this:

        <?php
        echo Breadcrumbs::widget([
          'itemTemplate' => "
{link}
\n",
          'homeLink' => [
            'label' => Yii::t('yii', 'Dashboard'),
            'url' => Yii::$app->homeUrl,
          ],
           'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
       ]);
        ?>

and on any of the view page it I add a snippet
$this->params['breadcrumbs'][] = "Item Details";

The above is a simple example. The issue with this is that it does not truly give out the tree structure for navigation. I will have to write a helper function to track the history or tree path for each view page.


text:
Q: Can't seem to get an output and I do not know why I have a perl code that basically opens up a file, read it and then print it but for some reason, when I run it, I can't seem to get any output nor any error and I don't know why.
Here's my code:
#!usr/bin/perl

$syslogFile = '/Home/osboxes/Documents/syslog';
open(INFO, $syslogFile);
@lines = <INFO>;
close(INFO);
print @lines;

A: And this is why you need do two things:

*

*enable use strict; use warnings; at the start of your code.

*Check return codes from open.

I would also suggest that 3 arg open is greatly preferred to using a default:
open ( my $input, '<', $syslogfile ) or die $!;

And lastly - double check that file contains what you expect it to. E.g. it isn't empty.
Something like this:
#!/usr/bin/env perl
use strict;
use warnings;

my $syslogFile = '/Home/osboxes/Documents/syslog';
open(my $info, '<', $syslogFile) or die $!;
my @lines = <$info>;
close($info) or warn $!;
print @lines;

I suspect it will tell you either "No such file or directory" or "permission denied".


text:
Q: Why != is not correct for this self joins query in psql The following is the code for creating the table
create table residences(
id integer
references students,
building text
references buildings(name),
room text
);

The following is the code for query.
select a.id, b.id, a.building, a.room
    from residences as a, residences as b
where a.building = b.building
and a.room = b.room
and a.id > b.id
order by a.building, a.room;

|     id |     id | building | room |
+--------+--------+----------+------+
| 881256 | 413001 |   Crosby |   10 |
| 741532 | 496747 |   Crosby |   19 |
| 931027 | 612413 |   Crosby |   31 |
| 958827 | 170267 | Dolliver |    1 |
| 707536 | 104131 | Dolliver |   14 |
| 505241 | 477801 | Dolliver |    8 |
| 824292 | 118199 | Kendrick |   1A |
| 231742 | 105540 | Kendrick |   3B |
+--------+--------+----------+------+

I tried both
and a.id > b.id

and
and a.id < b.id

both produced the same result above.
However, when I used
and a.id != b.id

It didn't work, instead it produced
+--------+--------+----------+------+
|     id |     id | building | room |
+========+========+==========+======+
| 413001 | 881256 |   Crosby |   10 |
| 881256 | 413001 |   Crosby |   10 |
| 496747 | 741532 |   Crosby |   19 |
| 741532 | 496747 |   Crosby |   19 |
| 612413 | 931027 |   Crosby |   31 |
| 931027 | 612413 |   Crosby |   31 |
| 170267 | 958827 | Dolliver |    1 |
| 958827 | 170267 | Dolliver |    1 |
| 104131 | 707536 | Dolliver |   14 |
| 707536 | 104131 | Dolliver |   14 |
| 477801 | 505241 | Dolliver |    8 |
| 505241 | 477801 | Dolliver |    8 |
| 118199 | 824292 | Kendrick |   1A |
| 824292 | 118199 | Kendrick |   1A |
| 105540 | 231742 | Kendrick |   3B |
| 231742 | 105540 | Kendrick |   3B |
+--------+--------+----------+------+

Could anyone tell me why?

A: This is quite normal. The results you have are as expected, except that the first two results are not exactly the same. If you pay attention to the first two columns, you'll see that they are swapped when comparing the first two results.
But the condition a.id != b.id is less restrictive than the other two and will therefore give more results.
For example:
If you have values 1, 2, and 3 and required a.id < b.id, then you get as possible combinations:
            (1, 2), (1, 3) and (2, 3).
If you require a.id > b.id you get these combinations:
             (2, 1), (3, 1) and (3, 2).
Note how these pairs are similar as above, but not the same: the order of the values in each pair is opposite -- corresponding to the condition.
And finally if you (only) require (the less restrictive) a.id != b.id then you get all of the above, i.e. all possible pairs except (1, 1), (2, 2), (3, 3):
          (1, 2), (1, 3), (2, 3), (2, 1), (3, 1) and (3, 2)
In your query they are then ordered, but that does not change the essence: you get twice as many results with a.id != b.id than with one of the other conditions.


text:
Q: Replace two strings at the same time with one in Notepad++ using regular expressions How to replace two strings at once with one in Notepad++ using regular expressions?
I need this:
================
================

Replace with this:
--------------

A: By "two strings", I suppose you mean two lines.
Globally, it can be achieved by seeing the two lines as a single string containing a new line character. So the regular expression (RegEx) pattern should be something like that:
<first line pattern><new line character><second line pattern>

The new line pattern can be either \r\n or \n depending of the file, you should test the both.
For your specific case, the match pattern should be the following
=+\r\n=+

=+ means at least one = sign. + is greedy, so it will take all = sign if there are more than one.


text:
Q: FileSystemWatcher surpassing file system permissions While experimenting with FileSystemWatcher, I've found out that it somehow surpasses my user account's permissions to files and folders, and will raise change events with information about what has changed in files and folders that you don't even have access to.
I have two questions about that:
1) Why does this happen ?
2) Is this a problem in the AD configuration ? how do I fix it ?
3) Is there any way to gather these files, or even create a FileSystemInfo of them to get more info about the files (not only the changes made on them) ?
As far as I've tried, only the FileSystemWatcher immune to the restrictions, I can't run any other thing over it, here's a list of what I've tried:

*

*File.Exists

*Directory.Exists

*FileInfo instance on found files

*DirectoryInfo instance on found files

*File.Copy

*File.Delete

Update: Tried helge's solution, with somethin similar to what he's sugested, not through windows' api, but through the command prompt:
robocopy /B \myserver\folder c:\somefolder
Best command name ever.
You can check through robocopy that /B stands for "backup mode", which is what helge's suggested that would be the cause to this security surpassing.
I'll try anything, I want to find out what exactly causes FileSystemWatcher to be able to watch folders I do not have permission to open. Knowing why, I want to learn both how to block FileSystemWatcher, and how to gather found files.
I'd make a survey if I was with my personal account. Please, can someone help me ? I'll write a blog post about the solution, among other things that might help anyone with the same doubt in the future.

A: According to this answer on SO the FileSystemWatcher is based on the API function ReadDirectoryChangesW. If that is true it explains the behavior witnessed by you - and why that is not a security hole.
As documented on MSDN ReadDirectoryChangesW needs the privilege SeBackupPrivilege (which is requested by the parameter FILE_FLAG_BACKUP_SEMANTICS to CreateFile). If a file is opened in that mode, the returned handle grants full access to the file, circumventing access checks. This feature is designed for backup programs that need to be able to read everything on disk regardless of permissions.
This is not a security hole because the privilege SeBackupPrivilege which is required for this to work is by default granted to administrators only. Administrators, and in fact anyone with physical access to a machine, are always capable of taking control of and reading every file - unless it is encrypted.
As to which functions can be used to access files in backup mode: There is at least BackupRead for reading. Enumeration is easily possible with FindFirstFile/FindNextFile. Of course this requires the real Windows API, not the crippled .NET file system functions.


text:
Q: Fourier transform of an exponentially singular radial function I am trying to compute the 3D Fourier transform of a spherically symmetric function of the form
$$f(r) = e^{\frac{1}{r} e^{-r}} - 1\, ,$$
which entails the integral
$$\begin{aligned}F(k) =& \int d^3\!r \, e^{-i\mathbf{k}\cdot\mathbf{r}} f(r) \\
       =& \int_0^\infty dr\!\int_0^{\pi}\!d\theta\!\int_0^{2\pi}\!d\phi \, r^2 \sin\theta \, e^{-ikr\cos{\theta}} f(r) \\
 = & \, 2 \pi \int_0^\infty\! dr \, r^2 f(r) \int_0^{\pi}\!d\theta  \sin\theta \, e^{-ikr\cos{\theta}}  \\
=& \, 4\pi \int_0^\infty\!\! dr \, r^2 \mathrm{sinc}(kr) \, f(r) \,.\end{aligned}  $$
Based on the answer to this question, I'm inclined to think that this integral will not converge even if I attempt to regularize it because exponent grows without bound near $r=0$. However, since the integral is not a usual Fourier transform, I'm holding out hope that the integral converges, though by what means, I do not know. My main questions are then:

*

*Is the reasoning within the linked answer applicable to this "3D" Fourier transform? That is, does this spherically symmetric function follow the same convergence rules as that of a one-dimensional cartesian-coordinate function?

*If the link answer does not apply here, what tools are available to try to compute this transform? I can readily accept a good approximation, as this is with regards to a physics problem.


text:
Q: Too many watchable $scope variables and f'unctions result in RangeError When I kept on adding $scope variables and functions, all of a sudden, I now see "RangeError: Maximum call stack size exceeded". The JS file is valid and does not have errors. Is there a way to get rid of this? Or, can I increase the the amount of watchable variables/functions?

$scope.calculator:
"totalpay": function(){
    var total = 0.00;
    total += parseFloat($scope.fields.totalrate.value);
    total += parseFloat($scope.fields.totalovertime.value);
    total += parseFloat($scope.calculator.totalvacation());
    total += parseFloat($scope.calculator.totalholiday());
    total += parseFloat($scope.calculator.totalsickleave());
    $scope.fields.totalpay.value = total;
    return total;
},