text:
Q: Is relation R isotone isomorphism with operation * I have follow operation $*$ defined like $MxM \rightarrow M$ where $M=\{a,b,c,d\}$

and relation $R=\{(a,a),(b,b),(c,c),(d,d),(a,b),(b,c),(a,c)\}$
Decide, if $R$ is isotone  with operation $*$ on M.
Solution
I know definition of isotone isomorphism:
$(G,\leq ), (H, \preceq )$ are ordered set
$f: G \rightarrow H$
$\forall x,y \in G: x \leq y \implies f(x) \leq f(y)$
But I don't know how to apply this rule.
My guess
I think, that from $R$ implies
$(a,a) \leq (a,b) \leq (a,c) \leq (b,b) \leq (b,c) \leq (c,c)$ and $(d,d)$
If I do map to $*$ operation a get:
$(a,a)\in R \rightarrow a\in M \\
(a,b)\in R \rightarrow b\in M \\
etc..$
I get:
$a \leq b \leq c \nleq a \leq d \leq a$
So, the answer is no, $R$ is not isotone isomorphism with M.
Please,is that good solution?
Or how should a solution looks like?

A: $R$ cannot be an isomorphism because it not a bijection, it is not even a function.
@amrsa $x\to x\star a $ is the identity map so it is an isotone isomorphism. Similarly for $x\to a\star x $.


text:
Q: What is "Modern Perl"? I have been hearing a lot about this "Modern Perl." What is it?
One of the things I heard was the new open syntax:
open my $FH, '<', $filename

and not
open FH, "<$filename";

What else is in Modern Perl?

A: Modern Perl isn't a proper noun; it's just something people might say to refer to Perl code that uses features only available in the last X years, where X will vary from person to person.
For information about various changes to Perl, see the perldelta files, for instance at http://perldoc.perl.org/index-history.html.

A: To quote the source

Modern Perl programming, circa 2010, relies on the collected wisdom of the entire Perl
  ecosystem. It's time to write elegant, reliable, maintainable, well-tested, and predictable
  code.

See also, the book.  And this quote from the book

Modern Perl is a loose description of how experienced and effective Perl 5 programers work. They use language idioms. They take advantage of the CPAN. They're recognizably Perlish, and they show good taste and craftsmanship and a full understanding of Perl.

A: To add some specifics to deinst's overview, Modern Perl:

*

*uses Perl 5.10's new features, like switch statements (given / when) and say

*follows good Perl programming practices, like use strict and use warnings

*may use the Modern::Perl CPAN module to streamline all of this

*uses Moose for writing high-level OO code

A: In order to be specific to your question related to opening a file handle in modern Perl: You should use the three-argument form, instead two-argument form!
Use the three-argument form of open to specify I/O layers (also called "disciplines") to apply to the handle. It affects how read-write is processed (see http://perldoc.perl.org/functions/open.html  for more details). For example:
open(my $fh, "<:encoding(UTF-8)", "filename")
|| die "can't open UTF-8 encoded filename: $!";

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wordpress plugin for nicer looking slugs? Have multiple pages named the same but they get different slugs This wordpress site I'm touching up has a page hierarchy which is responsible for the urls.
Basically the urls look like page1/subpage/subsubpage etc.
The problem is, this site is for a recurring competition and therefore the urls are like
2011/results
2012/results
2013/results
Which wordpress in turn makes
2011/results
2012/results-1
2013/results-2
Which doesn't look that great..
Is it possible to mod_rewrite or something to work around this? I understand the need in Wordpress for unique slugs but I really can't see why they enforce it even when it's impossible to get duplicate urls for different pages...

A: I use the Custom Permalinks plugin for Wordpress.  With it, you can choose the permalink of each post/page individually.  It is great for situations like yours where you want to fine tune the URLs in some corner cases.


text:
Q: Edit Custom Metadata on a JPG file - Live Photo I am trying to edit a custom metadata value of a JPG file (static image of a Live Photo created by iPhone). Tried the exiftool but it doesnt work for me.
For reference this is the metadata of one of the file - https://www.metadata2go.com/result/93287b28-1c16-4491-affe-8ffbd6d9dd1a
the field I would like to edit and update is

Content Identifier DF64C2AE-ED3C-4778-BFCA-C15277E521D2

I tried updating the field with exiftool

exiftool -ContentIdentifier=5A0FFB8D-5410-4464-A343-61AE4A6C1109
LW16.jpg

It always throw error like file cannot be read or Warning: Tag 'ContentIdentifier' is not defined
Nothing to do.
Anyone can help me with this or guide me with another method to change the value ?


text:
Q: Is mankind correctly used as 3rd person singular or plural? Is "mankind" used correctly as 3rd person singular? Or 3rd person plural?
For example:  "Mankind knows" or "mankind know"?

A: It's always used as a singular noun. The word encompasses all of humankind as a unitary whole.


text:
Q: How to extract frustum planes from Ortho matrix? I have extracted the frustum planes from a perspective matrix with some help from this homepage.
Can I use the same equations for an orthographic matrix?
************************UPDATED************************
I'm using cascaded shadow mapping(CSM) with 4 cascades and need therefore cull objects in different cascades from the lights perspective. It would be quite expensive to calculate the 6 frustum planes with this method:
Fore each cascade:

*

*Calculate the inverse matrix from the finalMatrix = lightOrthoMatrix * lightViewMatrix.

*Use the inverse final matrix and multiply it with the 8 frustum NDC corners to get the final frustum corners in world space.

*Use these corners to finally calculate the 6 frustum planes.

I discovered today that you can use the same "cheap" method to calculate the 6 frustum planes by extracting them from the final matrix. See this homepage. It doesn't matter if we use Perspective Projection or Orthographic Projection.


text:
Q: Prompt comes up when running report I have created a report from the following query
SELECT TasksEntries.Project, TasksEntries.Task, Sum(TimeTracker.WorkHours) AS
TotalHours
FROM TasksEntries INNER JOIN TimeTracker
ON (TasksEntries.EmployeeId = TimeTracker.EmployeeId) AND (TasksEntries.TaskID
= TimeTracker.TaskId)
GROUP BY TasksEntries.Project, TasksEntries.Task;

The start and end dates are captured from a form and passed like shown below. WorkDate is a column in the TimeTracker table and is not present in any other table.
strWhere = "WorkDate BETWEEN #" & txtMgrRptStartDate & "# AND #" &
txtMgrRptEndDate & "#"
DoCmd.OpenReport "rptTotalProjectHours", acViewPreview,
"qryTotalProjectHours", strWhere, acWindowNormal

When the report is invoked, I get a box where it says
"Enter parameter value" for Workdate.. I am unsure why I get that.
The query runs fine when I run it separately with the start and end dates hard coded in there. The problem seems to occur only when it is passed through the docmd.openreport. Can someone help me get to the bottom of this? When passing the WorkDate thru the OpenReport, is it mandatory that the column name be present in the SELECT statement?
Appreciate your help in advance.

A: I solved it by including the date criteria in the WHERE clause of the SELECT statement and specifying the form text box names of start and end dates.
The other thing that I did was to eliminate the query name from the Docmd.openreport since the report was created from the named query.


text:
Q: count function is showing by default value as 1 I am using count function of php to count the how many files are chosen while file uploading the files. Depend upon the count I want to apply some conditions. When no files chosen, then I checked the count value, its showing as 1, and when I chose a single file it shows 1, after selecting two files it will show count as 2. I am not getting whats going wrong here. Please find the below code,  I have written. Thanks for any suggsetions..
  $form['upload_fieldset']['file'] = array(
    '#type' => 'file',
    '#title' => 'Choose a File',
    '#name' => 'files[]',
    '#attributes' => array('multiple' => 'multiple'),

  );
function xxx_submit_file_upload($form, &$form_state) {
  $num_files = count($_FILES['files']['name']);

echo '<pre>';print_r($num_files);exit;//Here I am getting count as 1. if no files were chosen also.

A: Even if you don't have a file, $_FILES['files']['name'] is set to '' so it does count as 1.
You can check if a file is uploaded or not and then count :
$upload_error = $_FILES['files']['error'][0];

if ($upload_error === UPLOAD_ERR_NO_FILE) {
    $num_files = 0;
} else {
    $num_files = count($_FILES['files']['name']);
}

A: Below code is working for me. You can try it.
    $num_files = 0;
foreach ($_FILES['files']['name'] as $name) {
    if (!empty($name))
        $num_files++;
}

if( $num_files == 0 ){
    echo "No file selected";
}else{
    echo $num_files." files uploaded.";
}


text:
Q: What's the mistake I'm making in evaluating the below limit? $\lim_{x \to 0}\frac{x\sin(\sin x) - \sin^{2}x}{x^{6}}$ Below is my solution for this limit. I get $0$, but the answer, is in fact, $\frac{1}{18}$. What's the mistake I'm making?
{From here: A limit problem $\lim\limits_{x \to 0}\frac{x\sin(\sin x) - \sin^{2}x}{x^{6}}$}

$$\lim_{x \to 0}\frac{x\sin(\sin x) - \sin^{2}x}{x^{6}}$$
$$=\lim_{x \to 0}\frac{x\sin(\sin x)}{x^{6}}-\lim_{x \to 0}\frac{\sin^{2}x}{x^{6}}$$
$$=\lim_{x \to 0}\frac{x\sin(\sin x)}{x^{6}}\cdot\frac{\sin x}{\sin x}\cdot\frac{x}{x}-\lim_{x \to 0}\frac{\sin^{2}x}{x^{2}}\cdot\frac{1}{x^4}$$
$$=\lim_{x \to 0}\frac{\sin(\sin x)}{\sin x}\cdot\frac{\sin x}{ x}\cdot\frac{x^2}{x^6}-\lim_{x \to 0}\frac{1}{x^4}$$
$$=\lim_{x \to 0}\frac{1}{x^4}-\lim_{x \to 0}\frac{1}{x^4}
=\lim_{x \to 0}\left(\frac{1}{x^4}-\frac{1}{x^4}\right)=0$$

A: $$ \sin t = t - \frac{t^3}{6} + \frac{t^5}{120} \mp ...  $$
$$ \sin \sin x = \sin x -\frac{\sin^3 x}{6} + \frac{\sin^5 x}{120} \mp  $$
$$ \sin \sin x = \left( x - \frac{x^3}{6} + \frac{x^5}{120} \mp ... \right) - \frac{\left( x - \frac{x^3}{6} \pm \right)^3}{6} + \frac{\left( x - \mp \right)^5}{120} \pm $$
$$ \sin \sin x = \left( x - \frac{x^3}{6} + \frac{x^5}{120} \mp ... \right) - \frac{\left( x^3 - \frac{x^5}{2} \pm \right)}{6} + \frac{ x^5 - \mp }{120} \pm $$
$$ \sin \sin x =  x - \frac{x^3}{3} + \frac{x^5}{10} \mp  $$
$$ x \sin \sin x =  x^2 - \frac{x^4}{3} + \frac{x^6}{10} \mp  $$
$$  \sin^2 x =  x^2 - \frac{x^4}{3} + \frac{2 x^6}{45} \mp  $$
$$ x \sin \sin x - \sin^2 x =   \frac{x^6}{10} -  \frac{2 x^6}{45} \pm  $$
$$ x \sin \sin x - \sin^2 x =   \frac{9x^6}{90} -  \frac{4 x^6}{90} \pm  $$
$$ x \sin \sin x - \sin^2 x =   \frac{5x^6}{90} \pm  $$
$$ x \sin \sin x - \sin^2 x =   \frac{x^6}{18} + O( x^7)  $$
Meanwhile, the function depicted is even, all exponents in the final expression must be even, so we can say the slightly stronger
$$ x \sin \sin x - \sin^2 x =   \frac{x^6}{18} + O( x^8)  $$


text:
Q: How to transpose concatenated values in columns to rows Input:
item   number
ABC     123

I want to output like this:
item   number
 A       1
 B       2
 C       3

A: Split your you strings using split(), explode using posexplode() and use lateral view.
Split by empty string '' will generate arrays with extra empty elements, filter them out, connect items and numbers by their positions in array.
Demo (replace s subquery with your table):
select i.itm as item, n.nbr as number
from
(--replace this subquery with your table
 --this is two rows example
select stack(2,'ABC', '123',
               'DEF', '456') as (item, number)
) s --your_table
lateral view posexplode(split(s.item,'')) i as pos, itm
lateral view posexplode(split(s.number,'')) n as pos, nbr
where i.itm!='' and n.nbr!='' and i.pos=n.pos ;

Result:
OK
item    number
A       1
B       2
C       3
D       4
E       5
F       6
Time taken: 0.094 seconds, Fetched: 6 row(s)
hive>

Update: simplified version
select i.itm as item, substr(s.number,i.pos+1,1) as number
from
(--replace this subquery with your table
 --this is two rows example
select stack(2,'ABC', '123',
               'DEF', '456') as (item, number)
) s --your_table
lateral view posexplode(split(s.item,'')) i as pos, itm
where i.itm!='';


text:
Q: Применение нескольких эффектов к фото UWP Есть возможность применения фильтров к картинке, но могу применить только 1 фильтр, используется lumia imaging sdk. При разработке на Win 8.1 использовал массив с фильтрами и они сразу все применялись, здесь так не получается, есть какой-нибудь способ применить сразу несколько фильтров?
Код для применения эффекта:
  public async Task<bool> ApplyEffectAsync(StorageFile file)
    {
        WriteableBitmap temp = new WriteableBitmap(1280, 720);

            temp = new WriteableBitmap(1280, 720);
            FileStream = await File.OpenAsync(FileAccessMode.Read);
            temp.SetSource(FileStream);
            OriginalPicture = temp;
            FileStream.Seek(0);
            original.Invalidate();
            ((IImageConsumer) Effect).Source = new RandomAccessStreamImageSource(FileStream);
            M_renderer = new WriteableBitmapRenderer((IImageProvider)Effect, original);
            FilteringPicture = await M_renderer.RenderAsync();
            filtering.Invalidate();
        return true;
    }

A: Для применения эффектов вы можете использовать библиотеку Win2D
Пример можете найти здесь
Для совмещения нескольких эффектов там можно использовать CompositeEffect
Пример:
var myTextBitmap = new CanvasRenderTarget(sender, 300, 100);
using (var ds = myTextBitmap.CreateDrawingSession())
{
  ds.Clear(Color.FromArgb(0, 0, 0, 0));
  ds.DrawText("Неоновый текст!", 0, 0, Colors.White, new CanvasTextFormat
  {
      FontSize = 24,
      FontWeight = Windows.UI.Text.FontWeights.Bold
  });
}

var effectGraph = new CompositeEffect();
effectGraph.Mode = CanvasComposite.Add;

effectGraph.Sources.Add(new ColorMatrixEffect
{
  Source = new GaussianBlurEffect
  {
      Source = new MorphologyEffect
      {
          Source = myTextBitmap,
          Mode = MorphologyEffectMode.Dilate,
          Width = 7,
          Height = 4
      },
      BlurAmount = 3f
  },
  ColorMatrix = new Matrix5x4
  {
      M11 = 0f, M12 = 0f, M13 = 0f, M14 = 0f,
      M21 = 0f, M22 = 0f, M23 = 0f, M24 = 0f,
      M31 = 0f, M32 = 0f, M33 = 0f, M34 = 0f,
      M41 = 0f, M42 = 1f, M43 = 0f, M44 = 1f,
      M51 = 1f, M52 = -0.5f, M53 = 0f, M54 = 0f
  }
});

effectGraph.Sources.Add(myTextBitmap);
args.DrawingSession.DrawImage(effectGraph,100,100);

Кроме того можно использовать Lumia Imaging SDK, но как там с несколькими эффектами сказать не могу.

A: В Effect.Source необходимо передавать уже отфильтрованное ранее изображение, а не считывать его из FileStream


text:
Q: PlacesService creation failing with reference to an agm-map element When I try to create the PlacesService  using a reference to an agm-map element it fails. If I create a map dynamically (new google.maps.Map(somediv)) and use that map for a parameter it succeeds. I've condensed my code as much as I can to show the problem. First my map is declared like so.

  <agm-map [latitude]="lat" [longitude]="lng" [fitBounds]="bounds" [zoom]="zoom">
    <agm-marker *ngIf="repo.state == 2" [(latitude)]="repo.searchLocation.marker.lat"
      [(longitude)]="repo.searchLocation.marker.lng"
      [markerDraggable]="repo.searchLocation.marker.draggable"
      (dragEnd)='markerDragEnd($event)'></agm-marker>
  </agm-map>

I get my reference to the map like so:
   @ViewChild(AgmMap, { static: true })
   map: AgmMap;

To condense the code I've put my search in the MarkerDragEnd handler.
markerDragEnd(m: any, $event: any) {
    this.repo.searchLocation.marker.lat = m.coords.lat;
    this.repo.searchLocation.marker.lng = m.coords.lng;
    this.findAddressByCoordinates();

    let request = {
        location:  { lat: m.coords.lat, lng: m.coords.lng},
        radius: "25000",
        type: ["rv_park"]
    };

    let service = new google.maps.places.PlacesService(this.map);
    service.nearbySearch(request, (results, status) => {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            for (var i = 0; i < results.length; i++) {
                var place = results[i];
            }
        }
    });
}

I'm rewriting an app that was previously ASP.NET with razor pages and all of the work was done on the server. I had hoped to move the server work to the client side but this is failing miserably and the errors that I can find appear in the console of the debugger.
I don't know if it is clue but I see this error when the app launches and I'm not sure when it first started. I'm certain I've seen it before but have no clue what is causing it.
sockjs.js:1684 WebSocket connection to 'wss://localhost:5005/sockjs-node/826/5h1gkgu3/websocket' failed: Error during WebSocket handshake: Unexpected response code: 400

The next two errors appear immediately after executing the search code and again I'm clueless as to what causes them I see that they originate out of zone.JS I've tried running the code outside and inside the zone and still get the same errors. the first is this.h.getElementByTagName is not a function.
    core.js:4002 ERROR Error: Uncaught (in promise): TypeError: this.h.getElementsByTagName is not a
function
TypeError: this.h.getElementsByTagName is not a function
    at u$.attributionText_changed (places_impl.js:74)

The the second exception is the "NearBySearch" isn't a property of "null" after the service creation failed.
As I mentioned at the beginning what does succeed is to create a div with no height and create a second map dynamically and then use that for the PlacesService(fakemap) parameter and it works fine. I've tried several things to get this to work and only have the one html declared map but can't seem to get a correct reference to it.

A: Correct, AgmMap is an angular directive, not a google Map object.
What you want to do is the following:
map: GoogleMap;

  <agm-map [latitude]="lat" [longitude]="lng" [fitBounds]="bounds" [zoom]="zoom">
    <agm-marker *ngIf="repo.state == 2" [(latitude)]="repo.searchLocation.marker.lat"
      [(longitude)]="repo.searchLocation.marker.lng"
      (mapReady)="map = $event"
      [markerDraggable]="repo.searchLocation.marker.draggable"
      (dragEnd)='markerDragEnd($event)'></agm-marker>
  </agm-map>

I'd also point out that

*

*there is no latitudeChange event, so latitude cannot be
bidirectionally bound.

*your markerDragEnd expects two parameters,
but you're only sending one


text:
Q: Eager Loading - Only load Specific Records Quick question about eager loading. I have the following code:

@user =
  User.includes(:restaurants).find_by_unique_identifier(params[:unique_identifier])

However, I only want to load restaurants associated with a given user only if the restaurants have a list_id of X (which is one of the columns of the restaurants table).
How would I go about this?
I tried the following, but it still loaded all the restaurant records associated with the user.
@user = User.includes(:restaurants).where(:restaurants => {:list_id => params[:list_id]}).find_by_unique_identifier(params[:unique_identifier])

A: Assuming you have all the associations requirements setup, then you can use joins:
@user = User.all(:conditions =>["restaurants.list_id = ?", params[:list_id] ], :joins => [:restaurants])

UPDATE:
My code fetches a list of users. However, You can use your filtering methods to narrow down the list or get the individual records.


text:
Q: "Search" the members of an object in .NET's JIT debugger I'm a relatively new employee at my current company, so I'm still "drinking from the fire hose" in terms of learning my way around the software and architecture. I've found myself dealing with some very large objects while writing unit tests, let's say for discussion a "SavedOrder", and I need to find where to find a particular piece of data I'm looking for.
The problem I'm having is that I know that each SavedOrder has, somewhere in the innards of it's inheritances and members (who have members, of whom have members, and so on and so on), the piece of data I'm looking for.
For now I find myself mindlessly expanding my watches and mousing over the objects to hopefully find what I'm looking for. Does anybody know of a plugin/technique to use to find if this object has something of "Type A" or something of value "SomeEnum.SomeValue"?
EDIT: All good input, nothing yet that completely solves my goal. The object browsers (Object Browser and Reflector) do a good job of browsing the members of each object, but in the goal of linking point A to point D, they really just help in bringing point A to point B or D to C.
I guess the pseudo c# recursive algorithm that would best describe a solution would be:
WheresWaldo FindMember(Object o)
{
    foreach(PublicMember member in o)
    {
         if(o.IsType(MyType))
            return Success!;
         else
            return WheresWaldo(member);
    }

}

Who knows, maybe not possible.

A: I am not sure I follow you completely, but perhaps you could use a conditional break point. Set a break point on the relevant code, right click and select conditional break point. From here you can write a piece of code, that will be evaluated each time the break point is evaluated. That way you can specify to only stop when the condition is met.
EDIT: Based on your comments, I would say that Reflector may be useful. It has the option to search for specific types or members. Launch Reflector with you relevant assemblies. Press F3 for search and select Ctrl-M for members and type the name of the member you're looking for. You can toggle exact match on/off to help you with the search.

A: ObjectBrowser is probably what you want to use. You can search for properties using that.


text:
Q: Preventing git automatic file merge My company just wants to switch from Microsoft VSS to Git with KDiff3, and we ran into a problem.
As known, Git tracks contents instead of files. That is a great feature, and we love that. But it happens that two different parts of the same file has to be editied by two programmer at the same time.
Git tries to do a diff and a merge and if it can insert both editing into the final, it does that.
But there are many times when these two editings are exclusive to each other.
Example:
Original version:
<Grid>
  <Grid.RowDefinitions>
   <RowDefinition />
   <RowDefinition />
   <RowDefinition />
  </Grid.RowDefinitions>

</Grid>

Edit #1:
<Grid>
  <Grid.RowDefinitions>
   <RowDefinition />
   <RowDefinition />
   <RowDefinition />
  </Grid.RowDefinitions>

 <Button Content="Click here" Grid.Row="1" />
</Grid>

Edit #2:
<Grid>
  <Grid.RowDefinitions>
   <RowDefinition />
   <RowDefinition />
   <RowDefinition />
  </Grid.RowDefinitions>
 <CheckBox Content="Check it!" Grid.Row="1" />

</Grid>

As you can see, these two editions are not creating a merge conflict, but - if you are somewhat familiar with WPF, XAML - the Grid.Row attributes will "kill" each other, resulting an awkward visual.
So this "conflict" is not in the text, but in the logic.
Of course, this is a simple example, and with strict coding style it can be solved. But we are changing the version control system, so we have lots of codes like this, so we are simply not capable to rewrite the whole project by a new coding style.
Is it possible to tell Git or KDiff3 to just check if the files themselves are different, and that means conflict instead of the content?
Thanks,
SanTa

A: There are situations where text files should not be compared for merge due the nature of the file, such as a database file or a code generated file. With that thought one could make the files appear to git as binary data files which are not compared.
In the .gitattributes file specify this to setup a compare ignore type checkin situation:
*.xaml binary

To quote Git - Git Attributes

Some files look like text files but for all intents and purposes are
  to be treated as binary data. For instance, Xcode projects on the Mac
  contain a file that ends in .pbxproj, which is basically a JSON
  (plain-text JavaScript data format) dataset written out to disk by the
  IDE, which records your build settings and so on. Although it's
  technically a text file (because it's all UTF-8), you don't want to
  treat it as such because it's really a lightweight database – you
  can't merge the contents if two people change it, and diffs generally
  aren't helpful. The file is meant to be consumed by a machine. In
  essence, you want to treat it like a binary file.


text:
Q: Grant 'Log on as a service' permissions to a Network Service account for specific machine Is it possible to grant 'Log on as a service' permissions to a Network Service account for specific machine or domain and restrict it for Network Service accounts from all other machines or domains?
Properties: Log on as a service
For example, when I add DOMAIN\Network Service user to the list on the screenshot above, it automatically converts to Network Service user. Does it mean that there is no possibility to restrict 'Log on as a service' access to Network Service user from another machine or domain?


text:
Q: How to elegantly and imperatively generate the nth string of an alphabet? Given an alphabet such as: ["a","b","c","d"], the sequence of all strings made up from characters of that alphabet is:
""
"a"
"b"
"c"
"d"
"aa"
"ab"
"ac"
...

Haskell can generate the nth element of that sequence elegantly and recursively:
nth :: Int -> String
nth n = reverse $ alphabet !! n where
    alphabet = [""] ++ concatMap (\ str -> map (: str) "abcd") alphabet

But that's inefficient. Using base conversions, you could try generating it imperatively as (using JavaScript just for demonstration):
function nth(n) {
  var str = "";
  while (n > 0) {
    str += String.fromCharCode(97 + n % 4);
    n = Math.floor(n / 4);
  }
  return str;
};

for (var i = 0; i < 64; ++i) {
  console.log(nth(i));
}

But that actually generates the following sequence:
""
"b"
"c"
"d"
"ab"
"bb"
"cb"
"db"
"ac"
"bc"
"cc"
"dc"
"ad"
"bd"
"cd"
"dd"
"aab"

Which is not what was desired: notice the missing "a", "aa", "ba", etc. I'm probably missing some simple operation to fixes the imperative implementation, thus, my question is: is there any elegant way to imperatively generate the nth string of an alphabet?

A: Insert n-- at the beginning of the while loop. If you want the results in short lexicographic order, reverse the string before printing.


text:
Q: i am trying to get SHA1 to firebase console and when i ran gradlew signingReport on my android studio terminal an error i am trying to add SHA1 to my firebase console and when i ran gradlew signingReport i got this error
C:\Users\23480\StudioProjects\woerrortisunmi\android\app>build.gradle
     C:\Users\23480\StudioProjects\woerrortisunmi\android\app>gradle signingReport

     FAILURE: Build failed with an exception.

     * Where:
     Build file 'C:\Users\23480\StudioProjects\woerrortisunmi\android\app\build.gradle' line72

     * What went wrong:
     A problem occurred evaluating project ':app'.
     > Could not find method implementation() for arguments [androidx.browser:browser:1.0.0] on
   project ':app' of type org.gradle.api.Project.

  * Try:
  > Run with --stacktrace option to get the stack trace.
  > Run with --info or --debug option to get more log output.
  > Run with --scan to get full insights.

  * Get more help at https://help.gradle.org

  BUILD FAILED in 9s

this is what is in my android/app/build.gradle file
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
    localProperties.load(reader)
}
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the
local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID
(https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.woerrortisunmi"
        minSdkVersion 21
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    classpath "com.android.tools.build:gradle:7.4.2"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation platform('com.google.firebase:firebase-bom:30.0.2')
    implementation 'com.google.firebase:firebase-auth'
}
apply plugin: 'com.google.gms.google-services'
implementation 'androidx.browser:browser:1.0.0'

this is what is in my is my android/build.gradle file
buildscript {
    ext.kotlin_version = '1.6.10'
    repositories {
        google()
        mavenCentral()
        url "https://plugins.gradle.org/m2/"
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.4.2'
       // classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.0"
        classpath 'com.google.gms:google-services:4.3.10'
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
apply plugin: "org.jetbrains.kotlin.android"

this is what is in my gradle-wrapper.properties file
#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-all.zip

thanks in advance.

A: In your android/app/build.gradle file, you should not put your implementation for browser outside dependencies.
dependencies {
    classpath "com.android.tools.build:gradle:7.4.2"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation platform('com.google.firebase:firebase-bom:30.0.2')
    implementation 'com.google.firebase:firebase-auth'
}
apply plugin: 'com.google.gms.google-services'
implementation 'androidx.browser:browser:1.0.0'

Instead, try this
dependencies {
    classpath "com.android.tools.build:gradle:7.4.2"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation platform('com.google.firebase:firebase-bom:30.0.2')
    implementation 'com.google.firebase:firebase-auth'
    implementation 'androidx.browser:browser:1.0.0'
}
apply plugin: 'com.google.gms.google-services'


text:
Q: Canvas not showing I've followed tutorials regarding creating a canvas, however it is not working and neither is the rectangle drawn on it. Is it a necessity to have the script in the ? Any help would be appreciated!
Here's a JSFiddle with my code.
<!DOCTYPE html>

        <title>Simple animations in HTML5</title>

 Optical Illusion

<video id="illusion" width="640" height="480" controls>
    <source src="Illusion_movie.ogg">
</video>

     <button onclick="changeSize()">Big/Small</button>

Watch the animation for 1 minute, staring at the centre of the image. Then look at something else near you.
For a few seconds everything will appear to distort.
Source: Wikipedia:Illusion     movie

<canvas id= "myCanvas " width= "500 " height= "500 ">
    style="border:1px solid #000000;">
</canvas>

A: i think you need to remove ">" from this also remove the extra spaces
<canvas id= "myCanvas " width= "500 " height= "500 ">
    style="border:1px solid #000000;">
</canvas>

to become like so
<canvas id="myCanvas" width="500" height="500" style="border: 1px solid #000000;">
</canvas>

A: I've cleaned up your code you had a few spaces that were causing problems.

Also when you use the script tag set the type attribute:

Here's a corrected Fiddle: http://jsfiddle.net/8bK4y/
Edit: As pointed out below type attribute is not needed for the HTML5 Doctype.


text:
Q: Arduino mkr1000 does not Serial print upon GET using aRest library I'm trying to create a REST server on an arduino mkr1000. upon searching google i came upon the aRest library which handles most of the stuff i need.
aRest library documentation
So i created a sample sketch based on the guides. Here is the code:
#include < SPI.h >
#include < WiFi101.h >
#include < aREST.h >

aREST rest = aREST();

int status = WL_IDLE_STATUS;
WiFiServer restServer(80);

char ssid[] = "user";  // not actual username
char pass[] = "pass";  // not actual password

int clapMode(String data){
  Serial.println("Request Recieved: " + data);
}

void setup() {

 Serial.begin(115200);

 rest.set_id("000");
 rest.set_name("MKR1000");
 rest.function("test",clapMode);

 while ( status != WL_CONNECTED) {
   Serial.print("Attempting to connect to SSID: ");
   Serial.println(ssid);
   // Connect to WPA/WPA2 network. Change this line if using open or WEP
network:
   status = WiFi.begin(ssid, pass);
   // wait 10 seconds for connection:
   delay(10000);
 }

 Serial.println();

 // you're connected now, so print out the status:
 printWifiStatus();

 // Start server
 restServer.begin();
 Serial.println(F("Listening for connections..."));

}

void loop() {
  WiFiClient client = restServer.available();
    if (!client) {
    return;
  }
  while(!client.available()){
    delay(1);
  }
  rest.handle(client);
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  IPAddress subnet = WiFi.subnetMask();
  Serial.print("Netmask: ");
  Serial.println(subnet);

  IPAddress gateway = WiFi.gatewayIP();
  Serial.print("Gateway: ");
  Serial.println(gateway);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

The code works mostly. Upon using POSTMAN to perform a GET the arduino is able to give the appropriate response.
Now for the part that is not working is the endpoint i just have created using this code
rest.function("test",clapMode);

upon performing a GET in postman, the arduino is able to give a response, but it should perform this code
int clapMode(String data){
  Serial.println("Request Recieved: " + data);
}

but on my serial Monitor i am not getting anything.

Also i could not find on how to tailor the response of the arduino from the request. How do i it ?
Thank you very much

A: You have to send the request to <host>/test?params=0, not <host>/clapMode.
Furthermore, you can modify the ID and name with
rest.set_id("device ID");
rest.set_name("device name");

and add variables with
rest.variable("variable name", &variable);

The response is hard-coded into the library, therefore if you want to add/remove other stuff, you have to edit the library by yourself.


text:
Q: DTYPE Column discriminator as a Catalog class I everyone, I have the following
A user can have multiples profiles but each profile has its own function so I will have just one user entry and multiples roles entries
@Entity
@Table(name = "USER", indexes = {
        @Index(unique = false, columnList = "NAME,LAST_NAME,EMAIL")})
public class USER implements Serializable {

    private static final long serialVersionUID = 1L;
    @SequenceGenerator(name = "USER_SEQ", sequenceName = "USER_SEQ", allocationSize = 1)
    @GeneratedValue(generator = "USER_SEQ")
    @Id
    @Column(name = "ID_USER")
    private Long id;
    @Column(name = "NAME")
    private String name;
    @Column(name = "LAST_NAME")
    private String lastName;
    @Column(name = "EMAIL")
    private String email;
    // getters and setters
}

A parent class for each profile
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Profile implements Serializable {

    @SequenceGenerator(name = "PROFILE_SEQ", sequenceName = "PROFILE_SEQ", allocationSize = 1)
    @GeneratedValue(generator = "PROFILE_SEQ")
    @Id
    private Long idProfile;
    @ManyToOne(optional = false)
    private User user;

    //getters and setters

}

At least two son classes
@Entity
public class Administrator extends Profile{

}

@Entity
public class Regional extends Profile {

    public Regional () {
    }

    private Long idAsignedRegion;
    //getters and setters

}

So far I can select all of them or by specific profile, but now I want to have something in the front end for example a .xhtml page and I wish to have a select component representing all the DTYPES availables as objects in order to generate a strategy method for resolve at runtime each user/profile that the user enters
So my specifics questions are two

*

*Is there a way to get all the DTYPES availables in order to treat them as a catalog?

*Or there is a way to specify the DTYPE as a reference of a catalog?

Something like this
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(discriminatorType = ProfileCatalog.class, value="idProfileCatalog")
public abstract class Profile implements Serializable

Thanks!


text:
Q: How to create animation in html output using R Markdown Here is the list of things I've tried.
---
title: "test_gif"
output: html_document
---

``` {r, animation.hook='gifski', dev='png', interval=0.2}
library(gganimate)
ggplot(airquality, aes(Day, Temp, group = Month)) +
  geom_line() +
  transition_reveal(Month)
```

Error:
Quitting from lines 8-12 (test_gif.Rmd)
Error in hook_animation(options)(x, options) :
  To use hook_gifski(), the code chunk must generate 'png' images instead of 'gif'.
Calls:  ... hook_plot -> hook_plot_md_base -> hook_plot_html ->
Execution halted
Even though, I used dev = 'png' as mentioned here https://yihui.name/en/2018/08/gifski-knitr/, I couldn't able to make it work.
Then I've tried using FFmpeg renderer
---
title: "test_gif"
output: html_document
---

```{r, animation.hook='ffmpeg', interval=0.2}
library(gganimate)
ggplot(airquality, aes(Day, Temp, group = Month)) +
  geom_line() +
  transition_reveal(Month) -> p
animate(p)
```

Error: executing: ffmpeg -y -r 5 -i test_gif_files/figure-html/unnamed-chunk-1-%d.gif -b:v 1M -crf 10 test_gif_files/figure-html/unnamed-chunk-1.webm
ffmpeg version 4.2.1 Copyright (c) 2000-2019 the FFmpeg developers
  built with Apple LLVM version 10.0.0 (clang-1000.11.45.5)
  configuration: --prefix=/usr/local/Cellar/ffmpeg/4.2.1 --enable-shared --enable-pthreads --enable-version3 --enable-avresample --cc=clang --host-cflags='-I/Library/Java/JavaVirtualMachines/adoptopenjdk-12.0.1.jdk/Contents/Home/include -I/Library/Java/JavaVirtualMachines/adoptopenjdk-12.0.1.jdk/Contents/Home/include/darwin' --host-ldflags= --enable-ffplay --enable-gnutls --enable-gpl --enable-libaom --enable-libbluray --enable-libmp3lame --enable-libopus --enable-librubberband --enable-libsnappy --enable-libtesseract --enable-libtheora --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libx265 --enable-libxvid --enable-lzma --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librtmp --enable-libspeex --enable-videotoolbox --disable-libjack --disable-indev=jack --enable-libaom --enable-libsoxr
  libavutil      56. 31.100 / 56. 31.100
  libavcodec     58. 54.100 / 58. 54.100
  libavformat    58. 29.100 / 58. 29.100
  libavdevice    58.  8.100 / 58.  8.100
  libavfilter     7. 57.100 /  7. 57.100
  libavresample   4.  0.  0 /  4.  0.  0
  libswscale      5.  5.100 /  5.  5.100
  libswresample   3.  5.100 /  3.  5.100
  libpostproc    55.  5.100 / 55.  5.100
test_gif_files/figure-html/unnamed-chunk-1-%d.gif: No such file or directory
  |.................................................................| 100%
  ordinary text without R code
output file: test_gif.knit.md
/usr/local/bin/pandoc +RTS -K512m -RTS test_gif.utf8.md --to html4 --from markdown+autolink_bare_uris+tex_math_single_backslash+smart --output test_gif.html --email-obfuscation none --self-contained --standalone --section-divs --template /Library/Frameworks/R.framework/Versions/3.5/Resources/library/rmarkdown/rmd/h/default.html --no-highlight --variable highlightjs=1 --variable 'theme:bootstrap' --include-in-header /var/folders/pv/cs874rmn7dj9n08xdyc7s3nm0000gn/T//RtmpOqkC3V/rmarkdown-str28173033d049.html --mathjax --variable 'mathjax-url:https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML' --lua-filter /Library/Frameworks/R.framework/Versions/3.5/Resources/library/rmarkdown/rmd/lua/pagebreak.lua --lua-filter /Library/Frameworks/R.framework/Versions/3.5/Resources/library/rmarkdown/rmd/lua/latex-div.lua
File test_gif_files/figure-html/unnamed-chunk-1.webm not found in resource path
Error: pandoc document conversion failed with error 99
Execution halted
Then I followed this method, to save the gif using gifski::save_gif and then display in a subsequent chunk using include_graphics.
https://community.rstudio.com/t/make-an-rstudio-notebook-inline-animation-that-loops-with-gganimate/27489/2
---
title: "test_gif"
output: html_document
---

```{r}
library(gganimate)
library(gifski)
ggplot(airquality, aes(Day, Temp, group = Month)) +
  geom_line() +
  transition_reveal(Month) -> p
animate(p)
```

```{r, animation.hook='gifski', interval = 0.2}
p
```

Error(same):
Quitting from lines 18-19 (test_gif.Rmd)
Error in hook_animation(options)(x, options) :
  To use hook_gifski(), the code chunk must generate 'png' images instead of 'gif'.
Calls:  ... hook_plot -> hook_plot_md_base -> hook_plot_html ->
Execution halted
My end goal is to create animation in the final html document without producing any temporary files in-between. I would be happy even if there is any other alternative method to make this work.

A: With the gganimate package, you don't need to set the chunk option animation.hook. This is enough:
```{r, dev='png', interval=0.2}
library(gganimate)
ggplot(airquality, aes(Day, Temp, group = Month)) +
  geom_line() +
  transition_reveal(Month)
```


text:
Q: Java Spring Boot connection pool can't reconnect to DB when it restarts I currently have an issue with our java spring boot application where the tomcat connection pool can't reconnect to the mysql DB when it goes down. Our current process is to restart the application once the DB is back up or else the app never reconnects to the DB.
This is our current tomcat config:
internal.datasource.url=jdbc:mysql://localhost:3306/table?autoReconnect=true&failOverReadOnly=false&maxReconnects=10
internal.datasource.driver-class-name=com.mysql.jdbc.Driver

internal.datasource.jmx-enabled=true
internal.datasource.tomcat.defaultAutoCommit=false

# Tomcat JDBC Connection Pool properties
internal.datasource.tomcat.initial-size=5
internal.datasource.tomcat.min-idle=5
internal.datasource.tomcat.max-active=50
internal.datasource.tomcat.max-idle=10
internal.datasource.tomcat.min-evictable-idle-time-millis=600
internal.datasource.tomcat.time-between-eviction-runs-millis=3000
internal.datasource.tomcat.max-wait=15000
internal.datasource.tomcat.validation-query=SELECT 1 FROM DUAL
internal.datasource.tomcat.test-on-borrow=true
internal.datasource.tomcat.remove-abandoned=true
internal.datasource.tomcat.remove-abandoned-timeout=60
internal.datasource.tomcat.test-while-idle=true

Here is the stacktrace:
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 32,388,217 milliseconds ago.  The last packet sent successfully to the server was 1 milliseconds ago.
    at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:431)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.handleExistingTransaction(AbstractPlatformTransactionManager.java:433)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:353)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:463)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy189.createInventoryJob(Unknown Source)
    at com.att.eg.heads.ads.assist.bdms.etl.service.InventoryServiceImpl.generateInventoryCsvs(InventoryServiceImpl.java:135)
    at sun.reflect.GeneratedMethodAccessor261.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:283)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy201.generateInventoryCsvs(Unknown Source)
    at com.att.eg.heads.ads.assist.bdms.etl.service.job.Scheduler.performInventoryJob(Scheduler.java:66)
    at com.att.eg.heads.ads.assist.bdms.etl.service.job.Scheduler$$FastClassBySpringCGLIB$$e2dddb94.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:736)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.interceptor.AsyncExecutionInterceptor$1.call(AsyncExecutionInterceptor.java:115)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.lang.Thread.run(Thread.java:748)
Caused by: javax.persistence.PersistenceException: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 32,388,217 milliseconds ago.  The last packet sent successfully to the server was 1 milliseconds ago.
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1700)
    at org.hibernate.jpa.internal.TransactionImpl.begin(TransactionImpl.java:48)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:189)
    at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
    ... 29 common frames omitted
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 32,388,217 milliseconds ago.  The last packet sent successfully to the server was 1 milliseconds ago.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:990)
    at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3517)
    at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3417)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3860)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2524)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2675)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465)
    at com.mysql.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:4776)
    at sun.reflect.GeneratedMethodAccessor216.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)
    at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)
    at org.apache.tomcat.jdbc.pool.interceptor.AbstractCreateStatementInterceptor.invoke(AbstractCreateStatementInterceptor.java:79)
    at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)
    at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81)
    at com.sun.proxy.$Proxy161.setAutoCommit(Unknown Source)
    at io.opentracing.contrib.jdbc.TracingConnection.setAutoCommit(TracingConnection.java:85)
    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.begin(AbstractLogicalConnectionImplementor.java:67)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:238)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:214)
    at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:52)
    at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1512)
    at org.hibernate.jpa.internal.TransactionImpl.begin(TransactionImpl.java:45)
    ... 31 common frames omitted
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
    at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2969)
    at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3427)
    ... 53 common frames omitted

Not sure if I'm missing a configuration or if it is a limitation but any ideas are appreciated, thanks!


text:
Q: Fatal Error when implementing FriendsOfCake\Search to query a date range using CakePHP I'm trying to implement the FriendsOfCake\Search plugin in a CakePHP. I'm not 100% sure that I've implemented the search type correctly, but when I submit my form to try and use a date to search I'm receiving the following Fatal Error:

Error: Call to a member function format() on a non-object

I'm assuming somewhere along the way my date isn't being formatted as a date object, but not sure where I'm needing to do that at, if at all. Here are the code snippets I'm working with.
UsersTable.php - Inside of my searchConfiguration() method
    ->compare('created_start', [
        'field' => $this->aliasField('created')
    ])

index.ctp - Generation of my form
<?= $this->Form->label('created_start') ?>
<?= $this->Form->date('created_start') ?>

I think that's all, I have text boxes and select boxes working as a part of the form, it's just the date that I haven't been able to get up and running.
Here is the Stack Trace for the error message (I believe this is what was being asked for, it's the left hand column of my page.
Cake\Error\BaseErrorHandler->handleFatalError

Core/src/Error/BaseErrorHandler.php, line 90

Cake\Error\BaseErrorHandler->Cake\Error\{closure}

[internal function]

The full Error block says:
Error: Call to a member function format() on a non-object
File /var/www/<project_name>/vendor/cakephp/cakephp/src/Database/Type/DateTimeType.php
Line: 94

Line 94 of the DataTimeType.php is a part of the toDatabase() method. It is attempting to convert a datetime object into a string to use with the database. Specifically line 94
return $value->format($this->_format);

Using Cake version 3.1.0


text:
Q: How to erase duplicates of Child array in Parent array without hardcoring index I have two arrays as fallows,
NSArray *First=@[@"a", @"b", @"c",@"d", @"e", @"f",@"g", @"h", @"i", @"j", @"k"];
NSArray *Second=@[@"a",@"d", @"e",@"g",@"i"];

Now In a
 NSMutableArray *Result=[[NSMutableArray alloc]init];

When i NSLog result array i wnated the output as
[
b
c
f
h
j
k
]
Means the result array should delete the elements in second array from first array,And the condition is Witout usuingremoveObjectAtIndex Method
Thanks in-advance.

A: for (id object in First)
    if (![Second containsObject:object]) [Result addObject:object];

A: Following is the code to get output as you want Without using removeObjectAtIndex Method.Try this :
NSArray *First=@[@"a", @"b", @"c",@"d", @"e", @"f",@"g", @"h", @"i", @"j", @"k"];
    NSArray *Second=@[@"a",@"d", @"e",@"g",@"i"];

    NSMutableArray *result=[[NSMutableArray alloc]init];

    for (NSString *tempChar in First) {
        if (![Second containsObject:tempChar]) {

            [result addObject:tempChar];
            NSLog(@"result arr :%@",result);
        }
    }

A: // *** Most Efficient way to achieve with just 3 Lines of code ***
// *** `NSMutableSet` will do the job for you. ***
// *** method `minusSet` performs subtraction operation between two given sets. ***
NSMutableSet *first = [[NSMutableSet alloc] initWithArray:@[@"a", @"b", @"c",@"d", @"e", @"f",@"g", @"h", @"i", @"j", @"k"]];
NSMutableSet *second = [[NSMutableSet alloc] initWithArray:@[@"a",@"d", @"e",@"g",@"i"]];
[first minusSet:second];
NSLog(@"%@",first);

A: Without loop you can archive it with NSSet
NSMutableSet *firstSet1 = [NSMutableSet setWithArray: First];
NSSet *secondSet2 = [NSSet setWithArray: Second];
[firstSet1 minusSet: secondSet2];
NSArray * Result = [firstSet1 allObjects];


text:
Q: How to get a number from the Call log and use it to save to an Object - Android From the android device i do need to select a number from the CAll Log and use it to set in my own object . I am looking at CallLog.Calls but only outgoing is provided?

A: I use the following to query the Call Log.
    final String[] projection = null;
    final String selection = null;
    final String[] selectionArgs = null;
    final String sortOrder = "DATE DESC";
    Cursor cursor = _context.getContentResolver().query(
            Uri.parse("content://call_log/calls"),
            projection,
            selection,
            selectionArgs,
            sortOrder);
    if (cursor != null) {
        //Loop through the call log.
        while (cursor.moveToNext()) {
            //Common Call Log Items
            String callNumber = cursor.getString(cursor.getColumnIndex(
                                    android.provider.CallLog.Calls.NUMBER));
            String callDate = cursor.getString(cursor.getColumnIndex(
                                    android.provider.CallLog.Calls.DATE));
            String callType = cursor.getString(cursor.getColumnIndex(
                                    android.provider.CallLog.Calls.TYPE));
            String isCallNew = cursor.getString(cursor.getColumnIndex(
                                    android.provider.CallLog.Calls.NEW));
            //DO YOUR WORK HERE...
        }
    }

I hope this helps.


text:
Q: Disabling std. and file I/O in Python sandbox implementation I'm trying to set up a Python sandbox and want to forbid access to standard and file I/O. I am running the sandbox inside of a running Python server.
I've already looked at modules like RestrictedPython and PyPy; however, I want to be able to compile the sandbox code inside of my running Python server, not through an external process.
Are there any alternative ways to prevent access to commands like print, raw_input, or open? Could the aforementioned modules be used in a way where sandbox code is compiled in a running Python program?
At worst, how would you prevent access to raw_input?
EDIT: According to this tutorial on safely evaluating Python code, would it be possible to pass in a manipulated builtins module?

A: The rough consensus on this is that the complexity and introspection abilities of CPython make for unreliable attempts of blacklisting parts of the interpreter. I believe one of the major attempts was tav's safelite. It's also not that hard to cause CPython to crash, which opens another path to be exploited from running arbitrary code. Avoiding resource exhaustion or CPU-use DoS from arbitrary code is probably impossible to do in-process (you'd need a watchdog, system limits, etc.).
Something crucial for people wanting to have sandboxed code execution in Python is to avoid rolling your own (or simply modifying sys, __builtins__): it's very easy to convince yourself it's rock solid and yet miss some obvious workaround that bypasses your protection. Keep in mind Python used to include a module that offered this kind of protection and even that had glaring issues that allowed to escape its restrictions. IIRC, it was vulnerable to fishing non-restricted objects (via introspection) into the restricted environment.
That said, pysandbox is written by a core Python developer who believes it to be safe when restricting e.g. IO (and it incorporates a lot of previous research) and can run in-process like you want (albeit with a few less features, like DoS protections from CPU and memory use).


text:
Q: Reset plugins version cache | pre_set_site_transient_update_plugins In my plugin, I use those filters for auto-update and check the license.
add_filter( 'pre_set_site_transient_update_plugins', array( &$this, 'check_for_update' ) );
add_filter( 'plugins_api', array( &$this, 'plugin_api_call' ), 10, 3 );

But as I see, WordPress calls that filters once, when changed Version tag in my plugin.
Can anyone explain how I can reset that cache, for update user rules to download a new version of the plugin.
Thanks!

A: I find a solution. Just need use filter hook 'site_transient_update_plugins'
So that work
add_filter( 'site_transient_update_plugins', array( &$this, 'check_for_update' ) );
add_filter( 'plugins_api', array( &$this, 'plugin_api_call' ), 10, 3 );


text:
Q: How to find the lowest number in an array
This is the data frame. I'm trying to get the lowest number in the key column and create an additional column showing the lowest value. I was trying this but it isn't working.
def minUdf = udf((arr: dat1[String])=> {
  val filtered = arr.filterNot(_ == "")
  if(filtered.isEmpty) 0
  else filtered.map(_.toInt).min
})
dat1.select(col("placekey"), minUdf(col("key")).as("lowest_value").show(false)


text:
Q: Reevaluate command CanExecute on child model property change Currently we have the following models:
public class Model : ModelBase
{
    public Model()
    {
        ChildModel = new ChildModel();
    }

    public string FirstName
    {
        get { return GetValue<string>(FirstNameProperty); }
        set { SetValue(FirstNameProperty, value); }
    }

    public static readonly PropertyData FirstNameProperty = RegisterProperty("FirstName", typeof(string), string.Empty);

    public ChildModel ChildModel
    {
        get { return GetValue<ChildModel>(ChildModelProperty); }
        set { SetValue(ChildModelProperty, value); }
    }

    public static readonly PropertyData ChildModelProperty = RegisterProperty("ChildModel", typeof(ChildModel), null);
}

public class ChildModel : ModelBase
{
    public static readonly PropertyData TestStringProperty = RegisterProperty("TestString", typeof(string), null);

    public string TestString
    {
        get { return GetValue<string>(TestStringProperty); }
        set { SetValue(TestStringProperty, value); }
    }
}

We use a Model in our ViewModel
[Model]
public Model AModel
{
    get { return GetValue<Model>(AModelProperty); }
    private set { SetValue(AModelProperty, value); }
}

public static readonly PropertyData AModelProperty = RegisterProperty("Prescription", typeof(Model));

There is a command in our ViewModel with a CanExecute function.
I'd like the CanExecute to reevaluate any time a property in the Model or in the ChildModel changes.
Is there an easy way to do this?
(Note that our actual production model has multiple child models and lists that contain other ModelBases)
Currently i'm doing it by hooking into all the PropertyChanged events on all the child models, but this seems like a dirty way to do this.

A: You will need to write your own "watching mechanism". You can use the ChangeNotificationWrapper in Catel for this.
Whenever a child model updates, you can call ViewModelCommandManager.InvalidateCommands(true).


text:
Q: Suggestions for KSPA on undirected graph There is a custom implementation of KSPA which needs to be re-written. The current implementation uses a modified Dijkstra's algorithm whose pseudocode is roughly explained below. It is commonly known as KSPA using edge-deletion strategy i think so. (i am a novice in graph-theory).
Step:-1.  Calculate the shortest path between any given pair of nodes using the Dijkstra algorithm. k = 0 here.
Step:-2.   Set k = 1
Step:-3.   Extract all the edges from all the 'k-1' shortest path trees. Add the same to a linked list Edge_List.
Step:-4.  Create a combination of 'k' edges from Edge_List to be deleted at once such that each edge belongs to a different SPT (Shortest Path Tree). This can be done by inspecting the 'k' value for each edge of the combination considered. The 'k' value has to be different for each of the edge of the chosen combination.
Step:-5.   Delete the combination of edges chosen in the above step temporarily from the graph in memory.
Step:-6.   Re-run Dijkstra for the same pair of nodes as in Step:-1.
Step:-7.   Add the resulting path into a temporary list of paths. Paths_List.
Step:-8.   Restore the deleted edges back into the graph.
Step:-9.   Go to Step:-4 to get another combination of edges for deletion until all unique combinations are exhausted. This is nothing but choosing 'r' edges at a time among 'n' edges => nCr.
Step:-10. The 'k+1' th shortest path is = Minimum(Paths_List).
Step:-11. k = k + 1 Go to Step:-3, until k < N.
Step:-12. STOP

As i understand the algorithm, to get kth shortest path, 'k-1' SPTs are to be found between each source-destination pair and 'k-1' edges each from one SPT are to be deleted simultaneously for every combination.
Clearly this algorithm has combinatorial complexity and  clogs the server on large graphs. People suggested me Eppstein's algorithm (http://www.ics.uci.edu/~eppstein/pubs/Epp-SJC-98.pdf). But this white paper cites a 'digraph' and I did not see a mention that it works only for digraphs. I just wanted to ask folks here if anyone has used this algorithm on an undirected graph?
If not, are there good algorithms (in terms of time-complexity) to implement KSPA on an undirected graph?
Thanks in advance,

A: Time complexity: O(K*(E*log(K)+V*log(V)))
Memory complexity of O(K*V) (+O(E) for storing the input).
We perform a modified Djikstra as follows:

*

*For each node, instead of keeping the best currently-known cost of route from start-node. We keep the best K routes from start node

*When updating a nodes' neighbours, we don't check if it improves the best currently known path (like Djikstra does), we check if it improves the worst of the K' best currently known path.

*After we already processed the first of a nodes' K best routes, we don't need to find K best routes, but only have K-1 remaining, and after another one K-2. That's what I called K'.

*For each node we will keep two priority queues for the K' best currently known path-lengths.

*

*In one priority queue the shortest path is on top. We use this priority queue to determine which of the K' is best and will be used in the regular Djikstra's priority queues as the node's representative.

*In the other priority queue the longest path is on top. We use this one to compare candidate paths to the worst of the K' paths.


text:
Q: Opencv imread jpg and change quality Is there any function where I can change the quality of a JPG image without saving it first?
img = cv2.imread('image.jpg')
cv2.imwrite('image_high.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
img_high = cv2.imread('image_high.jpg')

Edit:
I edited the word 'increase' to 'change'.

A: Because JPEG uses lossy compression, when color components (Cb, Cr) are decimated, and all the components (Y, Cb, Cr) have losses also at the DCT, quantization stages - you can't just "increase the quality" of the compressed image, because some information (moslty high-frequency and color) is already lost.
You can take a look at this great paper for further information about JPEG techniques.
By the way, there is lossless variation of JPEG.


text:
Q: Format javascript array with multiple key and value So after i got all data separately how can i organize my array look like this:
var arr = [{_1489378560544_544 : [customer_group_id : 0 , permission_id : 'permission_id'] }]

Here is my javascript get data function:
$('#category_permission > tbody > tr').each(function() {
            var id = $(this).attr("id");
            var customer_group_id = $(this).children('td:first').children('select:first').val();
            var permission_id = $(this).children('td:nth-child(2)').children('select:first').val();
        });

Thank for your help!

A: I think array is not keys and values. object only have keys and values.so use like this
var arr=[];
    var n =[];

    $('#category_permission > tbody > tr').each(function() {
                var id = $(this).attr("id");
                var customer_group_id = $(this).children('td:first').children('select:first').val();
                var permission_id = $(this).children('td:nth-child(2)').children('select:first').val();

          var  inside = {
           customer_group_id : customer_group_id,
            permission_id: permission_id,
            }
            n.push(inside)
               var k ={
               _1489378560544_544:n,
               }
             arr.push(k)
              });

    console.log(arr)

var arr = [{
  _1489378560544_544: [{customer_group_id: 0, permission_id: 'permission_id'}]
}]

console.log(arr)

It give the result look like this


text:
Q: Projetos criados com o Ionic 2 não executam Crio meus projetos sem problemas, mas ao comando: ionic serve, tenho o seguinte resultado:
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Users\\allan\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'ionic:serve',
1 verbose cli   '--',
1 verbose cli   '--v2',
1 verbose cli   '--address',
1 verbose cli   '0.0.0.0',
1 verbose cli   '--port',
1 verbose cli   '8100',
1 verbose cli   '--livereload-port',
1 verbose cli   '35729' ]
2 info using npm@4.4.4
3 info using node@v6.10.1
4 verbose run-script [ 'preionic:serve', 'ionic:serve', 'postionic:serve' ]
5 info lifecycle ionic-hello-world@~preionic:serve: ionic-hello-world@
6 silly lifecycle ionic-hello-world@~preionic:serve: no script for preionic:serve, continuing
7 info lifecycle ionic-hello-world@~ionic:serve: ionic-hello-world@
8 verbose lifecycle ionic-hello-world@~ionic:serve: unsafe-perm in lifecycle true
9 verbose lifecycle ionic-hello-world@~ionic:serve: PATH: C:\Users\allan\AppData\Roaming\npm\node_modules\npm\bin\node-gyp-bin;C:\Users\allan\Documents\workspace-ionic\app2\node_modules\.bin;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\Git\cmd;C:\Users\allan\AppData\Local\Android\sdk\platform-tools;C:\Program Files\nodejs\;C:\Users\allan\AppData\Local\Microsoft\WindowsApps;C:\Users\allan\AppData\Local\atom\bin;C:\Users\allan\AppData\Roaming\npm
10 verbose lifecycle ionic-hello-world@~ionic:serve: CWD: C:\Users\allan\Documents\workspace-ionic\app2
11 silly lifecycle ionic-hello-world@~ionic:serve: Args: [ '/d /s /c',
11 silly lifecycle   'ionic-app-scripts serve "--v2" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"' ]
12 silly lifecycle ionic-hello-world@~ionic:serve: Returned: code: 1  signal: null
13 info lifecycle ionic-hello-world@~ionic:serve: Failed to exec ionic:serve script
14 verbose stack Error: ionic-hello-world@ ionic:serve: `ionic-app-scripts serve "--v2" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"`
14 verbose stack Exit status 1
14 verbose stack     at EventEmitter.<anonymous> (C:\Users\allan\AppData\Roaming\npm\node_modules\npm\lib\utils\lifecycle.js:279:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:191:7)
14 verbose stack     at ChildProcess.<anonymous> (C:\Users\allan\AppData\Roaming\npm\node_modules\npm\lib\utils\spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:191:7)
14 verbose stack     at maybeClose (internal/child_process.js:886:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid ionic-hello-world@
16 verbose cwd C:\Users\allan\Documents\workspace-ionic\app2
17 verbose Windows_NT 10.0.14393
18 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\allan\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "run" "ionic:serve" "--" "--v2" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"
19 verbose node v6.10.1
20 verbose npm  v4.4.4
21 error code ELIFECYCLE
22 error errno 1
23 error ionic-hello-world@ ionic:serve: `ionic-app-scripts serve "--v2" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"`
23 error Exit status 1
24 error Failed at the ionic-hello-world@ ionic:serve script 'ionic-app-scripts serve "--v2" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"'.
24 error Make sure you have the latest version of node.js and npm installed.
24 error If you do, this is most likely a problem with the ionic-hello-world package,
24 error not with npm itself.
24 error Tell the author that this fails on your system:
24 error     ionic-app-scripts serve "--v2" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"
24 error You can get information on how to open an issue for this project with:
24 error     npm bugs ionic-hello-world
24 error Or if that isn't available, you can get their info via:
24 error     npm owner ls ionic-hello-world
24 error There is likely additional logging output above.
25 verbose exit [ 1, true ]

Todos os novos projetos estão assim. Projetos mais antigos rodam normalmente. Alguém pode me ajudar?

A: Segundo a mensagem de erro, você pode estar rodando uma versão mais antiga ou incompatível do node.js ou npm. Neste caso, recomendo que tente instalar a versão mais atual (caso não a tenha já). Você pode instalar pelo prompt de comando (assumindo que esteja usando Windows) usandonpm install -g npm-windows-upgrade.Fora isso, a mensagem indica que você pode obter mais informações do bug rodando o comando npm bugs ionic-hello-world.


text:
Q: How to to add a Content Query WebPart programatically and use a SPSIteDataquery? This is the current scenario.
I have a central site called: XXX.
I have many subsites called with the year name: 2012, 2011, 2010, etc.
In the central site I have a list called Beneficiaries.
In ALL year sites I have a list called Request, every one of those lists have a lookup column to the Beneficiaries list in the central site.
I need to create one webpart in the central site to show all the Requests that a  Benefeciary has in all sub sites. (year sites).
I wonder if the contentquery webpart will do the work because I think I will have to use spsitedataquery not use spquery.
This is the code I have so far.
/// <summary>
        /// Update dashboard beneficieries.
        /// </summary>
        /// <param name="currentUnsafeWeb"></param>
        private void UpdateDashboardBeneficiaries(SPWeb currentUnsafeWeb)
        {
            Logger.LogDebug("NLSubsidiesSiteConfigSubsidyCentralEventReceiver", "UpdateDashboardBeneficiaries(SPWeb currentUnsafeWeb)", "BEGIN");

            SPFile page = null;
            try
            {
                page = currentUnsafeWeb.GetFile("beneficiaries.aspx");
                page.CheckOut();

                //Add Content Query WebPart or something else to show all request in all yearsubsites that are related to the beneficiaries list.

                page.CheckIn(string.Empty);

            }
            catch (Exception)
            {
                if (page != null) page.UndoCheckOut();
                throw;
            }

            Logger.LogDebug("NLSubsidiesSiteConfigSubsidyCentralEventReceiver", "ConfigureDashboardBeneficiaries(SPWeb currentWeb)", "END");
         }

A: this post pointed me in the right direction.
http://msdn.microsoft.com/en-us/library/aa981241.aspx


text:
Q: How to add a column in a pandas dataframe with values that repeat? If I have a pandas dataframe that looks like this:
     X [ m ]  Y [ m ]  Z [ m ]
0         1     1      0.0
1         2     0.5    0.1
2         3     2      0.3
3         4     1      0.4
4         5     3      0.5
5         1     4      0.6
6         2     1.5    0.8
7         3     6      1.0
8         4     3      1.2
9         5     4      1.5
...

How would I add a fourth column (Z_2) that would look like this (only include values that are a 0.5 jump):
     X [ m ]  Y [ m ]  Z [ m ]  Z_2 [ m ]
0         1     1      0.0      0.0
1         2     0.5    0.1      0.0
2         3     2      0.3      0.5
3         4     1      0.4      0.5
4         5     3      0.5      0.5
5         1     4      0.6      0.5
6         2     1.5    0.8      1.0
7         3     6      1.0      1.0
8         4     3      1.2      1.0
9         5     4      1.5      1.5
...

A: You can try :
df["Z_2"] = (df["Z"] // 0.5) * 0.5

If you're talking about only 0.5 "jump"in the Z column.

A: You could try something like:
df["Z_2"] = (df["Z"] % .5 == 0).cumsum() * .5

Here the df["Z"] % .5 == 0 finds the values in df["Z"] that are on the .5 boundary, the cumsum will only add 1 when a True is encountered.


text:
Q: Django JSONField string containment Using Django 1.10's JSONField, i want to filter queryset by the json field that have a value at specific key that contains a sub string (sql like).
e.g. there is a json field link, with the url key. i want the objects that it's url contains .jpg

A: If you can, I will create this with a 'get_queryset' function for the view/model:
    def get_queryset(self):
        queryset = Entry.objects.all()
        json = params.get('json', None)
        if json is not None:
            """ DO STUFF HERE TO STRIP THE JSON TO THE WANTED LINK """
            q = queryset.filter(json__icontaints=".jpg")
        return q

read more about this subject here: https://docs.djangoproject.com/en/1.10/topics/db/queries/


text:
Q: How do I get the document id by clicking the button on the tableview cell? I am using a xib file apart from the main storyboard in my view controller for displaying a post item, and there is comment button, upon being clicked it should go to another page where the list of comments related to that post is available. for that I need to pass the documentId of the post as well so that the accurate segue operation could be performed.
I have tried my things by searching google but till now nothing had worked for me.
if any more details are required please let me know
HomeViewController Swift Class
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView:UITableView!

    var posts = [Post]()
    var db: Firestore!

    var postKey:String = ""
    private var documents: [DocumentSnapshot] = []
    //public var posts: [Post] = []
    private var listener : ListenerRegistration!

    var detailView: Post?

    override func viewDidLoad() {
        super.viewDidLoad()

        db = Firestore.firestore()

        self.navigationController?.navigationBar.isTranslucent = false
        tableView = UITableView(frame: view.bounds, style: .plain)

        let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: "postCell")
        tableView.backgroundColor = UIColor(white: 0.90,alpha:1.0)
        view.addSubview(tableView)

        var layoutGuide:UILayoutGuide!

        if #available(iOS 11.0, *) {
            layoutGuide = view.safeAreaLayoutGuide
        } else {
            // Fallback on earlier versions
            layoutGuide = view.layoutMarginsGuide
        }

        tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true

        tableView.delegate = self
        tableView.dataSource = self
        tableView.reloadData()
        retrieveAllPosts()
        //checkForUpdates()
        postKey = detailView!._documentId

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
        cell.set(post: posts[indexPath.row])
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let post = self.posts[indexPath.row]

        performSegue(withIdentifier: "toCommentsList", sender: indexPath)
    }

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       //segue.forward(posts, to: segue.destination)
        guard let details = segue.destination as? CommentListViewController,
        let index = tableView.indexPathForSelectedRow?.row

       else {
        return
        }
       // details.detailView = posts[index]

    }
    //I tried to connect this action to the button in the XIB file but not able to do so.
    @IBAction func toCommentsSection(_ sender: Any) {

        print(postKey + "hello")
        //  let postId11 = detailView?._documentId
        performSegue(withIdentifier: "toCommentsList", sender: self)

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        var vc = segue.destination as! CommentListViewController
        vc.postId = postKey
    }

}

PostViewCell Class
class PostTableViewCell: UITableViewCell {

    @IBOutlet weak var usernameLabel: UILabel!
   @IBOutlet weak var profileImageView: UIImageView!
    @IBOutlet weak var subtitleLabel: UILabel!
    @IBOutlet weak var postTextLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

       // profileImageView.layer.cornerRadius = profileImageView.bounds.height / 2
       // profileImageView.clipsToBounds = true
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func set(post:Post) {
      if let userprofileImagUrl =  post._postuserprofileImagUrl,
            let imageUrl = URL(string: userprofileImagUrl) {
            ImageService.getImage(withURL: imageUrl) { image in
                self.profileImageView.image = image
            }
        }
        usernameLabel.text = post._username
        postTextLabel.text = post._postContent
        subtitleLabel.text = post._postcategory
    }

}

A: In PostTableViewCell create outlet of comment buttons
class PostTableViewCell: UITableViewCell {

@IBOutlet weak var btnComment: UIButton!

now in cellForRowAtIndex do add following line too
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.btnComment.tag = indexPath.row
cell.btnComment.addTarget(self, action: #selector(self. toCommentsSection(sender:)) , for: .touchUpInside)
    cell.set(post: posts[indexPath.row])
    return cell
}

and in
 @IBAction func toCommentsSection(_ sender: Any) {

    let commentbutton = sender as! UIButton
    let post = posts[commentbutton.tag]
    postKey = post.postKey // or what key value it is
    print(postKey + "hello")
    //  let postId11 = detailView?._documentId
    performSegue(withIdentifier: "toCommentsList", sender: self)

}


text:
Q: Max-height overflow issue I am working on a modal window, trying to get its height to set automatically (with a max-height previously set). But, when the height is set to 'auto', the inner div does not create a scroll bar, making it impossible to read its content.
The question is: How could I have a automatic height, while maintaining the inner scroll bar?
I made a fiddle to demonstrate: https://jsfiddle.net/x1um8tqz/6/
Here is the modal basic structure:

        Header

And the CSS:
.fade {
  position: fixed;
  background: rgba(0,0,0,0.4);
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

.modal {
  position: absolute;
  background: #fff;
  border-radius: 5px;
  width: 400px;
  max-height: calc(100% - 100px);
  height: auto;
  /* Works but window will be always max height */
  /*height: calc(100% - 100px);*/
  top: 50px;
  left: calc(50% - 200px);
  overflow: hidden;
}

.modal-contents {
  position: relative;
  width: 100%;
  height: 100%;
}

.modal-header {
  height: 25px;
  padding: 0 10px;
  line-height: 25px;
}

.modal-body {
  height: calc(100% - 25px);
  overflow: auto;
}

A: Update 2
Perhaps this is a little more what you wanted?

.fade {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.4);
}
.modal {
  width: 80%;
  margin: 0 auto;
}
.modal-contents {
  margin: 100px 5px;
  padding: 5px;
  border-radius: 5px;
  background-color: white;
  min-height: 1px;
}
.modal-header {
  font-weight: 600;
  height: 25px;
  line-height: 25px;
}
.modal-body {
  min-height: calc(100% - 25px);
  max-height: 80vh;
  overflow: auto;
}

        Header

        Test

123

Test

123

Test

123

Test

123

Test

123

Test

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nemo, ipsa.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat, odio!

Incidunt consequuntur consectetur praesentium, optio nulla maiores maxime culpa quisquam?

Perferendis similique cupiditate cum expedita mollitia temporibus quam doloremque nemo.

Temporibus aperiam cumque amet, necessitatibus modi repudiandae! Tenetur, magni, error!

Expedita et libero tenetur consequatur explicabo esse, quibusdam nulla voluptas.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem modi, facilis quas, accusamus illum ex quidem magni consectetur similique saepe cupiditate. Culpa, cum, expedita. Aut reprehenderit velit deserunt minus placeat.

Voluptate aliquam autem soluta pariatur ducimus qui molestias doloremque officia alias sapiente corrupti recusandae possimus fuga laudantium, assumenda minus est blanditiis, ex voluptas ab ipsam natus. Quidem doloribus voluptate illum.

Delectus inventore neque optio sequi deserunt. Quaerat nisi, autem alias quas quo veritatis dolore ullam, aliquid deserunt, aspernatur consequatur eligendi? Minus dolorem, illo accusantium dolorum magnam porro asperiores temporibus nesciunt.

Accusantium culpa nam vero in quae eveniet ipsam dolorum quo nihil maiores. Esse aspernatur eos quibusdam, temporibus reiciendis reprehenderit omnis cumque aliquam tenetur et! Qui praesentium beatae reiciendis repellendus quos.

Debitis ullam perspiciatis, ratione dolorem repellat odit incidunt placeat cumque enim aliquid culpa esse, sit fugit harum quisquam animi. Mollitia sequi est ad, expedita commodi dignissimos officiis, debitis quia fugiat!

Update 1
This is a very hacky solution, but basically I just made the position of the header element fixed, made its z-index higher and gave it a background. I also had to change the padding of the .modal-body element. Give me a bit more time to fiddle with this and I'll post another update.
Original
I believe this does what you want. By default (unless I'm totally mistaken and if I am someone please let me know) the height for elements is auto, so there's no real need to declare it. I tested it a few different times by adding in paragraphs to allow the scroll and taking it out to make sure that the div shrank.

.fade {
  position: fixed;
  background: rgba(0, 0, 0, 0.4);
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}
.modal {
  position: absolute;
  background: #fff;
  border-radius: 5px;
  width: 400px;
  max-height: calc(100% - 100px);
  /* Works but window will be always max height */
  /*height: calc(100% - 100px);*/
  top: 50px;
  left: calc(50% - 200px);
  overflow-y: auto;
}
.modal-contents {
  position: relative;
  width: 100%;
  height: 100%;
}
.modal-header {
  position:fixed;
  height: 25px;
  padding: 0 10px;
  line-height: 25px;
  z-index:100;
  background-color:white;
}
.modal-body {
  padding-top:25px;
  height: calc(100% - 25px);
  overflow: auto;
}

        Header

        Test

123

Test

123

Test

123

Test

123

Test

123

Test

123

Test

123

Test

123

Test

123

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nemo, ipsa.

A: I erased the height from .modal-contents (making it auto that way and allowing it to get higher) and added overflow-y: auto; to modal. If you erase some of the sample content infrom the HTML, you'l see the height shrinking (which I think is what you also wanted - if not, add a min-height setting).
.fade {
  position: fixed;
  background: rgba(0,0,0,0.4);
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

.modal {
  position: absolute;
  background: #fff;
  border-radius: 5px;
  width: 400px;
  max-height: calc(100% - 100px);
  height: auto;
  top: 50px;
  left: calc(50% - 200px);
  overflow-y: auto;
}

.modal-contents {
  position: relative;
  width: 100%;
}

.modal-header {
  height: 25px;
  padding: 0 10px;
  line-height: 25px;
}

.modal-body {
  height: calc(100% - 25px);
  overflow: auto;
}

Here it is in a fiddle: https://jsfiddle.net/en5fb3mf/
ADDITION/EDIT after seeing comments to other answers: Here is a version with a fixed header: https://jsfiddle.net/en5fb3mf/2/

A: Changing the overflow property on .modal seemed to do the trick.
Switch overflow: hidden; to overflow: scroll


text:
Q: Remove word only for first line using php I have text:
I have new blue car
I have new red and blue cars

How remove what word i want from first line using php?
Ex:
        $text = preg_replace("/^(blue>){1}/", "", $text);

The result should be:
I have new car
I have new red and blue cars

And i want example for remove "p br " it is posible.

I have new blue car
I have new red and blue cars

A: The following will find the first row, replace the 'blue' word on that line with nothing (remove it), strip tags and remove leading/trailing space.

*

*Will only remove whole words, e.g. not 'blue' in 'blues'

*Will not remove word from following lines if not found in first line

*Will not strip tags from following lines

Code:
$text = "

I have new blue car
I have new red and blue cars";
$word = 'blue';

$text = preg_replace_callback(
    '/.*$/m', // Match single line
    function ($matches) use ($word) {
        // Remove word (\b = word boundary), strip tags and trim off whitespace
        return trim(
            strip_tags(
                preg_replace('/\b' . $word. '\s*\b/', '', $matches[0])
            )
        );
    },
    $text,
    1 // Match first line only
);

echo $text, PHP_EOL;

Output:
I have new car
I have new red and blue cars


text:
Q: Big Sur keyboard shortcut to select text Before upgrading to Big Sur I was able to use Shift-Command-Left/Right arrow to highlight a single word while typing.  This was in any app - email, browser, text, etc.
After upgrading to Big Sur, that command now changes the color profile.
For what it's worth, Shit-Left/Right arrow will still highlight a single character.  Shift-Command-Left/Right arrow will still highlight the start/end of the line of text.  And Option-Left/Right arrow still moves the cursor one word at a time.
I'm just missing the option to highlight one word at a time.
I know how to add keyboard shortcuts but not sure the best way to change this back?

A: Testing in macOS Big Sur and macOS Catalina, the shiftoptionleft/right arrow keyboard shortcut highlights one word at a time.
By default shiftcommandleft/right arrow highlights from the cursor to the end/beginning of the line.


text:
Q: When is best way to open a file to write to? Let's say I need to crunch some data and then write the results to some file.
Would it be better to open the file first, then process the data, then write to the file?
with open('file', 'w') as f:
    summary = process_data()
    f.write(summary)

Or would it be better to open the file just before writing to it?
summary = process_data()
with open('file', 'w') as f:
    f.write(summary)

My intuition tells me that if process_data() requires a lot of memory and if file is large, there may be some issues with the first approach.
Edit:
To clarify from some of the responses, what are the pros and cons of each approach?

A: Python doesn't have c-like scopes, only scoping constructs are def and class blocks, so summary is not cleaned up after with block has ended in the second example.
I can think of only one difference: opening file in a write mode clears it, so if the process_data takes a long time inside the with block - it leaves file in an empty state for longer.
If that's not a concern this is 2+3 vs 3+2.

A: define better...
I can think of a few aspects:

*

*Amount of time the file is takes - if this file is needed by other users, it would be best to keep it open for your usage as little as possible --> process before

*Clean coding - the with statement is neater than the open + close --> process inside

My intuition tells me that if process_data() requires a lot of memory and if file is large, there may be some issues with the first approach.

The size of file shouldn't matter, as you don't read it, you only open it for writing...