text:
Q: User preferences in Rails with Admin edit and i18n support We've been working on a ruby project involving users, private messages and any kind of network based related features.
We already have some preferences system that allow users to describe their self. Hair color, wear-style, height, weight, shape, hobbies, etc.
We face the fact that some option list (content of combo box) need to be edited by admin user and translated in many languages (we already use the classic's yml support for i18n in Rails 3).
The admins, want to add users descriptions.
For instance imagine you have a user model with :
date of birth, Current city, mail, username
We already have everything ready with has_many and related tables named preferences.
We use a seed that contain :
hair_style :

*

*long

*short

*semi-long

hair_color :

*

*red

*white

*brown

*black

*blond

eye_colors :
 - brown
 - green
 - yellow
 - blue
Now, the administrator want to add pink to the hair color and gray to the eye_colors property. Also he wants this to preferences/descriptions to be well translated for french users and so he need to translate them.
To summarize we have two issues :

*

*on-the-fly and non-model bind descriptions preferences (we know the list is going to get larger and larger has many idea will pop up)

*translation of this descriptions as we can not use yml files here.

We'll be happy to hear from you ! hope someone will guide us.
P.S : already read this :
Best approach to save user preferences?
Rails: How do I model preferences? Should I use has_many :through?
and found that :
https://github.com/pluginaweek/preferences
https://github.com/huacnlee/rails-settings-cached
I've also found that one :
http://code.lancepollard.com/posts/the-missing-rails-key-value-gem
and was wondering if it would be intersting to get inspiration from it.
I've also read this :
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002284
And found that one :
http://blog.project-sierra.de/archives/1379
But I'm wondering how to be able to create dynamically the user preferences ?


text:
Q: Как сделать задержку при открытии тега details с помощью JQuery? По некоторым причинам выполнил вертикальное выпадающее меню на сайте с помощью details. При наведении мыши появляется выпадающий список. Но т.к. главных списков меню с подразделами много, есть небольшие неудобства при перемещении мыши. Никак не могу сделать, чтобы меню выпадало только после 1-2 секунд удержания мыши.
JQuery код:

function checkWidth() {
      var windowWidth = $('body').innerWidth(),
          elem = $(".number-bullets");
      if(windowWidth < 640){
        $("details").attr("open","true");
      }
      else{
        $(function() {
            $('details').on('mouseover', function() {
              $(this).attr('open', true);
            }).on('mouseout', function() {
              $(this).attr('open', false);
            })
          });
      }
    }

    checkWidth();

    $(window).resize(function(){
      checkWidth();
    });

  Oral surgery

Tooth Extraction

Wisdom Tooth Extraction

Corrective Jaw Surgery (TMJ)

Dental Implants

Periodontics Surgery

  Restauration

White Filling

Crown and Bridge

Implant Crown

Inlays - Onlays

Tooth-Colored- Fillings

Night Guard

Root Canal Treatment

Holistic Amalgam Removals

A: Решил сам :) Спасибо за помощь
function checkWidth() {
  var windowWidth = $('body').innerWidth(),
      elem = $(".number-bullets"); // лучше сохранять объект в переменную, многократно чтобы не насиловать
                                  // страницу для поиска нужного элемента
  if(windowWidth < 640){
    $("details").attr("open","true");
  }
  else{
    $(function() {
      $("details").on("mouseenter mouseleave", function(event) {
        window.clearTimeout(timer);
        var that = this;
        if (event.type == "mouseenter") {
          timer = window.setTimeout(function() {
             that.setAttribute('open', true)
          }, pause)
        } else this.removeAttribute('open')
      });
      });
  }
}

checkWidth(); // проверит при загрузке страницы

$(window).resize(function(){
  checkWidth(); // проверит при изменении размера окна клиента
});

var timer, pause = 400;

A: Замените mouseover на hover и используйте setTimeout c проверкой hover на добавление атрибута open

var moveTimer;
function checkWidth() {
  var windowWidth = $('body').innerWidth(),
      elem = $(".number-bullets");
  if (windowWidth < 640) {
    $("details").attr("open", true);
  } else {
    $('details').hover(
      function () {
        var $this = $(this);
        setTimeout(function(){
          if ($this.is(':hover')) {
            $this.attr('open', true);
          }
        }, 300);
      },
      function () {
        $(this).attr('open', false);
      }
    )
  }
}

    checkWidth();

    $(window).resize(function(){
      checkWidth();
    });

  Oral surgery

Tooth Extraction

Wisdom Tooth Extraction

Corrective Jaw Surgery (TMJ)

Dental Implants

Periodontics Surgery

  Restauration

White Filling

Crown and Bridge

Implant Crown

Inlays - Onlays

Tooth-Colored- Fillings

Night Guard

Root Canal Treatment

Holistic Amalgam Removals

redpajama_set_name: RedPajamaStackExchange


text:
Q: EventKit does not provide day of recurrence in recurrence rule for single day weekly recurring event I am using EventKit to fetch all events from the default Apple Calendar in my app.
When there is a custom recurring event in the Apple Calendar with multiple days of recurrence then EventKit returns an array of daysOfTheWeek in the recurrence rule
What I mean is Event_A is recurring weekly every Friday and Saturday then EventKit returns an array of objects like this
  calendar = "testingcurvecalendar@gmail.com";
  endDate = "2022-07-30 11:00:00";
  id = "5FFF5521-18BB-497C-8EF5-4E72647A6A24:2AE552B8-85C4-489C-8A36-DACF95D83E61";
  lastModifiedDate = "2022-05-20 10:25:01";
  rrule =   {
    calendar = gregorian;
    daysOfTheWeek =     (
            {
        dayOfTheWeek = Friday;
        weekNumber = 0;
      },
            {
        dayOfTheWeek = Saturday;
        weekNumber = 0;
      }
    );
    freq = weekly;
    interval = 1;
    until =     {
      count = 0;
      date = "2022-07-31 23:59:59";
    };
  };
  startDate = "2022-07-30 10:00:00";
  title = MultipledayswithEnd;
},

But if an event is recurring for only single day then eventkit
does not return daysOfTheWeek object
i.e. Event_B is recurring weekly every Monday then the object received from the eventkit is as follows
  calendar = "testingcurvecalendar@gmail.com";
  endDate = "2022-07-27 11:00:00";
  id = "5FFF5521-18BB-497C-8EF5-4E72647A6A24:C57AFD95-75A0-4F75-B4F0-00D7321BFB21";
  lastModifiedDate = "2022-05-20 10:27:23";
  rrule =   {
    calendar = gregorian;
    freq = weekly;
    interval = 1;
    until =     {
      count = 0;
      date = "2022-07-31 23:59:59";
    };
  };
  startDate = "2022-07-27 10:00:00";
  title = Singlewithend;
},

The issue is I would like to display the day of recurrence in my app which I am able to in case of Multi-day recurring events because I receive the days in dayOfTheWeek object but I cannot do it in Single-day recurring events.
The code for fetching events from the Calendar is as follows
  NSPredicate *fetchCalendarEvents = [eventStore predicateForEventsWithStartDate:[NSDate date] endDate:endDate   calendars:calendarArray];
  NSArray *matchingEvents = [eventStore eventsMatchingPredicate:fetchCalendarEvents];
  NSMutableArray * eventsDataArray = [self eventsToDataArray:matchingEvents];

Can someone please help me with this issue?


text:
Q: Hide line from legend I need to hide 4 lines from the legend. I'm using shadedErrorBar so I have 3 line for a sigle group (mean, upper edge of standard deviation and bottom edge) and if i use the classic code legend('line1','line2,'...) I'll have 3 label. I want in the legend only the mean for each group.
I have 2 groups.
shadedErrorBar(x,y1,e1);
shadedErrorBar(x,y2,e2);

y1 and y2 are my means, while e1 and e2 standard deviations.
I think I should use IconDisplayStyle but I don't understand how. I read this http://it.mathworks.com/help/matlab/creating_plots/controlling-legends.html but is like hide a plot to hide a line. With shadedErrorBar I have a graph with 3 plot on it for each group.

A: When you create the legend, you can specify only the plot objects that you would like to create legend entries for. The output of shadedErrorBars is a struct containing all of the plot objects so you can use these to grab the patch objects and create legend entries for only those.
h1 = shadedErrorBar(linspace(1,10), linspace(1,10), linspace(0,1));
hold on
h2 = shadedErrorBar(linspace(1,10), linspace(1,20), linspace(1,0));

legend([h1.patch, h2.patch], {'Item1', 'Item2'})


text:
Q: Change sharing message to icons I find the "Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook." a bit messy. Could this be changed to the traditional sharing buttons that appear on a lot of websites today. I think it would give a more refined look to the sight.

A: Lets keep it the way it is. As @random states, text is much lighter than images.
We should be looking to reduce the load on the server.. As I ironically post an image..
Would more icons be added, or would we just change the existing ones? Either way..

A: We do already have icons in the "share" popup:

I don't think that looks cluttered.


text:
Q: Individual ID's pdf print by Laravel8 I'm studying laravel using this gentleman's awesome code.
https://github.com/savanihd/Laravel-8-CRUD/blob/master/app/Http/Controllers/ProductController.php
I use Laravel Framework 8.48.2
I would like to add PDF pritabile view to each ID's "show" page
I could success PDF export using this simple test page.
public function generate_pdf() {

    $pdf = \PDF::loadView('products.generate_pdf');
    return $pdf->stream('yokoya_test.pdf');

}

so I had been trying to add PDF export to "show" function .
Here is my current code
Controller
public function each_print(Product $product)
{
    $pdf = \PDF::loadView('products.each_print');
    return $pdf->stream('each_print.pdf');
}

original index.blade.php code is this
id) }}">Show

I changed this as below
id) }}">Print

Here is my current WEB.php
Route::get('products/each_print', [ProductController::class, 'each_print']);
Route::resource('products', ProductController::class);

but I got this error

Symfony\Component\Routing\Exception\RouteNotFoundException
Route [products.each_print] not defined.
C:\xampp0827\htdocs\lara\ic0630-simple\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php:427

Could you teach me right code please?

UPDATE

index.blade.php
https://jsfiddle.net/diessses/m72bs54r/1/
each_print.blade.php
https://jsfiddle.net/diessses/8Lg5wot3/

A: you need define the name to the route like:
Route::get('products/each_print/{product}', [ProductController::class, 'each_print'])->name('products.each_print');

UPDATED
first refactor your code in the index blade table like:

id) }}">detail
id) }}">edit
id) }}">Print

<form action="{{ route('products.destroy',$product->id) }}" method="POST">
   @csrf
   @method('DELETE')

   <button type="submit" class="btn btn-danger">×</button>
</form>

and in the each_print function pass the product instance to the view like:
public function each_print(Product $product)
{
    $pdf = \PDF::loadView('products.each_print', ['product' => $product]);
    return $pdf->stream('each_print.pdf');
}


text:
Q: Using Opto-Coupler with STM32 My question might be already answered but I have some problem with resolving it.
I'm using PC817 Opto-Coupler to turn on a relay. My VCC voltage is about 4.2 volts and the MCU is an STM32F4 with 3.3v voltage level.
When I set the MCU pin (M_Relay) low, it seems that Opto doesn't turn on. I measure the voltage of the input diode(Opto input) and it was about 1v which is below the minimal voltage. I'm not sure about what value should I use for R56.

A: From the data sheet, Forward diode voltage is 1.2V, and it seems to want 20mA.
Thus, the resistor has 4.2-1.2=3.0V across it.  For 20mA, Ohm's law says you want 150 Ohms.
There will be some current when you have the input at 3.3V, and it remains to be seen if it's too much for an "off".
You could avoid the issue of the off current by grounding pine 2 and driving the LED from the MCU I/O pin idrectly, if it can provide 20mA (in fact, you'd already be sinking 20mA the way you're doing it now).  In that case, the voltage drop across the resistor would be 3.3-1.2=2.1V, and you would use a resistor of 100 Ohms.  If the MCU can't do 20mA, you could probably configure the pin as open collector.


text:
Q: How to setup hijri datepicker by jquery datepicker or bootstrap datepicker? I need to setup datepicker for hijri date.I can use jquery datepicker or bootstrap datepicker. however I wrote this code

    <meta charset="utf-8" />
    <title></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.css" rel="stylesheet" />

    <input type="text" id="datepicker" name="name"   />

but do not work . I see number website that datepicker has Georgian date but days name is arabic.I need to days name is arabic and datepicker date are hijri together.
Note : After select date ,  datepicker should be fill by hijri date.
How to do this?

A: Just use language option instead of regional (see snippet below).

$.fn.datepicker.dates['ar'] = {
                days: ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد"],
                daysShort: ["أحد", "اثنين", "ثلاثاء", "أربعاء", "خميس", "جمعة", "سبت", "أحد"],
                daysMin: ["ح", "ن", "ث", "ع", "خ", "ج", "س", "ح"],
                months: ["يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"],
                monthsShort: ["يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"],
                today: "هذا اليوم",
                rtl: true
            };
$('.datepicker').datepicker({
  language:'ar',
  format: 'yyyy, MM dd'
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" />

    <input type="text" class="form-control datepicker">

To change displayed date format set datepicker format.


text:
Q: Real scalar field with a set of interacting particles This is quite complicated. I will appreciate if you give some hint of this problem.
First we have the following Lagrangian, $L= L_f+L_i$, where $L_f$ is just the Klein-Gordon Lagrangian
\begin{align}
L_f = \frac{1}{2} \int d^3x [(\frac{\partial \phi(x,t)}{\partial t})^2 - c^2 (\nabla\phi(x,t))^2-\mu^2 \phi^2(x,t)]
\end{align}
and $L_i(t)$ gives interaction between field and a set of particles,
\begin{align}
L_i = -\sum_n g_n \phi(x_n(t),t) + \sum_n \frac{m_n}{2}(\dot x_n(t))^2 - V(x_n(t)).
\end{align}
In this case, the question requires three things.
(1) The field equation for $\phi$.
(2) $\phi$ in terms of creation/annihilation operators in interaction picture.
(3) Total Hamiltonian.
I do not know how I can approach to this problem. Is this okay to change  $\phi(x_n(t),t)$ as $\int d^3 x \phi(x,t)\delta(x-x_n(t))$ to find the field equation? In this regard, the field equation is
\begin{align}
-\mu^2 \phi(x,t) - \sum_n g_n\delta(x-x_n(t)) = \ddot\phi - c^2\nabla^2\phi .
\end{align}
However, I am fully doubtful about this approach. Furthermore I don't know how to proceed into (2) and (3). Could you just give me some hint of this problem?


text:
Q: Unable to connect to any of the specified MySQL hosts RDS with mysql I am trying to make a remote connection from my web API in net core 3.1 and when performing scaffold it returns the following message where it cannot connect.
I already tried several alternatives until opening the ports of my RDS without success, what can I be missing?
Build started...
Build succeeded.
MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.
   at MySqlConnector.Core.ServerSession.ConnectAsync(ConnectionSettings cs, ILoadBalancer loadBalancer, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ServerSession.cs:line 442
   at MySqlConnector.Core.ConnectionPool.GetSessionAsync(MySqlConnection connection, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ConnectionPool.cs:line 112
   at MySqlConnector.Core.ConnectionPool.GetSessionAsync(MySqlConnection connection, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ConnectionPool.cs:line 141
   at MySql.Data.MySqlClient.MySqlConnection.CreateSessionAsync(ConnectionPool pool, Nullable`1 ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 645
   at MySql.Data.MySqlClient.MySqlConnection.OpenAsync(Nullable`1 ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 312
   at MySql.Data.MySqlClient.MySqlConnection.Open() in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 280
   at Pomelo.EntityFrameworkCore.MySql.Scaffolding.Internal.MySqlDatabaseModelFactory.Create(DbConnection connection, DatabaseModelFactoryOptions options)
   at Pomelo.EntityFrameworkCore.MySql.Scaffolding.Internal.MySqlDatabaseModelFactory.Create(String connectionString, DatabaseModelFactoryOptions options)
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineerScaffolder.ScaffoldModel(String connectionString, DatabaseModelFactoryOptions databaseOptions, ModelReverseEngineerOptions modelOptions, ModelCodeGenerationOptions codeOptions)
   at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContext(String provider, String connectionString, String outputDir, String outputContextDir, String dbContextClassName, IEnumerable`1 schemas, IEnumerable`1 tables, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable`1 schemaFilters, IEnumerable`1 tableFilters, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to connect to any of the specified MySQL hosts.


text:
Q: What is the difference between the following methods in rails? users_path and user_path(user1)
I guess former goes to index action and the later to the show action of specific user

A: Your expectation is right:
users_pathgives the path to the controller action users#index while
user_path(user1)gives the path to controller action users#show with params[:id] set to user1.id

A: users_path returns /users
new_user_path returns /users/new
edit_user_path(:id) returns /users/:id/edit (for instance, edit_user_path(10) returns /users/10/edit)
user_path(:id) returns /users/:id (for instance, user_path(10) returns /users/10)

For more details
http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions

A: users_path will routes to users#index as you expected

And
user_path(user) will redirect to users#show if method is get

or
It will redirect or routes to users#destroy if method is delete


text:
Q: MVVM and WPF - how to combine sources for a DataGrid I am fairly new to WPF/MVVM but I have read through a lot of tutorials and done some small projects so have gained an elementary understanding.
My problem:
I have a Model class which holds a collection of data. My main View must display several of Models' data on a DataGrid. My current approach is making a DataGrid in the Model's View by defining a Datatemplate with a DataGrid whose ItemsSource is the Model's Collection.
This approach sort of works but it creates a Datagrid for each Model. Does anyone know of a good way to have only a single DataGrid?

A: If the view should display a single grid you might want to make a ViewModel with a single collection and fill the collection from several Model collections.
That is what the ViewModel is for.


text:
Q: Excel - Count number of occurrences of number string with Criteria I've looked around here, and other online sources but can't seem to find the solution to what I'm after.
I have a data table with 78,000 rows. The table is set up as follows:
A               B          C
Issue           Client ID  Ticket Number
Printer Jam     123456     HP-123
Monitor         987654     HP-124
Keyboard        123456     HP-125
Printer Jam     123456     HP-126
Keyboard        987654     HP-127
Printer Jam     987654     HP-128

This goes on and on. I need to count the number of times a Client ID appears for each Issue, so that I can report the number of repeat "offenders" on it like this:
Issue         1   2   2+
Keyboard      2   0   0
Printer Jam   1   2   0

Hopefully that makes sense! I've tried using a Pivot Table, and while it gives me the counts I need it doesn't really do what I need.
Thanks!

A: I would probably use COUNTIFS together with a pivot table if I had to do this:

COUNTIFS will be moderately slow due to the size of your data, but the pivot table will make the grouping part relatively fast.
From the picture, I am using this for the COUNTIFS:
=COUNTIFS(A:A,A2,B:B,B2)

A: Use the following:
=SUMPRODUCT(--(COUNTIFS($A$2:$A$7,$E2,$B$2:$B$7,$B$2:$B$7,$A$2:$A$7,$A$2:$A$7)=1))

Change the =1 to =2 and >2 for the next columns.

A: This solution uses two PivotTables and one Range.
It assumes the DATA range is located at B6:D111111

*

*Add a PivotTable (PtCount), with the DATA range as source and starting at G6, to obtain the Issue \ Client Id counts. (see Fig. 1 below)
Fig. 1

Change the settings of the PivotField "Issue", by right clicking the PivotField then click on Field Settings… \ tab Layout & Print \ Repeat item labels (see Fig. 2 below)
Fig. 2

*Use a Range, located at L6 and parallel to the PivotTable (PtCount), to manipulate the PivotTable results (i.e. change counts higher than 2 to "2+". (see fig. 3)
The range should have these items\formulas:
Issue : =T($G7)
Count : =IF(EXACT($L7,""),"",$I7)
Offenders : =IF(EXACT($L7,""),"",IF($I7>2,"2+",$I7))
Fig. 3

*Add a second PivotTable (PtSummary), with the Range starting at L6 as source and located at G6, to generate the final report. (see fig. 4)
Fig. 4


text: Q: BusterJS and Sinon, spies don't reset Is there a way to reset a spy for every spec in a buster test case. I'm aware of spy.restore but I'm looking for a behavior like in Jasmine where spies automatically reset after every spec.


text:
Q: Does the ring (in the picture) experience Lorentz force? Does the ring in the picture below experience Lorentz force? Or should I say it's just some magnetic force? (Notice that the poles repel eachother.) I am unsure because of the setting with the electromagnet.

A:
Does the ring in the picture below experience Lorentz force?

Rather yes than no, but we need to make clear in what sense.
The Lorentz force is a somewhat confusing term, because people use it to name different concepts.
The term has some history, but nowadays it most often refers to a force acting on a tiny charged particle in an external electromagnetic field.  Depending on the source and context, it means either the magnetic force $q\mathbf v\times\mathbf B_{ext}$, or the entire electromagnetic force $q\mathbf E_{ext} + q\mathbf v\times\mathbf B_{ext}$, where $\mathbf E_{ext},\mathbf B_{ext}$ are the external fields at the point where the particle is.
For example, think of the electrons circling in magnetic field of a cyclotron, or electrons flying through a CRT tube (old-generation kind of TV). The force electron experiences there is accurately given by the  Lorentz force formula, where the external fields are determined by the magnets of the cyclotron and the voltage imposed on the metallic plates of the CRT.
However, the ring in question is not a tiny charged particle. It is rather big in the sense that the values of electric and magnetic field vary across the ring. The Lorentz force formula in the above sense is not applicable for the ring as a whole.
The total EM force in such cases is calculated in a different way. The standard approach is based on the formula
$$
\mathbf F = \int_V \rho\mathbf E + \mathbf j\times \mathbf B \,dV
$$
which, unfortunately, is sometimes referred to as the Lorentz force as well.
This formula is quite different from the first one. An integration over region of space $V$ containing the entire body is involved. Second, although the integrand $\rho\mathbf E + \mathbf j\times \mathbf B$ is quite similar to the expression $q\mathbf E_{ext} + q\mathbf v\times\mathbf B_{ext}$, there is an important difference; the first formula (for tiny particles) involves velocity of the particle $\mathbf v$ and external fields, but the expression in the integrand here involves total current density $\mathbf j$ in the body and total electric and magnetic fields.

Or should I say it's just some magnetic force?

The process illustrated in the picture involves electric and magnetic field changing in time inside the ring. In such cases there is no reason to think the force is purely electric or purely magnetic, without careful calculation. I'd describe it as electromagnetic force due to solenoid acting on the ring.

A: No. Lorentz force act on moving charges in a magnetic field. The current in your ring is created by a changing magnetic field (induction). Lorentz force also acts perpendicular to the particle velocity vector and the magnetic field, which is not the case here.

A: First at all think about induction processes.

*

*An electric current in a coil induces a magnetic field. This happens because the electrons in the coil get accelerated in a circle and any acceleration (the motion in a circle is an acceleration) of electrons induces a magnetic field.

*A magnetic field induces a electric field in a moving conductor. Because the aluminum ring is a conductor there will be a electric current in the ring. Than faster the ring is falling than faster the electric current will increase.

*Last step, an changing electric current induces an magnetic field. For all this induction processes one can use the hand rules and thumb rules, you find them on Wikipedia. All this rules show, that the induction of both the electric and the magnetic field from the vis-a-vis field are directed perpendicular to each other. You will have used the rules right, when as a result the magnetic field from the coil and the magnetic field from the aluminum ring will be directed counterwise.
Because of the gravitational acceleration of the ring, the delayed reaction of the induction processes and the energy transmission from the electric current from the coil to the ring the ringt gets accelerated in a "explosive" way.
The Lorentz force is the deflection of a current-carrying conductor in a - not-parallel to the current - magnetic field. If lower a wire to the coil there will be an induced current and the coils magnetic field will deflect the wire or to or away from the coils symmetry axis. So if one let the ring fell not properly symmetric to the coil, the ring get deflected additional sideways. So sometimes the experiment does not give the expected result. Try it.
Edit: If I remember right the ring has to be from aluminum due to the property of aluminum that there will be eddy currents which are the cause of the delay. Hope to get some comments to get enlightened.


text:
Q: Class linked list I'm a newbie and I don't understant clearly about linked list, so when I write my program, I'm in trouble with it . It have a error in ostream& operator<<(ostream& os, const LinkedList &ll) and I don't figure out. This is my code:
LinkedList.h
#pragma once
#include<iostream>
using namespace std;
struct Node
{
    int infor;
    Node *pNext;
};
class LinkedList
{
    Node *pHead, *pTail;
    int curN;
public:
    //default constructor
    LinkedList();
    //destructor
    ~LinkedList();
    static Node* CreateNode(const int& n);
    Node* AddHead(const int &n);
    Node* AddTail(const int &n);
    Node* RemoveHead();
    Node* RemoveTail();
    friend ostream& operator<<(ostream& os, const LinkedList &ll);
    int& operator[](const int& i);
    static int SoNguyenMax();
};

LinkedList.cpp
#include "LinkList.h"

LinkedList::LinkedList()
{
    pHead = pTail = NULL;
}
LinkedList::~LinkedList()
{
}
static Node* CreateNode(const int &n)
{
    Node *NewNode = new Node;
    if (NewNode == NULL)
    {
        cout << "Khong du bo nho" << endl;
        return NULL;
    }
    else
    {
        NewNode->infor = n;
        NewNode->pNext = NULL;
    }
    return NewNode;
}
Node* LinkedList::AddHead(const int &n)
{
    Node *u = new Node;
    u->infor = n;
    if (pHead == NULL)
        pHead = pTail = u;
    else
    {
        u->pNext = pHead;
        pHead = u;
    }
    return pHead;
}
Node* LinkedList::AddTail(const int &n)
{
    Node *u = new Node;
    u->infor = n;
    if (pHead == NULL)
        pHead = pTail = u;
    else
    {
        pTail->pNext = u;
        pTail = u;
    }
    return pTail;
}
Node* LinkedList::RemoveHead()
{
    Node *p;
    p = pHead;
    pHead = pHead->pNext;
    delete p;
    return pHead;
}
Node* LinkedList::RemoveTail()
{
    Node *p, *q;
    p = pHead;
    while (p != pTail)
    {
        q = p;
        p = p->pNext;
    }
    pTail = q;
    q->pNext = NULL;
    delete p;
    return pTail;
}
ostream& operator<<(ostream& os, const LinkedList &ll)
{
    for (Node *k = ll.pHead; k != NULL; k = k->pNext)
        os << k->infor << "   ";
    return os;
}

main function
#include"LinkList.h"
int main()
{
    LinkedList l;
    l.AddHead(15);
    l.AddHead(123456);
    cout << l << endl;
    return 0;
}

and:
[Autos table: ]

*

*k   0xcdcdcdcd {infor=??? pNext=??? }   Node *

*ll.pHead    0x00abf4d8 {infor=123456 pNext=0x00abf238 {infor=15 pNext=0xcdcdcdcd {infor=??? pNext=??? } } } Node * const

*ll{pHead=0x00abf4d8 {infor=123456 pNext=0x00abf238 {infor=15 pNext=0xcdcdcdcd {infor=??? pNext=??? } } } ...}

Please help me. Thanks!

A: Try using a while loop:
ostream& operator << (ostream &os, const LinkedList &ll)
{
    Node* k = ll.pHead;
    while (k != NULL)
    {
        os << k->_data << ", ";
        k = k->pNext;
    }
    return os;
}

But I found something. "INFOR" variable can be confused with "INFO".


text:
Q: Unable to think of starting point to create a Plugin in JIRA Our requirement is to develop a plugin in JIRA in the next 3 days that will enable

*

*Tag/link the JIRA issue/user story/bug/task with a KPI in our application. User will search the KPI's assigned to him in a search box and will link it with selected KPI.

*Update the status of the KPI in our application when the JIRA issue/user story/bug/task is completed.
I have read the following documentation links and able to develop a simple/raw JIRA plugin, but now not sure how to approach and what to do to achieve the above-stated requirement.
https://developer.atlassian.com/cloud/jira/platform/getting-started/
https://developer.atlassian.com/cloud/jira/platform/extending-the-user-interface/
https://bitbucket.org/atlassian/atlassian-connect-express?_ga=2.219680473.1920394266.1551270522-162753333.1543052768
I am looking for help on the following question from all the experts out there

*

*Where to start next and how to go about it. We know Nodejs and will be comfortable in developing the plugin in same?

*What kind of modules are required to display the KPIs from our application in the search box on the JIRA UI where the issue and its details are displayed?

*When the issue/user story/bug/task is completed, how I can write/inject a script that will invoke the REST API of our application and will update the KPI status?

*Where I can store the JIRA issue and KPI mapping information? Can this information be stored in JIRA?
Thanks........

A: *

*The links you listed are the right place to get started, connect express has links to another repository with a sample Jira project - https://bitbucket.org/atlassianlabs/atlassian-connect-jira-example

*I'm not sure exactly where you are looking to extend the UI. If you want to add a new button or similar to the view issue page then check out the available locations in https://developer.atlassian.com/cloud/jira/platform/issue-view-ui-locations/
The other possible locations are listed on that page as well through the links on the left, check out the location modules.

*This sounds like you are trying to listen for webhooks, have a look at https://developer.atlassian.com/cloud/jira/platform/webhooks/ for the hooks you can listen for.

*Jira provides some very basic storage key value storage via the entity properties api, see https://developer.atlassian.com/cloud/jira/platform/modules/entity-property/ if you need something more sophisticated then you might need to build your own.


text:
Q: NGINX: Serve /images/ folder statically I've already tried so much stuff in order to do this, also, by putting a php file inside /images/test.php to test if it will be downloaded or executed, and it always gets executed.
Also, I have lots of seo rewrites, so I don't really know what is happening.
This is what I am currently trying (and I already red lots of docs about it):
Server Config:
user nginx nginx;
worker_processes 1;

error_log /var/log/nginx/error_log info;

events {
    worker_connections 1024;
    use epoll;
}

http {
    #proxy_cache off;
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main
        '$remote_addr - $remote_user [$time_local] '
        '"$request" $status $bytes_sent '
        '"$http_referer" "$http_user_agent" '
        '"$gzip_ratio"';

    client_header_timeout 10m;
    client_body_timeout 10m;
    send_timeout 10m;

    connection_pool_size 256;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 2k;
    request_pool_size 4k;

    gzip on;
    gzip_min_length 1100;
    gzip_buffers 4 8k;
    gzip_types text/plain;

    output_buffers 1 32k;
    postpone_output 1460;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    keepalive_timeout 75 20;

    ignore_invalid_headers on;

    index index.php;
    proxy_buffering on;
    proxy_buffer_size 8k;
    proxy_buffers 2048 8k;

    server {
        listen 127.0.0.1;
        server_name <<my_domain>>;

        access_log /var/log/nginx/access_<<my_domain>> main;
        error_log /var/log/nginx/error_<<my_domain>> info;

        root <<doc_root>>;

        error_page 403 /errors.php?type=403;
        error_page 404 /errors.php?type=404;

        location ~* /images  {
            root    <<doc_root>>;
            #expires 30d;
        }

        location ~ \.php$ {
            #internal;
            try_files $uri =404;
            expires off;
            include /etc/nginx/fastcgi.conf;
            fastcgi_pass unix:/var/run/php-fpm.socket;
        }

        #For virtual folders which are links seo-friendly and language
                location ~ (*UTF8)^.*$ {
                        include "rewrites.conf";
                }

    }

    server {
        listen 127.0.0.1:443;
        server_name <<my_domain>>;

        ssl on;
        ssl_certificate /etc/ssl/nginx/.crt;
        ssl_certificate_key /etc/ssl/nginx/.key;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
        ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:DHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA256:RC4-SHA;
        ssl_protocols TLSv1.2 TLSv1.1 TLSv1 SSLv3;
        ssl_prefer_server_ciphers on;

        access_log /var/log/nginx/access_ssl_<<my_domain>> main;
        error_log /var/log/nginx/error_ssl_<<my_domain>> info;

        root <<doc_root>>;
        error_page 403 /errors.php?type=403;
        error_page 404 /errors.php?type=404;

        <<the_same_locations_than_www_server_before>>
    }
}

So, can I serve all content inside /images/ statically without passing through php? In this testcase, the file /images/test.php should be downloaded rather than showing phpinfo();

A: Because ~* matches but continues searching for other regex matches I think what you want is:
    location ^~ /images/  {
        #This should match /images/ and stop checking.
        root    <<doc_root>>;
        #expires 30d;
    }

    location ~ \.php$ {
        #internal;
        try_files $uri =404;
        expires off;
        include /etc/nginx/fastcgi.conf;
        fastcgi_pass unix:/var/run/php-fpm.socket;
    }

A: Based on your location blocks, files ending with '.php' will only be passed through PHP. So if you have an actual file in the '/images' directory, it should serve it as a static file, or otherwise return a 404 error. If the file ends with '.php' and is in the '/images' directory, it will run through both location blocks in order.
Should it do otherwise?


text:
Q: python code does not show data in mysql database I have created a touch screen buttons consist of "start" "Request material" "Receive material" "Lap" "Emergency" "Finish"
Now i am trying to store integers as numbers of finished products (1,2,3,etc) and lap times when an operator presses the lap button (similar to stopwatch). Basically, there are only two columns. The result shows in the terminal after i ran the program and there was no error, but it didn't show in the mysql database and i am using phpmyadmin. Here is my code can be seen below:
from Tkinter import *
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
import time
import datetime
import RPi.GPIO as GPIO
import MySQLdb

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(0)
#-------------------------------------------------------GPIO
GPIO.setup(21, GPIO.OUT)#red led
GPIO.setup(20, GPIO.OUT)#yellow led
GPIO.setup(16, GPIO.OUT)#green led

GPIO.output(21, GPIO.HIGH)
GPIO.output(20, GPIO.HIGH)
GPIO.output(16, GPIO.HIGH)
#-------------------------------------------------------GPIO

class Screen(Frame):
  def __init__(self, master):
      Frame.__init__(self, master)
#-------------------------------------------------------Main
      self.lbttn_clicks = 0
      self.start_button()
      self.material_button()
      self.receive_button()
      self.emergency_button()
      self.lap_button()
      self.finish_button()
      self.minutes = 0
      self.seconds = 0
#-------------------------------------------------------Modbus Var
      self.LedRed_State = False
      self.LedYellow_State = False
      self.LedGreen_State = False
      self.db = MySQLdb.connect("localhost","root","raspberry","DB_ASSY")
      self.sql = "INSERT INTO Table_Assembly (Finished Product, Lap Time) VALUES (%s, %s)"
      self.c= self.db.cursor()
      self.client = ModbusClient('192.168.4.166')
      self.client.connect()
      print "ModbusClient connected..."
#-------------------------------------------------------Modbus Var

      self.time_start = time.time()
      self.pack(fill=BOTH, expand=1)
#-------------------------------------------------------Main

#-------------------------------------------------------Stopwatch
      self._start = 0.0
      self._elapsedtime = 0.0
      self._running = 0
      self.timestr = StringVar()
      # self.makeWidgets()
#-------------------------------------------------------Stopwatch

#--------------------------------------------------------------------Main funcs
 def start_button(self):
     self.gbttn = Button(self)
     self.gbttn['text'] = "Start"
     self.gbttn['command'] = lambda: [ f() for f in  [self.Start,
self.LedGreen, self.LedYellowOff, self.LedRedOff]]
    self.gbttn.place(x = 100, y = 0)

 def material_button(self):
     self.ybttn = Button(self)
     self.ybttn['text'] = "Request Material"
     self.ybttn['command'] = self.LedYellow
     self.ybttn.place(x=100, y=50)

 def receive_button(self):
     self.rbttn = Button(self)
     self.rbttn ['text'] = "Receive Material"
     self.rbttn ['command'] = self.LedYellowOff
     self.rbttn.place(x=100, y=100)

 def emergency_button(self):
     self.ebttn = Button(self)
     self.ebttn['text'] = "Emergency"
     self.ebttn['command'] = lambda: [f() for f in [self.LedRed, self.LedYellowOff, self.LedGreenOff]]
     self.ebttn.place(x=100,y=150)

 def lap_button(self):
     self.lbttn = Button(self)
     self.lbttn['text'] = "Lap"
     self.lbttn['command'] = lambda: [ f() for f in  [self.lap_count, self.Start, self.insert_to_db]]
     self.lbttn.place(x=100,y=200)

 def finish_button(self):
     self.fbttn = Button(self)
     self.fbttn['text'] = "Finish"
     self.fbttn['command'] = lambda: [f() for f in [self.Finish, self.Stop, self.Reset]]
     self.fbttn.place(x=100, y=250)

 def lap_count(self):
     self.lbttn_clicks += 1
     print str(self.lbttn_clicks)

 # def stop_watch(self):
 #     print self.seconds
 #     time.sleep(1)
 #     self.seconds = int(time.time() - self.time_start)
#--------------------------------------------------------------------------------------Main funcs

#--------------------------------------------------------------------------------------Modbus funcs

#--------------------------------------------------------------------------------------Modbus funcs

#--------------------------------------------------------------------------------------Stopwatch funcs
 # def makeWidgets(self):
 #     """ Print the time. """
 #     l = Label(self, textvariable=self.timestr)
 #     self._setTime(self._elapsedtime)
 #     l.pack(fill=X, expand=NO, pady=2, padx=2)
 def _print(self):
     print self._elapsedtime

 def _update(self):
     """ Update the label with elapsed time. """
     self._elapsedtime = time.time() - self._start
     self._setTime(self._elapsedtime)
     self._timer = self.after(50, self._update)

 def _setTime(self, elap):
     """ Set the time string to Minutes:Seconds:Hundreths """
     minutes = int(elap / 60)
     seconds = int(elap - minutes * 60.0)
     hseconds = int((elap - minutes * 60.0 - seconds) * 100)
     self.timestr.set('%02d:%02d:%02d' % (minutes, seconds, hseconds))

 def Start(self):
     """ Start the stopwatch, ignore if running. """
     print self._elapsedtime
     if not self._running:
         self._start = time.time() - self._elapsedtime
         self._update()
         self._running = 1

 def insert_to_db(self):
     self.sql = "INSERT INTO Table_Assembly ('Finished_Product', 'Lap_Time') VALUES (%s, %s)"
     try:
         self.execute(sql,( str(self.lbttn_clicks), str(self._elapsedtime)))
         self.db.commit()
     except:
         self.db.rollback()

 def read_from_db(self):
     try:
         #c.execute("SELECT * FROM TTAB_CPU WHERE ID = (SELCET MAX(ID) FROM TAB_CPU)")
         self.c.execute("SELECT * FROM Table_Assembly ORDER BY ID DESC LIMIT 1")
         self.result = self.c.fetchall()
         if result is not None:
              print ('Finished_Product: ' , result[0][1], '| Lap_Time: ' , result[0][2])
     except:
         print ("read error")

 def LedGreen(self):
     self.rr = self.client.read_coils(0,6)
     print "Start Button Pressed"
     if self.LedGreen_State == False:
        self.rr.bits[3] = True
        self.rq = self.client.write_coil(3, True)
        self.rq = self.client.write_coil(0, True)
        GPIO.output(16, GPIO.LOW)
        self.LedGreen_State = True

 def LedGreenOff(self):
     self.rr = self.client.read_coils(0,6)
     print "Green light is off"
     if self.LedGreen_State == True:
        self.rr.bits[3] = False
        self.rq = self.client.write_coil(3, False)
        self.rq = self.client.write_coil(0, False)
        GPIO.output(16, GPIO.HIGH)
        self.LedGreen_State = False

 def LedYellow(self):
     self.rr = self.client.read_coils(0,6)
     print "Request Material"
     if self.LedYellow_State == False:
        self.rr.bits[4] = True
        self.rq = self.client.write_coil(4, True)
        self.rq = self.client.write_coil(1, True)
        GPIO.output(20, GPIO.LOW)
        self.LedYellow_State = True

 def LedYellowOff(self):
     self.rr = self.client.read_coils(0,6)
     print "Material replenished"
     if self.LedYellow_State == True:
        self.rr.bits[4] = False
        self.rq = self.client.write_coil(4, False)
        self.rq = self.client.write_coil(1, False)
        GPIO.output(20, GPIO.HIGH)
        self.LedYellow_State = False

 def LedRed(self):
     self.rr = self.client.read_coils(0,6)
     print "Assembly process jammed"
     if self.LedRed_State == False:
        self.rr.bits[5] = True
        self.rq = self.client.write_coil(5, True)
        self.rq = self.client.write_coil(2, True)
        GPIO.output(21, GPIO.LOW)
        self.LedRed_State = True

 def LedRedOff(self):
     self.rr = self.client.read_coils(0,6)
     print "Red light is off"
     if self.LedRed_State == True:
        self.rr.bits[5] = False
        self.rq = self.client.write_coil(5, False)
        self.rq = self.client.write_coil(2, False)
        GPIO.output(21, GPIO.HIGH)
        self.LedRed_State = False

 def Finish(self):
     self.rr = self.client.read_coils(0,6)
     print "Assembly is finished"
     if self.LedGreen_State == True:
        self.rr.bits[3] = False
        self.rq = self.client.write_coil(3, False)
        self.rq = self.client.write_coil(0, False)
        GPIO.output(16, GPIO.HIGH)
        self.LedGreen_State = False

    if self.LedYellow_State == True:
        self.rr.bits[4] = False
        self.rq = self.client.write_coil(4, False)
        self.rq = self.client.write_coil(1, False)
        GPIO.output(20, GPIO.HIGH)
        self.LedYellow_State = False

    if self.LedRed_State == True:
        self.rr.bits[5] = False
        self.rq = self.client.write_coil(5, False)
        self.rq = self.client.write_coil(2, False)
        GPIO.output(21, GPIO.HIGH)
        self.LedRed_State = False

 def Stop(self):
     """ Stop the stopwatch, ignore if stopped. """
     if self._running:
        self.after_cancel(self._timer)
        self._elapsedtime = time.time() - self._start
        self._setTime(self._elapsedtime)
        self._running = 0
        GPIO.cleanup()

 def Reset(self):
     """ Reset the stopwatch. """
     self._start = time.time()
     self._elapsedtime = 0.0
     self._setTime(self._elapsedtime)

 def main():
     while 1:
         insert_to_db()
         read_from_db()

 if __name__ == '__main__':
     try:
         db = MySQLdb.connect("localhost","root","raspberry","DB_ASSY")
         self.c= self.db.cursor()

     except:
         print ("No connection to server...")
win = Tk()
win.title("Screen")
win.geometry('800x400')
app = Screen(win)

win.mainloop()

Please share
Thank you
and by the way i am using raspberry pi with raspbian stretch

A: Every transnational(Insert, update and delete) query required to commit than after reflect db engine. So try with autocommit(True) or commit manual after query execution.
 self.db = MySQLdb.connect("localhost","root","raspberry","DB_ASSY")
 self.sql = "INSERT INTO Table_Assembly (Finished Product, Lap Time) VALUES (%s, %s)"
 self.c= self.db.cursor()
 self.db.commit()


text:
Q: Send key from C# to interrupt Fortran process I need to communicate with a command line Fortran app using a c# wrapper. The Fortran process is started using the following c# code.
var process = new Process();

process.StartInfo = new ProcessStartInfo(pathToFortranExe)
{
  WorkingDirectory = directory,
  UseShellExecute = false,
  RedirectStandardError = true,
  RedirectStandardInput = true,
  RedirectStandardOutput = true
};

...
//listen for prompts from the Fortran program
//and send replies using standardInput as follows
process.StandardInput.WriteLine(data);

When the Fortran program is waiting for user input on the command line I can successfully send messages using the above code.
Now here is the problem. The Fortran program uses long running analysis loops which can be interrupted by sending keys such as Esq or Q. I've been told this interrupt feature is implemented in the Fortran code using the Intel Fortran command PEEKCHARQQ. When I try and trigger these keys from c# using StandardInput they are ignored by the Fortran program. To send these interrupt signals I use:
char key = 'q'
process.StandardInput.Write(key);
//Note that StandardInput.AutoFlush==true

I've also tried SendMessage via pinvoke, but again no luck so far:
 [DllImport("user32.dll", CharSet = CharSet.Auto)]
 private static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

 private const UInt32 WM_KEYDOWN = 0x0100;
 private const UInt32 WM_KEYUP = 0x0101;

 public static void SendKey(Process process, char key)
 {
     var keyCode = (IntPtr)key;
     var hWnd = process.Handle;

     SendMessage(hWnd, WM_KEYDOWN, keyCode, IntPtr.Zero);
     SendMessage(hWnd, WM_KEYUP, keyCode, IntPtr.Zero);
 }

So the question is: Are there any other ways to place keys into the keyboard buffer such that they might be picked up PEEKCHARQQ in the Fortran process? Or anything else that I might be missing here?
Update 1:
I've also tried WriteConsoleInput, but I don't think I have the right handle:
var keyCode = (short)key;
var hWnd = process.Handle;

INPUT_RECORD[] lpBuffer = new INPUT_RECORD[1];

lpBuffer[0].KeyEvent.wVirtualKeyCode = keyCode;

int nLength = lpBuffer.Length;
int lpNumberOfEventsWritten;

if (!WriteConsoleInput(
   hWnd,
   lpBuffer,
   nLength,
   out lpNumberOfEventsWritten))
{
   //this results error code 6: Invalid handle
   Console.WriteLine("Error: {0}", GetLastError());
}

A: You can write to the console input buffer for the child process using a handle to the CONIN$ device with the WriteConsoleInput API.
Two Fortran programs below to demonstrate.   The program for the child process:
PROGRAM peek_a_boo
  USE IFCORE
  IMPLICIT NONE

  CHARACTER(*), PARAMETER :: fmt = "('Press any key!')"

  PRINT fmt
  DO WHILE (.NOT. PEEKCHARQQ())
    CALL SLEEPQQ(2000)
    PRINT fmt
  END DO
END PROGRAM peek_a_boo

The program that shows the Windows API calls.  You can translate this to whichever language floats your boat.
PROGRAM peek_parent
  USE IFWIN
  IMPLICIT NONE

  INTEGER(BOOL) :: api_result
  INTEGER(HANDLE) :: console_input
  TYPE(T_STARTUPINFO) :: startup_info
  TYPE(T_PROCESS_INFORMATION) :: process_info
  TYPE(T_INPUT_RECORD) :: input_record
  INTEGER(DWORD) :: events_written
  INTEGER(DWORD) :: wait_event

  ! Create the child process.
  CALL ZeroMemory(LOC(startup_info), SIZEOF(startup_info))
  startup_info%cb = SIZEOF(startup_info)

  api_result = CreateProcess( &
      'peek_a_boo.exe',  &
      NULL,  &      ! command line.
      NULL,  &      ! process security attributes.
      NULL,  &      ! thread security attributes.
      .FALSE.,  &   ! inherit handles.
      0_DWORD,  &
      NULL,  &      ! environment.
      NULL,  &      ! current directory.
      startup_info,  &
      process_info )

  IF (api_result == 0) THEN
    ERROR STOP 'Couldn''t start it :('
  END IF

  api_result = CloseHandle(process_info%hThread)

  ! Let the child run for a bit.
  CALL SLEEPQQ(5000)

  ! Get a handle to our console input buffer.
  console_input = CreateFile(  &
      'CONIN$',  &
      GENERIC_WRITE,  &
      IANY([FILE_SHARE_READ, FILE_SHARE_WRITE]),  &
      NULL,  &       ! security attrs
      OPEN_EXISTING,  &
      0_DWORD,  &    ! attributes
      NULL )         ! template file
  IF (console_input == 0) THEN
    ERROR STOP 'Couldn''t open it :('
  END IF

  ! Poke something into the buffer.
  input_record%EventType = KEY_EVENT
  input_record%KeyEvent%bKeyDown = .TRUE.
  input_record%KeyEvent%wRepeatCount = 1
  input_record%KeyEvent%wVirtualKeyCode = INT(Z'51', WORD)
  input_record%KeyEvent%wVirtualScanCode = INT(Z'51', WORD)
  input_record%KeyEvent%AsciiChar = 'Q'
  input_record%KeyEvent%dwControlKeyState = 0
  api_result = WriteConsoleInput(  &
      console_input,  &
      input_record,  &
      1,  &
      LOC(events_written) )

  ! Wait for the child to terminate.
  wait_event = WaitForSingleObject(process_info%hProcess, INFINITE)
  api_result = CloseHandle(console_input)
  api_result = CloseHandle(process_info%hProcess)
END PROGRAM peek_parent


text:
Q: AS3 - The index is out of range (Error #1125 ) I downloaded this tutorial file and by testing it I got this error:

RangeError: Error #1125  The index is out of range

    // MAIN BLIT CANVAS
var canvas:BitmapData = new BitmapData(1024, 768, false);
addChild(new Bitmap(canvas));
addChild(sl);

// PROPERTIES
var ind:int;
var offset:int;
var rect:Rectangle;
var zp:Point = new Point();
var destX:int = 0;
var currentX:int = 0;

// LOAD PHOTOS FROM LIBRARY
var photos:Vector.<BitmapData> = new Vector.<BitmapData>();
for(var i:int=1; i<5; i++)
{
    var ref:Class = getDefinitionByName("p"+i) as Class;
    photos.push(new ref());
}

// LOAD BITMAPDATA INTO MEMORY
for(i=0; i<4;i++)
    canvas.copyPixels(photos[i], new Rectangle(0,0,1,1), zp);

// FIGURE OUT POSITION OF SLIDER AND CALL RENDER
stage.addEventListener(Event.ENTER_FRAME, function(e:Event):void {
                     destX = Math.ceil((sl.thumb.x/908) * 13312);
                     currentX += (destX - currentX) * 0.15;
                     render();
                       });

// RENDER PIXELS TO CANVAS
function render():void
{
    ind = currentX / 1024;
    offset = currentX % 1024;
    rect = new Rectangle(offset, 0, 1024-offset, 768);
    canvas.copyPixels(photos[ind], rect, zp);
    if(currentX < 13312)
        canvas.copyPixels(photos[ind+1], canvas.rect, new Point(1024-offset, 0));
}

//START DRAGGING SLIDER
sl.thumb.addEventListener(MouseEvent.MOUSE_DOWN, function(e:MouseEvent):void {
      sl.thumb.startDrag(false, new Rectangle(0, 0, 909, 0));
      });

//START DRAGGING SLIDER
stage.addEventListener(MouseEvent.MOUSE_UP, function(e:MouseEvent):void {
      sl.thumb.stopDrag();
      });

What causes the error?

A: canvas.copyPixels(photos[ind], rect, zp);

Or
canvas.copyPixels(photos[ind+1], canvas.rect, new Point(1024-offset, 0));

Do checks on ind and ind+1 to make sure they're less than photos.length


text:
Q: Another phrase for 'the same as' What is another phrase that could be used to replace 'the same as'?
To be used in a sentence such as: He was walking around the area, the same as everyone else.

A: just like
He was walking around the area, just like everyone else.
similar to
He was walking around the area, similar to everyone else.

A: 'Exactly like' may work. 'Identical' looks less appropriate for the sample sentence.
References:
http://www.oxforddictionaries.com/definition/english/exactly

Used to emphasize the accuracy of a figure or description:
  they met in 1989 and got married exactly two years later

http://www.oxforddictionaries.com/definition/english/identical

Similar in every detail; exactly alike:
  four girls in identical green outfits

A: Consider,
He was walking around the area the way everyone else was.

the way:  like, as we have cats the way other people have mice —
  James Thurber

M-W


text:
Q: oracle datasource java.sql.SQLException: String index out of range: -1 in spring I have a spring boot 1.5.22 app and i am trying to connect to oracle 10g with tomcat-jdbc and ojdbc6.
i have the datasource getproperties() function to connect to my db :
DataSource dataSourceProperties()  {
     DataSource ds=null;
    try {
    ds = DataSourceBuilder.create()
            .driverClassName("oracle.jdbc.OracleDriver")
            .url("jdbc:oracle:thin:@//host:port/DBname")
            .username("xxx")
            .password("xxx")
            .build();
    }catch (Exception e) {
        System.out.println(e.toString());}

when the url was with this SID format : jdbc:oracle:thin:@host:port:DBname
i got an oracle error : refused:ROR=(code=12505)(EMFI=4)
when i changed it to jdbc:oracle:thin:@host:port/DBname i got  java.sql.SQLException: String index out of range: -1
and finally this format jdbc:oracle:thin:@//host:port/DBname and still getting java.sql.SQLException: String index out of range: -1
that's how i make call to that function in getConnection function :
public Connection getConnection() throws SQLException
    {

        Connection conn=null;
            try {
                this.ds=this.dataSourceProperties();
                conn=ds.getConnection();
            }catch (SQLException e ) {
                System.out.println(e.toString());

            }
            return conn;}

here are somme error logs :
2021-08-16 18:33:59.926 ERROR 22476 --- [bio-8080-exec-1] o.a.tomcat.jdbc.pool.ConnectionPool      : Unable to create initial connections of pool.

java.sql.SQLException: String index out of range: -1
        at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:332) ~[tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:212) ~[tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:736) [tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:668) [tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:483) [tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:154) [tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:118) [tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:107) [tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:131) [tomcat-jdbc-8.5.43.jar:na]
        at com..web.services.DBConnection.getConnection(DBConnection.java:68)

[classes/:na]
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
java.sql.SQLException: String index out of range: -1
Mon Aug 16 18:33:59 CEST 2021
java.lang.NullPointerException

here are new error logs after modifying the url to the correct format jdbc:oracle:thin://xx:1509/xxx
2021-08-17 11:25:27.368 ERROR 15440 --- [bio-8080-exec-5] o.a.tomcat.jdbc.pool.ConnectionPool      : Unable to create initial connections of pool.

java.sql.SQLException: Connection refused: connect
        at oracle.jdbc.dbaccess.DBError.check_error(DBError.java:223) ~[jdbc-oracle-11.2.0.3.jar:na]
        at oracle.jdbc.driver.OracleConnection.<init>(OracleConnection.java:100) ~[jdbc-oracle-11.2.0.3.jar:na]
        at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:146) ~[jdbc-oracle-11.2.0.3.jar:na]
        at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:319) ~[tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:212) ~[tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:736) [tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:668) [tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:483) [tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:154) [tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:118) [tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:107) [tomcat-jdbc-8.5.43.jar:na]
        at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:131) [tomcat-jdbc-8.5.43.jar:na]

A: Solved :
this one worked for me :)
jdbc:oracle:thin://host:port/ServiceName
An example:
jdbc:oracle:thin://hostname:1509/ServiceName(or DatabaseName)


text:
Q: Windows 10 changed how quotation marks work. How do I fix this? I've always been used to pressing the ' and " button twice to get the respective characters. But recently, it changed without my involvement.
Now, when I press the button, I get 2 of them immediately. Aside from being just a pain in the gluteus maximus, it also doesn't allow me to type apostrophe characters.
I don't know when this started, but I believe it had something to do with the last big update, which required rebooting several times. Since this might be an intended feature by Microsoft, I don't know if it's fixable, so any and all answers would be appreciated.

A: I assume you're currently using the "US – QWERTY" layout. What you probably want is the US International keyboard. It has all the so-called "dead keys" you want:

*

*' + vowel → vowel with acute accent, e.g., '+e → é

*` + vowel → vowel with grave accent, e.g., `+e → è

*" + vowel → vowel with diaeresis (or umlaut), e.g., "+e → ë

*^ + vowel → vowel with circumflex accent, e.g., ^+e → ê

*~ + a, n or o → letter with tilde, e.g. ~+n → ñ, ~+o → õ

*' + c → ç (Windows)

To enable it, go to Settings → Time & language → Region & language (sidebar). There, select the language (English, Dutch, whatever) you want to modify, click "Options". Then, under "Keyboards" add the "United Status-International" layout. Then remove the regular US layout.

A: In Windows 10, go to Languages, click your preferred language (English) and then Options. Ensure that United States QWERTY keyboard is being used instead of United States-International QWERTY. Add it if you need to. Delete the international keyboard and Viola! No more annoying accents.


text:
Q: Emoji symbol at left and emoji box also left side using plugin I am developing a new chatbot. in this, I am created input just like WhatsApp web. I face trouble to take the emoji symbol before the input tag.
My code is below

$("#mytext").emojioneArea({
  pickerPosition: "bottom"
});
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/emojionearea/3.4.1/emojionearea.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/emojionearea/3.4.1/emojionearea.js"></script>
<div>
  <input type="text" id="mytext" />
</div>

I am trying to build this type of input

and emoji panel opens above from smiley

A: I would do the pseudo-code but if you're going off of javascript in which html is created, then you can do this:
.emojionearea{
  margin-left: 25px;
  position: relative;
  width: 300px;
}

.emojionearea-button{
  position: absolute;
  left: -30px;
}

https://jsfiddle.net/d9gsvjrq/


text:
Q: Binary Symmetric Channels: Crossover probability and reliability I am having difficulties understanding how it is possible to create, given one binary symmetric channel (BSC) with crossover probability $p<\frac{1}{2}$, an equivalent BSC with crossover probability $p'>\frac{1}{2}$, while maintaining reliability of the underlying transmission.
To allow discussion of reliability w.r.t BSC, I want to introduce transmission schemes. Let us suppose we are dealing with the transmission scheme described in the following figure:

The current question places the given BSC as the channel in the middle, and also ensures us the existence of an encoder-decoder pair, denoted $(E,D)$, that allows for reliable transmission. Let us denote this transmission scheme $T_1$.
I want to build a new transmission scheme, denoted $T_2$, with its own encoder-decoder pair, $(E',D')$, that builds on $T_1$, and for which the crossover probability is $p'>\frac{1}{2}$.
According to Wikipedia, the receiver can use bit-flip on top of the existing BSC. I am trying to translate this into a formal answer. I have:

*

*The encoder stays the same. Thus, $E' = E$. .

*The bit-flip is an preliminary operation performed by the old channel decoder. Let us denote the bit-flip operation as $BF$. Then, we have $D' = D\circ BF$.

But here as where I come across the following difficulty: Since I used bit-flip, and it is the only difference between the two transmission schemes, how is it possible that reliability is maintained?
Formally:

*

*Let $T_1$ be the original transmission scheme with crossover
probability $p$, and encoder-decoder pair $(E,D)$. It has output
$\hat{W_1}$, with high probability.

*Let $T_2$ be the new transmission scheme with crossover probability
$p'$, and encoder-decoder pair $(E',D')$. It has output $\hat{W_2}$, with high probability.

But, since, the transmission schemes are different in and only in the bit-flip step, we have $\hat{W_1} \neq \hat{W_2}$, with high probability.
Then, let $c$ is the noise induced by the original channel, which is unchanged in both $T_1,T_2$.
We know that $T_1$ is reliable, and so, with high probability:
$$W = \hat{W_1} = D(E(W)+c)$$
But since $\hat{W_1} \neq \hat{W_2}$, we also have, with high probability:
$$W\neq \hat{W_2} = D'(E'(W)+c)$$
So how is the new transmission still reliable?

Edit:
I did not understand the following:

*

*A binary symmetric channel is actually a set of channels, with a parameter that is changeable.

*The function of a decoder.

*If I know one transmission scheme satisfies what I want, I do not have to take the channel from it "as-is" to create a new transmission scheme. I might need to take the encoder of the decoder of that transmission scheme.

Thank you!

A: With respect to the question I had:

*

*For $T_2$, I do not need to take the same BSC channel as in $T_1$. I need to put a BSC channel there with parameter $p'=1-p$. Then, the bit-flip is not the only difference between the two transmission schemes, but the parameter and the bit-flip operation.

*The role of a decoder: Let us assume that we have a decoder with the following property: Given $k\in[0,1]$ and an input $L$, if $P(D(E(W)+c) \neq W) = P(L \neq W) < k$, the decoder knows how to reach the original $W$. Then, to create a successful new transmission that uses that same decoder, all I need to do to get a successful transmission in the new scheme is to ensure that there exists an input $L$ to the old decoder such that the decoder property holds for it. This allows the new transmission scheme to get $W$ with high probability. Notice that the relation $<k$ is not the only possible relation (or rather predicate) that has to occur. Any predicate on the probability can occur, as it depends on the original decoder.

*Here I use $(E,D)$ from $T_1$, and them alone, for the creation of $T_2$. More precisely, I use $(E,D)$ to create $(E',D')$. The BSC channel from $T_1$ (with parameter $p$) is not the same BSC channel in $T_2$ (with parameter $p'=1-p$).


text:
Q: Signing data is throwing exception for RSA SHA512 algo with key size as 512 and 1024 Signing data using RSA key with below dotnet function is throwing exception :
var rsa = RSA.Create();

rsa.SignData(data, hashAlgorithm, padding);

Exception:

"The parameter is incorrect."

Table with more combinations:
enter image description here


text:
Q: How to store one string and arrayvalue in sharedpreference? I have array values of up[]={0,0,0,0,0} and view="adult" thesetwo value i want to store and retrieve in from sharedpreference how to do that...

A: Assuming that you have a list of preferences for you app called MY_PREFS, I'd do this:
SharedPreferences settings = getSharedPreferences(MY_PREFS, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putInt("arrayLength",up.size());
      for(int i=0; i<up.size(); i++){
         editor.putInt("up"+String.valueOf(i), up[i]);
      }
      editor.putString("view", "adult");

To retrieve them do:
   SharedPreferences settings = getSharedPreferences(MY_PREFS, 0);
   int arraySize = settings.getInt("arrayLength");
   int up[] = new int[arraySize];
   for(int i=0; i<arraySize; i++){
      up[i] = settings.getInt("up"+String.valueOf(i));
   }
   String view = settings.getString("view");

A: you can do by simple way, like this
SharedPreferences settings = getSharedPreferences("pref_name", 0);
      SharedPreferences.Editor editor = settings.edit();

     String values="";

      for(int i=0; i<yourArray.length; i++){
         values+=","+Integer.toString(yourArray[i]);
      }

      editer.putString("array",values);
      editor.putString("view", "adult");

To get those values,
 SharedPreferences settings = getSharedPreferences("pref_name", 0);

 String[] strArray=settings.getString("array").split(",");
int[] yourArray=new int[strArray.length];

for(int i=0;i<strArray.length;i++){
   yourArray[i]=Integer.toParseInt(strArray[i]);
}

A: Well as far as I have seen you can't directly store an array in shared preferences. You can however use a for loop to save an int with an increasing name and have it call it back the same way when you need it and store it into another array.
for(int i=0; i<numInYourArray; i++){
editor.putInt("up"+i, up[i]);
}

If you aren't sure on how to use Shared Preferences in general look here


text:
Q: TypeError: Cannot read properties of undefined (reading 'filename') in multer I have a very similar problem with respect to this fellow community contributor. How do i produce multer error message in my postman I followed through the comments made by other users and it was successful! However, when i tried to post a image that is a jpg formatted image( which i managed to do before the editing), it now fails and state that TypeError: Cannot read property 'filename' of undefined.

// multer.js file
successfully setup multer

 **please tell me why this error comes on my code and give me a solution**

const multer = require('multer');

    const storage = multer.diskStorage({
      fileSize: 1024*1024*2,
      destination: function (req, file, cb) {
        cb(null, './uploads')
      },
      filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, file.fieldname + '-' + uniqueSuffix)
      }

    })

    const filter = function (req, file, cb) {
      if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
        cb(null, true);
      } else {
        cb(new Error('unsupported files'), false)
      }
    }

    var upload = multer({
      storage: storage,
      limits: {
          fileSize: 1024 * 1024 * 5
      },
      fileFilter : filter
    });

    module.exports = upload;

//controller.js file
//create function

here's my logic to create a new user

exports.create = (req, res, next) => {
        if (!req.body) {
            res.status(400).send({ message: "content cannot be empty !!" })
            return
        }
        let data = { name: req.body.name, description: req.body.description, brand_url:
        req.body.brand_url, image_file: req.body.file.filename }; getting error here
        let sql = "INSERT INTO influencer SET ?";
        db.query(sql, data, (err, results) => {
            if (err) throw err;
            console.log('data inserted succesfully')
            res.redirect('/admin');
        });
    }

//api.js file
//post API

router.post('/api/create', upload.single('image') ,controller.create) //when I am
sending file its throw back error undefined filename

A: *

*Please make sure you have added enctype="multipart/form-data"
 <form action="/api/create" enctype="multipart/form-data" method="post">

*I have tested the codes & found the problem.
 exports.create = (req, res, next) => {
 if (!req.body) {
     res.status(400).send({ message: "content cannot be empty !!" })
     return
 }
 let data = {
   name: req.body.name,
   description: req.body.description,
   brand_url: req.body.brand_url,
   image_file: req.file.filename
 }; // Remove "body", I have tested, it works well.

 let sql = "INSERT INTO influencer SET ?";
 db.query(sql, data, (err, results) => {
     if (err) throw err;
     console.log('data inserted succesfully')
     res.redirect('/admin');
 });

}


text:
Q: SQL Server "FOR JSON AUTO" Excluding Column Names I have a SQL Server 2016 query that returns the results in JSON format using the FOR JSON AUTO clause.
It returns the following (line break added for readability's sake):
[{"Count":0},{"Count":0},{"Count":0},{"Count":0},{"Count":36},{"Count":25},
 {"Count":22},{"Count":22},{"Count":1},{"Count":13},{"Count":0},{"Count":1}]

I'm however wanting it to return the data minus the "Count" column name.
Is this possible? As it's a new feature, I haven't been able to find much documentation on this.

A: I ended up just dealing with the JSON result-data through .NET core code and it worked well.


text:
Q: How do I force redraw of canvas api using js? How do I force a redraw of canvas api ?
I have a js button  which I want to force a redraw when clicking.
It only redraws after I hover on the canvas.
Have access to canvas and ctx in js.

A: I can't say for certain without seeing your code but I think you could simply take the function being called in the canvas onhover and use that same function for your button using the onclick attribute.


text:
Q: Ubuntu says the disk is full but it's not Very complex situation.
My main server is in a 5TB raid.
I'm currently on holiday so I use Teamviewer and ssh to remote into my server.
2 Days ago I ran a backup which was configured to be stored to my external hard drive. (10TB)
Backup started successfully and I left it to backup.
However later at night I had errors everywhere, here is what I noticed.
External drives aren't mounted.
No connection to network. (though I can ssh)
Teamviewer stopped working.
All critical applications stopped working. (VirtualBox for example)
Package Manager stopped working.
I ran df and all kinds of disk utilities in ssh to see what was taking up the drive.
But the confusing part is that the drive isn't even full.
The Trash is empty.
All partitions aren't even past 50% full.
Now back to when I ran that backup.
I thought maybe I accidentally routed the backup to store on the main drive, but there is no signs of the backup at all.
I've scanned and rebooted multiple times, however it shows that the disk isn't full, but Linux still says it's full.
I have attached some images to give a better understanding.

I was wondering if the /dev/loopx partitions in the image could be the issue but I'm not sure what to do with those.

A: According to doneal24 you need to run lsof to find files that are deleted but still opened by a process. In my case I deleted /var/log/syslog* but it didn't free any space on my ssd
But if I do echo>/var/log/syslog it frees up a lot
In my case this information helped me - finally after a reboot the space is freed because the process that's using this file's shut down
Maybe something used your hd space and removed the files afterwards but they were still used or it didn't free it because of some bug


text:
Q: Function sometimes returns old values when beeing called twice I have got an URL encoder which sometimes returns the value from the previous call. But it only happens sometimes...
Caller method of get_encoded_string:
char* call_api(const char* api_key, const char* pokerName, const char* message) {

CURL* curl;
CURLcode res;
curl = curl_easy_init();

char errbuf[CURL_ERROR_SIZE];

/* string builder */
char url[MAX_MESSAGE_SIZE];
snprintf(
    url,
    sizeof(url),
    "%s%s%s%s%s%s",
    "http://xdroid.net/api/message?k=",
    api_key,
    "&t=",
    get_encoded_string(pokerName),
    "&c=",
    get_encoded_string(message));

curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
struct curl_slist* headers = NULL;
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
const char* data = "";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
res = curl_easy_perform(curl);

if (res == CURLE_OK) {
    return "success";
}
else {
    return errbuf;
}
curl_easy_cleanup(curl);

Class thats returns previous value:
char* get_encoded_string(char* string_to_encode) {

CURL* curl = curl_easy_init();

/* convert a string into a URL encoded string */
char* encoded_message = curl_easy_escape(curl, string_to_encode, 0);
curl_free(encoded_message);
curl_easy_cleanup(curl);
return encoded_message;

Example:
call_api gets called with this values:
call_api("api_key", "pokerName","message")
so get_encoded_string gets called with "pokerName" and then with "message"
But sometimes get_encoded_string returns "pokerName" twice.
Any ideas why this is happening?

A: #define CURL_STATICLIB
#include <string.h>
#include <Curl/curl.h>
#include "push_notification_api.h"

char* call_api(const char* api_key, const char* pokerName, const char* message) {

    CURL* curl;
    CURLcode res;

    curl = curl_easy_init();

    /* escape the strings for the API call */
    char url[MAX_MESSAGE_SIZE];
    char *esc_name = curl_easy_escape(curl, pokerName, 0);
    char *esc_message = curl_easy_escape(curl, message, 0);

    /* string builder */
    snprintf(
        url,
        sizeof(url),
        "%s%s%s%s%s%s",
        "http://xdroid.net/api/message?k=",
        api_key,
        "&t=",
        esc_name,
        "&c=",
        esc_message);
    curl_free(esc_name);
    curl_free(esc_message);

    char errbuf[CURL_ERROR_SIZE];
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
    struct curl_slist* headers = NULL;
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    const char* data = "";
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
    res = curl_easy_perform(curl);

    if (res == CURLE_OK) {
        return "success";
    }
    else {
        return errbuf;
    }
    curl_easy_cleanup(curl);
}


text:
Q: How to redirect user not in proper role to Not Permitted? While using SimpleMembershipProvider in MVC 4 project, when user without proper role runs action, he's redirected to Account/Login. How can I redirect user to my own "Not enough permissions to view the page" action?

A: You can overwrite the method to do it
public class CustomAuthorizeAttribute : AuthorizeAttribute {
    public override void OnAuthorization(AuthorizationContext filterContext) {
        base.OnAuthorization(filterContext);

        if (filterContext == null) {
            throw new ArgumentNullException("filterContext");
        }

        if ({your code detecting no user is logged}) {
            filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?returnUrl=" + filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));
            return;
        }

        if ({your code detecting that the user has no access}) {
            var ViewData = new ViewDataDictionary();
            ViewData.Add("Title", "No access");
            ViewData.Add("Description", "blah blah blah blah blah blah blah ");
            filterContext.Result = new ViewResult { ViewName = "~/Views/Shared/NoAccess.cshtml", ViewData = ViewData };
        }

    }


text:
Q: Code for pin icon on a map Is there any way I can get the pin icon / symbol (that us usually used on maps)? Any icon similar to the attached one would do. I am trying to use this symbol instead of stating 'Address' in one of my documents. Any input, suggestions or advice will be greatly appreciated.

A: You can use the command \faMapMarker from the package fontawesome. Like this:
\documentclass{scrartcl}
\usepackage{fontawesome}

\begin{document}
Map Symbol: \faMapMarker
\end{document}

Output:

This symbol is available in pdflatex now as well, since the fontawesome-package added support for pdflatex recently.

A: A tikz solution (as standalone image):
\documentclass{standalone}

\usepackage{xcolor}
\usepackage{tikz}

\newdimen\pinA
\newdimen\pinB
\newdimen\pinC

\setlength{\pinA}{10mm}
\setlength{\pinB}{20mm}
\setlength{\pinC}{40mm}

\definecolor{pin}{gray}{0}

\begin{document}
  \begin{tikzpicture}
    \useasboundingbox (-\pinB, -\pinC) (\pinB, \pinB);
    \pgfmathsetmacro{\pinAngle}{acos(\pinB/\pinC)}%
    \pgfmathsetmacro{\pinAngleRight}{270+\pinAngle}%
    \path[fill=pin, even odd rule]
      (\pinAngleRight:\pinB)
      arc[
        at={(0,0)},
        start angle=\pinAngleRight,
        delta angle=360-2*\pinAngle,
        radius=\pinB,
      ]
      -- (0, -\pinC) -- cycle
      circle[
        at={(0,0)},
        radius=\pinA,
      ]
    ;
  \end{tikzpicture}
\end{document}

The both radii and the length of the tip can be configured using the dimen registers \pinA, \pinB, \pinC, all three measured from the origin in the middle of the circles. The color can be set via color name pin.
Usage
The file can be stored as pin.tex, then run pdflatex pin to get pin.pdf.
The following example automatically scales the image to the size of uppercase letters, when included as image:
\documentclass{article}
\usepackage{graphicx}
\usepackage{calc}

\newcommand*{\pin}{%
  \includegraphics[height=\heightof{M}]{pin}%
}

\begin{document}
{\Huge \pin~Hello World}
{\normalsize \pin~Hello World}
{\tiny \pin~Hello World}
\end{document}


text:
Q: Delete a Fragment from ViewPager I have a ViewPager, and there's a button when clicked, deletes the current fragment from the PagerAdapter, and prevents the user from swiping there. I researched and found this Remove Fragment Page from ViewPager in Android to be the closest to what I want.
In my fragment to be deleted:
       @Override
        public void onClick(View v) {
            db.delete(count); //SqliteDatabase deletion
            displayActivity.removeCurrentFragment(0);
        }

My PagerAdapter
    public class PagerAdapter extends FragmentPagerAdapter {

long baseId = 0;
public static List<Fragment> fragmentArrayList = new ArrayList<Fragment>();

public PagerAdapter(FragmentManager fm){
    super(fm);
    fragmentArrayList.add(new FragmentOne());
    fragmentArrayList.add(new FragmentTwo());
    fragmentArrayList.add(new FragmentThree());
}
@Override
public Fragment getItem(int position) {
    return fragmentArrayList.get(position);
    }

}

@Override
public int getCount() {
    return fragmentArrayList.size();
}

@Override
public int getItemPosition(Object object){
    return PagerAdapter.POSITION_NONE;
}
@Override
public long getItemId(int position) {
    // give an ID different from position when position has been changed
    return baseId + position;
}

}
This is the activity (DisplayActivity) that hosts the pagerAdapter
public class DisplayActivity extends AppCompatActivity {

ViewPager viewPager;
PagerAdapter pagerAdapter;

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

    viewPager = (ViewPager) findViewById(R.id.pager);

    PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
    viewPager.setAdapter(pagerAdapter);

}

public void removeCurrentFragment(int position){
    pagerAdapter.fragmentArrayList.remove(position);
    pagerAdapter.notifyDataSetChanged();
}

What did I do wrong here?
I'm getting an error of
 .removeCurrentFragment(int)' on a null object reference

So this error suggests that my method call removeCurrentFragment is referencing a null object, how do I fix it?

A: You have used
    PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());

so you are creating a new local variable instead of using your global variable. Instead change your line as
     pagerAdapter = new PagerAdapter(getSupportFragmentManager());

It should work.

A: Your onCreate method should look like this.
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.db_layout);

    viewPager = (ViewPager) findViewById(R.id.pager);

    pagerAdapter = new PagerAdapter(getSupportFragmentManager());
    viewPager.setAdapter(pagerAdapter);

}


text:
Q: Traefik - Redirect Requests to AWS Lambda How I redirect incoming requests to my AWS Lambda functions?
When sends a request to api.example.com/path send it to path function in AWS Lambda.
Whats must be my traefik.toml file content?
Thanks.

A: You can't call AWS Lambda functions directly, unless Traefik makes specific code for that case. This is because Lambda functions by default don't have inbound HTTP connections.
However, once you configure AWS API Gateway for the Lambda function, then you have a HTTP endpoint that you can proxy traffic to via Traefik. I recommend you use the API Gateway's Lambda proxy functionality to just pass through the HTTP requests, so you don't have to configure the API Gateway any further.
How to configure your traefik.toml.. https://docs.traefik.io/basics/#modifiers advices using ReplacePath modifier for Lambda use case. It all depends on how you want your URL prefix structure laid out.. say do you want to be able to mount the Lambda API at root (/) or from a subresource downwards..?


text:
Q: django manytomany through If I have two Models that have a manytomany relationship with a through model, how do I get data from that 'through' table.
class Bike(models.Model):
   nickname = models.CharField(max_length=40)
   users    = models.ManyToManyField(User, through='bike.BikeUser')

The BikeUser class
class BikeUser(models.Model):
   bike     = models.ForeignKey(Bike)
   user     = models.ForeignKey(User)
   comment  = models.CharField(max_length=140)

And I would add a user to that bike (presuming I have a myBike and a myUser already)
BikeUser.objects.create(bike = myBike, user = myUser, comment = 'Got this one at a fancy store')

I can get all the users on 'myBike' with myBike.users.all() but how do I get the 'comment' property?
I would like to do something like
for myBikeUser in myBike.users.all():
   print myBikeUser.comment

A: The through table is linked by standard ForeignKeys, so you do a normal ForeignKey lookup. Don't forget that there's a comment for each bikeuser, ie one for each bike/user pairing.
for myBikeUser in myBike.bikeuser_set.all():
    print myBikeUser.comment, myBikeUser.user.first_name


text:
Q: export from .shp to .gpx and .kml fails I've just upgraded to QGIS Dufour and I am having some problems with the exportation of a simple track from .shp to .gpx and .kml format.
I imported from mi smartphone a .gpx track (SR WGS84 EPSG:4326), i converted it into .shp (EPSG:3857 in order to have it correctly projected over the google maps layer); I modified it and I finally need it to be exported into .gpx and .kml formats.
For .gpx: I did the "Save as", chose GPX format, set the RS to EPSG:4326, wrote "GPX_USE_EXTENSIONS=YES" in the Data Source field and "FORCE_GPX_TRACK=YES" in the Layer field. Qgis says it all went ok (and it loads the track in the viewer and it looks fine), but when I load the .gpx track into my gps device I only see a straight line into the sea.
For .kml: I did the "Save as", chose KML format, set the RS to EPSG:4326. Qgis says it all went ok, but when I load it in the viewer it looks just empty and in google earth I can see a huge red cross over Africa... and I was looking for a road in Sardinia.
Can anyone help me, please? Thanks a lot!


text:
Q: i am trying to implement a caesar cipher in java but have no ideas since i have to need a char[] key as parameters and not an int shift  public static void getkey() {

        char[] resultat = new char[256];

        for (char r = 0; r < 256; r++) {

            resultat[r] = r;
            System.out.print(r);
        }

    }

Hello , when i run this programm it shows me all the 256 characters in  java.like thisjava console
 But my goal is to use a parameter of type String like this.
public static void getkey(String key)

this parameter are the letter of the alphabet. when i run the programm , it should replace the position of the caracters that are already stored as showed in the imagelink. And the result would be , if i add "ZYXWVUTSRQPONMLKJIHGFEDCBA" as a parameter , A would become Z , B would become Y , C = X , until Z becomes A.
And i will have to create a method encrypt , As i am trying to create a caesar cipher , and i will have to call this method getkey(String key) in other to encode my text, i am not using an int shift , the signature of the method looks like this:
public static void encrypt(String text , char[] key)

i am looking every where and i don't find any answer , please does somebody have an idea , i am a beginner at java programming . Thank you.

A: You want to do something like this:
private static char[] key = ZYXWVUTSRQPONMLKJIHGFEDCBA".toCharArray(); //for reference

public String encrypt(char[] key, String plaintext){
    char[] encryptedText = new char[plaintext.size];
    for(int i = 0; i < plaintext.size(); i++){
       int charIndex = plaintext.charAt[i] - 'A'; //normalizes to A=0, Z=24
       encryptedText[i] = key[charIndex % key.length];
    }
    return new String(encryptedText);
}

It seems like you will have edge cases with ' ' characters and others so you may need to add some logic to ignore characters not within the range you are encrypting.


text:
Q: Display date, id column and other columns in Folium HeatMapWithTime I have a taxi frequency dataset like this:
ID   Date         Latitude   Longitude   Sample_Mean
01   2019-10-09   40.431753  -3.711294   0.1
03   2019-10-21   40.431753  -3.711294   0.05
32   2020-03-22   40.458772  -3.699815   0.2
44   2020-03-29   40.431753  -3.711294   0.22

I am trying to create a heat map with time using folium to display the volume of taxi's on different days. I'm trying to do the following:

*

*How to display the 'Date' as an index on the animation?

*How to display the 'ID' on each heat map spot?

*How to display the 'Sample_Mean' on each heat map spot?

This is what I have tried:
# Make basemap
map = folium.Map(location=[25.41, -3.703], zoom_start=15, tiles='CartoDB positron')
df['date'] = df['date'].sort_values(ascending=True)
data = []
for _, d in df.groupby('date'):
    data.append([[row['latitude'], row['longitude'], row['Sample_Mean']] for _, row in d.iterrows()])

hm = plugins.HeatMapWithTime(data, auto_play=True,display_index=True,max_opacity=0.8)
hm.add_to(map)

A: The only thing that can be done with the heatmap animation in folium is to display the index as a date. As far as I know, it is not possible to display or annotate any other value. Instead, you can set the color distinction by threshold and the size of the circle radius. Here is an example. See also the official sample.
import pandas as pd
import numpy as np
import io

data = '''
ID   date         latitude   longitude   Sample_Mean
01   2019-10-09   40.431753  -3.711294   0.1
03   2019-10-21   40.431753  -3.711294   0.2
04   2019-10-30   40.431753  -3.711294   0.8
32   2020-03-22   40.458772  -3.699815   0.4
44   2020-03-29   40.458772  -3.699815   0.66
45   2020-04-07   40.458772  -3.699815   0.95

'''

df = pd.read_csv(io.StringIO(data), delim_whitespace=True)
df['date'] = df['date'].sort_values(ascending=True)
data = []

for _, d in df.groupby('date'):
    data.append([[row['latitude'], row['longitude'], row['Sample_Mean']] for _, row in d.iterrows()])

import folium
import folium.plugins as plugins

m = folium.Map(location=[40.43, -3.703], zoom_start=13, tiles='CartoDB positron')
hm = plugins.HeatMapWithTime(data, auto_play=True,
                             display_index=True,
                             gradient={0.2: 'blue', 0.4: 'lime', 0.6: 'orange', 1: 'red'},
                             index=df['date'].tolist(),
                             max_opacity=0.8)
hm.add_to(m)

m


text:
Q: SQL Server: Concurrent read of non repeatable rows How is it possible to make such scenario:
I have table with Order objects. There are many orders in DB. There is mechanism with few threads that can get the next order from DB (but need locks, that same order won't be executed few times).
How is it possible in SQL Server level to make that one thread reads the row (order), deletes it from DB and returns it to C# written mechanism which executes it, when other thread can see the row is locked, it skips that row and takes the next one?
The orders have execution priority and clustered index is on priority column.
This stuff will be executed in stored procedure.

A: I'd add a column to the table called "locked_by_thread" with a thread number, and it'd be null when no thread had it locked. You'd have to commit more often with this scenario, but it's what I'd do.


text:
Q: Enumeration For Application.InputBox Whenever I use Application.InputBox() I bring up VBA Help to remind me which Type to use:
Sub MAIN()
    Dim s As String

    s = Application.InputBox(Prompt:="enter data", Type:=2)
End Sub

Does there exist, or can I create an Enumeration for Type so I could code like:
Sub MAIN()
    Dim s As String

    s = Application.InputBox(Prompt:="enter data", Type:=vbString)
End Sub

It would be easier for me to remember an Enumeration rather than an arbitrary integer.

A: No there isn't, but you can just create an enumeration by yourself:
Public Enum InputBoxType
    ibtFormula = 0
    ibtNumber = 1
    ibtText = 2
    ibtBoolean = 4
    ibtRange = 8
    ibtError = 16
    ibtArray = 64
End Enum

A: Using IntelliSense
As the main intention seems to be fastening inputs without consulting extra help,
I'd propose to benefit from using IntelliSense:
Simply start input within a code module by
vba.VbVarType.

or in the immediate window by
?vba.VbVarType.

and choose the proposed DropDown values:

Alternatively you could have a look into the Object Browser, too giving a better overview.


text:
Q: Array - Remove records with the value zero i got an array i would like to remove all records where [quantity] => 0
 Array (
 [0] => Array ( [id] => 1 [is_sub] => 0 [product] => Town [quantity] => 0 [price] => [total_item_price] => 0 [comments] => )

 [1] => Array ( [id] => 3 [is_sub] => 0 [product] => City [quantity] => 0 [price] => [total_item_price] => 0 [comments] => )
 )

 [2] => Array ( [id] => 3 [is_sub] => 0 [product] => News [quantity] => 1 [price] => [total_item_price] => 0 [comments] => )
 )

thanks for your help

A: Use array_filter:
$array = array_filter($array, function($x) {
    return $x['quantity'] != 0;
});

A: I'll presume it's PHP.
You could do:
foreach($arr as $key => $value) {
    if($value['quantity'] < 1) {
        unset($arr[$key]);
    }
}

or
$arr = array_filter($arr, function($val) {
    return ($val['quantity'] > 0);
});