text:
Q: Async call using Java thread I have two methods in my application, that want to be executed one after other.
removeAllNonSyncedData();
getFullDbFromREST();

First method is removeAllNonSyncedData() which remove all of non sync data from db.
When all data get cleared, I want to execute getFullDbFromREST()
private void removeAllNonSyncedData() {
        try {

            ContentResolver cr = getContentResolver();
            ContentProviderHelp helper = new ContentProviderHelp();

            ObjectPropertyValueTable ObjectPropertyValueTable = new ObjectPropertyValueTable(helper);
            ObjectPropertyValueAuditTrailTable ObjectPropertyValueAuditTrailTable = new ObjectPropertyValueAuditTrailTable(helper);
            PhotoInfoTable PhotoInfoTable = new PhotoInfoTable(helper);
            PropertyDefinitionTable PropertyDefinitionTable = new PropertyDefinitionTable(helper);

            SyncManagerTable SyncManagerTable = new SyncManagerTable(helper);

            cr.delete(ObjectPropertyValueTable.getContentURI(), ObjectPropertyValueTable.SyncStatus+"<>1", null);
            cr.delete(ObjectPropertyValueAuditTrailTable.getContentURI(), null, null);
            cr.delete(SyncManagerTable.getContentURI(), null, null);
            cr.delete(PhotoInfoTable.getContentURI(), PhotoInfoTable.SyncStatus+"<>1", null);

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

How can I execute the second method after first method is done (data cleared completely from database) ?

A: Well, this is the default case, unless you call the first method asynchronously. Otherwise, methods are always executed one after the other.

A: I have already achieve that kind of condition using thread like that
I want to write a file after complete write then i want to Read a file so i make two thread read and write like following manner and user wait and notify function.
public  Object isWrite=new Object();
    private class WriteThread extends Thread {
        @Override
        public void run() {
            super.run();
            synchronized (isWrite){
                        //Do something as you want
                        isWrite.wait();
        }
}
}

    private class ReadThread extends Thread {
        @Override
        public void run() {
            super.run();
            synchronized (isWrite){
                      //Do something as you want
                      isWrite.notify();

        }
}
}

        //Calling of write thread then read thread.
        try {
            WriteThread mWriteThread=new WriteThread();
            mWriteThread.start();

            mReadThread = new ReadThread();
            mReadThread.start();

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


text:
Q: Find all entries that contain more than one colon character I need to find all entries that contain more than one colon (:) character.
However when I do LIKE %:% it shows the entire table because of http://. How can I find more than one colon?
SELECT *
FROM  `downloads`
WHERE  `url` LIKE  '%:%'
LIMIT 0 , 30

A: If you want to find a colon that occurs after the scheme of your URL, then change your LIKE clause accordingly:
SELECT *
FROM  `downloads`
WHERE  `url` LIKE  '%:%:%'
LIMIT 0 , 30

The first colon will be in your scheme, and the second will be somewhere else in the Url after the scheme.
A word of caution, however - it is completely valid to have a colon in the Url when a port number is specified, e.g.: http://localhost:8080

redpajama_set_name: RedPajamaStackExchange


text:
Q: syntaxError: (unicode) error 'utf-8' codes can't decode byte 0xfb in position 0: invalid start byte

Доброго времени суток.
Пытаюсь написать в команде print('любой текст с русскими буквами') и собственно ничего не получается. Пишу на английском языке текст, все работает.
Не подскажете как исправить?
Язык - Python

A: Если у вас python2, то у вас все строки по умолчанию - байтовые. Следовательно при попытке вывести получаете ошибку.
Чтобы байтовую строку перевести в unicode строку нужно либо добавить явное преобразование типов (напр. print(unicode(my_string)) ), либо, если строка задаётся прямо в файле или интерпретаторе, указать python'у, что это юникод-строка добавив символ 'u' перед открывающей кавычкой, например, print(u'строка')
Для решения этой проблемы в последних версиях python 2 (в частности в 2.7) произведено портирование юникодовых строк из python 3. Чтобы все строки в файле .py стали юникодовыми необходимо добавить вверху файла
from __future__ import unicode_literals

Если вы пытаетесь сделать это в файле .py, то необходимо указать первой строкой кодировку этого файла, так как python2 считает это ascii файлом. Это можно сделать добавив строку
# -*- coding: utf-8 -*-

в начало файла.
В python 3 все строки unicode и таких проблем обычно не возникает.
Обновлено 2
Исправьте файл, чтобы он выглядел так
# -*- coding: utf-8 -*-
print('ку-ку')

Обновлено 3
coding: utf-8 лишь говорит python, что содержимое файла следует интерпретировать как utf-8. Проверьте в вашем редакторе действительно ли это так. Мне кажется если решение выше не поможет, то проблема именно в этом - ваш редактор сохраняет в windows-1251 кодировке. Надо найти где это настраивается и изменить


text:
Q: Switching View Controllers I tried to search this site and all over the internet, but I haven't found a way that will let me switch between multiple view controllers while sharing data between them.
I tried to use the following code (the first method calls another method then switches view):
-(IBAction) choosePhoto:(id)sender {
[self startMediaBrowserFromViewController: self
                            usingDelegate: self];
if(firstViewController.view.superview == nil)
{
    [secondViewController viewWillAppear:YES];
    [firstViewController viewWillDisappear:YES];

    [firstViewController.view removeFromSuperview];
    [self.view insertSubview:self.secondViewController.view atIndex:0];

    [firstViewController viewDidDisappear:YES];
    [secondViewController viewDidAppear:YES];
}

//3. now add animation
[UIView beginAnimations:@"View Flip" context:nil];
[UIView setAnimationDuration:1.25];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//blue view will appear by flipping from right
if (secondViewController.view.superview == nil)
{
    [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromRight
                           forView:self.view cache:YES];

    [secondViewController viewWillAppear:YES];
    [firstViewController viewWillDisappear:YES];

    [firstViewController.view removeFromSuperview];
    [self.view insertSubview:self.secondViewController.view atIndex:0];

    [firstViewController viewDidDisappear:YES];
    [secondViewController viewDidAppear:YES];
}
[UIView commitAnimations];
    }

- (IBAction)switchViews:(id)sender {
if(self.secondViewController.view.superview == nil)
{
    [firstViewController.view removeFromSuperview];
    [self.view insertSubview:secondViewController.view atIndex:0];
}
    }

This does a nice animation but doesn't switch the view controllers.
Help please?
EDIT:
Also putting another view inside the first view controller and how to switch the views will be helpful.

A: In your code you're switching views and not view controllers in fact. This means that from the point of view of view controller internal messaging (e.g: view load/unload, view appear/disappear, autorotation), nothing changes, the original "current" view controller will still be at the top.
Now in iOS this is normally managed using a container view controller, that is a view controller that "manages" a set of sub-viewcontrollers and takes care of internal messaging and transitions. The most common cases are the UINavigationController and the UITabBarController, with the iPad you can see also UISplitViewController and PageViewControllers.
With iOS5 Apple provided a way to inform the container view controller (which is an ordinary view controller) of changes of its contained VCs using the so-called "View Controller Containment". There is a video taken from WWDC 2011 and published on iTunes (for registered developers only) that you can see.
Basically this methodology adds a few methods that allow to inform the container view controller of changes in its contained VCs structure. I will not enter in much detail here and invite to look at the WWDC video and read this stack overflow answer or this post. I think the latter is exactly what you're looking for.

A: As the other poster says, you should not be swapping or mixing the content views of view controllers as you are doing. If you want to do that you need to use the new parent child view controller support in iOS 5.
If you DO use the new parent view controller support in iOS 5, there is a very cool, very powerful method called transitionFromViewController:toViewController:duration:options:animations:completion: that does most of the heavy lifting for you. It's pretty easy to use.
(I haven't watched the WWDC video on parent/child view controllers, but it would be a good place to start. I just started using the new methods.)

A: You should use UINavigationController for switching between UIViewController.
[[self navigationController] pushViewController:firstViewController animated:YES];

Putting a UIView inside a UIViewController
[[self view] addSubview:view1];

And I would use UIView.hidden for switching the views
view1.hidden = YES;
view2.hidden = NO;


text:
Q: How to change Websphere 9 log files' permissions In a WebSphere 9 installation on Linux, I am trying to change the default file permissions of the generated log files to be more permissive. The default permissions of the log files are these:
-rw-r--r-- 1 was root SystemOut.log

(I am referring to the JVM logs)
I want to allow all users to also write the log files. In development, I find it useful to delete log content so that I can start fresh when analyzing exceptions.
My research only returned that some parameter exists, that is only described for Liberty (WLP_SKIP_UMASK) without any details on usage, effect, etc.
What can I set up in WebSphere so that the JVM log files have permission -rw-rw-rw-  ?
To be even more specific about my setup and why I need this: my WAS is set up in a docker container; the log directory in WAS is linked to a location on my disk. It would be a hassle to manually change permission every time, as the log files get rotated.

A: I wonder how this thread remained unanswered for last 8 months. I assume you might already have found te solution. However, if no, then you have to set te umask for the JVMs as 000.
Setting umask to 000 will give the folder permissions as 777 (if it doesnt exist already) and file permissions as 666 (-rw-rw-rw-) to the newly created files.
Here are some references of umasks value and chmod values :
How to change the umask for a JVM:

*

*Take the backup of the profile using backupConfig.sh from Profile bin directory. (This step is a life saver in all cases)

*Stop the JVM you need to change the umask for.

*Login to WAS Console

*Go to Servers --> Server Types --> WebSphere Application Servers

*Select the JVM you wish to change the umask for

*Expand Java and Process Management on the right

*Click Process Execution

*Change the value of UMASK to 000

*Rename the existing log file. This is needed if the logs are not rolled after every restart. If the file is not renamed, then the new permissions will not be in effect till the new file is generated.

*Start the JVM

Just for the reference, please find the chart below for umask and corresponding chmod values
 Umask   |  Created Files     |   Created Directories

*

*000        666 (rw-rw-rw-)       777   (rwxrwxrwx)

*002        664 (rw-rw-r--)       775   (rwxrwxr-x)

*022        644 (rw-r--r--)       755   (rwxr-xr-x)

*027        640 (rw-r-----)       750   (rwxr-x---)

*077        600 (rw-------)       700   (rwx------)

*277        400 (r--------)       500   (r-x------)


text:
Q: Google App maker user picker validation In App maker user picker widget is populating the users added in the organization.
But it is not throwing any error when a valid value is not entered in the field. It just saves as an empty field.
How to use the Validation display and Validation error message when an error encountered. I want display different error message when a particular error occurs.

A: First of all, you can enforce it on Model level by making the field required. Secondary, you can add your custom validation logic on UI:
// UserPicker onValidate event
if (widget.value === null || widget.value === '') {
  return 'validation error message goes here';
}

Be sure, that your form's submit button is bound to @widget.parent.parent.valid (it is default App Maker binding for forms) or forces validation on click:
// submit button onClick event for AM auto-generated form
if (widget.parent.parent.validate()) {
  widget.datasource.createItem();
}

This will trigger onValidate event for the UserPicker widget.


text:
Q: Drawing a function between two intersections with two other functions I have three functions defined, red, blue and green.  I would like to plot the red function only between the intersections with blue and green function.  What is the easiest way to do that?
\documentclass{minimal}
\usepackage{tikz,pgfplots}

\begin{document}

\begin{tikzpicture}
\begin{axis}
\addplot[red] coordinates {(0,0)(15,30)(30,33)(45,28)(60,10)};
\addplot[green] coordinates {(0,20)(30,0)(60,0)};
\addplot[blue] coordinates {(0,10)(30,10)(60,25)};
\end{axis}
\end{tikzpicture}

\end{document}

Red function above is simplified.
I was also looking for to declare coordinates for the red function as a proper function, but I could not find the way.

A: While you are waiting for a pgfplots answer, here is a Metapost version, showing the useful cutbefore and cutafter functions for trimming paths.

\documentclass[border=5mm]{standalone}
\usepackage{luamplib}
\begin{document}
\mplibtextextlabel{enable}
\begin{mplibcode}
beginfig(1);
numeric u, v;
u = 5; v = 6;

path R, B, G;
R = ((0,0) -- (15,30) -- (30,33) -- (45,28) -- (60,10)) xscaled u yscaled v;
B = ((0,10) -- (30,10) -- (60,25)) xscaled u yscaled v;
G = ((0,20) -- (30,0) -- (60,0)) xscaled u yscaled v;

draw R cutbefore G cutafter B withcolor 2/3 red;
draw B withcolor 1/2 blue;
draw G withcolor 1/2 green;

path xx, yy;
xx = (origin -- (65u, 0)) shifted 10 down;
yy = (origin -- (0, 35v)) shifted 10 left;

drawarrow xx;
drawarrow yy;

for x = 0 step 10 until 60:
    draw (up--down) shifted (x*u, ypart point 0 of xx);
    label.bot(decimal x, (x*u, ypart point 0 of xx));
endfor

for y = 0 step 10 until 30:
    draw (left--right) shifted (xpart point 0 of yy, y * v);
    label.lft(decimal y, (xpart point 0 of yy, y * v));
endfor

endfig;
\end{mplibcode}
\end{document}

This is wrapped in luamplib, so you need to compile it with lualatex.
(Note that I used the co-ordinates you put in your MWE rather than the slightly different ones in your sample drawing).

A: A solution with clip.
\documentclass{minimal}
\usepackage{tikz,pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}
    \begin{scope}
        \clip (0,20) -- (30,0) -- (60,0) -- (60,35) -| cycle;
        \clip (0,10) -- (30,10) -- (60,25) -- (60,35) -| cycle;
        \addplot[red] coordinates {(0,0)(15,30)(30,33)(45,28)(60,10)};
    \end{scope}
    \addplot[green] coordinates {(0,20)(30,0)(60,0)};
    \addplot[blue] coordinates {(0,10)(30,10)(60,25)};
\end{axis}
\end{tikzpicture}
\end{document}

A: You can achieve the desired result with the help of intersection segments from the fillbetween library. If show it with some debug code so it is a bit easier to follow what is happening.
% used PGFPlots v1.18.1
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
    \usepgfplotslibrary{fillbetween}
\begin{document}
\begin{tikzpicture}
    \begin{axis}
        % for the final result change the first `red` to `none`
        \addplot [draw=red,name path=red] coordinates {(0,0)(15,30)(30,33)(45,28)(60,10)};
        \addplot [green,name path=green]  coordinates {(0,20)(30,0)(60,0)};
        \addplot [blue,name path=blue]    coordinates {(0,10)(30,10)(60,25)};

        % store the path from the first intersection of "red" and "green" to the next
        \path [
            name path=red2,
            % -------------------------
            % for debugging only
            draw=red!50!white,
            decorate,decoration={
                saw,
                post=lineto,
                post length=10pt,
            },
            % -------------------------
            intersection segments={
                of=red and green,
                sequence={L2},
            },
        ];
        % draw a path from the beginning of "red2" to the first intersection of "red2" and "blue"
        \path [
%            draw=red,
            % -------------------------
            % for debugging only
            draw=red!50!black,
            decorate,decoration={
                snake,
                post=lineto,
                post length=10pt,
            },
            % -------------------------
            intersection segments={
                of=red2 and blue,
                sequence={L1},
            },
        ];

    \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Editors opening on top of IPageLayout I am using the 3.x-4.x compatibility layer and have the following configuration in my IPerspectiveFactory.createInitialLayout method:
String editorArea = layout.getEditorArea();
layout.setEditorAreaVisible(false);

// NavigationView
layout.addStandaloneView(NavigationView.VIEW_ID,
    true, IPageLayout.LEFT, 0.20f, editorArea);
layout.getViewLayout(NavigationView.VIEW_ID).setCloseable(false);
layout.getViewLayout(NavigationView.VIEW_ID).setMoveable(true);

topRightFolder = layout.createFolder("perspective.toprightfolder", IPageLayout.TOP, 0.25f, editorArea);
topRightFolder.addView("myView");
topRightFolder.addPlaceholder("my.code.*"); //$NON-NLS-1$

All views that begin with my.code.* will open at the top of the Page Layout and will stack in tabs as each subsequent one is selected. I also have a couple different editors in my navigation view and when they open, they are positioned at 0.26f from the top of the page, as expected.
My question is this: Is there any way to configure the page layout so that editors behave like views and open at the top of the IPageLayout? I noticed that when an editor opens, I can drag it to the top of the page layout, so it made me wonder is there a way to default the editor to open at the top?

A: No. When using Eclipse 3.x compatibility layer editors always open in the editor area.


text:
Q: Difference between Factorization theorem and Fischer-Neymann theorem for t to be sufficient estimator of $\theta$
Difference between Factorization theorem and Fischer-Neymann theorem for t to be sufficient estimator of $\theta$

Factorization theorem says for parameter t to be sufficient statistic of $\theta$, joint density must be equal to product of 2 functions - one function is only function of random sample and other function is function of t and $\theta$
While Fischer-Neyman theorem just says the same but instead of that factor function to be that of t and $\theta$, it adds that it must be pdf(or pmf) of function of t and $\theta$
Can you please explain the difference?

A: It seems you are quite confused. The Fisher-Neymann factorization theorem says that if the density f can be factored into nonnegative functions g, h such that $f(x)=h(x)g(T(x),\theta)$, then T(x) is a sufficient statistic for theta. Usually people say factorization theorem for short.
By contrast, the definition of sufficiency is that T(x) is a sufficient statistic for theta if f(x|T(x)) does not depend on theta.


text:
Q: Client-Side Filtering of a CheckBox List I have a checkbox list which contains more than 100 entries. I need a filter option for the checkbox list.
The desired functionality would be that when I type in the filter TextBox, the contents of the CheckBox list will be filtered based on the text that was entered (similar to autocomplete).

A: You should use jQuery, or a similar client-side JavaScript framework to set up an OnBlur event for your filtering Input box, so that when its text changes, it shows/hides the specific items in the CheckBox list based on matches between the text that has been entered, and Attribute values for the individual CheckBox entries. Without seeing your specific html setup, can't be more specific than that.


text:
Q: Spatial reference data from all layers in MXD I have a MXD with many group which has many layers. I have tried to get coordinate system data from all layers with the code from Iterating through layers in mxd and describing coordinate system. So far no luck.
I have tried with this code. I also tried with comments on the given answer but no luck. This is my code:
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, '')[0]
layerlist = arcpy.mapping.ListLayers
for layer in layerlist(mxd, '', df): # Loop through layers
    sr = arcpy.Describe(layer).spatialReference
    if spatialReference.type == "Unknown":
        print layer + " has an unknown spatial reference\n"
    else:
        print layer.name + sr.name + "\n"
del mxd

And this is error I get.
Runtime error
Traceback (most recent call last):
  "<string>", line 6, in <module>
 AttributeError: DescribeData: Method spatialReference does not exist

And if I try this code, from official ESRI site, nothing happens:
import arcpy
arcpy.env.workspace = "C:/PATH_TO_FOLDER/"
feature_classes = arcpy.ListFeatureClasses()
for fc in feature_classes:
    spatial_ref = arcpy.Describe(fc).spatialReference
    if spatial_ref.name == "Unknown":
        print("{0} has an unknown spatial reference".format(fc))
    else:
        print("{0} : {1}".format(fc, spatial_ref.name))
del mxd

A: You have a number of issues with your script which will either cause issues now, or will cause issues when you reach Python 3.
import arcpy

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, '')[0]
for layer in arcpy.mapping.ListLayers(mxd, None, df): # function variable elimination

    # Ignore layers without local data
    if (layer.isGroupLayer or layer.isServiceLayer):
        continue

    # Skip layers with invalid source
    if (layer.isBroken):
        print("Warning: Layer '{:s}' source is broken!".format(layer.name))
        continue

    sr = arcpy.Describe(layer).spatialReference
    # Avoid undefined variable
    if (sr.type == "Unknown"):
        # print is function at Python 3; use string.format()
        print("Warning: Layer '{:s}' has an unknown spatial reference\n".format(layer.name))
    else:
        # print is function at Python 3; use string.format()
        print("{:30s}: {:s}\n".format(layer.name,sr.name))

del mxd


text:
Q: Rails communicating with jquery through erb I'm querying Rails for whether a record exists through a has many through relationship in erb:
<% if @hack.serials %>

Ultimately if a 'serial' does not exist within the '@hack' I want to add 'display: none' to a div's class through jquery.
Is there a pattern for communicating between rails and jquery through erb in this way?
Edit
The idea here is that if there's no data, than the I don't want the tabs and its content to show up.  And until the 'hack' is edited and the page is reloaded the div "chart-table" will not have data, so will not need to become visible.
<div class = "chart-table"
  <% if @hack.serials %>
    <%= raw 'style="display:block"' %>
  <% end %>>

Chart

Last 5 Table

    <%= @hack.id %>
    <% @hack.serials.each do |s| %>

       Series Title
        Series Name
        Series Id
      <% s.observations.sort{|a,b| a.id <=> b.id}.last(5).each do |o| %>
        <%= o.date %>
      <% end %>

      <%= link_to s.title, [@hack, s] %>
      <%= s.series_name %>
      <%= s.id %>
    <% s.observations.sort{|a,b| a.id <=> b.id}.last(5).each do |o| %>
      <% if s.units_short == 'Mil. of $' %>
        <%= number_to_currency(convertMtoBHack(o.value), :precision => 0) %>
        <% else %>
          <%= number_to_currency(o.value, :precision => 0) %>
        <% end %>
      <% end %>

      <%= s.frequency_short %>
      <%= s.units_short %>

    <% end %>

A: I'm not sure why you feel the need to do this via jQuery.
Why not write the div's style attribute directly?
<div <%= @hack.serials ? 'style="display:none"' : '' %>>

A: Something like:

If you are looking for the serial which name is "My Serial" and do not find it, then stop displaying the corresponding div.
Rails code is executed on the server side and then rendered to the client which executes the javascript. So you can pass anything you want from Rails to javascript.
FIY passing javascript to Rails would require other tricks and magic stuff (like ajax for instance).

A: Will this div be displayed later after some ajax class (prior the DOM reloading)?  If not, I would question whether you should even write it.
I would be wary of Mark Hollands answer because, although it works, it could present problems if you have any future UI changes on that element.  If you need to write the element, I would stick to a straight conditional with and put the "static" code in a partial:

<% if @hack.serials %>

    <%= render 'something' %>

<% else %>

    <%= render 'something' %>

<% end %>

A: The good folks over at Rails Hotline helped me to the answer.
<% if @hack.serials.present? %>

Chart

Last 5 Table

<% end %>

If "empty" @hack.serials returns an empty array but returns true.  Using @hack.serials.present? returns false if it's an empty array which is the behavior I was looking for.


text:
Q: Read the source code for the command flink run -m yarn-cluster I am reading Flink's latest source code forked from master branch of github.
I would like to read the code path for the following command, but I didn't find where the code starts to interact with YARN and submit an application to YARN.
flink run -m yarn-cluster -yqu Q1 -yn 6 -c my.MyFlink./myflink.jar
The code path is:
1. CliFrontend#main
2. CliFrontend#parseParameters
3. CliFrontend#run(The ACTION_NAME is run in my case)
4. CliFrontend#getPackagedProgram and CliFrontend#buildProgram
5. CliFrontend#executeProgram
6. ClientUtils.executeProgram
7. program.invokeInteractiveModeForExecution();

my.MyFlink's main method starts to run and the yarn cluster should have already been created,but I didn't where the code that starts to interact with YARN in the above code path
Could someone help? Thanks.

A: Looks I find the answer.
protected void executeProgram(final Configuration configuration, final PackagedProgram program) throws ProgramInvocationException {
    ClientUtils.executeProgram(new DefaultExecutorServiceLoader(), configuration, program, false, false);
}

The code path to interact with YARN resides in the DefaultExecutorServiceLoader, but this heavy/important operation hides in a parameter of ClientUtils.executeProgram, kind of bad code practice.


text:
Q: Applied Hierarchical Modeling in Ecology function sim.fn not found In the book "Applied Hierarchical Modeling in Ecology" (ISBN: 978-0-12-801378-6), the first function called fails immediately.
library("unmarked")
tmp <- sim.fn( quad.size = 10, cell.size = 1, intensity = 1)

sim.fn( quad.size = 10, cell.size = 1, intensity = 1)

I get the message:
Error: could not find function "sim.fn"

I have verified that the library "unmarked" is properly loaded and installed.
What am I missing?

A: There are further packages to install, as sim.fn is located in the AHMbook library:
install.packages(c("unmarked", "plotrix", "sp", "raster", "RandomFields", "coda"))
install.packages("AHMbook", repos = "http://mikemeredith.net/R")

library("unmarked")
library("AHMbook")

tmp <- sim.fn( quad.size = 10, cell.size = 1, intensity = 1)


text:
Q: How to close Facebook Send Dialog (v2.9) automatically after completion? First, I'm using react and the only way I've found to load a script inside a specific component is by adding it dynamically using reference. I don't like it but the dialog shows up correctly and the message is deliver.
My problems is that the iframe doesn't close automatically after delivering the message.
I've searched in Send Dialog documentation and  Facebook Sdk documentation but still can't do it.
Any advice would be greatly appreciated
Thank you
Code:
class FbSendDialogComponent extends React.Component {

  componentDidMount() {
    const facebookScript = document.createElement('script')
    facebookScript.type = 'text/javascript'
    facebookScript.async = false
    facebookScript.innerHTML = `
    window.fbAsyncInit = () => {
      FB.init({
        appId: 'my app id',
        autoLogAppEvents: true,
        xfbml: true,
        version: 'v2.9'
      })
      FB.AppEvents.logPageView()
    }
    (function(d, s, id){
       var js, fjs = d.getElementsByTagName(s)[0];
       if (d.getElementById(id)) {return;}
       js = d.createElement(s); js.id = id;
       js.src = "//connect.facebook.net/en_US/sdk.js";
       fjs.parentNode.insertBefore(js, fjs);
     }(document, 'script', 'facebook-jssdk'));`
    this.node.appendChild(facebookScript)
  }

  openDialog = () => {
    FB.ui({
      method: 'send',
      link: 'https://www.google.com/'
    })
  }

  render() {
    return (

 (this.node = ref)}>

You have no connections yet

         this.openDialog()}>Invite

    )
  }
}

A: So you could insert the FB script without using your ref approach by just the running the JS Facebook provides instead of creating a new script element. The creation of a new script element is pretty redundant since you're creating JS to later run JS when you could just run the JS directly. In other words, you could remove that ref you have and do the following in your componentDidMount lifecycle method:
class FbSendDialogComponent extends React.Component {
  componentDidMount() {
    window.fbAsyncInit = () => {
      FB.init({
        appId: '1419915028316261',
        autoLogAppEvents: true,
        xfbml: true,
        version: 'v2.9'
      })
      FB.AppEvents.logPageView()
    }

    var js, fjs = document.getElementsByTagName('script')[0];
    if (document.getElementById('facebook-jssdk')) {return;}
    js = document.createElement('script'); js.id = 'facebook-jssdk';
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }

  openDialog() {
    FB.ui({
      method: 'send',
      link: 'https://www.google.com/'
    })
  }

  render() {
    return (

You have no connections yet

         this.openDialog()}>Invite

    )
  }
}

(I would personally clean up their JS to make it more readable since you probably minify your code at a later point anyway, but the above would still work. I'd also probably extract the fbAsyncInit method into a separate module in case I had to do other things, but that's out of the scope of this question.)
In terms of the iframe closing after success, I'm not sure what you're referring to. When I run your code locally and click "Invite", the opened dialog closes for me as expected.

A: For people who get the same error, I was running my app on localhost and didn't add this domain to my facebook app. I guess facebook failed to redirect you to an unknown domain so it leaves the dialog open.


text:
Q: how sort a gridview when using entity datasource? I have a Gridview witch has an entity datasource I'm trying to sort By columns when user press any column's header so I wrote this code:
protected void Page_Load(object sender, EventArgs e)
{

    griddata();
}

private void griddata()
{
    string name = Request.QueryString["name"];
    string Tel = Request.QueryString["Tel"];
    string Address = Request.QueryString["Address"];
    string Description = Request.QueryString["Description"];
    int? CaseNumber = string.IsNullOrEmpty(Request.QueryString["CaseNumber"]) ? (int?)null : Convert.ToInt16(Request.QueryString["CaseNumber"]);

    dbModel db = new dbModel();
    var datasource = from source in db.Files
                     where
                            (source.Name == null || source.Name.Contains(name)) &&
                            (source.Tel == null || source.Tel.Contains(Tel)) &&
                            (source.Address == null || source.Address.Contains(Address)) &&
                            (source.Description == null || source.Description.Contains(Description)) &&
                            (CaseNumber == null || source.CaseNumber == (CaseNumber)) &&

                     select source;

    GridView1.DataSource = datasource.ToList();
    GridView1.DataBind();
    DataTable dtbl = GridView1.DataSource as DataTable;
    ViewState["dbl"] = dtbl;
}

and my sorting codes are:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    DataTable dataTable = ViewState["dbl"] as DataTable;
    if (dataTable != null)
    {
        DataView dataView = new DataView(dataTable);
        dataView.Sort = e.SortExpression + " " + ConvertSortDirection(e.SortDirection);

        GridView1.DataSource = dataView;
        GridView1.DataBind();
    }

}
private string ConvertSortDirection(SortDirection sortDirection)
{
    string newSortDirection = String.Empty;
    switch (sortDirection)
    {
        case SortDirection.Ascending:
            newSortDirection = "ASC";
            break;

        case SortDirection.Descending:
            newSortDirection = "DESC";
            break;
    }

    return newSortDirection;
}

But when I press gridview headers nothing happen!
can anybody knows where is my mistake?


text:
Q: Is "the most edifying of experiences" grammatical? When I search the word 'edifying' in the Cambridge Advanced Learner's Dictionary, I get the sample sentence:

Being left in a bar all afternoon with a load of football fans is not the most edifying of experiences.

My question is if this sentence is grammatical. What part of speech is the word 'of' in the above sentence? Should it be the following instead?

Being left in a bar all afternoon with a load of football fans is not the most edifying experiences.


text:
Q: Drawing primitives in WPF is extremely slow. How to improve? I'm writing a CAD-like application which needs to display maybe tens of thousands of lines when stuff is zoomed out.
At the moment I use C++ and Direct2D, which works quite smoothly: I can draw 100000 lines in something like 16 milliseconds. So I know my (average) machine can handle that.
I'm trying to move to WPF but I'm finding the performance disappointing. With the code below the redraw takes nearly one second (when I resize the window for example).
Profiling says the bottleneck is somewhere in [wpfgfx_v0400.dll], but I can't see exactly which functions.
So my questions: What am I doing wrong? How can I improve the performance of the code below?
public partial class MainWindow : Window
{
    public MainWindow ()
    {
        InitializeComponent ();

        var gg = new GeometryGroup ();

        Random random = new Random ();
        for (int i = 0; i < 1000; i++)
        {
            Point p0 = new Point (random.Next (1000), random.Next (1000));
            Point p1 = new Point (random.Next (1000), random.Next (1000));
            var lineGeometry = new LineGeometry (p0, p1);

            gg.Children.Add (lineGeometry);
        }

        var stroke = new SolidColorBrush (Colors.Red);

        gg.Freeze ();
        stroke.Freeze ();

        this.Content = new Path () { Data = gg, Stroke = stroke };
    }
}

A: Drawing things in WPF is slower than you'd expect! A line with 1000 points shouldn't be a problem in general, but I wouldn't hope to draw anywhere near 100000 points using WPF geometry primitives - instead you'll eventually have to drop down to either rasterizing yourself or using some raw DirectX embedded in your WPF application.
Specifically the case of a single line of 1000 points should be well within the bounds of reason, some thoughts:

*

*With random data, if the line goes back and forth to cover a lot of area, this can lead to some very ugly performance. This is not simply a case of creating a large area to redraw - going back and forth seems to cause some bad situation with WPF geometries

*If you're drawing a single line, try using a PolyLine or PolyLineSegment in your Path

*If you do actually want a number of disconnected lines, rather than a GeometryGroup full of LineGeometry, use a Path with many PathFigures.
For the general case as other answers have pointed out, you can look into OnRender or DrawingVisual type approaches, depending what you're doing the performance may or may not be better. I think you'll still struggle with the amount of elements you're suggesting, unless you can do some kind of virtualization.


text:
Q: Phonegap 2.9 android toast plugin What is best toast plugin in phonegap 2.9?
I used this plugin, but NOT working.
CatLog say : exec() call to unknown plugin : ToastPlugin
Please Help me.. Thanks

A: Here are links (first, second) for android toast message plugin, please try if it works for you.
There are some changes that you would like to do:

*

*In res-> xml-> config.xml write this line
<plugin name="ToastPlugin" value="org.apache.cordova.plugin.ToastPlugin"/>

*Set <script src="toast.js"></script> in your html page properly.

A: If you're on PhoneGap 3: check out this one, which supports iOS as well: http://www.x-services.nl/phonegap-toast-plugin/796


text:
Q: Serve static context jboss as 7.1 outside of webcontext Question is very similar to this, sadly the answer is not Jboss specific.
This recent post, and this question have lead me to the conclusion that there are 3 ways of achieving this in Jboss AS 7:

*

*A custom servlet.

*Add a Jboss Module.

*Just install another webserver like Apache/Nginx.

Which are the pros/cons of each one?
The specific purpose is to serve images stored in the file system that were previously uploaded by users.


text:
Q: Как определить начало движения курсора и окончание движения курсора? Подскажите, пожалуйста, как определить начало движения курсора и окончание движения курсора?
В чем суть:
Есть родительский блоки и дочерний, который спозиционирован в правом верхнем углу.
При начале движения курсора в родительском блоке ширина дочернего блока должна увеличится с 0 до 20%.
При окончании движения курсора (когда мышь не двигается) ширина дочернего блока уменьшается до нуля.

const chart = document.querySelector('#chart')
const menuTaget = document.querySelector('#context-memu-target')

chart.addEventListener('mousemove', (event) => {
  console.log(event.clientX)
});
#chart {
  position: relative;
  width: 250px;
  height: 150px;
  background-color: orange;
}

#context-memu-target {
  position: absolute;
  top:1%;
  right:1%;
  width: 0;
  height:50%;
  background-color: red;
}

#context-memu-target.active{
  width:20%;
  transition: width 0.3s ease;
}

A: смотри комментарии.

const chart = document.querySelector('#chart')
const menuTarget = document.querySelector('#context-memu-target')

let animationStopInterval;

chart.addEventListener('mousemove', (event) => {
  clearInterval(animationStopInterval) //сбрасываем интервал
  const isActive = menuTarget.classList.contains('active')
  if (!isActive) // устанавливаем класс только если он еще не установлен
    menuTarget.classList.add('active')
  animationStopInterval = setTimeout(()=>menuTarget.classList.remove('active'), 500) //задержка закрытия
});
#chart {
  position: relative;
  width: 250px;
  height: 150px;
  background-color: orange;
}

#context-memu-target {
  position: absolute;
  top:1%;
  right:1%;
  width: 0;
  height:50%;
  background-color: red;
  transition: width 0.3s linear; /*должно быть здесь*/
}

#context-memu-target.active{
  width:20%;
  /* transition: width 0.3s linear; это должно быть в #context-memu-target */
}


text:
Q: HTML5 Transition and Transform effect. When I click a button, I wanna do some things listed below using HTML5 and CSS3. But I don't know how can I achieve these things at the same time.
When I click a button:
Change element A's CSS3 property -webkit-transform to rotateY(180deg) in 1 second (using -webkit-transition:-webkit-transform 1s;)
Change element A's CSS3 property -webkit-transform to scale(0.8) in 0.5 second (using -webkit-transition:-webkit-transform 0.5s;). Then change element A's CSS3 property -webkit-transform back to scale(1) in 0.5 second (using -webkit-transition:-webkit-transform 0.5s;).
Are there any solutions about this issue?
Thank you!

A: You'd have to use animation rather than transitions:
@-webkit-keyframes myAnimation{
    from {
        -webkit-transform: rotate(0deg) scale(1);
    }
    50% {
        -webkit-transform: rotate(90deg) scale(0.8);
    }
    to {
        -webkit-transform: rotate(180deg) scale(1);
    }
}

div {
    -webkit-animation-duration: 1s;
}
div:hover {
    -webkit-animation-name: myAnimation;
    -webkit-transform: rotate(180deg) scale(1);
}

Here's a demo.


text:
Q: How to Customise default Alert in xamarin forms I am trying to change the colour of Alert Buttons.
my alert like below.
await DisplayAlert("Question?", "Would you like to play a game", "Yes", "No");

I need to make Yes button Red both Android and iOS.
I need to get default alert view for both platform rather than creating a custom pop up.
is there any way to write a renderer for this?

A: Hello man hope to get nice day
in iOS you need to use MessageCenter wherever you need to display Dailog and subscribe it in ApprDelegate as following:
        UIAlertController vc = UIAlertController.Create("", titleWeSendFromMessageCenterArgs, UIAlertControllerStyle.Alert);
        UIAlertAction action = UIAlertAction.Create("OK", UIAlertActionStyle.Default, null);
        vc.AddAction(action);

        vc.View.TintColor = UIColor.Red;//or whatever you want

        Window.RootViewController.PresentViewController(vc, true, null);

in Android you just change colorAccent in you style file in resource
hope to be useful.

A: If you need exact visual effect on both platforms you must write custom renderer, because DisplayAlert is not rendered by XF.


text:
Q: Having trouble locating (connecting to) a database using relative path I am having trouble accessing my database on a server.  I am using code snippet this to try to connect.
String currentDir = new File(".").getAbsolutePath();
String currdir = System.getProperty("user.dir");
System.out.println("EPIC currentDir = " + currentDir);
System.out.println("EPIC currdir = " + currdir);
String builder = "jdbc:sqlite:"+ currentDir +"dbname";

Now.. the printlns are telling me that:
currentDir = /usr/local/cpanel/base/.
currdir = /usr/local/cpanel/base

and I know that this is going to give SQLException because my db is located in
    ../WEB-INF/lib/dbname
So no surprise that I get this error message:
java.sql.SQLException: opening db: '/usr/local/cpanel/base/.dbname': Permission denied

So my question is this.. what is after base and how does that relate to my directory (from  where the servlet is run)? I don't have SSH to go looking for it (rolls eyes) and if anyone can shed some light on the subject I would be greatful!
Thanks in advance!
Edit: Weird stuff
I am testing all this with these commands..
String currentDir = new File("dbname").getAbsolutePath();
String currdir = System.getProperty("user.dir");
System.out.println("EPIC currentDir = " + currentDir);
System.out.println("EPIC currdir = " + currdir);
System.out.println("EPICER  = " + this.getClass().getResource("dbname").toString());
System.out.println("EPICEST!  = ");

this is the output:
EPIC currentDir = /usr/local/cpanel/base/dbname

<< this one gives me "Permission Denied"
EPIC currdir = /usr/local/cpanel/base

<< this one gives me "Permission Denied"
EPICEST!  =

<< this is ok.. but wait.. NO EPICER???
System.out.println("EPICER  = " + this.getClass().getResource("dbname").toString());

DOES NOT PRINT!! what? is my log being filtered to prevent me from viewing the path? Also, none of those paths work :(
<<<<---UPDATE--->>>>
Did not print because "this" was returning null and i was actually getting NPE on this line; thus, no println. duh.
LAST EDIT:
SOLVED!
Ok, so I was going about it all wrong and I'm posting this just in case some other poor guy is about to waste three days like I did..
this.getClass().getResource("dbname").toString())

"this" was coming back null because what? SURPRISE, no ServletContext
so
getServletContext()

was also returning null ( something I experimented with later)
I learned from other resources on the internets that the way I was going about doing this was all wrong because, every time I re-deploy the WAR file, the DB will be overwritten.. so I created a little directory in my /home/username/ called dbfiles and used the commands:
String dir= "jdbc:sqlite:/home/username/dbfiles/dbname.db";
connection = DriverManager.getConnection(dir);

and it works!!
Thanks everyone

A: user.dir is directory of system user.
If you want to find file inside your application war, then use ServletContext.getRealPath()

A: To access a database from an Applet using JDBC (read-only):
I made a connection similar to the one listed here http://www.shoaibinamdar.in/blog/?p=313 but insread of
    ds.setUrl("jdbc:sqlite::resource:"+
    getClass().getResource("sample.db").toString());

I put
    ds.setUrl("jdbc:sqlite:resource/sample.db");

the sample.db went in /myprojectname/resource/sample.db, with resource being in the same dir (myprojectname) as /myprojectname/src/
Hope this helps someone


text:
Q: How to Extract the Count Value into a Variable - Used for ForEach Loop I need to trap the Count value of 2 into a Count variable - how can I perform this?  The idea in this example is to loop continuously until two hotfixes are installed - which means I can perform a service restart.
C:\WINDOWS\system32> Get-HotFix |? installedon -gt 4/13/2022 | Group installedon –NoElement
Count Name
----- ----
    2 4/14/2022 12:00:00 AM

A: Count is a property of the Microsoft.PowerShell.Commands.GroupInfo instances that Group-Object (a built-in alias of which is group) outputs, so you can simply access the Count property on each object emitted by your pipeline:
$count =
  Get-HotFix | ? installedon -gt 4/13/2022 | Group installedon –NoElement |
    ForEach-Object Count

Note that $count will end up with an array of counts if the Group-Object call resulted in multiple groups.


text:
Q: Attaching and Positioning Movieclips with XML in Flash Im trying to build a script that attaches and positions an instance of a movieclip for each node of an xml sheet. However, I can't seem to get it to loop properly. The script is simply attaching and positioning a single movieclip according to the last node in the xml file. Can anyone tell me what I am doing wrong?!!
Here is my script:
var myXML:XML = new XML();
myXML.ignoreWhite=true;
myXML.load("map.xml");
myXML.onLoad = function(success) {
if (success) {
var myPin = myXML.firstChild.childNodes;
for (i=0; i<myPin.length; i++) {

var imageNumber = i+1;

_root.attachMovie("box", "pin"+i, _root.getNextHighestDepth());
var xpos = myPin[i].attributes.xpos;
var ypos = myPin[i].attributes.ypos;
_x = xpos;
_y = ypos;

}
}
};

A: You are not getting the attached movieclip when positionning. Your mc are generated on _root with the name "pin" + i, so you need to use _root["pin" + i] to get the related instance.
Try this :
_root.attachMovie("box", "pin"+i, _root.getNextHighestDepth());
var xpos = Number(myPin[i].attributes["xpos"]);
var ypos = Number(myPin[i].attributes["ypos"]);
_root["pin" + i]._x = xpos;
_root["pin" + i]._y = ypos;


text:
Q: Linq to Entities and Drop Downs I am loading the values into a drop down using linq to entities.
I need the first value in the drop down to read "Select" with value of 0 or "".
How can I add that value to my linq query or to the drop down in asp.net forms.
My current code:
    'Payment Types
    Dim SourcePaymentTypes = (From s In db.PayoutAdjustmentTypes.OrderBy("Name") Select s).ToList
    CmbReason.DataSource = SourcePaymentTypes
    CmbReason.DataTextField = "Name"
    CmbReason.DataValueField = "AdjustmentTypeID"
    CmbReason.DataBind()

A: You need to .Add() a new PayoutAdjustmentType { Name = "Select", AdjustmentTypeId = 0 } record to your SourcePaymentTypes variable before you set it as the DataSource of your CmbReason
(Apologies it's in C# syntax, but I'm sure you can translate)


text:
Q: Problems minimizing a two variable function with "scipy.optimize.brute" I'm trying to minimize a function of two variables using scipy.optimize.brute algorithm, but I've receiving the error TypeError: Fcone() missing 1 required positional argument: 'R'.
Here's my code:
import numpy as np
import scipy.optimize as opt

gamma = 17.
C = 45.
T = 12.
H = 1.2
R = 1.3
H1 = 0.57

def Fcone(alpha, beta, H1, gamma, C, T, H, R):
    return np.pi/((np.cos(alpha))**2 * (np.cos(beta))**2) * ((np.cos(alpha))**2
             * ((np.cos(beta))**2 * (gamma*H1**3 + 2*H1**2*(C-T-gamma*H) - H*H1*
                    (2*C-2*T-gamma*H) + H*(gamma*R**2 + H*(C-T)-(gamma*H**2)/3)) -
                2*R*(H-H1)*np.cos(beta) * ((gamma*H1/2 - gamma*H/2 + C -T)*
                    np.sin(beta) - C) + (C*np.sin(beta) + gamma*H/3 - gamma*H1/3
                        -C + T)*(H-H1)**2) - 2*H1*np.cos(beta)*np.cos(alpha)*(
                        R*np.cos(beta)*((gamma*H1/2 + C -T -gamma*H)*np.sin(alpha)
                    - C) + np.sin(alpha)*(H-H1)*((gamma*H1/2 - gamma*H/2 + C -T)
                                *np.sin(beta)-C)) + (np.cos(beta))**2 * H1**2 *
                                                 (gamma*H + C*np.sin(alpha)
                                                  -2*gamma*H1/3 -C+T))

ranges = (slice(0, np.pi/2, np.pi/10000), slice(0, np.pi/2, np.pi/10000))
res = opt.brute(Fcone, ranges, args=(H1, gamma, C, T, H, R), finish=None)

Where gamma, C,T, H, R1 and H1 are given parameters. Despite the very large (and probably confusing equation), how can I fix this problem and minimize the function for the two parameters alpha and beta? Thank you!
P.S.: The function alone is running fine when I assign all values for the parameters.

A: Amend Fcone() as follows...
def Fcone(alpha_beta, H1, gamma, C, T, H, R):
    alpha = alpha_beta[0]
    beta  = alpha_beta[1]
    .....

The variables being optimized have to be put into a 1D array, check docs here. Their values will be in res[0]


text:
Q: Juypter Notebook crashes when I run pandas join I am trying to join two tables TRAIN and STUDENT with an inner join. For some reason the whole juypter kernal keeps crashing when I run this line:
X_student = TRAIN.join(STUDENT, on='UserId', how='inner', sort=True)

Here are what the tables look like:

*

*NOTE: These tables are pandas dataframes

*TRAIN.shape = (15867850, 6)

*STUDENT.shape = (118971, 390)
I am trying to join the tables across the UserId. I know every UserId that occers in TRAIN will be in STUDENT and every UserId from STUDENT is used at least once in TRAIN. Note that the UserId is the index for STUDENT.
Running TRAIN.head().join(STUDENT, on='UserId', how='inner', sort=True) yields:

Why is my kernal crashing and how can I fix it?
This is the link to my google colab for the exact code that I am using.


text:
Q: How to synatx a piecewise where x=0 is undefined? How to write the synatx for a piecewise where x=0 is undefined in the domain of the function, and according to the below conditions ?
y := Piecewise[{{1, 0 < x < Pi}, {-1, -Pi < x < 0}}]

A: From help

Compare
y[x_] := Piecewise[{{1, 0 < x < Pi}, {-1, -Pi < x < 0}}];
Plot[y[x], {x, -2 Pi, 2 Pi}]

To make it undefined, one way is to do this
y[x_] := Piecewise[{{1, 0 < x < Pi}, {-1, -Pi < x < 0}}, Nothing];
Plot[y[x], {x, -2 Pi, 2 Pi}]

So any $x$ not in conditions will have Nothing as its value instead of zero.


text:
Q: Properly display React component in react-tabulator column I am trying to display a material-ui react component inside a tabulator table. Things display properly, except for the row's height. I suspect that a re-rendering is required after the first render, so tabulator knows the React component's height, but I am not quite sure of how to do that. Code looks something like this:
import { Fab, } from '@material-ui/core';
import { Lock,} from '@material-ui/icons'

const RegisterButton = (props) => {
    const cellData = props.cell._cell.row.data;
    return (
        <Fab
            size='small'
            onClick={handleTownRegisterClick(cellData.id)}
        >
            <Lock fontSize="inherit" />
        </Fab>
    )
}

const columns = [
    { title: 'Id', field: 'id', width: 45 },
    { title: "Register",
        field: "custom",
        align: "center",
        formatter: reactFormatter(<RegisterButton />),
        width: 100,
        headerSort: false
    }
];

Which are used in my table later on:
<React15Tabulator
    columns={columns}
    layout={'fitColumns'}
...

With this, my row is ~ 2/3 the Fab component's height.
I see that the formatter prototype is formatter:function(cell, formatterParams, onRendered).
Should I somehow use onRendered, is that where I would force the table to take into account that cell's height? If so how would I do that?
Thanks.

Edit:
Looking further, it looks like tabulator is ignoring the padding it is adding in its own 'tabulator-cell' div (it adds a 11px padding, which pushes my button by that much) on the first render.
When re-ordering other columns, which forces a re-render, the height becomes right.
There are a few redraw calls accessible through props.cell._cell inside my RegisterButton, I just don't see how and when to call them...

A: did you ever solve this?
I have the exact same isue but with width - whereby everything is fine post a column sort.
I solved the cell padding issue with the CSS:
.tabulator-row .tabulator-cell {
    padding: 0;
}

To center vertically you can edit the base styles with the below, this worked for my use case
.tabulator-row {
    flex-direction: row;
    align-items: center;
}
.tabulator-row .tabulator-cell {
    padding: 0;
    height: auto;

    .formatterCell {
        height: 100%;
        display: flex;
        flex-direction: row;
        align-items: center;
    }
}

In case that solves your issue


text:
Q: Concrete5 (5.7.5.6) How to register package service provider the whole application? If I use provider located from the application source it works:
app.php:
return array(
    'providers' => append_config(array(
        '\Application\Src\Utility\UtilityServiceProvider',
    ))
);

but if I try to register a provider located from a package, just got "not found" error
return array(
    'providers' => append_config(array(
        '\Application\Src\Utility\UtilityServiceProvider',
        '\Concrete\Package\MyPackage\Src\Utility\MyPackageServiceProvider',
    ))
);

The MyPackageServiceProvider inside the package works well.
Of course, if I register manually ex. in the PageTypeController:
$app = Core::make('app');
$provider = new \Concrete\Package\MyPackage\Src\Utility\MyPackageServiceProvider($app);
$provider->register();

it also work, but I don't want to register all of controller outside the package, if possible.
I found this question, but it's not Laravel and not help me.
Thank you


text:
Q: Using Degree Symbol in Times-New-Roman Font with Itextpdf I am creating a PDF file using itextpdf and need the degree symbol. I know it exists in the Times-New-Roman font. Using the unicode string works for Swing but not with itext. It just displays the literal string.
Font headerFont = new Font(FontFamily.TIMES_ROMAN, 10.f, Font.BOLD, BaseColor.BLACK);

I have my degree symbol set in a variable:
tempScale="\\u00B0C";

I add the string to my PDF thus:
table.addCell(createCell("Actual\nTemperature\n"+tempScale,headerFont));

I read about adding basefont.IDENTITY_H to access all symbols in the font but it is unclear how I incorporate that into the Times-New-Roman font instance. Can someone tell me how to get the degree symbol displayed? TIA.

A: Don't escape the unicode character
String tempScale = "\u00B0C";


text:
Q: Can GameObject automatically find references? I'm new to unity and going through a simple breakout clone.  Currently, i'm working on a game manager and trying to switch between panels as the ui.
However, unity can't seem to find the PanelMenu object from my project and I keep getting a null instance error.
I'm not sure why this error is suddenly popping up since I didn't (or don't remember) accessing panel objects from GameObject previously.
Here's my code and unity hierarchy:

Can someone explain to me why GameObject cant find the panels or how to assign the panel instance?
Thanks!

A: Create your panel objects as prefabs, like you've done with Ball, Player, etc. then change your panel references in your game manager class to public instead of private.
Then, when you click on your game manager in the inspector, you'll see your panel references listed under its properties (they will be unassigned). Drag the appropriate panel prefabs from your assets browser into the correct properties on your manager object.


text:
Q: Unusual form's appearance after calling TCustomForm.SetFocusedControl function First of all, my goal isn't that to set the focus on a control but I'm trying to understand why a form has a different appearance after deactivating and reactivating it.
Here is TCustomForm.SetFocusedControl function's description:

Sets focus to a control on the form.
Use SetFocusedControl to give a control on the form input focus. SetFocusedControl returns false if the Control specified by the Control parameter was already in the process of receiving focus, true otherwise.
Note: A return value of true does not indicate the control has successfully received input focus. If the Control can't have focus (for example, if it is not visible), SetFocusedControl will still return true, indicating that an attempt was made.

I've created a simple test application in order to reproduce the observed behavior:

procedure TForm1.Button1Click(Sender: TObject);
var
  Res : Boolean;
begin
  Res := Self.SetFocusedControl(Edit2);
  if(Self.ActiveControl <> nil) then
  begin
    Memo1.Text :=
      'ActiveControl is ' + Self.ActiveControl.Name + sLineBreak +
      'SetFocusedControl result is ' + BoolToStr(Res, True);
  end;
end;

Here are steps I followed to reproduce that behavior:
1) At start, the form appears as follows:

2) After clicking on "Button1", this is what I can see:

Memo1.Text reports that Edit2 is the active control but it hasn't the tipical focused appearance (selection and cursor).
Form's caption isn't grayed and clicking on it doesn't cause any change.

3) I've clicked outside the form (on the windows taskbar).

Form's caption became grayed.

4) I've reactivated the form by clicking on its caption:

Edit2 now looks like it has focus.
Could someone explain the differences between the form at point 2 and at point 4? In both cases, Edit2 was the active control and I can't understand that appearance difference.
Further informations:
Tested on Delphi 2007, Windows 10 Pro.

A: Despite what the documentation says, TForm.SetFocusedControl() does not actually set input focus onto Edit2 (the Win32 SetFocus() function is not called).  Button1 receives the input focus when clicked on, and remains in focus after SetFocusControl() is called.  That is why Edit2 does not render as focused.  If you want to move input focus to Edit2, call Edit2.SetFocus() instead of Self.SetFocusedControl(Edit2).
However, calling SetFocusedControl() does change the VCL's internal state.  It sets the Form's ActiveControl and FocusedControl properties, and it sets the global Screen object's ActiveControl, ActiveCustomForm, ActiveForm, and FocusedForm propeties and reorders the entries of its CustomForms and Forms properties.
When the Form is deactivated and then reactivated, the VCL sets input focus to the last known "focused" control, which is now Edit2 instead of Button1.


text:
Q: What's the best way to implement ACLs to a Rails application? I just wanted to compare different solutions used when implementing ACLs in Rails.

A: I use the authorization plugin (Created by Bill Katz):

Roles can be authorized for the entire application, a model class, or a specific object. The plugin provides a way of checking authorization at the class or instance method level using permit and permit? methods. It also provides english-like dynamic methods like "user.is_manager_of project" (where "user" acts as authorized, "manager" is a role, and "project" is an authorizable model). You can specify how control is redirected if authorization is denied. (quote source)

Homepage:
http://www.writertopia.com/developers/authorization
Docs:
http://github.com/DocSavage/rails-authorization-plugin/tree/master/authorization/README.rdoc

You might also be interested in reading this comparison (from last year but still somewhat useful; it's where I got the above quote from):
http://www.vaporbase.com/postings/Authorization_in_Rails
And a more recent comparison:
http://steffenbartsch.com/blog/2008/08/rails-authorization-plugins/

A: The best I've found is role_requirement.  It plugs straight into the restful_authentication plugin.

A: There's a plugin called acl_system2 which operates by having a users table and a roles table. There's a lot more useful information in the README and the project is on github too.


text:
Q: Is there a way via the command line to cause .icloud files to download? Under iCloud in the Settings app, I have "Optimize Mac Storage" checked and "Desktop & Documents Folders" checked under "Apps that store documents and data in iCloud will appear here:"

This will cause some files in my "Documents" folder to be offloaded and replaced with a small file ending in ".icloud". I can download them by clicking on the cloud icon in the detail view in the Finder. I can also use "find" from the command line to show which files have been offloaded, eg "find . -name *.icloud | more".
Is there a command line way to cause these files to be downloaded, either by file or directory?

A: To my knowledge, there is no command included that allows you to directly download an iCloud file or folder.
But since I had exactly the same problem as you, I found that it was possible to do it in Swift with the startDownloadingUbiquitousItem function.
So I wrote a really simple Swift script for downloading both folder and file. You can download it on Github: iCloud Downloader
I hope I have answered your issue.

A: Scott Garret and Allan's answer above is very close.
In the terminal, however, each *.icloud file is prefixed with a . when NOT downloaded.
For example, a directory called foo with optimised (i.e., offloaded to icloud) files a.txt and b.txt will look like this
$ cd foo
$ find . -name '.*icloud'
./.a.txt.icloud
./.b.txt.icloud

To resolve (i.e., download) the files from icloud, you need to pass the path to the resulting path to /usr/bin/brctl.
Thus, the following works.
find . -name '.*icloud' | perl -pe 's|(.*)/.(.*).icloud|$1/$2|s' | while read file; do brctl download "$file"; done

You can monitor the download activity as per this answer as follows :
brctl log --wait --shorten

A: The command you are looking for is brctl (located in /usr/bin).  man brctl will tell you all you need, but basically just brctl download /path/to/filename (without the .icloud extension)  and evict will purge the locally cached copy.


text:
Q: Выбрать id строки, где максимальная дата создания и максимальная дата изменения

id
Дата создания
Дата изменения

1
31.01.2023
31.01.2023 15:46

2
29.12.2022
31.01.2023 16:00

3
31.01.2023
31.01.2023 15:30

В таблице две строки с максимальной датой создания (31.01.2023) из них мне нужно получить id строки, где максимальная дата изменения (31.01.2023 15:46). Запрос должен вернуть id = 1.
Приведенный ниже запрос очевидно нерабочий! Какой диалект sql используется в базе не знаю, но GREATEST не поддерживается.
select id from table
where дата_создания = (select max(дата_создания) from table)
and дата_изменения = (select max(дата_изменения) from table)

A: SELECT id, max(Дата изменения)   FROM table WHERE Дата создания in (SELECT MAX(Дата создания) FROM table) group by id

A: Вернет верный результат при стремящейся к нулю вероятности дубля по дате изменения.
select first 1 id from table
order by дата_создания desc, дата_изменения desc


text:
Q: Substitute special character into blank space do you have any idea to translate all special character into blank spaces
^@^@^@^@<9C>^G^@^@*+^@^@ABD
^@^@^@^@*+^@^@<DC>_^@^@ASD
^@^@^@^@*+^@^@<DC>_^@^@ASaa
^@^@^@^@<80><C2>^A^@<C2>p^A^@ABD

od
0000000 040136 040136 040136 040136 034474 037103 043536 040136
0000020 040136 025452 040136 040136 041101 005104 040136 040136
0000040 040136 040136 025452 040136 040136 042074 037103 057137
0000060 057100 040500 042102 057012 057100 057100 057100 025100
0000100 057053 057100 036100 041504 057476 040136 040136 041101
0000120 005104 040136 040136 040136 040136 034074 037060 041474
0000140 037062 040536 040136 041474 037062 057160 057101 040500
0000160 042102 000012
0000163

cat -vET
^@^@^@^@<9C>^G^@^@*+^@^@ABD$
^@^@^@^@*+^@^@<DC>_^@^@ABD$
^@^@^@^@*+^@^@<DC>_^@^@ABD$
^@^@^@^@<80><C2>^A^@<C2>p^A^@ABD$

I've tried
LC_ALL=C sed -e 's/[^[:blank:][:print:]]//g'
sed -r 's/[^[:print:]]//g'

or from this one https://unix.stackexchange.com/questions/336677/sed-and-remove-string-between-two-patterns
and the output not as expected
output
ABD
ASD
ASaa
ABD

A: There is no generic definition of a "special character" and you may need to specify what to keep -- so remove all characters other than those
$string =~ s/[^a-zA-Z0-9_,.-]//g;  # etc, spell out what to leave

and you can use the word character pattern \w
$string =~ s/[^\w,.-]//g;

where i've only given a few punctuation charters as example.
The POSIX character class, which you're trying to use, also work
$string =~ s/[^[:alnum:][:punct:]]/;

or using Perl extensions in the style of \p
Unicode properties for them
$string =~ s/[^\p{PosixAlnum}\p{PosixPunct}]//g;

where we can of course find actual Unicode properties as well, on the comprehensive page linked above.  Careful with the syntax; see "POSIX Character Classes" section in perlrecharclass.
Or perhaps you really mean to remove the non-printable characters
$string =~ s/[^[:print:]]//g;

To use this as a  command line program ("one-liner")
perl -wpe's/\W//g' file > new_file

to save the output as new_file, or
perl -i.bak -wpe's/[^[:print:]]//g' file

to change the file in-place (remove .bak if you don't want a backup).
If input is piped from another program
echo input | perl -wpe's/[^w,.-]//g'


text:
Q: Passing const char* variables to a function I'm having a weird and unexpected result in my code and I'd like your support to explain me what happens here.
I have a structure of a confiration :
struct sConfig {
  const char* ssid;
  const char* password;
}

I'm loading this configuration using LittleFS from a deserialized json :
config.ssid         = json["ssid"]; // so this is coming from the FS in a json file
config.password         = json["password"]; // so this is coming from the FS in a json file
So far, all is fine, I can print out the value using
Serial.println(config.ssid);
I'm then calling an internal void function
startWiFi(config.ssid, config.password);
void startWiFi(const char* ssid, const char* psswd) {
  Serial.println(ssid);
  Serial.println(psswd);
}

As a result, the console returns :
⸮
and
?:⸮?@⸮8⸮?<9⸮?⸮8⸮?:⸮?@⸮8⸮?<9⸮?⸮8⸮?:⸮?@⸮8⸮?<9⸮?⸮8⸮?.:⸮?@⸮
What can be wrong in my variables ?
Please help me as I'm stuck.
Thanks a lot.

A: To fix the issue I'd avoid copying a pointer and copy the actual data.
So, instead of config.password = json["password"];
I'd declare ssid and password as char arrays and copy the values from the json with strncpy()
struct sConfig {
    char ssid[32];
    char password[64];
}

or I'd allocate them on the spot with a custom copy function
char * myCopy (char *destination, const char *source)
{
    // I'm using 64 because is the max length of WPA2-PSK passwords
    size_t len = strnlen(destination, 64);
    destination = malloc((num + 1) * sizeof(char));
    strncpy(destination, source, num);

    return destination;
}
....
myCopy(config.ssid,     json["ssid"]);
myCopy(config.password, json["password"]);

A: What's probably happening here is a use-after-free bug.
At config.ssid = json["ssid"] you copy a pointer to the internal memory of the json object. It's probably valid at the time of that copy (so the print succeeds), but when the json changes its state or gets deallocated, you get garbage at that memory address.
The solution is - as suggested in the other answer - copy the whole string and not just its address.


text:
Q: How to initialize, create matrix and then print with using structure I want to create 2D array using structure and read from user, then display it. But I can't find out what's wrong with this.
/Sorry guys.First, I want it to read a matrix elements from user, then I want to display whole matrix. But it doesn't print properly, it prints address of elements. Why is it printing address, not value? /
Here is my code:
#include <stdio.h>

    struct Matrix {
      int n,m;
      int a[100][100];
    }array;
    int main() {
      struct Matrix *p;
      int i,j;
      p = malloc(sizeof(array));
      scanf("%d%d", &p->n, &p->m);
      for (i = 0;i < p->n;i++)
        for (j = 0;j < p->m;j++)

          scanf("%d", p->a[i][j]);
      for (i = 0;i < p->n;i++){

        for (j = 0;j < p->m;j++)

          printf("%d ", (p->a[i][j]));
        printf("\n");
      }
    }

A: *

*Change scanf("%d", p->a[i][j]); to scanf("%d", &p->a[i][j]);.  Better to check the result of scanf() to ensure code received the expected data.
if (scanf("%d", &p->a[i][j]) != 1) Oops();

*Enable all warning on your compiler.  This problem popped up right away.
#include <stdio.h>

struct Matrix {
    int n, m;
    int a[100][100];
} array;

int main() {
    struct Matrix *p;
    int i, j;
    p = malloc(sizeof(array));
    scanf("%d%d", &p->n, &p->m);
    for (i = 0; i < p->n; i++)
        for (j = 0; j < p->m; j++) {
            // scanf("%d", p->a[i][j]);
            scanf("%d", &p->a[i][j]);
        }
    for (i = 0; i < p->n; i++) {
        for (j = 0; j < p->m; j++)
            printf("%d ", (p->a[i][j]));
        printf("\n");
    }
}


text:
Q: Openfire database setup error I am trying to install openfire on my VPS server.
The service is up and running. I am stuck in the database configuration step for the openfire server. I have created the database for openfire on my mysql server and imported the schema. However when I try to use those settings in the web based setup I get the following error:
A connection to the database could not be made. View the error message by opening the "/logs/error.log" log file, then go back to fix the problem.

The settings are as follows
JDBC driver class : com.mysql.jdbc.Driver
Database url : jdbc:mysql://127.0.0.1:3306/openfire_db
I have tried almost every possible setting but its not working.

A: Sounds like your logs configuration might not have been properly set.  Most 'nix systems don't have a /logs/* directory, (different and important from "logs/error.log" which would be a relative path to the service.)  Triple check that the logs are being written to a location that is sensible and writable.


text:
Q: Want to get CakePHP 1.1 working on PHP 5.3 I manage a CakePHP 1.1 CMS website, and our hosts just upgraded PHP to 5.3, causing a number of errors, such as:
Notice: Undefined variable: banner_image in /home2/intiwara/cake/app/views/layouts/public_site.thtml on line 49
Notice: Undefined variable: news_menu in /home2/intiwara/cake/app/views/articles/volunteer_animal_refuge.thtml on line 73

I can hide the errors by altering cake/cake/libs/configure.php line 133 to be:
error_reporting(E_ERROR);

However the variables and models are still not found so the page does not render.
I realize I need to upgrade to CakePHP 2.1, and every post I find dwells on this. However I'm the only technical volunteer here, I have only a few hours tomorrow afternoon to get the site working, then I am offline for two weeks' work in rural Ethiopia, so I'm hoping there's a 'workaround' solution I can put in place in the meantime. (The hosts didn't tell us this was about to happen..)
I don't need the admin functionality, I don't mind hiding errors - I just need the site to render. Is there any way I can trick PHP 5.3 to 'see' these variables?
Thank you hugely
Chris

A: Here are the SVN comments from my conversion from 1.1 to 1.2. I haven't bothered tidying them up, (except for the odd "ED:"), as I'm probably the last person to upgrade from CakePHP 1.1 and I should turn the light out when I leave.. These are the steps after I'd done the standard 'replaced cake directory' and 'config' updates detailed in the appendices on the CakePHP site: http://book.cakephp.org/view/3/The-Manual#!/1.2/en/view/411/Migrating-from-CakePHP-1-1-to-1-2.
It took me two solid days to upgrade a reasonably simple CMS with my rusty PHP, and the effort dissuaded me from using CakePHP again due to the awful documentation and the intricacies the use of a framework introduced. (Although I wasted half a day hours when my host thought one of my template files was a virus so blocked every IP address I could get on.)
The biggest timesaver would have been if I'd have spotted form->error as a replacement for html->tagErrorMsg. Instead I removed them all, put the errors in the models following the standard practice in 1.2, then re-added them all. form->input displays errors automatically, but it was easier for me to use form->select than form->input('type'=>'select'.. due to the complexity of converting the options and parameters from html->select to form->input using regular expressions.

*

*Html helper migrated to Form helper

*->renderElement() needs to change to ->element()

*->del() needs to change to ->delete()

*generateList() needs to be migrated to find('list', array())

*VALID_EMAIL, VALID_NOT_EMPTY (and VALID_NUMBER) replaced with
array('rule' => array('email'))
and
array('rule' => array('minLength', 1))
-- ED: these were later updated to include default error messages, although I think I needn't have if I'd known about form->error(

*changed
form->input to form->text
form->submit
form->password
Look at the code here https://github.com/zeroasterisk/CakePHP-cake_up-shell/blob/master/cake_up.php for some handy detailed info.

*controller this->redirects are now relative in 1.2, so I put an initial "/" where I hadn't in the 1.1 version

*form->input(Model/property => form->text(Model.property
html->tagValue(Model/property => html->value(Model.property
html->selectTag(Model/property => form->select(Model.property
$form->textarea('Article.intro
$form->labelTag('Article.body

*error messages now specified in model rather than template files
with exception of controller-generated errors such as duplicate username when adding a user - these are set in the same way as before, but displayed using simply echo $username_error - ED: this was also a mistake - later changed to form->error('model.field', $custom_error, options eg css class)
html->labelTag=>form->label
tagValue=>value
selectTag=>select
in helper-generated HTML, use full stop as model.field separator rather than forward-slash, eg, html->value(model.field) instead of html->tagValue(model/field)

*Remove san->sql and cleanUpFields
Remove default error messages tagErrorMsg - ED: this and much of my validation updating was a mistake - I should have replaced html->tagErrorMsg with form->error
Remove accent from Espanol option in form->selects due to new bug in 1.2 that can't display accents in option

*creating model.saveString to generate sql insert statement seems to be working (ED: I'd put a method in the core of CakePHP that generated an INSERT stmnt for a model, allowing me to do automatic email backups)

*Alternative way of displaying errors using integrated form->input method - more elegant, displays errors and all types of HTML input control, but regular expression to replace specific calls with complex customization parameter arrays would have been too complex/unreliable.

*In controller, replaced model->validates(model) with this->set(this->data) then model->validates()

*Validation:
Added form->error calls to every input. (ED: should have used regular expression search and replace html->tagErrorMsg with form->error..this would have saved a lot of conversion effort)

*Custom controller generated error messages must invalidate a fieldname and in the template, the field in form->error must match that fieldname, even if it isn't a model fieldname, eg, password1 and password2.

A: If you followed the conventions you might have some luck and be able to upgrade to 1.3 withing a reasonable amount of time if you have a higher level of experience with CakePHP. From 1.1 to 2.1... this won't go that smooth.
Without knowing the whole code and all the issues it's hard to tell anything, it's not even really possible to say if it would be better to try to work around with fugly fixes or to do a proper upgrade to 1.3.
If this is really something mission critical contact me in private and I'll get you the contact to a company who can get it done.


text:
Q: DOM vs scripting language I am not aware about the relationship between scripting language and Document Object Model as exactly
All we know that DOM is an API for HTML and XML document to manipulate as objects generated by document structure tree , so API has propriety and method which we can use them to control changes in a document but if we say that we will find finally  there is no any intervention for scripting language like JavaScript
for example in case we type this line in our HTML document :
document.getElementById("demo").innerHTML = "Hello World!";

we will find just DOM API ( method and propriety ) , no any trace for JavaScript
what is relationship between DOM and JavaScript , why always appear together while I am not feel trace of JavaScript , if scripting take place in HTML document all I find API DOM tool ( method and propriety ) , I could not able to touch JavaScript working in our HTML document

A: Despite the fact that this post is currently at -3 points and poorly phrased, I think I can suss out the question the poster is asking and will try to answer it.  Hopefully the community won't punish me for answering on a negatively scored question.
Yes, you clearly have some confusion around the definition and relationship between what constitutes the JavaScript language and what constitutes the DOM API.
JavaScript is a programming language.  It has functions, inheritance, variables, operations, etc etc.
function addTwo(num) {
    return num + 2;
}

var eight = addTwo(6);
console.log(eight); // logs 8

It has some cool features that some other languages don't, like functions as first-class citizens.  We won't cover that here.
While JavaScript can run in a few different environments, it was originally written for the purpose of scripting in web browsers.  It is the only scripting language that the browser can execute (with probably a few exceptions not important here).  The DOM (Document-Object Model) is the interface by which JavaScript can interact with the document and nodes being shown in the web page.  It allows you to get elements on the page, manipulate them, create them, delete them, etc.  When you are interacting with the DOM, you are doing so in JavaScript.  It is simply an API available to JavaScript for manipulating the document, not a separate language unto itself.
Hopefully this clears things up for you.  Also note that JavaScript is not relegated to the browser-- the most common other environment for JavaScript is NodeJS, which allows for all sorts of fun stuff like tooling or writing your backend code with JavaScript.
This page from the Mozilla Developer Network characterizes the distinction elegantly:

...it's written in JavaScript, but it uses the DOM to access the document and its elements. The DOM is not a programming language, but without it, the JavaScript language wouldn't have any model or notion of web pages, HTML documents, XML documents, and their component parts (e.g. elements).

(Also, the world is probably not as 100% black and white as I have spelled it out here.  There are probably edge cases in which other languages can be made to run in a browser, or perhaps there is some way to interact in the DOM with Web Assembly, which is relatively new to the scene.  I'm just spelling out here the simplest case that probably covers the vast majority of scenarios existing today.  However, this page from MDN does give an example of interacting with the DOM using Python.)


text:
Q: DropDownList em Cascata MVC 4 View:
<asp:Content ID="Javascript" ContentPlaceHolderID="HeadContent" runat="server">
<script type="text/javascript">
    $(document).ready(function () {
        $("#estados").change(function () {
            var uf = listaCidade($(this).val());

        });
    });
    //chamada ajax para a Action ListaCidade
    //passando como parâmetro a Estado selecionado
    function listaCidade(uf) {

        // <%=Url.Action("listaCidade")%>
        $.getJSON('/AdmPaginaBranca/listaCidade/' + uf, listaCidadeCallBack);

    }
    //função que irá ser chamada quando terminar
    //a chamada ajax

    function listaCidadeCallBack(json) {

        //Limpar os itens que são maiores que 0
        //Ou seja: não retirar o primeiro item
        $("#cidades:gt(0)").remove();

        $(json).each(function (id, nome) {
            //adicionando as opções de acordo com o retorno
            //alert(data);

            $("#cidades").append("<option value='" + this.id + "'>" + this.nome + "</option>");
        });
    }
</script>

Controller:
 public ActionResult listaCidade(int id)
    {
        cidadeEstadoDAO obj = new cidadeEstadoDAO();

        var estado = obj.CarregarComboCidade(id);

       var data = estado.Select(m => new { m.id, m.nome }).ToList();

        return Json(new { Result = data }, JsonRequestBehavior.AllowGet);
    }

Estou com o seguinte problema: quando eu seleciono o estado na dropdownlist, ele chama o método normalmente e faz o select no banco (verifiquei pelo "inspecionar elemento") porém, na dropdown da cidade, ele está vindo com o valor undefined. Quando coloco um alert no "id" ou no "nome" aparece undefined também.
Alguma alma caridosa pode me ajudar?

A: Colocando como resposta a solução que indiquei nos comentários.
Na linha do seu retorno você não precisa criar um novo encapsulamento, altere a linha:
return Json(new { Result = data }, JsonRequestBehavior.AllowGet);

Para
return Json(data, JsonRequestBehavior.AllowGet);


text:
Q: DJI iOS SDK downloading multiple images programatically. Camera busy after first download Here is my actual code below. It always downloads the first image fine, but gives "Camera is busy or the command is not supported in the camera's current state". I tried with the solution proposed by How to programmatically download Images from drone using the IOS DJI-SDK
I have been struggling with this for the past 10 days and tried all sorts of combination with triggering in async queue etc. but no success. Though DJI samples have a lot of code, they all focus on single download and preview etc. but not the entire raw data with multiple file downloads. Greatly appreciate any help.
func downLoad(){
     guard let drone = (DJISDKManager.product() as? DJIAircraft) else {
            testAlert(viewC: self, title: "Message", msg: "Unable to detect Drone", buttonText: "Dismiss")
            return
        }
        // Get camera on drone
        guard  let camera: DJICamera = drone.camera else {
            testAlert(viewC: self, title: "Message", msg: "Unable to detect Camera in initDownload()", buttonText: "Dismiss")
            return
        }
        // check if we can download images with the product
        if !camera.isMediaDownloadModeSupported() {
            testAlert(viewC: self, title: "Message", msg: "Product does not support media download mode", buttonText: "Dismiss")
            return
        }
        camera.setMode( .mediaDownload, withCompletion: {(error) in

            if error != nil {
                self.testAlert(viewC: self, title: "Message", msg: "Error \(error!.localizedDescription)", buttonText: "Dismiss")
            } else {
                // get the media manager from the drone to gain access to the files
                let manager = camera.mediaManager!

                manager.refreshFileList(of: DJICameraStorageLocation.sdCard, withCompletion:  { (error) in
                    if error != nil {

Error here after first download
                        self.testAlert(viewC: self, title: "Message", msg: "Error refreshing list: \(error!.localizedDescription)", buttonText: "Dismiss")
                    }else {

                        // get list of files
                        guard let files = manager.sdCardFileListSnapshot() else {
                            self.testAlert(viewC: self, title: "Message", msg: "No files to download", buttonText: "Dismiss")
                            return
                        }
                        self.downloadImages(files: files, completion: { images in
                            //process images
                           self.testAlert(viewC: self, title: "Message", msg: "Successfully downloaded all images and count \(images.count)", buttonText: "Dismiss")

                        })//end of downloadImages

                    }// end of else
                }) // end of file-refresh block
            } // end of if else
        })// end of camera setMode block
    }

    func downloadImages(files: [DJIMediaFile], completion: @escaping ([String]) -> Void){
        func downloadNextImage( files: [DJIMediaFile], index: Int = 0, downloadedFileUrls: [String] = []) {
            // stop when we reach the end of the list

            if (index >= files.count - 1)  {
                completion(downloadedFileUrls)
                return
            }
            else {
                var imageData = Data()
                var file = files[index]
                let isPhoto = file.mediaType == DJIMediaType.JPEG || file.mediaType == DJIMediaType.TIFF;

                var previousOffset: UInt = 0

                file.fetchData(withOffset: previousOffset, update: DispatchQueue.main, update: {(_ data: Data?, _ isComplete: Bool, _ error: Error?) -> Void in
                    if let error = error {
                        self.testAlert(viewC: self, title: "Error", msg: "File index : \(index) previousOffset : \(previousOffset) name: \(file.fileName) error : \(error)", buttonText: "Dismiss")
                    }
                    else {
                        imageData.append(data!)
                        previousOffset =  previousOffset + UInt((data?.count)!);
                        if isComplete {
                            if let image = UIImage(data: imageData) {
                                var imageUrl : String = ""
                                if(isPhoto){
                                    imageUrl = saveFile(imag)
                                }else //video
                                {
                                    //process video
                                }
                                downloadNextImage( files: files, index: (index + 1), downloadedFileUrls: downloadedFileUrls + [imageUrl])
                            }// If image
                        } //If complete
                    }// no eroor
                }) // end of filedata fetch
            }   // end of else statement
        }
        // start the recursive function
        downloadNextImage( files: files, index: 0)
    }


text:
Q: How to Mark Traffic using IPtables? I'm trying to mark traffic, How shall I write following code in terms of IPtables?
/ip firewall mangle> add chain=prerouting src-address=10.1.1.1/32 action=mark-connection \
new-connection-mark=server_con

/ip firewall mangle> add chain=forward connection-mark=server_con action=mark-packet  \
new-packet-mark=server

/ip firewall mangle> add chain=prerouting src-address=10.1.1.2
action=mark-connection new-connection-mark=workstation_con
/ip firewall mangle> add chain=prerouting src-address=10.1.1.3
action=mark-connection new-connection-mark=workstation_con
/ip firewall mangle> add chain=prerouting src-address=10.1.1.4
action=mark-connection new-connection-mark=workstation_con

/ip firewall mangle> add chain='''forward''' connection-mark=workstation_con  action=mark-packet \
new-packet-mark=workstations

The above code was on mikrotik firewall and I want to implement them on LinuxBox

A: You can translate MikroTik firewall rules to Linux iptables rules pretty easily.  The only real difference is that iptables marking isn't quite as pretty, it likes 32 bit flags instead of nice long names, but "1" suffices most of the time.
According to the iptables man pages:

*

*add chain=prerouting : -t mangle -A PREROUTING (Appends a new rule to the end of the mangle PREROUTING chain)

*src-address=10.1.1.1/32 : -s 10.1.1.1/32 (Triggers on packets with a source address of 10.1.1.1/32)

*action=mark-connection new-connection-mark=server_con : -j CONNMARK --set-mark 1 (marks these connections as "1")

*connection-mark=workstation_con action=mark-packet new-packet-mark=workstations : -m connmark --mark 1 -j MARK --set-mark 1 (Marks all packets associated with connection "1" with packet mark "1")

You should be able to use these translations to create a set of rules to meet your needs.


text:
Q: Could not compile SwiftScript source: line 1:1: unexpected token: println I am learning Swift, and have downloaded the latest stable version (0.94.1) to a Linux machine and am trying to write some pure Swift code, and compiling it. So I have everything setup, and the examples from the examples folder work, and produce a file that says "Hellow, World!". But I want this to appear on the screen, just like println in the iOS documentation. So I have written a file which has one line println("Hello, World!") and tried to run it, but the output was Could not compile SwiftScript source: line 1:1: unexpected token: println.
Can someone post here a working hello world program?

A: For the one in your link, use trace() instead of println(). As Matt said, this is another 'Swift', not the one used by Apple.
trace() document:
http://swift-lang.org/guides/release-0.94/userguide/userguide.html#_trace
**9.3. trace**
trace will log its parameters. By default these will appear on both stdout and in the run log file. Some formatting occurs to produce the log message. The particular output format should not be relied upon. (since Swift 0.4)

Example:
trace("Hello world!!!")

You can also use this simulator to test swift
http://swift-lang.org/tryswift/


text:
Q: Handlebars.js grid with data I'm using Parse.com to pull data from my server and display it in a handlebars.js template.

This is the js for communicating with the API:
var Blog = Parse.Object.extend("Blog");

var Blogs = Parse.Collection.extend({
    model: Blog
});

var blogs = new Blogs();

blogs.fetch({
    success: function(blogs) {
        var blogsView = new BlogsView({ collection: blogs });
        blogsView.render();
        $('.main-container').html(blogsView.el);
    },
    error: function(blogs, error) {
        console.log(error);
    }
});

var BlogsView =  Parse.View.extend({
    template: Handlebars.compile($('#blogs-tpl').html()),
    render: function(){
        var collection = { blog: this.collection.toJSON() };
        this.$el.html(this.template(collection));
    }
});

How can I display this in a 5xn (5 column) grid?

A: Heh. Figured it out after some experimentation so here's my answer. Given that I'm using the Materialize framework I can just use the m3 class to set the width of the column (and get a grid of 4 columns).

I guess you can do the same thing with Bootstrap. The key is that #each appears outside of the div that determines the column width, i.e. col-sm-3, col-md-3, etc., so that you're repeating a 33.33% width column 3 three times, for example, before the next row is auto-generated.


text:
Q: Monogame, Nez: Switching scenes, opening menu I am starting with Monogame and Nez library/engine, and I am struggling with opening menu. My original idea was that game will be one Scene class, menu another one. On Esc key I will set Core.scene to new instance of menu scene and remember the original scene. When menu closes, I'll set Core.scene back to original one. However it does not work; when a scene is replaced, it is ended, and I cannot ressurect it.
So my question is - how should I do it? Clearly I have some flaw in my design, but can't see the right way to do it. Upon opening menu I want to pause game, show menu (possibly switch several menu screens), then unpause the game when menu closes and continue playing.

A: It's hard to be certain without seeing your code, but it sounds like what you need is to implement a state machine of some kind. You need to be able to hold a reference to the inactive/background state (a window, the play area, etc), so that once you are done with the current scene it resumes the old one.
One way to do this--and the one I personally like best--is to use a finite state machine(FSM) pattern.
The basic principle is that there is a stack of objects(scenes in this case), and each time a new scene begins you add that scene on the top of the stack. Once that scene concludes, you remove it from the stack (called popping from the stack).
It sounds convoluted but it's actually quite simple to use. Here's a simple example:
public class StateManager
{
    private ContentManager Content { get; set; }
    private Game1 Game { get; set; }
    private Stack<Scene> sceneStack = new Stack<Scene>();
    private GameState currentScene;
    private GameState previousScene;

    public StateManager(ContentManager content, Game1 game)
    {
        // Pretty common to pass one or both of these instances around in your code.
        this.Game = game;
        this.Content = content;
    }

    public void AddScene(GameState newScene)
    {
        // This is the crucial part. We are saving the state of the old scene.

        if (currentScene != null)
            this.previousScene = currentScene;

        sceneStack.Push(newScene); // New scene is stacked 'on top' of the old one
        this.currentScene = newScene;
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        // Out in Game1.cs we are calling this method from within
        // its own Draw() method.

        this.currentScene.Draw(spriteBatch);
    }
}

public class Scene : GameState
{
    // Any state information needed for your scene like menus, terrain, etc
}

public abstract class GameState
{
    // The base class for your Scenes which contains code relevant to all scene types.
    // You could go a step further and make an interface as well.

    public virtual void Draw(SpriteBatch spriteBatch)
    {
        // Logic to draw the game state. Textures, sprites, text, child
        // elements contained inside this state, etc.
    }
}

As you can see, with this set up, the StateManager's(and thus Game1's) Draw() method will always be actively rendering whatever scene is on the top of the stack, which should always be the newest scene added with the NewScene() method.
The RemoveScene() method is simple enough as you basically reverse what you did in NewScene(). Call sceneStack.Pop(); and and top scene is removed, setting the previous scene as currentScene will then ensure the last scene on the stack will pick up where it left off.
Of course there is a lot more logic you'll need to add for a real game, as things done in one scene might change the look or behavior of scenes further down the stack, but most of that can be handled within the Update() methods(which work fundamentally the same as the Draw() method here).
Hope that helps.


text:
Q: sqldatasource problem i have a listview with an sqldatasource and the link buttons don't get fired up, but if i use as datasource an String array they get fired up. Am i missing something in my code?
aspx page:
    <%
    SqlDataSourceArticoleUser.ConnectionString = conn;
    SqlDataSourceArticoleUser.SelectCommand = "SELECT top 10 * FROM (SELECT ROW_NUMBER() OVER (ORDER BY id desc) AS Row, * FROM articole) AS EMP WHERE Row >" + pag + " and username='" + user + "'";
            %>
<asp:ListView ID="ListViewArticoleUser" runat="server" DataSourceID="SqlDataSourceArticoleUser">
                <LayoutTemplate>
                    <ul>
                        <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
                    </ul>
                </LayoutTemplate>
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButtonEditArticolEdit" runat="server" Text="edit" CommandName="articoledit"></asp:LinkButton>
                    <asp:LinkButton ID="LinkButtonStergeArticolEdit" runat="server" Text="sterge" CommandName="articolsterge"></asp:LinkButton>
                </ItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSourceArticoleUser" runat="server"></asp:SqlDataSource>

aspx.cs page:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            SqlDataSourceArticoleUser.DataBind();
        }
    }
    protected void Page_Init(object sender, EventArgs e)
    {
        ListViewArticoleUser.ItemCommand += new EventHandler<ListViewCommandEventArgs>(ListViewArticoleUser_EventHandler);
    }
    protected void ListViewArticoleUser_EventHandler(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "articolsterge")
        {
        }
    }

A: I think you are missing something... When you use a string array as datasource, you will use the default c# dataadapter, that contains instructions for delete, update and insert.
When you are working with an sql datasource, you must configure how .net will deal with those operations. I can see you just configured the select operation. To have a full functional sqldatasource, I think you must fill other operations.
Check this article to help you with your datasource: http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/data/sqldatasource.aspx!
Specially this part:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
  ConnectionString="<%$ ConnectionStrings:Pubs %>"
  SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors]"
  UpdateCommand="UPDATE [authors] SET [au_id] = @au_id, [au_lname] = @au_lname,[au_fname] = @au_fname, [state] = @state WHERE [au_id] = @original_au_id"
  DeleteCommand="DELETE FROM [authors] WHERE [au_id] = @original_au_id"/>