text:
Q: Modal UITabBarController Design I am designing an iPhone App wherein I would like there to be a main screen. I then want users to be able to hit an info button in the bottom right of this screen and enter an entirely different interface that will handle options and various forms of data display.
After some research on View Controllers in Apple's documentation, I have determined that I definitely want to use a modal view when the info button is pressed. My problem, though, is that the interface that fits best is a UITabBarController. I'd like to have a tab in my UITabBarController that represents the main screen and, when touched, will tell the main screen to dismiss the UITabBarController.
I have seen quite a few examples on the web where people add custom view controllers with buttons that trigger the modal view dismissal to tabs on the UITabBarController, but I would like to entirely avoid displaying an extra view. As soon as the user touches the main screen tab, I'd like the modal view to dismiss. I have already experimented with approaches that placed the main screen in the UITabBarController, and was not satisfied, so I'm hoping somebody out there is familiar with the rare modal UITabBarController design and can offer me some guidance.
Is this at all possible? If not, how can I accomplish the same interface flow in a different way?
I haven't tried this yet, but is there a way I could set the UITabBarController up with an empty UIViewController to represent the main screen and call on a UITabBarControllerDelegate to send the dismiss message to the main screen before the empty view appears?

A: Ok, I figured this out. I admit this is probably not the most orthodox UI design, but I think it does make intuitive sense... somebody should probably link me to the Apple UI guideline that this violates, though.
The following code will allow a user to press an info button that will animate the presentation of a modal UITabBarController. In this example, the UITabBarController has only one tab and the tab bar has not been set up with icons or titles. Once in the modal view, the user can click the first tab in the bar and the modal view will be dismissed. (This logically means that you'll want to tell the UITabBarController to start at an index other than the first.)
- (IBAction)infoButtonPressed
{
     UIViewController *mainScreen = [[UIViewController alloc] init];
     NSArray *viewControllers = [[NSArray alloc] initWithObjects:mainScreen, nil];
     UITabBarController *tabBarController = [[UITabBarController alloc] init];
     tabBarController.viewControllers = viewControllers;
     //This means that "self" needs to implement the UITabBarControllerDelegate protocol
     tabBarController.delegate = self;
     [self presentModalViewController:tabBarController animated:YES];

     [mainScreen release];
     [viewControllers release];
     [tabBarController release];
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
     if (viewController == [tabBarController.viewControllers objectAtIndex:0]) {
          [self dismissModalViewControllerAnimated:YES];
     }
}

I am now, however, getting a warning about two-stage rotation animation:
Using two-stage rotation animation. To use the smoother single-stage animation, this application must remove two-stage method implementations.
Using two-stage rotation animation is not supported when rotating more than one view controller or view controllers not the window delegate

Preliminary research said that it was because I was using a UIImageViewController to display a background on my mainScreen view, but I have since changed that to UIColor initWithPatternImage. Anybody know how to get rid of the warning-- or if it even matters to ignore it?

A: Sounds like a confusing (or at least unusual) user experience. Tabs are expected to be the apps main navigation level.
You should consider showing the sections in a segmented button or in a vertical list with back navigation (e.g. The preferences app)


text:
Q: 403 Forbidden with laravel in shared hosting I've completed a project that i was working on, its a Laravel project,
and it's an application totaly separated, i have a page index.html with a link that anyone can click on to access to the application.
so i created a new file called espace and i placed all my project files there, also i put all laravel files in an other file called client, except the public file i placed all the files directly to the espace file.
Now, my probleme is that i keep getting 403 Forbidden error and that i cant acces to mywebsite.com/espace because i dont have the permission, i just dont know how i can solve this one ?
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java enter integer and output spaced digits and sum I'm a struggling newbie trying to finish a program assignment and am stuck with my output repeating itself with the digits of an integer that should be together on one line, but spaced (Correct Ex:The digits of 1234 are: 1 2 3 4). Here is an example of the incorrect output and below that is my program. Any guidance would be greatly appreciated.
Enter an integer: 1234
The digits of 1234 are: 1
The digits of 1234 are: 2
The digits of 1234 are: 3
The digits of 1234 are: 4
The sum of the digits = 10
My program:
import java.util.*;

public class IntegertoIndividualtoSum
{
   public static void main(String[] args)
   {

      long integer, digit, sum = 0;
      char digitAt;
      String Stringnum;

      Scanner keyboard = new Scanner(System.in);

      System.out.print("Enter an integer: ");
      integer = keyboard.nextLong();

      Stringnum = String.valueOf(Math.abs(integer));

      for (int count = 0; count < Stringnum.length(); count++)
      {
         digitAt = Stringnum.charAt(count);

         digit = Character.getNumericValue(digitAt);

         sum += digit;

         System.out.println("The digits of " + integer + " are: " + digit);
      }
         System.out.println("The sum of the digits = " + sum);
    }
}

A: You are using the method System.out.println, which will print a new-line at the end. You can use System.out.print, which won't do that.
Also, remember that you get the part "The digits of ... are: ..." many times because it is inside the for loop.
System.out.print("The digits of " + integer + " are: ");

for (int count = 0; count < Stringnum.length(); count++) {
    // ...
    System.out.print(digit + " "); // add space
}

System.out.println("\nThe sum of the digits = " + sum); // note new-line character '\n'

Note:

*

*You can add a new-line character inside the String you want to print with "\n".

A: Part of your problem is that you're printing the entire line for each digit. You're looping across the length of the string, and printing your output on every iteration.
Your second problem is that System.out.println automatically appends a newline character to the end of the argument you pass in. If you use System.out.print, you'll get your output on one line as you expect it.
That should be enough to get you started.

A: If you do something inside a loop, it will happen each time you go through the loop.
Think about what you want to do once before entering the loop, what you want to do for each iteration of the loop, and once after completing the loop.
Also, be aware that you can call print(...) rather than println(...) to print without going to a new line at the end, and you can call println() with no arguments to go to a new line without printing anything.


text:
Q: Hit-testing line segments 1) I have a list of line segments (defined by their two endpoints and a width.)
2) These line segments are drawn in a panel.
3) When my mouse moves (Panel.MouseMove event), I loop over the list of line segments.
4) Foreach:
  gPath.Reset();
  Pen Pen = new Pen(Color.White, 20);
  gPath.AddLine(P1, P2);
  return gPath.IsOutlineVisible(cursorPos, Pen);

5) If I get true, then I know my cursor is hovering over the current line segment.
This works fine for about... 300 lines or so. When I reach 1,000 my program slows to a halt (profiling shows that it's caused by IsOutlineVisible). So, is there any way I could increase performance of my hit-testing algorithm? I don't know how efficient IsOutlineVisible is, so I don't want to implement any optimizations that the method already uses. Any ideas?
EDIT:
After digging into my data I noticed some of the lines were extremely large. For example:
endpoint1 = (16000, -16000)
endpoint2 = (5041448, -32868734)
(yes, one of the coordinates is in the negative tens of millions...)
I verified that hit-testing against just one such line segment is enough to bring my program to a halt, (IsOutlineVisible takes 2-3 seconds to do the test, and the test is run whenever the cursor moves...).
I should have tested this more thoroughly before posting. Thanks to all that responded (a 2d spatial index is a great suggestion if I end-up handling thousands of lines).
p.s. If anyone knows why a large line-segment is that big a problem for IsOutlineVisible, that would be great.

A: Try this:
public Line GetHotSpottedLine(Point mousePos){
        var line = lines.Where(line =>
        {
            Point p1 = new Point(Math.Min(line.P1.X, line.P2.X), Math.Min(line.P1.Y, line.P2.Y));
            Point p2 = new Point(Math.Max(line.P1.X, line.P2.X), Math.Max(line.P1.Y, line.P2.Y));
            return mousePos.X >= p1.X && mousePos.X <= p2.X && mousePos.Y >= p1.Y && mousePos.Y <= p2.Y;
        }).FirstOrDefault(line => {
            using (GraphicsPath gp = new GraphicsPath())
            {
                gp.AddLine(line.P1, line.P2);
                //You can declare your pen outside and this pen should be used to draw your lines.
                using (Pen p = new Pen(Color.Red, 20))
                {
                    return gp.IsOutlineVisible(mousePos, p);
                }
            }
        });
        return line;
 }
 public class Line{
        public Point P1 { get; set; }
        public Point P2 { get; set; }
 }
 List<Line> lines = new List<Line>();

It depends on how you want to use your lines, if you want to draw them, we have to notice the performance of drawing not detecting the hovered line, yes in that case, drawing is your problem. I think we can use some Thread here. Anyway, I tested with 1000 lines and it works OK (with drawing all the lines in Form Paint) without using any thread.

A: IsOutlineVisible calls the Gdi+, maybe this slows it down a bit.
public bool GraphicsPath.IsOutlineVisible(PointF pt, Pen pen, Graphics graphics)
{
  int num;
  if (pen == null)
  {
      throw new ArgumentNullException("pen");
  }
  int status = SafeNativeMethods.Gdip.GdipIsOutlineVisiblePathPoint(new HandleRef(this, this.nativePath), pt.X, pt.Y, new HandleRef(pen, pen.NativePen), new HandleRef(graphics, (graphics != null) ? graphics.NativeGraphics : IntPtr.Zero), out num);
  if (status != 0)
  {
      throw SafeNativeMethods.Gdip.StatusException(status);
  }
  return (num != 0);
}

Beside that, these hit testing do not use optimizations like building an 2d index of all graphical elements used. To improve the performance I would try to

*

*implement hit testing yourself and iterating over all elements

*maybe use a 2D index, although for < 1000 elements I hardly believe this is necessary.


text:
Q: Postgresql internal record id / creation date I'm trying to determine whether or not postgresql  keeps internal (but accessible via a query) sequential record ids and / or record creation dates.
In the past I have created a serial id field and a record creation date field, but I have been asked to see if Postgres already does that.  I have not found any indication that it does, but I might be overlooking something.
I'm currently using Postgresql 9.5, but I would be interested in knowing if that data is kept in any version.
Any help is appreciated.
Thanks.

A: No is the short answer.
There is no automatic timestamp for rows in PostgreSQL.
You could create the table with a timestamp with a default.
create table foo (
foo_id serial not null unique
, created_timestamp timestamp not null
    default current_timestamp
) without oids;

So
insert into foo values (1);

Gives us

You could also have a modified_timestamp column, which you could
update with an after update trigger.
Hope this helps


text:
Q: Redirect too many in htaccess Currently I'm trying to work on my .htaccess file
What I want to do is to redirect all request to https://example.com/
Means all request for different pages of the domain should be redirect to the homepage/landing page for now.
I tried to do this in .htaccess
Redirect 301 / https://example.com/
But this gives me an output like this
redirect too many times

A: Well, looks like your are also redirecting requests to https://example.com/ to https://example.com/, right? ;-)
You need to take care that you only apply your redirection rule if the incoming request does not already request exactly that URL you are trying to redirect to. Two approaches here:
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/$
RewriteRule ^ https://example.com/ [R=301,L]

Or just:
RewriteEngine on
RewriteRule ^/?.+ https://example.com/ [R=301,L]

It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out...
This implementation will work likewise in the http servers host configuration or inside a distributed configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a distributed configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.
And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using distributed configuration files (".htaccess"). Those distributed configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).


text:
Q: Most efficient way to create lower resolution texture from a texture in Metal? I have a large MTLTexture (up to 16k) that I need to create a lower resolution texture from - say half or quarter scale.
I can draw the high res texture into a lower resolution texture with:
let descriptorSmallerCanvas = MTLRenderPassDescriptor()
descriptorSmallerCanvas.colorAttachments[0].texture = canvasTextureSmaller
descriptorSmallerCanvas.colorAttachments[0].storeAction = .store
descriptorSmallerCanvas.colorAttachments[0].loadAction = .clear
let renderSmallCanvas = commandBuffer.makeRenderCommandEncoder(descriptor: descriptorSmallerCanvas)
renderSmallCanvas?.pushDebugGroup("Render Small Texture")
renderSmallCanvas?.setRenderPipelineState(renderCanvasPipelineState)
renderSmallCanvas?.setFragmentTexture(canvasTexture, index: 0)
renderSmallCanvas?.setVertexBuffer(uniformOrthoBuffer, offset: 0, index: 0)
renderSmallCanvas?.setCullMode(.none)
renderSmallCanvas?.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4, instanceCount: 1)
renderSmallCanvas?.popDebugGroup()
renderSmallCanvas?.endEncoding()

That works, but I was wondering if there was a more efficient way to do this? Would MTLBlitCommandEncoder's generateMipmaps(for: canvasTexture) be more efficient, or is there a more efficent way?

A: The answer depends on the algorithm you want to downscale with.
Without knowing what renderCanvasPipelineState  is, I would guess that it renders a fullscreen quad that  Rendering larger texture into smaller texture will use minFilter of the sampler state you have in your shader (I guess it's a constexpr sampler since you don't bind any here) so it would only use MTLSamplerMinMagFilterLinear at best, which isn't "high-quality" downscaling.
I think your best bet without writing your own resize is to use MPSImageLanczosScale or MPSImageBilinearScale
 depending on the quality tradeoffs you want to make.
P.S. You don't need to .clear your attachment if you are filling the whole screen without blending, leave it at .dontCare and it will overwrite every pixel.


text:
Q: Uncountable connected graph such that complement is also connected Is there a connected simple undirected graph $G=(V, E)$ such that $|V| > \aleph_0$ and the complement of $G$ is also connected?

A: Sure.  Here's a construction that works for any vertex set $V$ with at least $4$ points.  Split $V$ into two sets $A$ and $B$ which both have at least two elements, and let $G$ be the complete bipartite graph with respect to the partition $V=A\cup B$ with one edge removed.  Since one edge was removed, the complement of $G$ is connected; since both $A$ and $B$ have at least two points, it is easy to show that $G$ is connected.

A: Sure. Let $V$ be a large enough ordinal. For $x\in V$ add an edge to $x+1$ and also add edges between any two non-successor ordinals in $V$.


text:
Q: ItemReader for JPARepository spring batch + spring boot I have a spring batch application wherein reader will read data from a source and processor would transform it to destination db compatible POJO , and writer would write the obtained transformed POJO to destination db
Following is my jpa repository code
public interface MyCrudRepository extends JpaRepository<MyDbEntity, String> {

    List<MyDbEntity> findByPidBetween(String start, String end);

    List<MyDbEntity> findByPidGreaterThan(String start);

}

I want my reader to call findByPidBetween or findByPidGreaterThan based on the check if job parameter contains endPid parameter or not.
I am struggling to figure out which ItemReader to use for the same? Below is what I tried
@Component
@StepScope
public class MyItemReader extends RepositoryItemReader<MxGaanaDbEntity> {

@Value("#{jobParameters}")
private Map<String, JobParameter> jobParameters;

@Value("${end.pid}")
private String endpid;

private List<MyDbEntity> myDbEntities;

@Override
public void setRepository(@Qualifier("myCrudRepository")PagingAndSortingRepository<?, ?> repository) {
    super.setRepository(repository);
}

@Override
public void setMethodName(String methodName) {

    if (StringUtils.isEmpty(endpid))
        super.setMethodName("findByPIdGreaterThan");
    else
        super.setMethodName("findByPIdBetween");

}

@Override
public void setArguments(List<?> arguments) {

    JobParameter rawStartPid = jobParameters.get("startPid");

    String startPid = (String) rawStartPid.getValue();

    List<String> args = new ArrayList<>();
    args.add(startPid);

    if (!StringUtils.isEmpty(endpid)) {
        args.add(endpid);
    }

    super.setArguments(args);

}

}
I keep getting following exception :
Caused by: java.lang.IllegalStateException: A PagingAndSortingRepository is required


text:
Q: Is the Schroedinger picture outside the contemporary maintstream? By the Schroedinger picture, I mean the notion that atoms exist in a superposition of states, as opposed to the Copenhagen picture, which I understand to mean that in a system of atoms, all the atoms are in discrete eigenstates and jump instantaneously from one state to another with the emission and absorption of photons. If I follow what I've called the Schroedinger picture, am I outside of standard physics (and therefore outside the parameters of this discussion group?
For example: let us consider a system of hydrogen atoms where 90% of them are in the ground state and 10% are in the 2s or 2p state (as described by the Copenhagen picture.) Am I justified as looking at the same system as though each atom was in a superposition of two states, 90% ground level and 10% excited state? Or does it put me outside the mainstream for me to take that point of view?
And do the two points of view lead to different physics? Can we say conclusively that one or the other is correct?

A: By "the Copenhagen version" you seem to have some kind of Bohr model picture in mind, in which there is no such thing as quantum superposition(please correct me if I am wrong), in which case it is this Copenhagen picture that is outside mainstream physics. Superposition is a phenomenon which has, at this point, been experimentally verified countless times.
It is, however, important to note that a collection of atoms in which 90% are in one state and 10% are in another is a very different state to one in in which all the atoms are in a 90%-10% superposition. The latter would be a pure state while the former would be a mixed state of the system.

A: First of all, I should say that you are not using "Schrodinger" and "Copenhagen" pictures in a way that I as a physicist recognize as mainstream. I would regard "Schrodinger picture" as just being one way of organizing time-dependence (as opposed to "Heisenberg") and the "Copenhagen interpretation" (not "picture") as being related to wavefunction collapse upon measurement.
However, I can answer the question of whether we can treat superpositions as ensembles or not. The answer is no, as I will argue from a quantum information perspective. Suppose we start with many atoms/qubits, which are all in a $| 0 \rangle + | 1 \rangle$ state. I then apply a rotation by $\phi$ about the Z axis of the Bloch sphere, and my state will be:
$$
\left( | 0 \rangle + e^{i \phi} |1 \rangle \right)^{\otimes N}
$$
Then I perform a Hadamard transform and measure. I will measure the state $|0 \rangle$ in each qubit with probability $\cos^2 \phi/2$.
Or, I could have started with half my atoms in $| 0 \rangle$ and half in $| 1 \rangle$. Under the transforms I said before, the Z-rotation no longer matters--it adds a trivial phase to each individual wavefunction. Therefore the Hadamard transform will simply map both of them to equal superpositions (population-wise) of $| 0 \rangle$ and $| 1 \rangle$, and I measure $|0 \rangle$ with probability $1/2$ for all of them. Since one of these measurement procedures is sensitive to the rotation, and one is not, I can clearly tell the difference between the two. This is precisely how Ramsey interferometry works, and so is the basis of e.g. atomic clock timekeeping, atomic magnetometry, atomic gravimetry, and other quantum measurement schemes.

A: The usual "Schroedinger picture" is only one way to formulate the standard "Copenhagen version" of quantum mechanics just like the "Heisenberg picture" or the Dirac picture. They are mathematically equivalent. As far as I know, there exists no "Copenhagen picture" as opposed to the Schroedinger picture. People talk about the "Copenhagen interpretation" of quantum mechanics which is the interpretation mostly propagated and assumed in textbooks. But different interpretations usually make the same predictions based on equivalent mathematics. Also in pictures other than the Schroedinger picture atoms can exist in a superposition of eigenstates. The quantum mechanics is exactly the same. When you prepare a system of hydrogen atoms 90% in the ground state and 10% in the 2s or any other definite state, this is not equivalent to a system of hydrogen atoms each prepared in a superposition of 90% probability of the 1s eigenstate and 10% probability in the other specific excited state. All pictures of standard quantum mechanics would give you this same answer.


text:
Q: What is the best way to setup my "main" for a class library? Okay so I'm trying to create an class library for an existing game.
I'm stuck with a problem though I'd like to clear up and have done properly.
So let's say I've got my Class library in the namespace Api
This api contains multiple classes for example: Memory, Client, Player, Keyboard
Now I don't want the person using this Api to have to initialize everything personally.
I came up with the solution to use an extra class containing the initialized instances for the other classes so the user can do the following
using Api

Api.API MyGame = new Api.API();

And then having the API class be something like this:
public class API {
    public Player player;
    public Client client;

    public API(){
        Player = new Player();
        Client = new Client();
    }
}

I'm wondering if this is a correct way of doing or if I'm totally in the wrong here.

A: Take a look at using Dependecy Injection / Inversion of Control:

*

*Autofac for registering (there are several others, such as Ninject, etc)

*Managed Extensibility Framework for assembly discovery (using export and imports)


text:
Q: Derivatives interpreted as fractions So I was wondering if manipulating differential as fraction is fine.In Physics problems ,usually, what I see is if we have equations of magnetic field ,we consider a magnetic field caused by a small length dl and the magnetic field is dB and integrating over the whole length.it seems we are treating dB as a infintesimal quantity.However ,after browsing for a while,the answer is that the notation dy/dx is not a infintesimal quantity but rather an operation on the function y.I am confused as to how it is valid in physics to treat it as infintesimal quantities.(After learning it,my notion for physics just got crushed and am now confused).I have not learned multivariable calculus yet,but from the arguments I've read ,I found that interpreting them as fractions does not work anymore.But it seems it works fine when in 2 dimensions.In mechanics when we derive equation for rocket motion (ejecting mass) we interpret differential as small quantities (dm) and divide by small time dt.Sorry for the long story... I am confused right now
TL:DR : In physics ,dy/dx can be operated as if it was a small quantity divided by small quantity,though from what I've read it is not supposed to be a ratio.
When does interpreting them work and when does it not. Any help would be very much appreciated ...

A: I think you meant "derivatives" rather than "differentials" and are asking if it is valid to "treat derivatives as fractions with differentials as numerator and denominator".
Yes, it is.  To show that any given property of a fraction still holds for a derivative, go back before the limit in the definition of the derivative to the "difference quotient", use the fraction property, then take the limit.


text:
Q: Android RecyclerView update Adapter I've got a recyclerView with adapter. I tried to set adapter programmatically, but it doesnt work.
Here's my code:
public class RecordAdapter extends RecyclerView.Adapter<RecordViewHolder>{

    private List<RecordData> records;

    public RecordAdapter(){
        records = new ArrayList<>();
    }

    @Override
    public RecordViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        FLog.d("Records: creating new recordViewHolder");
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.record_item, parent, false);
        return new RecordViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecordViewHolder holder, int position) {
        RecordData data = records.get(position);
        FLog.d("Records: binding new recordViewHolder");

        holder.mRecordText.setText("Record " + position);
    }

    @Override
    public int getItemCount() {
        FLog.d("Records: count is - " + records.size());
        return records.size();
    }

    public void addRecord(RecordData newRecord){
        records.add(newRecord);
        this.notifyDataSetChanged();
    }
}

My RecordViewHolder is:
public class RecordViewHolder extends RecyclerView.ViewHolder{

@Bind(R.id.record_play_button)
public ImageButton mRecordPlay;

@Bind(R.id.record_message_text)
public TextView mRecordText;

@Bind(R.id.record_seek_bar)
public SeekBar mSeekBar;

public RecordViewHolder(View itemView){
    super(itemView);
    ButterKnife.bind(this, itemView);
}

I've tried to set adapter like this:
if (adapter == null){
    adapter = new RecordAdapter();
}

adapter.addRecord(recordData);
holder.mIncomingRecordList.setAdapter(adapter);

But I my adapter didnt call methoda onCreateViewHolder and onBindViewHolder
My XML file with recyclerView:
<LinearLayout xmlns:a="http://schemas.android.com/apk/res/android"
            a:orientation="vertical"
            a:layout_width="wrap_content"
            a:layout_height="wrap_content">

    <LinearLayout
        a:layout_width="wrap_content"
        a:layout_height="wrap_content">

.......

        <LinearLayout
            a:layout_width="wrap_content"
            a:layout_height="wrap_content">

               <android.support.v7.widget.RecyclerView
                      a:layout_width="match_parent"
                      a:layout_height="match_parent"
                      a:id="@+id/record_list"/>
        </LinearLayout>
   </LinearLayout>
</LinearLayout>


text:
Q: UWP render 3D model in a I'm writing a C# Universal Windows Application that loads a model from a .obj file and I would like to render that model so that the user can rotate it and scale it. Is there a way to render it in the app? Preferably in the same window? Something like the Map control, it's wrapped inside the app but still interactive.

A: I found this MSDN article for Windows 8.1 phone that tells us to use PlaneProjection.
 <StackPanel.Projection>
    <PlaneProjection RotationX="-35" RotationY="-35" RotationZ="15"  />
</StackPanel.Projection>

DirectX may be the answer to loading the obj file. "  DirectX has limited features when it comes to loading a 3D model: It is recommended to use the DirectXTK (toolkit) to handle them. The 3D model file formats that it supports are: .CMO, .SDKMESH and .VBO. It should support .OBJ too (if my memory serves me well)...."
https://mva.microsoft.com/en-US/training-courses/c-directx-game-development-blending-and-models-8491?l=uG7SBIYz_8604984382


text:
Q: Is there any Algorithm, To find the available bandwidth between two peers on Internet? I am trying to develop a program which displays the available bandwidth between two peers. Later this module will be integrated in my application which facilitates various user interactions (chatting, desktop sharing etc) using P2P architecture.
Somewhere I read about Spruce algorithm to find the current available bandwidth between two peers, but I am not sure whether that can be used or not.
Is there any already developed algorithm to achieve this ? Plz remember  the architecture is P2P.
this seemed an easier problem when I started working on it, but now I realize it is alot tougher than it looks,.... So I need the help of experienced and enthusiastic network programmers......
thanks in advance..

A: I can think of one.
Send a file and time it. There's your approximate available bandwidth. Need a better approximation? Send a bigger file.

A: I found this thread on Stackoverflow that is somewhat similar to your question.
Calculating available bandwidth
Hopefully, you'll find an answer there.


text:
Q: Pressure loss in concentric reducer with low Reynolds number and high viscosity fluid This is my first question in stack Exchange,I'm making the overall calculus por a piston dossifier of viscous fluid like Honey and Carob Syrup, and I am currently struggling with the minor losses of concentric reducers in my system,
**The picture from below is a concept of the system **

So in the system a plunger goes back and forth sucking and pushing the liquid from a three way valve which change it's state depending of the phase.
The current problem that i found that it seems to be that all the current formulas that i've found in for concentric reductions do not consider Reynolds factor but one ( https://neutrium.net/fluid-flow/pressure-loss-from-fittings-expansion-and-reduction-in-pipe-size/) However using the equations from the website ( I couldn't find a book yet that corroborates the equation) the head loss becomes too big and therefore the pressure drop in the reducers is ludicrous high.
If you haven't read the website this is a sum up of the equations for K coefficient

As my system's Reynolds numbers do not go up from 20 you could imagine how much K rises, The equation by it's own seems to fit with normal reducers K value, considering how small is water viscosity and makes the Reynolds numbers which in turn make negligible the 160 value.
So as a conclusion i'll be glad to know if anybody knows another sources which considers Reynolds number for minor losses's elements ( like reducers)
The liquids which i'm working with have dynamic viscosity of 10 Pa.s and 60 Pa.s, therefore the low Reynolds number.
Thanks in advance


text:
Q: Spring Portlet MVC - how to catch mapping exceptions is there a way to provide my spring portlets a default state which is resolved if a unavailable expcetion occurs?
I recieve this exception
10:24:53,187 ERROR [517: org.jboss.portal.portlet.impl.jsr168.PortletContainerImpl] The portlet threw an exception
javax.portlet.UnavailableException: No matching handler method found for portlet request: mode 'view', phase 'ACTION_PHASE', parameters map[[empty]]
    at org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter$PortletHandlerMethodResolver.resolveHandlerMethod(AnnotationMethodHandlerAdapter.java:488)
    at org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:354)
    at org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter.doHandle(AnnotationMethodHandlerAdapter.java:345)
    at org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter.handleAction(AnnotationMethodHandlerAdapter.java:280)
    at org.springframework.web.portlet.DispatcherPortlet.doActionService(DispatcherPortlet.java:646)
    at org.springframework.web.portlet.FrameworkPortlet.processRequest(FrameworkPortlet.java:519)
    at org.springframework.web.portlet.FrameworkPortlet.processAction(FrameworkPortlet.java:460)

I would like to catch this exception and return simply the default "VIEW" state or something.
*-portlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        <context:annotation-config/>
        <!-- Controllers -->
        <bean id="portletController" class="de.nv.spring.portlets.PortletController"/>

        <!-- Handler Mappings -->
        <bean class="org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
</beans>

A: Do you have a default rendering/action -methods? For me the following default rendering method works:
@RenderMapping(params="!render")
public String defaultRender(RenderRequest req, RenderResponse res, Model model) throws PortalException, SystemException {
   // do something
}

The annotation value !render means that this is run if there exists no render-parameter. Intuitively, you could use the same approach on your action-parameter.

A: Fixed in Spring 3.0.5 (see https://jira.springframework.org/browse/SPR-7542?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel)


text:
Q: KafkaStreams: Getting Window Final Results Is it possible to get window final result in Kafka Streams by suppressing the intermediate results.
I can not achieve this goal. What is wrong with my code?
    val builder = StreamsBuilder()
    builder.stream<String,Double>(inputTopic)
            .groupByKey()
            .windowedBy(TimeWindows.of(Duration.ofSeconds(15)))
            .count()
            .suppress(Suppressed.untilWindowCloses(unbounded())) // not working)
            .toStream()
            .print(Printed.toSysOut())

It leads to this error:
Failed to flush state store KSTREAM-AGGREGATE-STATE-STORE-0000000001:
java.lang.ClassCastException: org.apache.kafka.streams.kstream.Windowed cannot be cast to java.lang.String

Code / Error details: https://gist.github.com/robie2011/1caa4772b60b5a6f993e6f98e792a380

A: Problem is with the KeySerde. Since WindowedBy operation results in Windowed<String> type key but .suppress() is using a default key type.
Hence you need to define KeySerde on the State store while calling the count method as given below:
      builder.stream<String,Double>inputTopic)
      .groupByKey()
      .windowedBy(TimeWindows.of(Duration.ofSeconds(15)))
      .count(Materialized.<String, Long, WindowStore<Bytes,byte[]>>as("count").withCachingDisabled().withKeySerde(Serdes.String()))
      .suppress(Suppressed.untilWindowCloses(BufferConfig.unbounded()))
      .toStream()
      . print(Printed.toSysOut());

A: The problem is a confusing asymmetry in the way that Streams automatically wraps explicit serdes during windowing, but does not automatically wrap the default serde. IMHO, this is an oversight that should be corrected, so I've filed: https://issues.apache.org/jira/browse/KAFKA-7806
As others have noted, the solution is to explicitly set the key serde upstream and not rely on the default key serde. You can either:
Set the serdes on the windowed aggregation with Materialized
val builder = StreamsBuilder()
builder.stream<String,Double>(inputTopic)
        .groupByKey()
        .windowedBy(TimeWindows.of(Duration.ofSeconds(15)))
        .count(Materialized.with(Serdes.String(), Serdes.Long()))
        .suppress(Suppressed.untilWindowCloses(unbounded())))
        .toStream()
        .print(Printed.toSysOut())

(as Nishu recommended)
(note that it is not necessary to name the count operation, which has the side effect of making it queriable)
Or set the serdes further upstream, for example on the input:
val builder = StreamsBuilder()
builder.stream<String,Double>(inputTopic, Consumed.with(Serdes.String(), Serdes.Double()))
        .groupByKey()
        .windowedBy(TimeWindows.of(Duration.ofSeconds(15)))
        .count()
        .suppress(Suppressed.untilWindowCloses(unbounded())))
        .toStream()
        .print(Printed.toSysOut())

(as wardziniak recommended)
The choice is yours; I think in this case it's not too much different in either case. If you were doing a different aggregation than count, you'd probably be setting the value serde via Materialized anyway, so maybe the former would be a more uniform style.
I also noticed that your window definition doesn't have a grace period set. The window close time is defined as window end + grace period, and the default is 24 hours, so you wouldn't see anything emitted from the suppression until 24 hours' worth of data have run through the app.
For your testing effort, I'd recommend trying:
.windowedBy(TimeWindows.of(Duration.ofSeconds(15)).grace(Duration.ZERO))

In production, you'll want to select a grace period that balances the amount of event lateness you expect in your stream with the amount of emission promptness you wish to see from the suppression.
One final note, I noticed in your gist that you haven't changed the default caching or commit interval. As a result, you'll notice that the count operator itself will buffer updates for the default 30 seconds before passing them on to suppression. This is a good config for production so you don't create a bottleneck to your local disk or to the Kafka broker. But it might surprise you while you're testing.
Typically for tests (or interactively trying stuff out), I'll disable caching and set the commit interval short for maximum developer sanity:
properties.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
properties.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 100);

Sorry about the serde oversight. I hope we get KAFKA-7806 addressed soon.
I hope this helps!

A: Add Consumed, when you create stream: builder.stream<String,Double>(inputTopic, Consumed.with(Serdes.String(), Serdes.Double())


text:
Q: Cordova android app crashes on Galaxy S3 ? I am creating new android app using cordova. My app was crashed on Galaxy S3 device. If i click link button on home page, it will crashed. Here i added the issue details. How to solve this issue. Please guide me.
I am using cordova version is 3.6.4.
    *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
    Build fingerprint: 'samsung/d2tmo/d2tmo:4.3/JSS15J/T999UVUENC2:user/release-keys'
    Revision: '16'
    pid: 18307, tid: 18320, name: WebViewCoreThre >>> com.rcs.rcs <<<
    signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad
    Abort message: '@@@ ABORTING: heap corruption detected by tmalloc_large'
    r0 00000027 r1 00000000 r2 00000008 r3 deadbaad
    r4 00000000 r5 5e8c0754 r6 5f752340 r7 5f752340
    r8 417dc000 r9 00000001 sl 000020ef fp 5e8c0c84
    ip 00000001 sp 5e8c0750 lr 400e4497 pc 400e19b8 cpsr 60000030
    d0 524f424120404040 d1 6568203a474e4954
    d2 7572726f63207061 d3 6564206e6f697470
    d4 4061db6db7281fda d5 000002d044870000
    d6 4434000044340000 d7 4499c000000004ce
    d8 0000000000000000 d9 0000000000000000
    d10 0000000000000000 d11 0000000000000000
    d12 0000000000000000 d13 0000000000000000
    d14 0000000000000000 d15 0000000000000000
    d16 0000000000000000 d17 0000000000000000
    d18 bf847ae147ae147b d19 0000000500000009
    d20 0000000100000001 d21 0000000000000000
    d22 42ea000042ea0000 d23 41500000441c8000
    d24 0000381f0000381f d25 00003aed00003b86
    d26 3a3b38383a3b3d39 d27 262928282a2b2c26
    d28 1b1d19191b1a1b16 d29 ffffffffffffffff
    d30 00008800ffff4d00 d31 e92d4000ffff1d80
    scr 60000013

    backtrace:
    #00 pc 0001e9b8 /system/lib/libc.so
    #01 pc 0001c914 /system/lib/libc.so (abort+4)
    #02 pc 00012495 /system/lib/libc.so
    #03 pc 0000ebb9 /system/lib/libc.so
    #04 pc 0000fa87 /system/lib/libc.so (dlmalloc+606)
    #05 pc 0000dc53 /system/lib/libc.so (malloc+10)
    #06 pc 0000091b /system/lib/libstdc++.so (operator new(unsigned int)+2)
    #07 pc 00291b79 /system/lib/libwebcore.so
    #08 pc 00291c41 /system/lib/libwebcore.so
    #09 pc 00291c79 /system/lib/libwebcore.so
    #10 pc 00020b4c /system/lib/libdvm.so (dvmPlatformInvoke+112)
    #11 pc 000516ab /system/lib/libdvm.so (dvmCallJNIMethod(unsigned int const*, JValue*, Method const*, Thread*)+398)
    #12 pc 00029fe0 /system/lib/libdvm.so
    #13 pc 0002e9a4 /system/lib/libdvm.so (dvmInterpret(Thread*, Method const*, JValue*)+184)
    #14 pc 0006382d /system/lib/libdvm.so (dvmCallMethodV(Thread*, Method const*, Object*, bool, JValue*, std::__va_list)+292)
    #15 pc 00063857 /system/lib/libdvm.so (dvmCallMethod(Thread*, Method const*, Object*, JValue*, ...)+20)
    #16 pc 000585bb /system/lib/libdvm.so
    #17 pc 0000cc60 /system/lib/libc.so (__thread_entry+72)
    #18 pc 0000cddc /system/lib/libc.so (pthread_create+208)

    code around pc:
    400e1998 461ce00b 2b006823 e026d1fb b12468e4
    400e19a8 21014a18 6011447a 4b1247a0 24002027
    400e19b8 f7fc7018 2106edcc e832f7fe 5180f04f
    400e19c8 a9029104 94022006 9403460a ebcef7fd
    400e19d8 46224629 f7fd2002 f7fcebda 2106edb8
    400e19e8 e81ef7fe f7fc2001 6960ea64 d1dc2800
    400e19f8 bf00e7d4 deadbaad 00029660 ffffff9c
    400e1a08 0002c904 0002c8e8 2400b510 aa04b088
    400e1a18 46699002 94014620 94039400 eb1cf7fd
    400e1a28 db0642a0 b1139b07 1c419806 98069106
    400e1a38 4620e000 bd10b008 4b1eb40e b082b5f0
    400e1a48 447b491d f107af00 585e021c f8522101
    400e1a58 68354b04 f852607d 31015b04 d1fa2d00
    400e1a68 320e008a 0507f022 0220f107 0d05ebad
    400e1a78 f107603a 46690224 9400466d 4c04f852
    400e1a88 f8453204 2c004f04 f8dfd1f8 f853c030

    code around lr:
    400e4474 4a0e4b0d e92d447b 260041f0 4680589c
    400e4484 686768a5 f9b5e007 2b00300c 4628dd02
    400e4494 430647c0 3f013554 6824d5f5 d1ef2c00
    400e44a4 e8bd4630 bf0081f0 00026b5c ffffffc4
    400e44b4 43f0e92d fb01461e 4b16f502 4916460f
    400e44c4 447bb087 aa014614 20019001 95029203
    400e44d4 90049505 681a585b b1124698 f0094630
    400e44e4 4630fd4a f7ffa903 4681fe9c 0000f8d8
    400e44f4 4630b110 fd4cf009 0f00f1b9 9c05d005
    400e4504 1b284639 ec4ef017 46204604 e8bdb007
    400e4514 bf0083f0 00026b0e ffffff60 46036842
    400e4524 60411e51 da012900 bbbcf000 f8126802
    400e4534 601a0b01 00004770 4a104b0f b570447b
    400e4544 589b4604 461e6819 f009b109 6860fd14
    400e4554 60651e45 da042d00 f0004620 4605fba3
    400e4564 6822e003 5b01f812 68336022 4620b113


text:
Q: Is there a way to change meters to miles in the app? I am looking for a way to change meters to miles in the app.
Are there any settings for this?  I have been looking all through my phone and the game and see nowhere to do this.
Thank you

A: No, there's no way to change the units of measure, it's fixed to meters. Here you can see a discussion about this on Google Groups.


text:
Q: Analytic $N$th roots: can my statements here be generalized? I'm generally having trouble seeing when and why analytic functions have analytic $N$th roots.  I know the following statements to be true, but I know that they can also be generalized in various ways.  However, I'm not very confident in my ability to generalize them without making mistakes.

1 .  I know that if $g$ is analytic on a simply connected domain $V$, and $g(z) \neq 0$ on $V$, then there is an analytic function $\log$, defined on the image $g(V)$ (an open set), with the property that $e^{\log g} = g$.  For an arbitrary choice of $c \in V$, all we have to do is let $k$ be a complex number such that $e^k = g(c)$, and then define $\log g(z) = \int_c^z \frac{g'}{g} + k$. Then $g$ has an analytic $N$th root, namely $e^{\frac{1}{N} \log g}$.
2 .  More generally if $V$ is a disc $D_r(c)$, $g$ has a unique zero at $c \in V$, and the order of the zero is divisible by $N$, then $g$ also has an analytic $N$th root on $V$: write $g(z) = a_k(z-c)^k + \cdots$ with $k$ divisible by $N$, then $g(z) = (z-c)^k h(z)$, where $h(z)$ is analytic and nonvanishing on $D_r(c)$.  By (1), $h(z)$ has an analytic $N$th root on $D_r(c)$, and writing $(z-c)^k = ((z-c)^{\frac{k}{N}})^N$, we see that $g$ has an analytic $N$th root on $D_r(c)$.
3 .  If $g$ has a pole of order $k$ divisible by $N$ at $D_r(c)$, and $g$ doesn't vanish on $D_r(c) \setminus \{c\}$, then the same argument as in (2) works: $g$ has an analytic $N$th root on $D_r(c) \setminus \{c\}$, with a pole at $c$ of order $k/N$.

So, I would be very interested in anyone explaining, at a glance, how statements in (1), (2), (3) can be generalized.  In particular, I would be grateful if someone could answer the following questions:

How many analytic $N$th roots are there of the function given in (1)?  Are there exactly $N$ of them?  How can they be defined?  What about those given in (2) and (3)?
Can replace the disc $D_r(c)$ in (2) and (3) be replaced by an arbitrary domain?
If $g$ is analytic on a domain $\Omega$ with various poles $c_i$ and zeroes $c_i'$, is there a necessary and sufficient condition for saying whether $g$ has an analytic $N$th root on $\Omega$?  If so, how many such functions are there?


text:
Q: Error Update picture product laravel 5 ErrorException in ProductController.php line 73:
Object of class Symfony\Component\HttpFoundation\File\UploadedFile could not be converted to boolean
my code ProductController
public function postEdit($id, Request $request){
    $product = product::find($id);
    $product->name          = Request::input('txtName');
    $product->alias         = changeTitle(Request::input('txtName'));
    $product->price         = Request::input('txtPrice');
    $product->intro         = Request::input('txtIntro');
    $product->content       = Request::input('txtContent');
    $product->keywords      = Request::input('txtKeywords');
    $product->description   = Request::input('txtDescription');
    $product->user_id       = 1;
    $product->categories_id = Request::input('sltParent');
    // Phần xử lý edit ảnh
    $img_current='resources/upload/'.Request::input('img_current');
    if(!empty(Request::file('fImages'))){ // line error
        echo "có file";
        $file_name=Request::file('fImages')->getClientOriginalName();
        $product->image= $file_name;
        Request::file('fImages')->move('resources/upload/',$file_name);
        if(File::exists($img_current)){
            File::delete($img_current);
        }
    }
    else{
        echo "Không có file";
    }

    $product->save();
    return redirect()->route('admin.product.list')->with(['flash_level'=>'success','flash_message' => 'Chỉnh sửa sản phẩm thành công']);
}

my error

A: Try changing your checking to
if($request->hasFile('fImages') && $request->file('fImages')->isValid()) {
   ...
}


text:
Q: Python win32com.client for Outlook : 'Move' function move limited number of emails from inbox to other folder Context : I have 100 emails with the a subject as 'Target subject <something>' in my Oulook inbox and I want to move them all in an other folder, let's say 'MyFolder'. Here is my python (version=3.9.6) program :
import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
root_folder = outlook.Folders.Item(1)

inbox = outlook.GetDefaultFolder(6)
myfolder = root_folder.Folders['MyFolder']
messages = inbox.Items

for message in messages:
    if 'Target subject' in message.Subject:
        message.Move(myfolder)

Problem: The program runs without throwing any error but only 20 emails of 100 expected are moved. If I run the program several times, it achieved to move all like 20 at a time.
Attempts:  I've searched in windows API documentation but found nothing useful.
Question : Any idea of what's causing this limitation and how to avoid it?
Thanks !

A: You are looping over the collection while changing it (by moving messages) - it is inevitable you will end up with skipped items.
You need a reverse loop from Count down to 1.

A: First of all, I have noticed the following lines of code:
for message in messages:
    if 'Target subject' in message.Subject:

That is really not a good idea to iterate over all items in the folder and check  whether a subject line contains specific keywords. Instead, I'd recommend using the Find/FindNext or Restrict methods of the Items class. Read more about these methods in the following articles:

*

*How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)

*How To: Use Restrict method to retrieve Outlook mail items from a folder
If you still deal with a collection of items (in the case of Restrict method) you need to iterate through all items using the for loop from the end and call the Move method in the following way:
for i in reversed(messages):
    i.Move(myFolder)


text:
Q: Download YouTube videos doesn't work I parsed the "url_encoded_fmt_stream_map=" entries with the direct video urls of some formats, example (decoded):
http://r7---sn-2apm-f5f6.c.youtube.com/videoplayback?gcr=de&cp=U0hUTFVUUl9LUENONF9NTlZHOkpGR0NWdWtvSk15&source=youtube&ip=46.59.194.67&upn=KHmKgXE5di4&fexp=917000,906357,911115,916611,920704,912806,928001,922403,922405,929901,913605,929104,913546,913556,908496,920201,913302,919009,911116,901451,902556&ms=au&itag=45&mt=1357571596&sparams=cp,gcr,id,ip,ipbits,itag,ratebypass,source,upn,expire&id=e4b675c403014739&expire=1357594666&ipbits=8&mv=m&newshard=yes&ratebypass=yes&sver=3&key=yt1&signature=1C8204D1180CAB0B57E3B3331409BD055CBA25B1.73FBEC95E020BBCAC6485D62601E8CF05ACA72DE,quality=hd720&itag=22&fallback_host=tc.v23.cache2.c.youtube.com&type=video/mp4;+codecs="avc1.64001F,+mp4a.40.2"

But I can't download or view it! VLC says: Cannot open! Firefox remains empty (white window, no error message)! Are the urls after "url_encoded_fmt_stream_map=" right?

A: In my answer  https://stackoverflow.com/a/14352995/307547   I described a solution for downloading youtube videos.
LBYouTubeExtractor *extractor = [[[LBYouTubeExtractor alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:(@"http://www.youtube.com/watch?v=%@"), self.videoID ]] quality:LBYouTubeVideoQualityLarge] autorelease];
[extractor extractVideoURLWithCompletionBlock:^(NSURL *videoURL, NSError *error) {
    if(!error) {
        NSLog(@"Did extract video URL using completion block: %@", videoURL);

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *data = [NSData dataWithContentsOfURL: videoURL];
            NSString *pathToDocs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *filename = [NSString stringWithFormat:(@"video_%@.mp4"), self.videoID ];
            [data writeToFile:[pathTODocs stringByAppendingPathComponent:filename] atomically:YES];
            NSLog(@"File %@ successfully saved", filename);
        });
    } else {
        NSLog(@"Failed extracting video URL using block due to error:%@", error);
    }
}];

You can show progress of downloading using technique described in the posts above.
You can replace dataWithContentsOfURL with more appropriate for you method.


text:
Q: Limiting File Access to One User at a Time on Sharepoint I want to set up a SharePoint folder where all of the files in it can be accessed by only one user at a time. While the file is open on one users account I want it so that no other user can view the file at all until it has been closed by the initial user. Is this possible?

A: No. This is not possible using OOTB SharePoint.
You could try writing an app to ensure your needs. Something along the lines of:

*

*Use item-level permissions

*disable all access

*create a ui to request access for one user

*

*on request grant, grant access to the one user

*ensure the user releases access to the document somehow.

However, I would recommend aginst developing such a solution.


text:
Q: What figure of speech is it when we say "This meat is swimming in fat."? What figure of speech is it when we say:

*

*"The meat is swimming in gravy. I'll have fish instead."

*"Her eyes were swimming with tears."

*"They say he's swimming in money."

A: Nothing plain about metaphor in my opinion! Metaphor is  a substitution based on a perceived similarity whilst allowing difference to remain clear. We know he is not really swimming in money, but we appreciate that he is surrounded by money, buoyed up by it, as a  swimmer is in water.
A well-used example, which I  find helpful, is the sentence 'fifty keels ploughed the deep.' in which 'ploughed'is the metaphor describing the movement of ships,but which is also used to distinguish metaphor from synecdoche and metonym.'Keels'  is an example of synecdoche - using a part of a ship to describe the whole, and 'deep' of metonym, using a quality of the sea to describe the sea itself.


text:
Q: Error when Passing string values from Python request to PHP What I am Trying to do
What I am attempting to do is, pass values from my python application to my web api where it gets saved to my database.
The problem
The reason why I am posting is because, I can send integers, 1,2,3 to my database from my python and that saves fine. But If I send "test","ape","tree" nothing is placed in the database. (PS, the data type is varchar(6) )
I can also pass string into the database (using post) from the browser and it works.
What have done
I have created my API , database and python script that passes the data around.
Python.
import requests
load={'par':'ape12'} //This doesnt save "ape" to the database
#load={'par':'3'} //This saves "3" to the database
r=requests.post("http://my-server.com/load.php",data=load)

PHP
<?php
//Connect to DB
include ("connectDB.php");
$loadgot=$_POST['load'];

mysqli_query($con,"INSERT INTO detect(l_result)
VALUES ($loadgot)");

mysqli_close($con);

?>

Hoping someone could assist me in this regard.
Thank you

A: You need to pass a properly formed query to mysql. The value needs to be surrounded by quotes, but also needs to escape any characters which will break out from the quoted environment. In practice, the best solution these days is to use parametrised queries (see example) like:
$stmt = mysqli_prepare($con, "INSERT INTO detect(l_result) VALUES (?)");
mysqli_stmt_bind_param($stmt, $loadgot);
mysqli_stmt_execute($stmt);

Or if you really want to use text query (you really shouldn't), you can do:
$loadgot_safe = mysqli_real_escape_string($con, $loadgot);
mysqli_query($con,"INSERT INTO detect(l_result) VALUES ('$loadgot_safe')");

The reason why you MUST NOT use:
mysqli_query($con, "INSERT INTO detect(l_result) VALUES ('$loadgot')");

is that anyone can submit multiple values - for example value1'), ('value2 will expand to INSERT INTO detect(l_result) VALUES ('value1'), ('value2') - which is definitely not what you want.

A: Modify the 'ape12' to  "'ape12'".
Because, in MySQL we give the query like this
INSERT INTO detect(l_result) VALUES 'Value1';
So pass the values to MySQL with quotes. But no need for the integers.
From @e4c5 comment. Users wont give the quotes while entering the input. So we ensure the query inside the script. So try to changed the code like this
mysqli_query($con,"INSERT INTO detect(l_result) VALUES ('$loadgot')");


text:
Q: Azure pipeline showing OSError: [Errno 22] Invalid argument: I am running this task in azure pipeline with microsoft hosted windows-latest agent but this step shows OSError: [Errno 22] Invalid argument: 'D:\a\1\a\**\*.zip' error.
- task: AzureCLI@2
  displayName: Azure CLI
  inputs:
    azureSubscription: '$(Parameters.connectedServiceName)'
    scriptType: ps
    scriptLocation: inlineScript
    inlineScript: |

      $apps= @('JustGoTestAgain, justgotesttwo')

      foreach ($app in $apps) {
         az webapp deployment source config-zip -g test_group -n $app --src '$(build.artifactstagingdirectory)/**/*.zip'
      }

WARNING: Getting scm site credentials for zip deployment
ERROR: The command failed with an unexpected error. Here is the traceback:
ERROR: [Errno 22] Invalid argument: 'D:\\a\\1\\a\\**\\*.zip'
Traceback (most recent call last):
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\knack/cli.py", line 231, in invoke
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/__init__.py", line 657, in execute
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/__init__.py", line 720, in _run_jobs_serially
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/__init__.py", line 691, in _run_job
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/__init__.py", line 328, in __call__
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/command_operation.py", line 121, in handler
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/command_modules/appservice/custom.py", line 402, in enable_zip_deploy_webapp
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/command_modules/appservice/custom.py", line 428, in enable_zip_deploy
OSError: [Errno 22] Invalid argument: 'D:\\a\\1\\a\\**\\*.zip'
To open an issue, please run: 'az feedback'
##[error]Script failed with exit code: 1

How to solve this issue?

A: First, you need to enable zip deployment for a webapp
The WEBSITE_RUN_FROM_PACKAGE app setting enables running from a package. To set it, run the following command with Azure CLI:
az webapp config appsettings set --resource-group <group-name> --name <app-name> --settings WEBSITE_RUN_FROM_PACKAGE="1"

WEBSITE_RUN_FROM_PACKAGE="1" lets you run your app from a package local to your app. You can also run from a remote package
Run the package
The easiest way to run a package in your App Service is with the Azure CLI
az webapp deployment source config-zip command.
Azure CLI
az webapp deployment source config-zip --resource-group <group-name> --name <app-name> --src <filename>.zip

Because the WEBSITE_RUN_FROM_PACKAGE app setting is set, this command doesn't extract the package content to the D:\home\site\wwwroot directory of your app. Instead, it uploads the ZIP file as-is to D:\home\data\SitePackages, and creates a packagename.txt in the same directory, that contains the name of the ZIP package to load at runtime.
If you upload your ZIP package in a different way (such as FTP), you need to create the packagename.txt file manually under D:\home\data\SitePackages directory.
The command also restarts the app. Because WEBSITE_RUN_FROM_PACKAGE is set, App Service mounts the uploaded package as the read-only wwwroot directory and runs the app directly from that mounted directory.
You can refer to Run your app in Azure App Service directly from a ZIP package and Azure DevOps Doesn't Publish Web App from ZIP Deploy, Runs It as Read-Only ZIP Package Instead


text:
Q: why is this snippet working when the positions should be the other way around?
news,tips and more!!

<button class="button" type="button">Contact us!</button>

    #title2{
  position: absolute;
  bottom: 100px;
  right: 560px;
  color: greenyellow;
}

.button {
   background-color: greenyellow;
   color: black;
   position: relative;
   bottom: 97px;
   left: 200px;

}

I'm just wondering why this works when position absolute you can only make it work by having position relative as parent?

A: You've misunderstood the relationship between position: absolute and position: relative.

When you absolutely position an element, it is positioned with respect to its nearest ancestor (not parent) which is positioned.
An element is positioned if the value of its position property is not static.
If there is no such element, then it is positioned with respect to the browser viewport. (This is what is happening in your example).

position: relative is the only positioning scheme which leaves the element in normal flow. If there is no left, top, etc property then it won't change how that element is laid out at all.
This makes it a popular way to make an element positioned so that a descendant that is absolutely positioned is positioned with respect to it.

Since you almost never want to position an element with respect to the viewport (and if you do then you might want to think about grid or flexbox layouts instead of positioning) it is usual to have a close ancestor that is position: relative to control where the absolutely positioned element goes.
i.e. it is a useful tool that you will want to use in 9/10 cases to get the effect you want, not a requirement.


text:
Q: How to login with Facebook in Laravel 4? I am trying to make an application where the user has to login with Facebook. I am using the laravel 4 framework. Since Facebook doesn't allow using development in localhost I have deployed my code in Heroku and tried it there. There is no problem with the app domain and the site url. I have successfully come to the redirect url. In my code the redirect url is the getFacebooklogin().
But the problem is in the redirect url. I cannot show the user information using the graph api. Heroku doesn't show what the error is. It just says that there is an error. I have checked Heroku logs. I still haven't found out what the error is.
This is the code of my controller.
<?php
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
class SiteController extends BaseController{
    protected $layout = 'layouts.master';

    public function __construct(){
        FacebookSession::setDefaultApplication('id','secret');
    }
    public function getIndex(){
        $this->layout->content = View::make('sites.home');
    }

    public function getFacebooklogin(){
        $helper = new FacebookRedirectLoginHelper(url('site/facebooklogin'));
        $session = $helper->getSessionFromRedirect();
        $request = new FacebookRequest($session, 'GET', '/me');
        $response = $request->execute();
        $graphObject = $response->getGraphObject();
        dd($graphObject);
    }
}

Here is the code of my view
<?php
    session_start();

    use Facebook\FacebookSession;
    use Facebook\FacebookRedirectLoginHelper;
    use Facebook\FacebookRequest;
    use Facebook\FacebookResponse;
    use Facebook\FacebookSDKException;
    use Facebook\FacebookRequestException;
    use Facebook\FacebookAuthorizationException;
    use Facebook\GraphObject;

    $helper = new FacebookRedirectLoginHelper(url('site/facebooklogin'));
?>
<a href="<?php echo $helper->getLoginUrl();?>">Sign in with Facebook

Here is the link for my project.


text:
Q: what can I do about GNU ld 'legacy __sync_synchronize' warning? I have some C++ code that uses a local-scope, program-lifetime object, e.g.
void testFunction(int arg) {
   static Tested tested(0);
   tested.use(arg);
}

which built fine with older versions of GCC.
With GCC 8.2.0, I get a puzzling warning at link time:
warning: legacy compatible __sync_synchronize used. Not suitable for multi-threaded applications
It points the line defining tested, and indeed there is a call to __sync_synchronize() that has been generated by the compiler. I guess it is there to ensure that no two threads could run the initializing code at the same time and have the lazy initialization produce the same result as if there was load-time initialization.
Issue is reproduced with this implementation of the Tested class:
class Tested {
  int sum;
public:
  Tested(int init) : sum(init) {}
  void use(int arg) {
    sum += arg;
  }
  int current() const {
    return sum;
  }
};

This code is expected to run on a mono-thread embedded platform.
Am I right believing that the warning is not relevant for me ?
What can I do (beside stopping using the static object) to get rid of the warning message ?

A: You're getting a linker warning, generated by that version of newlib, to tell you that your application has calls to __sync_synchronize and that there is no implementation of that function that actually synchronizes. The implementation of that function in newlib is a stub that does nothing (it probably just exists to ensure there are no undefined references to that function).
Those calls probably come from within libstdc++.so, as GCC on ARM will emit calls to __sync_synchronize for some atomic operations that happen inside the library (e.g. reference count updates in std::string or shared_ptr objects).
To get a working __sync_synchronize that makes the atomics correct you probably need to link to libatomic (using -latomic) which will have an implementation of that function. Because you aren't linking to that, you get the fallback stub implementation in newlib. If you don't need synchronized atomics (because your application is single-threaded and never tries to update atomics in signal handlers) then I think you can ignore the warning.
Another option would be to use a build of libstdc++.so that explicitly disables all threading, and in theory that wouldn't have any references to __sync_synchronize. But that build of libstdc++.so could only ever be used for single-threaded applications. The build you're using now can be used for both single-threaded and multi-threaded code (even if you get this warning that isn't very relevant for single-threaded cases).

A: It would have been better for you to wait on a reply at https://devkitpro.org/viewtopic.php?f=13&t=8822#p16213 rather than asking on a site where most people aren't familiar with devkitARM.
tl;dr; compile your code with -fno-threadsafe-statics & don't worry about it.


text:
Q: PHP: Accents does not working I'm hosting a website on CPanel and I've already done the proper configurations, however, the accents does not work.
php.init, default_charset = "utf-8" is enabled, my index.php file has the meta charset defined, also I wrote this PHP header.
<?php header("Content-type: text/html; charset=utf-8"); ?>
<!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Responder Header:
HTTP/1.1 200 OK
Date: Wed, 13 Jun 2018 21:38:37 GMT
Server: Apache
Content-Encoding: gzip
Vary: Accept-Encoding
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8

Is there anything more that I should do?


text:
Q: Stop maven reactor plugin from installing my modules I am using the maven reactor plugin , to build a set of modules from my multi-module project.
The issue here is, that after the packaging is over, then the reactor plugin installs artifacts inside my target directories.
I do not want that, as many parts of the team do not have install permission, and doing an install may lead to a build failure for the same.
Can someone guide me as to how to stop that??
Thanks
EDIT
==========================================
                 <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-reactor-plugin</artifactId>
                   <version>1.0</version>
                   <goals>
                       <goal>package</goal>
                   </goals>
                </plugin>

A: Looks to me like you need to add
 <configuration>
    <goals>package</goals>
 </configuration>

Note: inside configuration, not outside.


text:
Q: When using JQuery html() it returns the contents before using Ajax changing I have a  div to hold article content and it could be changed with ajax.
I need the content in this div and I use jquery function html() to do that, but it can only fetch the content before changing.
How can I get the immediate content using jquery?
Update:
It runs well in my own page and the problem comes with 'share it to facebook' button script from other sites.
This is an example script:

I use html() to get the article title to share but it's always the old one.
Any way to solve this?

A:

then insert the newly data in this div inside ajax success callback  and then try this-
var htmlAfterChange = $('#div').html();
alert(htmlAfterChange );

A: You can use Jquery to do an asynchronous call to a server then in the callback you can append some Html to a div.  I hope this helps.  If you post some code I can update the answer.
EDIT:
Create a div to put the result in:

var url = "http://hits.sinajs.cn/A1/weiboshare.html?' + temp.join('&');
$.get(url, function(data){
    $('#result').html(data);
});

In this way you can get the html from the server without having the complication of an iframe.
Then you can read the data from the div

A: set cache:false
$.ajax({
  url: "test.html",
  cache: false,
  success: function(html){
    $("#results").append(html);
  }
});

http://api.jquery.com/jQuery.ajax/


text:
Q: Wrapping an already existent class I've run into a bug where an iterator which loops through data is giving the shorter then expected remainder at the end of the set before looping back to the beginning. I need all iterations to be exactly the same size so I'd like it to drop the leftover part. Unfortunately The iterator is called as an argument for another object so I have no control over when __next__() is called. The solution that comes to mind is to make a custom class that inherits from the iterator and only redefine __next__().
I'm trying to do this as follows:
class CleanIterator(NumpyArrayIterator):

    def __init__(self, _super):
        super=_super

    def __next__(self, *args, **kwargs):
        return self.next(*args, **kwargs)

    def next(self, *args, **kwargs):
        while True:
            data= super.next(*args, **kwargs)

            # reject short data snippets
            if data[0].shape[0] == self.batch_size:
                return data

# .flow return a NumpyArrayIterator
data_generator= ImageDataGenerator().flow(
        valid_data, valid_labels,
        batch_size= 100)
data_generator= CleanIterator(data_generator)

This manages to inherit functions from multiple levels of inheritance, but only appears to inherit variables from NumpyArrayIterator.
As a result I get errors like this:
venv/lib/python3.6/site-packages/keras_preprocessing/image/iterator.py", line 68, in __len__
    return (self.n + self.batch_size - 1) // self.batch_size  # round up
AttributeError: 'CleanIterator' object has no attribute 'n'

where NumpyArrayIterator inherits from Iterator. Iterator has variable self.n and function __len__().
I've tried looking for the proper syntax but every example I can find builds the parent class from scratch rather than starting with an extant instance.
So I guess the question is: how do you create an new instance of child-class from an old instance of parent-class?

A: I am not sure if this is what you want. I am pretty confused as to what you are asking, does this answer your question?
class first:
    def test_function(self):
        print('it works')

instance = first()

class secondary(instance.__class__):
    """This class adds functionality to the already existent instance of the First class"""
    def __init__(self):
        super().__init__()

    def added_function(self):
        pass

As you see by using the __class__ attribute of an instance we can access its class.

A: If what you want is filtering, cannot you just use itertools.filterfalse?
import itertools
...
data_generator = itertools.filterfalse(
                    (lambda x:x[0].shape[0] == x.batch_size),
                    data_generator)

A: def clean_itterator(fn, index_array, generator):
    while True:
        data= fn(index_array)

        # reject under-sized batches
        if data[0].shape[0] == generator.batch_size:
            return data
        return None

data_generator= ImageDataGenerator().flow(
        valid_data, valid_labels,
        batch_size= 100)

original_fn= data_generator._get_batches_of_transformed_samples

data_generator._get_batches_of_transformed_samples= \
    lambda index_array: clean_itterator(
        original_fn,
        index_array,
        data_generator)

It's ugly as sin and it doesn't work the way I'd like but it runs


text:
Q: How to check duplicate entry in listview through listbox? I have three controls on my form and I am transferring the data from listbox and combobox to listview but before transferring the data I want to check whether the data existed or not.
suppose I have an object in combobox "Car" and on the basis of its selected event I am fetching the types of car and filling into the listbox. so after selecting CAR I got the list of different-2 CAR's in my list box. when i double click on the "SKODA" car, the information CAR+SKODA transferring to the listview like -
Car | SKODA
Car | FARRARI
Car | Maruti SWIFT

but I don't want to duplicate the data in the listview....
like if someone is inserting

"Car | Maruti SWIFT"

again then the ERROR message should occur .
so my code is -

A: you can use the .Contains() method:
List<Car> carsList;
Car selectedCar;

if(!carsList.Contains(selectedCar)){
    carsList.Add(SelectedCar)
}

You can override the Equals method on your Car object to specify how to compare if the cars are the same.

A: yeah of course your problem is solution contains property. contains are check out previous records in the list box.contains coding  here...
private void button5_Click(object sender, EventArgs e)
        {
        if (!textBox1.Text.Contains("joginder"))
        {
            MessageBox.Show("Duplicate entry");
        }
        else
        {
            MessageBox.Show("no duplicate entry");
        }

    }


text:
Q: Differences between compilers in Cygwin In Cygwin a search for g++ shows:

*

*gcc-g++

*mingw-gcc-g++

*mingw64-x86_64-gcc-g++

What are the differences between these?

A: Binaries built with Cygwin's gcc-g++ link against cygwin1.dll which is an implementation of the POSIX API for Windows.
mingw64-x86_64-gcc-g++ is instead part of the Mingw-w64 toolchain which builds native Windows applications that do not depend on Cygwin. The mingw-gcc-g++ on your system is probably either a symlink to this, or is the version that produces 32-bit binaries.
You can verify this difference by inspecting the import tables of a "hello world" program built with each using objdump -x hello.exe.


text:
Q: For loop in Laravel validation How can I make something like this:
for($x=0; $x<=14; $x++) {
    $this->validate($request, [
        'name' => 'required',
        'radio_'.$x => 'required',
    ]);
}

But I need loop only over radio_ not name. Like this, but it's wrong:
$this->validate($request, [
    'name' => 'required',
    for($x=0; $x<=14; $x++) {
        'radio_'.$x => 'required',
    }
]);

My blade file, if it will help:
@for($x = 0; $x <= 14; $x++)

@lang('leadersCompetence.questions.'.$x)

        @for($i = 0; $i <= 4; $i++)

                <input type="radio" name="radio_{{$x}}" @if(old('radio_'.$x) == $option[$i]) checked
                       @endif value="{{$option[$i]}}" required>
                {{$option[$i]}}

        @endfor

@endfor

A: You can do it like this by creating validation array::
$validate_array = ['name' => 'required'];
 for($x=0; $x<=14; $x++) {
     $validate_array['radio_'. $x] = 'required';
 }
$this->validate($request, $validate_array );

A: You can put your values into radios array and then use
'radios.*' => 'required'

in your controller.

A: What I would do, is build up a rules array and use it in the validator. For example:
$rules["name"] = "required";
for($x=0; $x<=14; $x++) {
   $rules['radio_'.$x] = 'required',
}
$this->validate($request, $rules);

A: Don't know laravel but you can validate two times and then combine result. Or you can create that array before passing it o validation, like this:
$validationArray['name']= 'required';
for($x=0; $x<=14; $x++) {
    $validationArray['radio_'.$x] => 'required',
}
$this->validate($request, $validationArray);

A: As you see validation parameter is a array. So you can make a custom array for radios and merge it with other fields:
$ar = array();
for ($x = 0; $x <= 14; $x++) {
    array_push($ar, ['radio_' . $x => 'required']);
}
$validator = array_merge($ar, ['name' => 'required']);
$this->validate($request, $validator);

A: There is no need for a loop. you can do below which validate arrays
$this->validate($request, [
     'name' => 'required',
     'radio.* => 'required', // change to "radio_.*" if name is radio_
]);


text:
Q: Is there a way to force Show to use a Datagrid? I am looking for a way to allow Show to be able to use a Datagrid on the show page. I want to be able to click on the show button and when the show page appears, I want to be able to take data and make another grid using Datagrid or something similar. Any Ideas how this is done?

A: it seems show page take 1 record and render its. on show page you can place related records with current. for example news can related with one project and one project has many news. code below get from api all related news and render its as a table. hope it helps you
export const ProjectShow = ({ ...props }) => (
  <Show title={<ProjectTitle />} {...props}>
    <SimpleShowLayout>
      <ReferenceManyField label="News" reference="news" target="project_id">
          <Datagrid>
            <TextField source="id" />
            <TextField source="title" />
            <DateField source="created_at" showTime />
            <DateField source="updated_at" showTime />
            <EditButton />
          </Datagrid>
        </ReferenceManyField>
    </SimpleShowLayout>
  </Show>
);

don't remember place in App.js line:
<Resource name="projects"  ...another actions... show={ProjectShow} />


text:
Q: Placing and styling EdgeLabels in Graph I have:
Graph[{1 \[DirectedEdge] 1, 1 \[DirectedEdge] 2, 1 \[DirectedEdge] 3,
  2 \[DirectedEdge] 1, 2 \[DirectedEdge] 2, 3 \[DirectedEdge] 1,
  3 \[DirectedEdge] 2, 3 \[DirectedEdge] 3},
 VertexStyle -> Orange,
 VertexSize -> 0.3, VertexLabelStyle -> Directive[Red, Italic, 16],
 VertexLabels -> Placed["Name", Center],
 EdgeStyle -> Black,
 EdgeLabels -> {1 \[DirectedEdge] 1 -> Placed["0.9", 0.5]}]

Which produces this image:

I'd like to center the 0.9 on the arrow below the vertex labeled 1 with a white background. How can I do this? And I'd like to increase its font size.

A: Version 9.0:
g =  Graph[{1 -> 1, 1 -> 2, 1 -> 3, 2 -> 1, 2 -> 2, 3 -> 1, 3 -> 2, 3 -> 3},
  VertexStyle -> Orange, VertexSize -> 0.3,
  VertexLabelStyle -> Directive[Red, Italic, 16],
  VertexLabels -> Placed["Name", Center], EdgeStyle -> Black,
  EdgeLabels -> {(1 -> 1) -> Placed[Framed[Style["0.9", 14, Italic, Bold, Blue],
     Background -> White, FrameStyle -> White], "Middle"]}]

Version 11:
If you don't mind having a Graphics object (instead of a Graph object), you can post-process Show[g] to adjust the label position:
Show[g] /. ImageScaled[{_, _}] :> ImageScaled[{.5, -.7}]

If you do need to have a Graph object, you can extract the edge shape  and edge label from ToBoxes[g], make the necessary adjustments and use the resulting expression as the value of EdgeShapeFunction for the edge 1->1:
edgeshape = Cases[ToBoxes[g], {ab : _ArrowBox, ib: _InsetBox} :>
  {ab, ib /. ImageScaled[{_, _}] :> ImageScaled[{.5, -.7}]}, {0, ∞}][[1]];

Row[{g, SetProperty[{g, 1->1}, {EdgeLabels -> None, EdgeShapeFunction -> (edgeshape &)}]}]


text:
Q: Tab bar controller not appearing correctly I'm trying to connect Tab Bar Controller to existing part of my app, but when I do that it's "malfunctioning".
However when I run Tab Bar Controller part standalone as initial view controller it works properly like in the image below :

This is how app looks when it is run(correct behavior) :

However when I go to this tab bar controller from my main app this is how it looks like this:

My main app looks like this :
Scroll View contains

*

*UIView 1

*UIView 2

*UIView 3

*UIView x

Each view does something not related to this tab bar controller. Only one view view x tries to "visit" tab bar controller and display some data there, but it's not. Any ideas?
I have this tab bar controller identifier set to test, and I here is how I do that from my view x :
UITabBarController *newViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"test"];
        [self.view addSubview:newViewController.view];

EDIT :
Entire app :

I'm creating views programatically. That's why I don't have any relationships/segues to the tab bar controller.
SOLUTION :
Change :
UITabBarController *newViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"test"];
            [self.view addSubview:newViewController.view];

To :
UITabBarController *newViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"test"];
        [self addChildViewController:newViewController];
        [self.view addSubview:newViewController.view];

A: You need to set a root viewController to the navigation Controller

A: Just don't do this. From the Apple UITabBarController referenece

Because the UITabBarController class inherits from the UIViewController class, tab bar controllers have their own view that is accessible through the view property. When deploying a tab bar interface, you must install this view as the root of your window. Unlike other view controllers, a tab bar interface should never be installed as a child of another view controller.

As I understand it means you must use UITabBarController only as a root view controller of the window. But you can alway use a general UIViewController and add UITabBar there.
(The view offset problem you've met is possible to be fixed, it will not follow the Apple guidelines however and not advised).


text:
Q: Merge two dataframes in R column-wise and sort columns by one value I have two dataframes in R that look like the following examples:
Dataframe 1
|word  |a1 |a2 |a3 |...|
|apple |0.5|0.3|0.2|...|
|pear  |0.2|0.2|0.6|...|
|banana|0.6|0.1|0.3|...|
|cherry|0.4|0.5|0.1|...|

    Dataframe 2
|a1     |a2     | a3    |...|
|banana |cherry |pear   |...|
|apple  |apple  |banana |...|
|cherry |pear   |apple  |...|
|pear   |banana |cherry |...|

The names in Dataframe 2 are sorted by their value in Dataframe 1 - these are the top terms I got from the textmineR package with the GetTopTerms function from my model. However, I do not know how I can combine the phi values I have with each word that the value belongs to. In other words, what I want as an output is a combination of the two dataframes above - where the phi value is listed from highest to lowest in each single column as seen below:
|a1_term |a1_phi | a2_term |a2_phi | a3_term  |a3_phi |...|
|banana  |0.6    |cherry   |0.5    |pear      |0.6    |...|
|apple   |0.5    |apple    |0.3    |banana    |0.3    |...|
|cherry  |0.4    |pear     |0.2    |apple     |0.2    |...|
|pear    |0.2    |banana   |0.1    |cherry    |0.1    |...|

Is there an easy function to merge these two tables as seen above as well as to sort each phi-value from lowest to highest while merging. Thank you!

A: Here's a solution using dplyr and reshape2. If you are sorting by phi, you don't need the second data frame. Here, df is the first data frame.
library(dplyr)
library(reshape2)
library(tidyselect)

do.call("cbind", melt(df) %>%
                 split(.$variable) %>%
                 lapply(function(x) x %>% arrange(-value))) %>%
select(!ends_with("variable"))

#>   a1.word a1.value a2.word a2.value a3.word a3.value
#> 1  banana      0.6  cherry      0.5    pear      0.6
#> 2   apple      0.5   apple      0.3  banana      0.3
#> 3  cherry      0.4    pear      0.2   apple      0.2
#> 4    pear      0.2  banana      0.1  cherry      0.1

Data
df <- structure(list(word = c("apple", "pear", "banana", "cherry"),
    a1 = c(0.5, 0.2, 0.6, 0.4), a2 = c(0.3, 0.2, 0.1, 0.5), a3 = c(0.2,
    0.6, 0.3, 0.1)), class = "data.frame", row.names = c(NA, -4L))

df
#>     word  a1  a2  a3
#> 1  apple 0.5 0.3 0.2
#> 2   pear 0.2 0.2 0.6
#> 3 banana 0.6 0.1 0.3
#> 4 cherry 0.4 0.5 0.1


text:
Q: How to override a function that returns a list of generic objects that extend a base class with a specific object I have a base class (Company) and want to derive a few classes (say CompanyA, CompanyB etc) from it.
This base class has an abstract method so that all derived classes have to override and implement it.
The catch is that this abstract method should be able return a list of any object that is derived from a given class (say CustomerContact).
I tried defining this method in the base class as follows:
public class Company
{
    ...
    public abstract List<T> getContacts<T>() where T : CustomerContact;
}

This give no compilation error. I try to override this method as follows in the derived class:
public class CompanyA : Company
{
    ...
    public override List<T> getContacts<T>()
    {
        return _contacts;
    }
}

Here _contacts is a List of class "CompanyAContact" where this class is derived from "CustomerContact".
However, I cannot override the method like this. The error I get is:
Cannot implicitly convert type 'System.Collections.Generic.List<CompanyAContact>' to 'System.Collections.Generic.List<T>'

A: Your method in the derived class is defined as a generic but returning a concrete list of CompanyAContact - what would happen if you called the method like this for example?:
CompanyA companyA = new CompanyA();
//we can't do this as the method returns List<CompanyAContact>
//but we would be asking it for List<CompanyBContact>
companyA.getContacts<CompanyBContact>();

As that wouldn't make any sense you receive the error that you can't convert from List<CompanyAContact> to List<T>. You can't return a List<CompanyAContact> when the method is defined in such a way that it could return any CompanyContact.
One solution would be to make the base Company class itself generic and define the CompanyContact type when you inherit the Company:
abstract class BaseCompany<T> where T : CustomerContact
{
    //When we inherit from BaseCompany we can define T
    public abstract List<T> getContacts();
}

//define T in this case as CompanyACustomerContact
class CompanyA : BaseCompany<CompanyACustomerContact>
{
    public override List<CompanyACustomerContact> getContacts()
    {
        return new List<CompanyACustomerContact>();
    }
}

//define T in this case as CompanyBCustomerContact
class CompanyB : BaseCompany<CompanyBCustomerContact>
{
    public override List<CompanyBCustomerContact> getContacts()
    {
        return new List<CompanyBCustomerContact>();
    }
}

A: I don't have Visual Studio in front of me to check, but I suspect you need to add the type constraint here also, to show that this method is compatible with the abstract method:
public class CompanyA : Company
{
    ...
    public override List<T> getContacts<T>() where T : CustomerContact;
    {
        return _contacts;
    }
}

A: You can return list of CustomerContact class and then derive specific classes from it,  like mobile,  email...

A: Try making the Base Class generic instead:
public class CustomerContact
{
    // ...
}
public class CompanyAContact : CustomerContact
{
    // ...
}

public abstract class Company<T> where T : CustomerContact
{
    // ...
    public abstract List<T> GetContacts();
}
public class CompanyA : Company<CompanyAContact>
{
    private List<CompanyAContact> _contacts;
    // ...
    public override List<CompanyAContact> GetContacts()
    {
        return _contacts;
    }
}


text: Q: how to compare two images based on luminosity of each pixel on matlab I am working on a project in which I have to compare two b&w images based on their luminosity. I wanted to create a program that compares the pixels of each image using MATLAB and I wanted some advice on how I could do this.


text:
Q: Document Viewer Defaulting to Inverted Colors Recently, when I use Document Viewer (Evince 3.18.2) to look at a PDF (especially one
I made by printing to a file), it comes out in inverted color mode (white type on
a black background).
I can change the mode by doing this: View -> Inverted Colors
Then I get a normal display.
I do not know how the Document Viewer got into this mode, but I'd like to get it
back to normal.

A: I figured out what happened. Apparently, I had been displaying inverted colors and I inadvertently clicked "Save Current Settings as Default".


text:
Q: Add references to meta posts in privilege wikis I would like to suggest that we add references to meta posts in the privilege wikis. Currently, the wikis are very lacking on the details on the appropriate way to use the tools/make use of the privilege (review tools, 10k tools, protect post, deletion, etc.).
I don't think that this is a new suggestion. At least, this question is a more specific request, regarding review privilege.
The tools are there, but the more specific issues are only accessible if the user frequents meta site. Sometimes, it doesn't appear to be an issue until the user is pointed out by other users. It also saves time when all the relevant meta posts are together in one place.
Update
I will list the privilege wikis that I have improved here as time goes:

*

*https://meta.stackoverflow.com/privileges/flag-posts

*https://meta.stackoverflow.com/privileges/moderator-tools

A: Sounds reasonable. If you find an appropriate question, you can suggest an edit to the tag wiki here on MSO (only):

If and when it is approved, it will eventually be pushed out to all sites, so be sure the faq post applies to all sites, not just M/SO.