text:
Q: Access from class library to appsetting.json or config.json in vNext I am creating a Nuget Package and I'm working in my class library. I need access to appsetting.json or config.json to access to default connection string.
What is the best way to migrate my actual working code to the new version of ASP.NET vNext?
I have read about it in this question, but it's a fine solution for me.
Working code:
/// <summary>
/// Retrieves the default connectionstring from the App.config or Web.config file.
/// </summary>
/// <returns>Returns the default connectionstring from the App.config or Web.config file.</returns>
public static string GetDefaultConnectionString()
{
    return ConfigurationManager.ConnectionStrings[DefaultConnectionstringName].ConnectionString;
}

A: The old class library read config values  automatically with the app.config. In the new class library you have to add this functionality. The Startup.cs is use to read the app.settings In a class library you have to add a Startup.cs also.
In your project.json make sure you have the dependency
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final"

Add an appsettings.json via add - new item. Filter on json
{
  "Data": {
    "MyDb": {
        "ConnectionString": "Server=.;Database=MyDb;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
  }
}

You can call your connection MyDb or DefaultConnection.
Add a Startup.cs to put the code to read the appsettings.json.
See below for the Startup constructor method doing this.
e.g.
using Microsoft.Data.Entity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace MyProject
{
    public class Startup
    {
        public IConfigurationRoot Configuration { get; set; }

        public Startup()
        {
            var builder = new ConfigurationBuilder()
             .AddJsonFile("appsettings.json");

            Configuration = builder.Build();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<MyDbContext>(options =>
                    options.UseSqlServer(Configuration["Data:MyDb:ConnectionString"]));
        }
    }
}

In the example above the reference
Configuration["Data:MyDb:ConnectionString]

will return a  type of IConfigurationRoot, not string.
To get the string value try the following
string connection = Configuration.Get<string>("Data:MyDb:ConnectionString");


text:
Q: How can I assign IPv6 addresses based on existing IPv4 addresses? I have several hundred Server 2008 R2 machines with static IPv4 addresses.  I'd like to enable IPv6 on each interface, and then automatically assign IPv6 addresses to them based on their existing IPv4 addresses.  Is there a good way to do this?
I wrote a power shell script that does this, but it uses "get-netadapter" and the like, so it will only work on my server 2012 R2 machines.

A: Well, there is more than one way to skin a cat.

*

*You could rewrite your script to use older commands that are compatible with previous versions of PowerShell. (A WMI call to the Win32_NetworkAdapterConfiguration class was the typical way to do this.)

*You could create a new script using the netsh command, which is the pre-PowerShell method of manipulating network settings via a CLI.

*You could install Windows Management Framework 4 (and PowerShell along with it) on your Windows 7 and Server 2008 R2 machines to make your existing script and the get-netadapter cmdlet work.

Having said that, especially with IPv6, static assignments and manually hunting through the address space is exponentially more painful and involved than it is with IPv4, so I'll repeat the advice of using DHCP to do this.  Assigning IP address is the whole reason DHCP exists, after all.

A: There's an unsupported tool that can turn on IPv6 from the command line called NVSPbind.  There are probably others as well.  Or you could use netsh, which is probably the path of least resistance.
This article might help.  It has a lot of handy netsh commands (netsh interface ipv6 isatap set state enabled, etc.), that you could include in a script.
Good luck!

redpajama_set_name: RedPajamaStackExchange


text:
Q: test: argument expected when using -z option I have a unix script that occasionally errors out with the message "test: argument expected". The following line of code is the only if statement in the script
if [ -z `grep ">Success<" $OUTFILE` ]

The $OUTFILE is a file created when the script starts to run. The script calls a web service that writes the output to the OUTFILE. If the outfile has "Success" in it, then it means that the web service completed successfully.
This script is called every 10 minutes and the logic above works perfectly fine for most of the cases. But on occasionally, the script errors out with the test argument expected error and I am unable to figure out the reason for this error. Has anyone else faced a similar problem? It would be great if someone can provide pointers to this issue.
Thanks.

A: You didn't wrap the `command` string in double quotes, so if the string isn't found, the command reduces to if [ -z ] which is an error (missing parameter).  (It expands to nothing, not to an empty parameter.)  And it's doing things the hard way.
if grep ">Success<" $OUTFILE

You may want the -s and (if GNU grep) -q options on grep.

A: You should quote the argument to -z!
if [ -z "$(grep ">Success<" $OUTFILE)" ]

Of course, to test whether >Success< is found, there's an even easier way:
if grep -q ">Success<" $OUTFILE


text:
Q: Finding largest number and deleting remaining smallest number I am trying to Delete cell by comparing Names within the same column, If I find the same name, Then make sure name is containing bigger number after forward
slash, If I find the bigger number then make sure my C column matching my criteria (NOT Playing). If it is matching then delete all cell which is a smaller number with column c saying Still Playing and keep only bigger number which is saying Not Playing. Any Ideas, I have posted my code but when I am finding a bigger number, it's going back and comparing with another cell so it's coming back to the same number. Here is my code..
Sub xm()
    Dim lastrow As Long
    Dim i As Long, firstD As Integer, secondD As Integer
    Dim firstForward As Integer
    Dim secondForward As Integer, score1 As String, score2 As String
    Dim fName As String, sName As String
    lastrow = ActiveSheet.UsedRange.Rows.Count

      For i = 2 To lastrow

          firstD = InStr(1, ActiveSheet.Cells(i, 1), "/")
          fName = Left(ActiveSheet.Cells(i, 1), firstD - 1)
          secondD = InStr(1, ActiveSheet.Cells(i + 1, 1), "/")
          sName = Left(ActiveSheet.Cells(i + 1, 1), secondD - 1)

              If fName = sName Then
                 firstForward = InStr(1, ActiveSheet.Cells(i, 1), "/")
                 score1 = Mid(ActiveSheet.Cells(i, 4), firstForward + 1)
                 secondForward = InStr(1, ActiveSheet.Cells(i + 1, 4), "/")
                 score2 = Mid(ActiveSheet.Cells(i + 1, 4), firstForward + 1)

                   If score1 > score2 Then
                      If ActiveSheet.Cells(i, 3) = "Not Playing" Then
                      'Delete entire cell
                      End If

                   End If
              End If
       i = i + 1
      Next i
End Sub

Output:---


text:
Q: Using an excel formula on filtered cells? I have the following excel spreadsheet:

The elevation is increasing in ascending order. The distance is culmulative. Criteria is a separate formula which can be explained here:
Selecting values in a list based on an interval?
I want to calculate the slope which is the difference in elevation divided by the difference in distance, but only for the values that have a criteria of "1". Here is a picture showing the spreadsheet filtered and cut where I get the expected values of slope:

I want to perform this formula on the unfiltered list and to get the desired result in the third image.

Are there any formula operations in excel that can perform this task? Can it be done in VBA?

A: You can add 2 helper columns to your table like so:

Col D tracks the last Elevation that met your criteria.  Similarly, Col E selects the last Distance that met your criteria.  This keep COL F's formula super simple.
Note this is a variation on Alan's comment, but I prefer the legibility and maintainability of the additional columns to the expert level (and lengthy) formula.


text:
Q: Search limit / slow default search? There is this method:
 def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
        if args is None:
            args = []
        if context is None:
            context = {}
        ids = []
        if name:
            ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit)
        if not ids:
            ids = self.search(cr, uid, [('city_id', operator, name)] + args, limit=limit)
        if not ids:
            ids = self.search(cr, uid, [('street_id', operator, name)] + args, limit=limit)
        return self.name_get(cr, uid, ids, context=context)

It finds what you want, but for some reason it searches very slowly when no search term is provided (note. It wouldn't be strange if it would return all records, but it still returns max 160 records).
There are few problems with this. First it has a limist search of 160 records for some reason even if you looked in method, it shows 100. And If I change to any number it still returns max records of 160 records. Looks like that parameter does not override default 160.
Now the other problem is that when I enter any phrase in search line, it finds results quite quickly, does not matter how many results it finds, because it limits to 160. That would be ok. But if I do not provide any phrase to search for and press little triangle (arrow) in openerp interface (look below for screenshot)

And the same thing happens when I delete search phrase in address completion field. It then also defaults to default search, which finds first 160 records ordered by zip (postal code) column order. For some reason this way it searches much slower. I only noticed this slow performance when I imported addresses (now there are more than 400k rows).
Does anyone know how could I improve this so called default search or at least limit return records so it might increase performance? (as I said for some reason changing limit= to some other number does not do anything).
Simple examples to understand problem:
1st example:
I write phrase City1 in address completion field. It finds first 160 records that has City1. Search is fast.
2nd example:
I don't write anyting in address completion field, but instead I press little arrow (the one in screenshot), to open detailed search. It finds first 160 records by postal code order. Search is slow.
3rd example:
I delete written phrase City1 (after I written it) from address completion field. It finds same records as in 2nd example. Search is slow.
P.S if anyone needs info about standard OpenERP parameters in ORM methods (like the one I provided): https://doc.openerp.com/6.0/developer/2_5_Objects_Fields_Methods/methods/

A: Removing order rows are returned (it was ordered by postal code), improved speed significantly. I guess if no one knows any better suggestion, this should be a good solution.
To be more specific in code there was this line:
_order = 'name' #name field is for postal code.
I deleted it.


text:
Q: Multidimensional array in numba njit function How to put multidimensional array into numba njit function?
example:
from numba import njit
import numpy as np

array =[
    [[0.0], [1.0, 2.0, 3.0]],
    [[4.0], [5.0, 6.0, 7.0]],
]

@njit
def show_array(arr):
    print(arr)

show_array(np.array(array))


text:
Q: Bitcoin symbol in LaTeX How do I write the Bitcoin symbol in LaTeX?

*

*Abusing Unicode, "B⃦" can be used in normal text files. I'm not a fan of writing non-ASCII in LaTeX, as you can run into all sorts of encoding issues.

*There does not seem to be a package defining it.

*I could use TikZ to roll my own version, but then that would probably not scale well (telling from past attempts at similar things).

So: what do you think would be the best way of writing the Bitcoin currency symbol in LaTeX?
For comparison, here's the Bitcoin wiki entry for the symbol.

A: A variant, more inline with the "official" rendering (see http://bitcoinsymbol.org)
\documentclass{article}

\DeclareRobustCommand{\bitcoin}{{%
  \normalfont\sffamily
   \raisebox{-.05ex}{\makebox[.1\width][l]{-\kern-.2em-}}B%
}}

\begin{document}

\bitcoin

\end{document}

Of course the adjustments depend on the document sans serif font.
From the site:

A: Thanks for the bitcoin symbol. Here is an attempt at drawing the Litecoin symbol in latex
\newcommand{\diaCo}{\mkern-\medmuskip\rotatebox[origin=c]{45}{\scalebox{0.9}{$-$}}\mkern-\medmuskip}%
\def\litecoin{\leavevmode\rlap{\hskip-1.3pt \textbf{$\diaCo$}}L}

A: Three examples, from here:
\def\bitcoinA{%
  \leavevmode
  \vtop{\offinterlineskip %\bfseries
    \setbox0=\hbox{B}%
    \setbox2=\hbox to\wd0{\hfil\hskip-.03em
    \vrule height .3ex width .15ex\hskip .08em
    \vrule height .3ex width .15ex\hfil}
    \vbox{\copy2\box0}\box2}}

and
\def\bitcoinB{\leavevmode
  {\setbox0=\hbox{\textsf{B}}%
    \dimen0\ht0 \advance\dimen0 0.2ex
    \ooalign{\hfil \box0\hfil\cr
      \hfil\vrule height \dimen0 depth.2ex\hfil\cr
    }%
  }%
}

and
\def\bitcoinC{\leavevmode\rlap{\hskip.5pt-}B}


text:
Q: How do I insert an improved dictionary into my collection in C# (Windows Store App) Hi I have found out that using a dictionary directly into a Combo Box does not work well for Windows Store apps. This was my full code that produced the error.
My Model
 class QuestionModel
{
    public QuestionModel(int Key, string Question, Dictionary<string, string> Answers)
    {
    key = Key;
    question = Question;
        answers=Answers;
    }

    public int key { get; set; }
    public string question { get; set; }
    public Dictionary<string, string> answers { get; set; }
}

Populating the collection code
    ObservableCollection<QuestionModel> questionCollection = new ObservableCollection<QuestionModel>();

foreach (KeyValuePair<int, Dictionary<string, string>> pair in CommonVariables.answersINR)
                    {

                        if (item.Key==pair.Key)
                        {
                         questionCollection.Add(new QuestionModel(item.Key, item.Value,pair.Value));

   }
   }

My Xaml combo box
 <ComboBox Height="40" VerticalAlignment="Stretch" x:Name="QuestioncomboBox" Grid.Column="1" FontSize="25" ItemsSource="{Binding Path=answers}" SelectedValuePath="Key" DisplayMemberPath="Value">
                    </ComboBox>

So as you can see the pair. value loads data in the answer section of my collection. But I just found out today through research that Windows Store Apps Combo box does not work well with the dictionary. So someone in stack modified pair.value to this line of code.
pair.Value.Select(f => new { Key = f.Key, Value = f.Value }).ToList();

Which works perfectly for populating the Combo Box. The only thing is how do I insert it into the questioncollection instead of pair.value? Can someone please help by rewriting my code to fit the line of code above like this?
questionCollection.Add(new QuestionModel(item.Key, item.Value,pair.Value.Select(f => new { Key = f.Key, Value = f.Value }).ToList();));

At the moment that gives me an error I cannot solve?


text:
Q: Purpose of #if 0 in cat.c First of all, I'm aware of what exactly does an if 0 endif block do?.
But I was looking FreeBSD's cat.c and the explanation in the other question doesn't explain the #if 0 in this file. The blocks commented out are so small than someone could have easily removed them, but instead he/she chose to wrap them within #if 0 ... #endif. Why would someone make such a choice instead of simply removing this code? If it's used somehow as meta data, why not put it in some comment?

A: In this case, it is keeping a historical record of the version of the code from which the source was originally derived in the source code (so even if you don't have access to the version control system, you can see this information), while not making the information available to the compiler proper.
#if 0
#ifndef lint
static char const copyright[] =
"@(#) Copyright (c) 1989, 1993\n\
    The Regents of the University of California.  All rights reserved.\n";
#endif /* not lint */
#endif

Once upon a time, that information would have been compiled into the binary.  Modern compilers eliminate unused variables like that.

A: #if 0 is used instead of commenting out the code. One day instead of 0 they could use an environment variable to selectively enable/disable the functionality.

A: Sometimes we really do want to disable a block of code temporarily, without discarding it. This may be for many reasons.
Perhaps it's under development so we really don't want people using it yet, but we don't want to maintain separate copies of the code for that development than for release.
Or perhaps it's an idea that we tried that didn't work, but that we want to keep around while we figure out why it didn't work.
Or perhaps it's one of several alternatives that we've considered and we haven't made a final decision among them yet -- in that case you'll see things like #if 0 ... #else ... #endif
We could comment out the code we want to disable, but C before C99 didn't have the // comment-until-end-of-line syntax that C++ does, and that made commenting out a block that has comments painful at best. And while it's possible to do some switching back and forth between alternative blocks of code by abusing comments, it's ugly at best and is NOT the right answer for a language which has a C-like preprocessor.
(The addition of // comments is a fine thing, but lots of us old C coders don't use them and they still don't address the desire to easily switch between alternatives while testing out a new solution.)
We could use #ifdef. But someone might take that as a suggestion that they could try turning it on, and complain when it blows up. #if 0 says clearly "don't use this."
I agree that #if 0 is ugly. Unfortunately, it's also useful, and is a fairly common idiom. There's absolutely no requirement that you ever use it, but you should get used to seeing it because other folks will do so.


text:
Q: How to add JavaScript Flow annotation for returning instance itself? I have the following es6 class:
// @flow
class MyClass {

  _active: bool

  setActive(value: bool) { // return type should be class if instance
    this._active = value
    return this
  }
}

class MySub extends MyClass {
  // something
}

How should I define the return type for setActive() if it may return MyClass or any of the SubClasses? Is MyClass also correct for subclasses?

A: Thanks so far I got the answer after asking the same in as issue for flow: https://github.com/facebook/flow/issues/4135
So the returned flow type should be also defined as this.
// @flow
class MyClass {

  _active: bool

  setActive(value: bool): this {
    this._active = value
    return this
  }
}

class MySub extends MyClass {
  // something
}


text:
Q: Is it possible to create a collapsible sidebar with Kivy and/or KivyMD? I'm working on a project for the GUI of an app written in Python that requires a collapsible sidebar like this one:
https://www.youtube.com/watch?v=-vQIcBKdhyk&t=9s
I already created a good portion of the GUI in Kivy and KivyMD. Applied also the Navigation Drawer that works as expected. However, it is fully retracted when not active, so not exactly what was asked.
Anyone managed to create something like this?
Thank you all in advance
Using Navigation Drawer component in KivyMD, it was possible to create something almost as required. Yet, there is no partial view (with little icons that would expand when the drawer were toggled).


text:
Q: How to programaticly access min and Max values defined in a core-data model designed with XCode? I was expecting to find that in the NSAttributeDescription class, but only the default value is there.
Behind the scene I tought a validationPredicate was created but trying to reach it using
    NSDictionary* dico= [[myManagedObject entity] propertiesByName];
NSAttributeDescription* attributeDescription=[dico objectForKey:attributeKey];
for (NSString* string in [attributeDescription  validationWarnings])

just get me nowhere, no validationWarnings, no validationPredicates...
any thoughts on this ?
Edit1: It seems that getting the entity straight from the managedObject doesn't give you the full picture. Getting the Entity from the NSManagedObjectModel  permits to reach the validationWarnings & validationPredicates...
Edit2:
Using the following code just after the creation of the model will list all the validationPredicates of the model. For some reasons, using it later (at the time I try too validate for example) will not display anything !
for (NSEntityDescription *entity in managedObjectModel) {
for (NSAttributeDescription* attributeDescription in [entity propertiesByName])
    for (NSPredicate* predicate in [attributeDescription validationPredicates])
    {
        NSLog(@"---%@",[predicate predicateFormat]);
    }

}

A: I think you problem is most likely caused by calling [entity propertiesByName] which returns dictionary of mixed NSAttributeDescription and NSRelationshipDescription. When I tried to run your code I got the odd result that the attribute objects where returned as NSCFStrings.
The following code works and note that it produces output even after the managed object model is frozen by use.
- (void) dumpAttributePredicates{

    NSLog(@"start dumpAttributePredicates");
    for (NSEntityDescription *entity in managedObjectModel) {
        NSDictionary *attribs=[entity attributesByName];
        for (NSAttributeDescription *eachA in [attribs allValues]) {
            NSArray *vps=[eachA validationPredicates];
            for (NSPredicate  *p in vps) {
                NSLog(@"p =%@",[p predicateFormat]);
            }
        }
    }
    NSLog(@"end dumpAttributePredicates");
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
    [self dumpAttributePredicates];
    NSManagedObject *mo=[NSEntityDescription insertNewObjectForEntityForName:@"TestEntity" inManagedObjectContext:self.managedObjectContext];
    NSLog(@"mo=%@",mo);
    [self dumpAttributePredicates];
}

Which produces this output:
start dumpAttributePredicates
p =SELF >= 0
p =SELF <= 100
p =length >= 0
p =length <= 100
end dumpAttributePredicates

mo=<NSManagedObject: 0x10016f490> (entity: TestEntity; id: 0x10016f540 <x-coredata:///TestEntity/tA91445DF-4669-4018-A761-7383E3A73EF42> ;
data: {
    attributeOne = 0;
    attributeTwo = nil;
})

start dumpAttributePredicates
p =SELF >= 0
p =SELF <= 100
p =length >= 0
p =length <= 100
end dumpAttributePredicates

Make sure you don't confuse entities with NSManagedObject or its subclasses. Entities are the analogs of classes, not instances and an entity only exist within a managed object model which in turn maybe an attribute of a managed object context.


text:
Q: dijit.form.Combobox show label Instead of value I've a dijit.form.Combobox field which uses a ItemFileReadStore to pull Its data.
Teh ItemFileReadStore has two attribute per Item value which will be used for form submission , generally Unique Integers and label which is Human Understandable String.
In ComboBox HTML I've done searchAttr="value" labelAttr="label"
When the ComboBox Shows the list it uses teh label Attribute.
But When the User selects one of the Item it shows the value of that Item.
What I want is , The value Attribute will Still be used for Form Submission. But the User will always see the label in the combobox Control.
alt text http://img822.imageshack.us/img822/6660/dijitcombo.jpg
e.g. I Want to Show The Label for value 3 (Admin) instead of 3

A: Use FilteringSelect instead of Combobox.
Note: ComboBox only has a single value that matches what is displayed while FilteringSelect  incorporates a hidden value that corresponds to the displayed value.

A: I have tried the following.
var cmbObject = Registry.byId('combo dojo id'); var id =
cmbObject.item.<Code Property>;

You should check if item is null.


text:
Q: Monitor and control remote Java servers I have to deploy some Java servers in a bunch of different networks. For each server, I need to monitor its status and send it tasks to be executed in that specific server. Something like distributed workers.
This servers would be used from different platforms and languages so I need to find a way to communicate with them and obtain the needed information. Which is the best way to do this? I've been reading about use JSONs to communicate with my servers but I'm trying to figure out if there is a better approach.
Another solution could be to have a web dashboard and control all through web petitions but I prefer the servers to be standalone. Any ideas on what I can do?

A: If multiple platforms are involved, web services are probably your best bet. You can have you java servers expose web services (for status and task execution) and you can call them from anywhere/any system.

A: At the moment I would suggest REST interfaces for your Java server. Since REST with Json is easy to implement in other languages too and you can even use HTML and JavaScript to write a Monitor client. So from my point of view this is the most flexible solution.
An other solution would be to use XMPP to "talk" with the server and "ask" them about there state. I remeber this as a solution for machine to machine communication, but this was before the Json and REST boom so I would not suggest to go with this.
When your other platforms consists of Java and C# mostly SOAP could also be a solution, since there are good code generator for both languages which can create the WSDL from code and vice versa. But its kinda difficult to use SOAP in JavaScript (as far as I experienced) and maybe other languages have the same problem with SOAP.


text:
Q: Which Launch Image Should I Use? I'm building a game for the iphone, and the main window displays an image in the background describing the game, and I have few other layers of images which are the buttons such as Start New Game, Options and Help.
Should the launch image be only the background image describing the game without the extra image layers or should it be image including the other layers which are Start New Game, Option and Help?
Thanks.

A: The launch image should give the illusion of a really fast launching of your app. So the better image in your case is an hybrid of your proposal.
You should have the background image describing the game with the extra image layers without the text inside your buttons (Start new game, etc.) If you include the text, the user could think that your app is loaded and would tap on it.
Hope this helps

A: All the Apple guidelines on launch images are available here (scroll down to "Launch Images" section). It seems like the convention is to show buttons but not table view data, based on the examples show and from observing other Apple apps.
It's probably up to you to determine which looks better. I have seen many apps on the app store that totally ignore all of these things you aren't supposed to do:

*

*An "application entry experience," such as a splash screen

*An About window

*Branding elements, unless they are a static part of your application's first screen

So I don't think it's that important for App Store acceptance, but it is very important for user experience.

A: The bit covering launch  images can be found here. Below is an example launch image (left) provided by Apple.
Their docs specifically site concerns about localization, so it's probably best to do without the text and provide an image that just has your background chrome for the view.


text:
Q: In IntelliJ IDEA, how can I reset the per file indentation decision? IntelliJ IDEA shows a small notice at the top of a file when the detected indentation inside the file does not match that configured in the settings dialog. It also allows to switch the indentation to the configured setting, which is a useful thing.
But now I have two files for which I would like to revert that decision and not apply my locally defined indentation. However this appears to be impossible...
Even changing the configured indentation setting does not have an effect on those files I once made that decision for. It appears that the decision is set and stored as a per file configuration.
Question: is there any way to remove that per file setting again?

A: Have you tried Edit -> Convert Indents -> To Spaces / To Tabs ?
This should be file specific.


text:
Q: valor del mapa se actualiza antes de evaluar condición Reformulo la pregunta que he hecho hace un momento. Estoy realizando un método el cual va añadiendo nuevos tipos a un almacén. La idea es llevar a cabo el método x veces hasta que el valor que paso como parámetro resultado después de realizar una iteración y actualizarlo, sea igual a su valor antes de la última iteración res0 y entonces devolver dicho resultado. Mientras que sea distinto, pues llamo recursivamente.
   public HashMap<String, List<String>> calcularTipoNoprimitivo2(HashMap<String,List<String>> resultado) {
    HashMap<String,List<String>> res0 =new HashMap<>();   //creo el hashmap quue contendra 'resultado' de la iteracion anterior
    res0 = (HashMap<String, List<String>>) resultado.clone();  //lo clono para que tenga el resultado antes de la iteracion

    for (Map.Entry<String, List<String>> dicIni : almacen_inicializaciones.entrySet()) {
        for (Map.Entry<String, List<List<String>>> diccTipos : almacen_tipos.entrySet()) {
            List<List<String>> cuerpoTipoNoPrimitivo;
            cuerpoTipoNoPrimitivo = almacen_tipos.get(diccTipos.getKey());
            if (!cuerpoTipoNoPrimitivo.isEmpty()) {

                for (int i = 0; i < cuerpoTipoNoPrimitivo.size(); i++) {
                    List<String> sublista;
                    sublista = cuerpoTipoNoPrimitivo.get(i);
                    if (dicIni.getValue().containsAll(sublista)) {    //si la entrada contiene a todos los valores de sublista entonces
                        List<String> listaAux = new ArrayList<>();   //creo listaAux que contendra el nuevo tipo que quiero introducir
                        listaAux = dicIni.getValue();               // extraigo  la antigua definicion
                        listaAux.add(diccTipos.getKey());            //añado a listaAux el nuevo tipo. Aquí es cuando el metodo falla y actualiza automaticamente el valor en 'resultado' y en el clon, 'res0'
                        if (!resultado.containsValue(listaAux)) {    // no llega a evaluar la condicion
                            resultado.put(dicIni.getKey(), listaAux);
                        }
                         if(!almacen_inicializaciones.containsValue(listaAux)){
                            almacen_inicializaciones.put(dicIni.getKey(), listaAux);
                        }

                    }
                }
            }
        }
    }
    if (!(res0.equals(resultado))) {      //después de la iteracion la idea es compararlos, si son distintos pues llamo recursivamente
        calcularTipoNoprimitivo2(resultado);
    }
    return resultado;                   //si son iguales ppues devuelvo ese resultado
}

Los problemas que tengo son, que a la hora de crear el clon de resultado, 'res0' cuando actualizo resultado dentro de la iteración también actualizo el clon, lo cual no entiendo porque son Hashmaps distintos,(o eso indica en su id). Por otra parte, tras llamar recursivamente la primera vez, cuando actualizo listaAux, se actualiza automáticamente el valor tanto en el map de resultado como en res0, sin antes comprobar la condición para ver si efectivamente quiero que se actualice o no.

A: Creo que te pasa lo típico que te crees que estás pasando por valor ( porque en java todo se pasa por valor ) pero java te está troleando porque los objetos no son valores.
Básicamente al hacer clone del array estas clonando el objeto, que a su vez digamos es una referencia, esto es lo que se conoce como "shallow copy". Tú lo que quieres hacer es un "deep copy".
Algún ejemplo:
https://howtodoinjava.com/java/collections/hashmap/shallow-deep-copy-hashmap/
Por ser algo mas específico, la solución sería en vez de hacer:
res0 = (HashMap<String, List<String>>) resultado.clone();

Harías algo como (usando SerializationUtils de apache commons):
res0 = SerializationUtils.clone(resultado);


text:
Q: How do I listen to 5.1 audio properly when my latop/headphones are only 2.0? A while back I was wondering why my dvd was so quiet on my computer then solved it by chosing the 2.0 track instead of the 5.1 track.
But now I have a DVD which only has 5.1, how can I watch it without losing the other channels?
If it helps, I'm using Media Player Classic.

A: Use the 5.1 track on the dvd, then set the output in the sound driver to stereo.  it should mux the front and rear channels together in hardware.  if it doesn't get a better soundcard

A: If you use VLC there is quite a few audio tweaks you can do, but in the standard Audio menu you can choose between 5.1, 2 front 2 rear, stereo and mono.
I only had a quick look around the preferences so there might be something even better among the many settings. To get to the cool/advanced menus be sure to click the All radio-button indicated in the picture.


text:
Q: Exporting state from functional components. Bad practice? When building components related to user input, the two ways I've done it is with controlled components or uncontrolled components with refs.
However, one way that it could be done by declaring the variable that will hold the state outside the component and exporting it.
export let input;
let setInput;
const Form = props => {
  [input, setInput] = useState("");
  const handleInput = e => setInput(e.currentTarget.value)
  ...
  return <input value={input} onChange={handleInput} />
}

Would this be considered bad practice? Are there any issues with this?

A: State of a component is a supposed to be an instance property, by declaring state outside of the component you restrict each component instance to have its own state
If you are looking to use state across your App, consider using ContextAPI or Redux


text:
Q: Efficient and practical flood fill algorithm in Java? I need a flood fill algorithm for using with BufferedImage and Graphics2D in Java. I do not need the simple recursive (DFS) or queue (BFS) versions of this algorithm due to their impractically. I need an efficient, practical, and salable version of this algorithm using scan lines method or any other method.

A: seems you're not the 1.st one: Flood fill using a stack
however their solution goes for the queue. But as marked as correct, should work in case you won't find anything more efficient.


text:
Q: Convergence of $\int_0^{\frac{\pi}{2}} \frac{\exp({-1/x)}}{\sqrt{ \sin x}}\, \mathrm{d}x$ Let $$f(x)=\frac{\exp(-1/x)}{\sqrt{ \sin x}}\, \mathrm{d}x.$$
$f(x)$ seems to not have any problems at $x=\frac {\pi}{2}$, but at $x=0$.
So I should understand behavior of $f(x)$ at $x=0$ by evaluating $\lim_{x\to0+}f(x)$.But I am stuck here as I can't apply Taylor expansions to $e^{-\frac{1}{x}}$ and using l'Hospital's rule gives me nothing.

A: Note that $e^{1/x}\ge 1+\frac1x$ for $x>0$ and $x\cos(x)\le \sin(x)$ for $x\in [0,\pi/2]$.
Hence for $x\in(0,\pi/2]$, we have
$$0\le \frac{e^{-1/x}}{\sqrt{\sin(x)}}\le \frac{1}{\left(1+\frac 1x\right) \sqrt{x\cos(x)}}=\frac{\sqrt x}{x+1}\sqrt{\frac{
1}{\cos(x)}} $$
Now apply the squeeze theorem.

A: Using the continuity of the square root, we can conclude
\begin{equation*}
I
:=\lim_{x \searrow 0} \frac{e^{-\frac{1}{x}}}{\sqrt{\sin(x)}}
= \sqrt{ \lim_{x \searrow 0} \frac{e^{-\frac{2}{x}}}{\sin(x)}}
= \sqrt{ \lim_{x \searrow 0} \frac{1}{e^{\frac{2}{x}} \sin(x)}}
\end{equation*}
Now, we can apply L'Hôpital to the following limit
\begin{equation*}
L
:= \lim_{x \searrow 0} e^{\frac{2}{x}} \sin(x)
= \lim_{x \searrow 0} \frac{\sin(x)}{e^{-\frac{2}{x}}}
= \lim_{x \searrow 0} \frac{ \frac{d}{d x}\sin(x)}{\frac{d}{d x} e^{-\frac{2}{x}}}
= \lim_{x \searrow 0} \frac{\cos(x)}{\frac{2}{x^2} e^{-\frac{2}{x}}}
= \lim_{x \searrow 0} \frac{x^2}{2} \cos(x) \cdot e^{\frac{2}{x}}.
\end{equation*}
And now, because the limits of the factors exist and one is finite we have by the product rule
\begin{equation*}
L = \frac{1}{2} \underbrace{\lim_{x \searrow 0} \cos(x)}_{= 1} \cdot \left(\lim_{x \searrow 0} x^2 \cdot e^{\frac{2}{x}}\right)
= \frac{1}{2} \underbrace{\left(\lim_{x \searrow 0} x^2 \cdot e^{\frac{2}{x}}\right)}_{:= \widetilde{L}}
\end{equation*}
Since $x \mapsto x^2$ is monotone and continuous, we have
\begin{equation*}
\widetilde{L}
= \big( \underbrace{\lim_{x \searrow 0} x \cdot e^{\frac{1}{x}}}_{=: \widehat{L}} \big)^2
\end{equation*}
Now, by L'Hôpital, we have
\begin{equation*}
\widehat{L}
= \lim_{x \searrow 0} \frac{e^{\frac{1}{x}}}{\frac{1}{x}}
= \lim_{x \searrow 0} \frac{\frac{d}{dx} e^{\frac{1}{x}}}{\frac{d}{dx} \frac{1}{x}}
= \lim_{x \searrow 0} \frac{-\frac{1}{x^2} e^{\frac{1}{x}}}{-\frac{1}{x^2}}
= \lim_{x \searrow 0} e^{\frac{1}{x}}
= \infty.
\end{equation*}
Therefore, we have $L = \infty$ and so $I = 0$.


text:
Q: Iterating over list I am currently doing a small pet project and i have come this far, currently my code accepts the string, changes the string into the respective cipher and displays it but its displaying the whole iterated string. What i am doing wrong ? i want only the translated string.
Code
def encrypt_letter(letter):
    cipher = {'a': 'n', 'b': 'o', 'c': 'p', 'd': 'q',
              'e': 'r', 'f': 's', 'g': 't', 'h': 'u',
              'i': 'v', 'j': 'w', 'k': 'x', 'l': 'y',
              'm': 'z', 'n': 'a', 'o': 'b', 'p': 'c',
              'q': 'd', 'r': 'e', 's': 'f', 't': 'g',
              'u': 'h', 'v': 'i', 'w': 'j', 'x': 'k',
              'y': 'l', 'z': 'm'}
    lowercase_letter = letter.lower()
    return cipher[lowercase_letter]

def encrypt(string):
    result = []
    letters = list(string)
    for letter in letters:
        encrypted_letter = encrypt_letter(letter)
        result.append(encrypted_letter)
        print "".join(result)

e = encrypt("hello")
print e

Output
u
ur
ury
uryy
uryyb
None

Expected output
'uryyb'

A: One minor change will do! What you want is to return the string.
def encrypt(string):
    result = []
    letters = list(string)
    for letter in letters:
        encrypted_letter = encrypt_letter(letter)
        result.append(encrypted_letter)
    return "".join(result) # change to return

e = encrypt("hello")
print e # will give you expected output

In fact, you can write shorter code with this:
def encrypt(string):
    cipher = {'a': 'n', 'b': 'o', 'c': 'p', 'd': 'q',
              'e': 'r', 'f': 's', 'g': 't', 'h': 'u',
              'i': 'v', 'j': 'w', 'k': 'x', 'l': 'y',
              'm': 'z', 'n': 'a', 'o': 'b', 'p': 'c',
              'q': 'd', 'r': 'e', 's': 'f', 't': 'g',
              'u': 'h', 'v': 'i', 'w': 'j', 'x': 'k',
              'y': 'l', 'z': 'm'}
    return ''.join(cipher[s] for s in string.lower())

A: You are printing out the list with each iteration of the for-loop.  You need to do two things to fix the problem:

*

*Dedent print "".join(result) one level.

*In that line, change print to return.
Here is the full code:
def encrypt_letter(letter):
    cipher = {'a': 'n', 'b': 'o', 'c': 'p', 'd': 'q',
              'e': 'r', 'f': 's', 'g': 't', 'h': 'u',
              'i': 'v', 'j': 'w', 'k': 'x', 'l': 'y',
              'm': 'z', 'n': 'a', 'o': 'b', 'p': 'c',
              'q': 'd', 'r': 'e', 's': 'f', 't': 'g',
              'u': 'h', 'v': 'i', 'w': 'j', 'x': 'k',
              'y': 'l', 'z': 'm'}
    lowercase_letter = letter.lower()
    return cipher[lowercase_letter]

def encrypt(string):
    result = []
    letters = list(string)
    for letter in letters:
        encrypted_letter = encrypt_letter(letter)
        result.append(encrypted_letter)
    ######################
    return "".join(result)
    ######################

e = encrypt("hello")
print e

Output:
uryyb

A: Your print is inside the for loop; dedent it one level, i.e.
    result.append(encrypted_letter)
print "".join(result)

This will prevent the repeated printing out through the loop. Also, nothing gets returned from your function, add:
return result

at the end (either additional to or replacing the print) to send your output to e.

A: The problem is that
    print "".join(result)

falls in the for loop.

A: I'd return a string from encrypt, not print one.
def encrypt(string):
    result = ""
    for letter in list(string):
        result += encrypt_letter(letter)
    return result

print(encrypt("hello"))

A: def encrypt(string):
  return ''.join([encrypt_letter(letter) for letter in string])

output:
uryyb


text:
Q: how to use cookie in laravel 5.4 to store data i am creating a website which needs to store user info and save to cookie.
here is my get cookie controller
public function index($id, Request $request)
{
    $petitions = Petitions::where('id',$id)->first();
    $sign->name  = $request->cookie('name');
    $sign->email = $request->cookie('email');

    return view('petitions.index', compact('petitions'))->with(['name'=>$sign->name,'email'=>$sign->email]);
}

and here is set cookie controller
public function store(Request $request)
{
    $sign = new ActionUsers();

    $sign->name = $request->get('name');
    $sign->email = $request->get('email');
    $sign->job = $request->get('job');
    $sign->reason = $request->get('reason');
    $sign->ip_address = $request->get('ip_address');
    $sign->petition_id = $request->get('petition_id');
    $sign->is_anonymous = $request->get('is_anonymous');

    $sign->save();

    $name_cookie = cookie('name', $sign->name, 30);
    $email_cookie = cookie('email', $sign->email, 30);

    return back()->withCookie($name_cookie,$email_cookie);
}

my view to check cookie existed
@if( isset($sign->name)  &&  isset($sign->email) )
    done!
@else Oops! Error

and return error Creating default object from empty value in  $sign->name  = $request->cookie('name');
    $sign->email = $request->cookie('email');
anyone help me solve that! thank you

A: Try return in store function as :
return back()->withCookie($name_cookie)->withCookie($email_cookie);

A: There are several ways to do this:
$response = new \Illuminate\Http\Response(view('your_view'));
$response->withCookie(cookie('cookieName' , 'cookieValue' , expires_in_minutes));
return $response;

or
\Cookie::queue('cookieName', 'cookieValue', expires_in_minutes);
return view('your_view');

you can also use this code to get cookies :
$request->cookie('coockieName');


text:
Q: Grails spring security using dynamodb I am unable to log in my user into a grails application using spring security and dynamodb.
Grails is 2.1 and installed plugins are spring-security core and dynamodb latest.
User and role are creatd by s2-quickstart and its only modification is by adding String id and static mapWith = "dynamodb" to user, role and userrole classes (String id is required since id on dynamodb is UUID generated)
Bootstrap is as per spring security tutorial.
Application starts fine and dynamodb tables and rows are created.
I keep getting
Authentication failed: password does not match stored value
by loggin in on LoginController (I didn't set the sample controller from tutorial). Any ideas?

A: If you have more then one data source configured, which I'm guesing you do since you have used the mapWith the beforeUpdate block will be called more then once. (Once for each data source) I added the following to my user domain object and it works correctly.
transient hasBeforeInsert = false
transient hasBeforeUpdate = false

...

  def beforeInsert()
  {
    if(!hasBeforeInsert)
    {
      hasBeforeInsert = true
      encodePassword()
    }
  }

  def beforeUpdate()
  {
    if(!hasBeforeUpdate)
    {
      hasBeforeUpdate = true

      if(isDirty('password'))
      {
        encodePassword()
      }
    }


text:
Q: Get the number of items in cart in wordpress using woocommerce i'm actually developping a website. But i'm facing an issue. I need to display the number of item that are in the cart but only the number, nothing else i dont want total amount or anything else. Juste the number of items.
I aim to display it over my " go to cart " link that is an image with an href. But this is not the main pb. The main pb is how to find a way to get only the number of item in the cart.
I'm using WordPress with Avada installed to be able to customize a bit more WP and get some includes features. But i'm not using the avada menu, I'm using a home made menu, and i want to display in it the number of item in cart.
And for the " shopping side " I'm using WooCommerce.
I saw many posts of hooks and everything about this but it was about " show number of items and total cart amount, i dont want to display total car amount, I just want the number. a bit like this way : Cart number of items: plein.com website

A: Try This Code
global $woocommerce;
print_r(count(WC()->cart->get_cart()));

A: $total_qty = WC()->cart->cart_contents_count;

A: Hey and welcome to the site, though I am new around here too! The WooCommerce documentation actually has a snippet for exactly this purpose:
https://docs.woocommerce.com/document/show-cart-contents-total/
In your case to just get the count, you could do something like this:
Cart Total: <?php echo WC()->cart->get_cart_contents_count(); ?>

Koda

A: From https://gist.github.com/mikejolley/2044101:
Add this code in your header.php file.
<a class="cart-contents" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf ( _n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> - <?php echo WC()->cart->get_cart_total(); ?>

A: Further to Kodaloid's answer, you can also only show the cart count if it is greater than 0.
$cartcount = WC()->cart->get_cart_contents_count();
if ($cartcount > 0) { echo $cartcount; }

A: From your given description I understand that you want to show cart count only and nothing else. Here goes the code to do that
Add This code block In header.php or in that file where you want to display this widget...
<a class="cart-customlocation" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php WC()->cart->get_cart_contents_count(); ?>

And Then Add this code block to functions.php
add_filter('add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment');

function woocommerce_header_add_to_cart_fragment( $fragments ) {
    global $woocommerce;

    ob_start();

    ?>
    <a class="cart-customlocation" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php WC()->cart->get_cart_contents_count(); ?>

    <?php

    $fragments['a.cart-customlocation'] = ob_get_clean();

    return $fragments;

}

A: get_cart_contents_count() show the total quantity of all product items.
i.e. you buy 2kg of product A and 1kg of product B, get_cart_contents_count() return 3.
If you need to show how many products are in cart, I did this in functions.php:
function count_item_in_cart() {
    $count = 0;
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $count++;
    }
    return $count;
}

then in your php file you can do this
<?php echo count_item_in_cart() . " products"; ?>

A: the best way for get the number of items:

*

*Number of products >> echo count(WC()->cart->get_cart());

*Number of products and number of orders for each product : echo WC()->cart->get_cart_contents_count();


text:
Q: Object Expected Error only in IE I keep on getting object expected in IE. This is the Javascript code where I think the problem is:
 $('#rv-sidebar-decline-all').click(function () {
        PageModuleContext.sendMessage("declineAll", null, this.handleMessage);

and this is its CSS.
#rv-sidebar-decline-all {
    cursor              : default;
    height              : 8px;
    width               : 8px;
    background-position : left top;
    background-image    : url({{:declineAll}});
}

Basically once this background image is clicked an event is supposed to happen. I get a popup which says Object Expected but if I want to continue running the script. When I click yes on the popup the event happens after that.


text:
Q: How to implement In-App Purchases Subscription in Flutter? I want to provide auto renewable subscription in my Flutter App for both iOS and Android devices. Users can subscribe for 1 Month.
There is not an officially maintained in-app purchase plugin yet. But there are lots of plugins about In-App Purchases in Flutter.
Which one is the best? How to implement? Are these secure?

A:
==== UPDATE from 11.03.2020
Hi, I can see this post still reading by people who looking for a
method of how to work with subscription in Flutter. During 2019 I made
two apps with thousands install where users can buy a renewable
subscription on the 2 platforms. Until February 2020 I used for this
package from Flutter team https://pub.dev/packages/in_app_purchase,
BUT - there is no way to get info about the user to unsubscribe in
iOS. This is not the plugin issue, but the iOS approach for the
process. We should implement our own backend for security reasons (by
the way Google also recommends to do the same, but still left the way
to check the state directly from the app).
So, after some researches, I found guys who made backend and plugin
and it is free until you have less than 10 000 USD revenue for the
month. https://www.revenuecat.com/
https://pub.dev/packages/purchases_flutter
I've implemented this plugin in my apps and it works like a charm.
There is some good approaches that allow you to get a subscription
state at any point in the app. I'm going to make an example and
article, but not sure about the timing.
==== UPDATE from 03.10.2019
I recommend using new package from Flutter
team  https://pub.dev/packages/in_app_purchase
The example with code is here https://github.com/flutter/plugins/tree/master/packages/in_app_purchase/in_app_purchase/example
With this plugin I successfully implemented payments and recursive
subscriptions to Android and iOS simultaneously. With the old package I
had some minor issues.

You can use nice plugin flutter_inapp_purchase
I've used it for the app that I developed and it works well. You can use my example of how to work with subscription - github
There is a complete working example - when you run it, you should get the screen

(do not forget to log in to Google play in an emulator or you will get "in-app billing version 3 NOT supported")

A: For those looking for resource on how to implement IAP, Flutter team wrote a tutorial using in_app_purchase package and Firebase as backend for validation.
Link: https://codelabs.developers.google.com/codelabs/flutter-in-app-purchases#0

A: Android and IOS both with In-App-Purchase with auto-renew working best and easy way in Revenuecat plugin Link https://docs.flutterflow.io/advanced-functionality/payments/revenuecat


text:
Q: How to prove this material derivative formula rigoriously with experiment or prove it without the chain rule?
How to prove this rigoriously by experiment or prove it with other mechanics law but without the chain rule?

This is coming from reddy's introduction to continuum mechanics.
Also please explain what the above formula is term by term since i don't quite understand what this seem-to-be simple formula is.

A: The equation in question is the convective derivative, used e.g. in the transport equation.
Its meaning in that context is "a box is moving downstream: the time-rate-of-change of stuff inside the box..." (with the other side of the equations saying "...is equal to the rate of stuff flowing into the box minus the rate flowing out, plus any intrinsic time-dependence of the stuff.")
To properly understand a box moving downstream we have to compute the following limit: $$\frac{{\rm D}f}{{\rm D}t} = \lim_{\delta t\to0} \frac{f(\vec r + \vec v~\delta t,~ t + \delta t) - f(\vec r,~ t)}{\delta t}.$$ In multivariable calculus you replace the tangent-lines of calculus with tangent-hyperplanes, so that the above term expands out to first order as: $$f(x + \delta x,~ y + \delta y,~ z + \delta z,~t+\delta t) \approx f(\vec r,~t) + \frac{\partial f}{\partial x}~\delta x + \frac{\partial f}{\partial y}~\delta y + \frac{\partial f}{\partial z}~\delta z + \frac{\partial f}{\partial t}~\delta t$$Therefore the above is, to first order in $\delta t$:$$\frac{{\rm D}f}{{\rm D}t} = \vec v\cdot\nabla f + \frac{\partial f}{\partial t}.$$


text:
Q: MS SQL 2008 R2 Queryanalyzer successful run in the code. Failed SQL code field within the LOGO application is running MS SQL 2008 R2 Queryanalyzer successful run in the code. Failed SQL code field within the LOGO application is running.
Error :
" The order by clause is invalid in views, inline functions,derived tables,subqueries and common table expressions,unless TOP or FOR XML is also specified"

My Code :
printf("goodbye world!");  /* his suicide note
                              was in C */

SELECT PLN.[DATE_] AS 'TARİH',
          CC.DEFINITION_ AS 'Cari Kodu',
          TANA.DONEM AS 'MNL_Dönem',
          CASE
        WHEN TANA.Oda_Tipleri='1' THEN 'Tek Kişilik'
        WHEN TANA.Oda_Tipleri='2' THEN '2 kişilik'
        WHEN TANA.Oda_Tipleri='3' THEN '3 kişilik'
        WHEN TANA.Oda_Tipleri='4' THEN '4 kişilik'
        WHEN TANA.Oda_Tipleri='5' THEN '2 kişilik odada TEK kişi'
        WHEN TANA.Oda_Tipleri='6' THEN '3 kişilik odada 2 kişi'
    ELSE 'SEÇİLMEMİŞ'
 END 'Oda_Tipi',
CASE        WHEN TANA.Oda_Ozellik= '1'      THEN 'Dışa Bakan Oda '
        WHEN TANA.Oda_Ozellik= '2'  THEN 'Kurangleze Bakan Oda '
        WHEN TANA.Oda_Ozellik= '3'  THEN 'İçe Bakan Oda '
        WHEN TANA.Oda_Ozellik= '4'  THEN 'Arkaya Bakan Oda '
        WHEN TANA.Oda_Ozellik= '5'  THEN 'Öne Bakan Oda '
    ELSE 'SEÇİLMEMİŞ'
END Oda_Ozellik,

CASE
        WHEN TANA.Sene_Bilgisi = '1' THEN '2011/2012 '
        WHEN TANA.Sene_Bilgisi = '2' THEN '2012/2013 '
        WHEN TANA.Sene_Bilgisi = '3' THEN '2013/2014 '
        WHEN TANA.Sene_Bilgisi = '4' THEN '2014/2015 '
        WHEN TANA.Sene_Bilgisi = '5' THEN '2015/2016 '
        WHEN TANA.Sene_Bilgisi = '6' THEN '2016/2017 '
        WHEN TANA.Sene_Bilgisi = '7' THEN '2017/2018 '
        WHEN TANA.Sene_Bilgisi = '8' THEN '2018/2019 '
        WHEN TANA.Sene_Bilgisi = '9' THEN '2019/2020 '
    ELSE 'SEÇİLMEMİŞ'
END Sene_Bilgisi,
CASE
        WHEN TANA.Donem_Bilgisi = '1' THEN 'Güz '
        WHEN TANA.Donem_Bilgisi = '2' THEN 'Bahar '
        WHEN TANA.Donem_Bilgisi = '3' THEN 'Yaz '
    ELSE 'SEÇİLMEMİŞ'
END Donem_Bilgisi,

CASE
        WHEN TANA.Burs_Tipi = '1' THEN 'YÖK'
        WHEN TANA.Burs_Tipi = '2' THEN '%25 Yönmetim Bursu'
        WHEN TANA.Burs_Tipi = '3' THEN '%50 Yönmetim Bursu'
        WHEN TANA.Burs_Tipi = '4' THEN '%75 Yönmetim Bursu'
        WHEN TANA.Burs_Tipi = '5' THEN '%100 Yönmetim Bursu'
        WHEN TANA.Burs_Tipi = '6' THEN '%50 Yurt Kredisi'
        WHEN TANA.Burs_Tipi = '7' THEN '%100 Yurt Kredisi'
        WHEN TANA.Burs_Tipi = '8' THEN '%100 Yönetim Burdu Mezuniyete Kadar'
        WHEN TANA.Burs_Tipi = '9' THEN '%50 Burs %50 Yurt Kredisi'
    ELSE 'Burssuz veya Seçilmemiş'
END Cinsiyet_Tipi,

CASE
        WHEN TANA.Cinsiyet_Tipi = '1' THEN 'Erkek '
        WHEN TANA.Cinsiyet_Tipi = '2' THEN 'Kız '
    ELSE 'SEÇİLMEMİŞ'
END Cinsiyet_Tipi,
CASE
        WHEN TANA.Uyruk= '0' THEN 'TC '
        WHEN TANA.Uyruk= '1' THEN 'Diğer '
        ELSE 'SEÇİLMEMİŞ'
END Uyruk,

PLN.[FICHEREF] As 'Sipariş Referansı',
SIP.SPECODE As 'Sip.ÖK',
SIP.FICHENO As 'Sip.No',
SIP.DOCODE As 'Sip.Belge No',
CASE WHEN (FAT.[FICHENO] IS NULL) THEN '0' WHEN (FAT.[FICHENO] IS NOT NULL) THEN FAT.[FICHENO] END AS 'Fatura No',
PLN.[TRCODE],
PLN.[TOTAL] AS 'PLN Taksit Tutarı',
CASE WHEN (FAT.[NETTOTAL] IS NULL) THEN '0' WHEN (FAT.[NETTOTAL] IS NOT NULL) THEN FAT.[NETTOTAL] END AS 'Kesilen.Fat.Tut',
CASE WHEN (PLN.[TOTAL]- FAT.[NETTOTAL] IS NOT NULL) THEN '0' WHEN (PLN.[TOTAL]- FAT.[NETTOTAL] IS NULL) THEN 'Faturalanmamış' END AS 'FARK',
CASE WHEN (FAT.[TOTALVAT] IS NULL) THEN '0' WHEN (FAT.[TOTALVAT] IS NOT NULL) THEN FAT.[TOTALVAT] END AS 'Kesilen KDV',
CASE WHEN (FAT.[TOTALVAT] IS NOT NULL) THEN '0' WHEN (FAT.[TOTALVAT]IS NULL) THEN ROUND((PLN.[TOTAL]-(PLN.[TOTAL]/1.08)),2) END AS 'KesileCEK KDV',
PLN.[CANCELLED] As 'İPTAL Durumu',
PLN.[MODIFIED],
PLN.[PAYNO] AS 'Öd.Pln.Satırı',
CASE WHEN (FAT.[TRACKNR] IS NULL) THEN 'Faturalanmamış' WHEN (FAT.[TRACKNR] IS NOT NULL) THEN FAT.[TRACKNR] END AS 'FAT.SIRA.NO'
FROM LG_011_01_PAYTRANS AS PLN
LEFT OUTER JOIN LG_011_CLCARD CC ON
CC.LOGICALREF = PLN.CARDREF LEFT OUTER JOIN
LG_011_01_INVOICE AS FAT ON  PLN.FICHEREF=FAT.DOCTRACKINGNR AND FAT.TRACKNR=PLN.PAYNO     LEFT OUTER JOIN
LG_011_01_ORFICHE AS SIP ON  PLN.FICHEREF=SIP.LOGICALREF INNER JOIN
LG_XT1015_011 AS TANA ON CC.LOGICALREF=TANA.PARLOGREF
Where MODULENR=3
ORDER BY  PLN.[DATE_] ASC

Also, any application for a report, t-sql code that runs smoothly, queryanalzer. If you stack overflow error can be identified right from the stack, then it might be possible that convert data? How is it? You can find a document that explains step by step on video?
Error Detail:
cpu registers: eax = 0d3e2f60 ebx = 0d40ef98 ecx = 00000000 edx = 0042967e esi = 00000019 edi = 0012fc24 eip = 0042967e esp = 0012efa8 ebp = 0012f004

A: If this is the error message - "The order by clause is invalid in views, inline functions,derived tables, sub-queries and common table expressions,unless TOP or FOR XML is also specified", you should enter "TOP 100 PERCENT" in the clause of the statement where "order" is used.
In your case I suppose it will be:
SELECT    TOP 100 PERCENT
          PLN.[DATE_] AS 'TARIH',
          CC.DEFINITION_ AS 'Cari Kodu',
          TANA.DONEM AS 'MNL_Dönem',
          CASE
          ...


text:
Q: How to get Products How to get Product.
I am adding my code here...
<?php
/**
 * Webkul Hello CustomPrice Observer
 *
 * @category    Webkul
 * @package     Webkul_Hello
 * @author      Webkul Software Private Limited
 *
 */
namespace Deep\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;

class CustomPrice implements ObserverInterface
{

 public function execute(\Magento\Framework\Event\Observer $observer) {
        $item = $observer->getEvent()->getData('quote_item');
        $price1 = $item->getPrice();
        $product = $item->getProduct();

         if (null !== $product->getCustomAttribute('deep_sample_price')) {
             $price = 5; //set your price here
             $item->setCustomPrice($price);
             $item->setOriginalCustomPrice($price);
             $item->getProduct()->setIsSuperMode(true);

        }
        else if(null == $product->getCustomAttribute('deep_sample_price')){
            echo $product->getCustomAttribute('deep_sample_price')->getValue();

        }
    }

}

A: You can get all quote items like this:
$quoteItems = $this->_checkoutSession->getQuote()->getAllVisibleItems();

And you can get product id from quote item like this :
$item->getProductId();

After that load that product by id and do your stuff


text:
Q: Open php outside of webroot I'm trying to write a stand alone web form to insert data into MySQL. I don't want it to be accessible to my web users. How do I get it to open up in my browser. It currently resides in my home folder. file:///home/user/file.php .

A: You have to setup a local LAMP, that is installing Apache and PHP (I assume MySQL is already installed)


text:
Q: WPF TreeView sub-items not displaying I am trying to build a TreeView by creating and adding my TreeViewItems in code. I have an object of Folders that that contain a list of sub-folders and a list of Sessions. All of this is kept inside a Root folder object. When I use recursion to create the TreeViewItems and add them to my TreeView, the Folders and Sessions in the root folder appear but none of the TreViewItems that belong to their collection are displayed.
When I write out the xaml for the page by hand it displays as desired but not when added with code. I have looked at the TreeView object in the debugger, I can see the second and third layer of TreeViewItems in the Items collection but none of them display.
My objects
    [Serializable]
    public class Session
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public Protocol ConnectionProtocol { get; set; }
        public int Port { get; set; }
    }

[Serializable]
    public class Folder
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual int ParentID { get; set; }
        public virtual List<Folder> SubFolders { get; set; } = new List<Folder>();
        public virtual List<Session> Sessions { get; set; } = new List<Session>();
    }

    [Serializable]
    public class Root : Folder
    {
        public KeyValuePair<ulong, int> Version
        {
            get
            {
                return new KeyValuePair<ulong, int>(_revisionNumber, GetHashCode());
            }
        }
        private ulong _revisionNumber = 0;

        public override int Id { get => 0; set { } }
        public override int ParentID { get => 0; set {  } }

        private void UpdateVersion()...

        public bool AddSession(Session session)...

        public bool RemoveSession(Session session)...

        public bool AddFolder(Folder folder)...

        public bool RemoveFolder(Folder folder)...
    }

And in the MainWindow
        private static Root root { get; set; }

        private void RefreshTree()
        {
            SessionsTree.Items.Clear();

            foreach (var sub in root.SubFolders)
                SessionsTree.Items.Add(GetNodesFromFolder(sub));

            foreach (var session in root.Sessions)
                SessionsTree.Items.Add(BuildTreeViewItem(session));

            SessionsTree.UpdateLayout();
        }

        private TreeViewItem GetNodesFromFolder(Folder folder)
        {
            TreeViewItem viewItem = BuildTreeViewItem(folder);
            foreach (var sub in folder.SubFolders)
                viewItem.Items.Add(GetNodesFromFolder(sub));

            foreach (var session in folder.Sessions)
                viewItem.Items.Add(BuildTreeViewItem(session));

            return viewItem;
        }

        private TreeViewItem BuildTreeViewItem(Folder folder)
        {
            TreeViewItem viewItem = new TreeViewItem();
            viewItem.Tag = folder;
            viewItem.Height = 14;

            Image image = new Image();
            image.Source = FolderImage;
            image.Height = 14;

            TextBlock textBlock = new TextBlock();
            textBlock.Text = folder.Name;

            StackPanel stackPanel = new StackPanel();
            stackPanel.Orientation = Orientation.Horizontal;
            stackPanel.Children.Add(image);
            stackPanel.Children.Add(textBlock);

            viewItem.Header = stackPanel;

            return viewItem;
        }

        private object BuildTreeViewItem(Session session)
        {
            TreeViewItem viewItem = new TreeViewItem();
            viewItem.Tag = session;

            Image image = new Image();
            image.Source = SwitchBlue;
            image.Height = 14;

            TextBlock textBlock = new TextBlock();
            textBlock.Text = session.Name;
            textBlock.Margin = new Thickness(4, 0, 0, 0);

            StackPanel stackPanel = new StackPanel();
            stackPanel.Orientation = Orientation.Horizontal;
            stackPanel.Children.Add(image);
            stackPanel.Children.Add(textBlock);

            viewItem.Header = stackPanel;

            return viewItem;
        }

I would expect a tree to display such as....
v {} Folder 1
  v {} SubFolder 1
      [] Session
      [] Session
  > {} SubFolder 2
      [] Session
  > {} SubFolder 3
> {} Folder 2
> {} Folder 3
  [] Session
  [] Session
  [] Session

But what I get is
v {} Folder 1
v {} Folder 2
v {} Folder 3
  [] Session
  [] Session
  [] Session

A: When items don't contain at least one child item, then the TreeView or the actual node won't be expandable. If you need to add child items to the tree at a later time (e.g. lazy loading) you need to add a dummy item to make the TreeView to show the expander. Since you are using a List as child collection, you would have to create the complete tree data structure first and add it at once to the TreeView.ItemSource or simply use an ObservableCollection.
To keep things simple all node types should be stored in one shared collection which requires a common base type. Then you can simply use a DataTemplateSelector to create the corresponding TreeViewItem dynamically.
MainWindow.xaml
<Window>
  <Window.DataContext>
    <ViewModel />
  </Window.DataContext>

  <TreeView ItemsSource="{Binding Folders}"
            ItemTemplateSelector="{DynamicResource DataTemplateSelector}">
    <TreeView.Resources>
      <local:DataTemplateSelector x:Key="DataTemplateSelector" />

      <HierarchicalDataTemplate x:Key="FolderDataTemplate"
                                DataType="Folder"
                                ItemsSource="{Binding ChildItems}">
        <TextBlock Text="{Binding Name}" />

      </HierarchicalDataTemplate>

      <DataTemplate x:Key="SessionDataTemplate"
                    DataType="Session">
        <TextBlock Text="{Binding Name}" />
      </DataTemplate>
    </TreeView.Resources>
  </TreeView>
</Window>

DataTemplateSelector.cs
class DataTemplateSelector : System.Windows.Controls.DataTemplateSelector
{
  public override DataTemplate
    SelectTemplate(object item, DependencyObject container)
  {
    FrameworkElement element = container as FrameworkElement;

     return item is Session
       ? element.FindResource("SessionDataTemplate") as DataTemplate
       : element.FindResource("FolderDataTemplate") as DataTemplate;
  }
}

ViewModel.cs
class ViewModel
{
  public ObservableCollection<Folder> Folders { get; set; }

  public ViewModel()
  {
    this.Folders = new ObservableCollection<Folder>
    {
      new Folder("Folder_1")
      {
        ChildItems = new ObservableCollection<TreeItem>
        {
          new Folder("Folder_1.1")
          {
            ChildItems = new ObservableCollection<TreeItem>
            {
              new Folder("Folder_1.1.1")
              {
                ChildItems = new ObservableCollection<TreeItem>
                {
                  new Session("SessionA"),
                  new Session("SeesionB")
                }
              },
              new Session("SessionA"),
              new Session("SeesionB")
            }
          },
          new Folder("Folder_1.2")
          {
            ChildItems = new ObservableCollection<TreeItem>
            {
              new Session("SessionA"),
              new Session("SeesionB")
            }
          }
        }
      }
    };
  }
}

Data item hierarchy
public abstract class TreeItem
{
  public TreeItem(String name)
  {
    this.Name = name;
  }
  public string Name { get; set; }
}

public class Folder : TreeItem
{
  public Folder(string name) : base(name)
  {
  }
  public ObservableCollection<TreeItem> ChildItems { get; set; } = new ObservableCollection<TreeItem>();
}

public class Session : TreeItem
{
  public Session(string name) : base(name)
  {
  }
}


text:
Q: How to refine generic WeakTypeTag inside quasi-quote macro We have the following typeclass
trait Mapper[A,M[_]]{
  def map[B](a:M[A], f:A => B):M[B]
}

For which we would like to provide instances for specific M. A naive implementation would look like the following:
def materializeMapperImpl[A : c.WeakTypeTag,M[_]](c:blackbox.Context)(implicit mTypeTag:c.WeakTypeTag[M[A]]): c.Expr[Mapper[A,M]] = {
    import c.universe._
    val aType = weakTypeOf[A]
    //println(mTypeTag.toString())
    c.Expr[Mapper[A,M]]{

      q"""
         new Mapper[$aType,$mTypeTag]{
            def map[B](a1:$mTypeTag, f: $aType => B): $mTypeTag = {
              ???
            }
          }
       """
    }
  }

However, this won't compile because the mTypeTag is not refined in its generic arguments and would rather look as List rather than List[Int] and List[String]. How do we refine the mTypeTag, setting its argument to A and B in the macro?

A: package so

import scala.language.experimental.macros
import scala.language.higherKinds
import scala.reflect.macros.blackbox

trait Mapper[A, M[_]] {
  def map[B](a: M[A], f: A => B): M[B]
}

object Mappers {
  def f[A, M[_]]: Mapper[A, M] = macro impl[A, M]

  def impl[A, M[_]](c: blackbox.Context)
                   (implicit
                    a: c.WeakTypeTag[A],
                    m: c.WeakTypeTag[M[_]]
                   ): c.Tree = {
    import c.universe._

    val ma = m.tpe match {
      case TypeRef(pre, sym, args) =>
        import compat._
        TypeRef(pre, sym, List(a.tpe))
    }
    //attention it is : new packageName.className {}
    val tree =
      q"""
       new so.Mapper[${a.tpe},$m]{
        override def map[B](a:$ma,f:($a) => B) = ???
       }
     """

    q"$tree"
  }
}

//test
Mappers.f[Int,Option]


text:
Q: How to write a Cplex constraint for product types I am trying to write a constraint in Cplex that will only allow certain types of items to be packed together (recipe) in a bin. I have all my product data in a tuple with the recipes represented by either "1" "2" or "3". My code so far:
{string} product = ...;

 tuple ItemInfo {
   int width;
   float amps;
   int recipe;
   int demand;
}

ItemInfo Items[product] = ...;

 dvar boolean x[Bin][product];
 dvar boolean y[Bin];

 minimize sum(b in Bin) y[b];

 subject to {

forall(b in Bin) sum(j in product) Items[j].width*x[b][j] <= Width*y[b];
forall(b in Bin) sum(j in product) Items[j].amps*x[b][j] >= MinAmps*y[b];
forall(b in Bin) sum(j in product) Items[j].amps*x[b][j] <= MaxAmps*y[b];
forall(j in product) sum(i in Bin) x[i][j] == Items[j].demand;
 }

Any ideas on how to ensure there is only one recipe per bin would be greatly appreciated! Thank you!

A: if you compute
{int} recipes={Items[i].recipe | i in product};

then you can write the constraint
forall(b in Bin) 1>=sum(r in recipes) (1<=sum(p in product:Items[p].recipe==r) x[b][p]);

which makes sure that you have max one recipe per bin
Full working example:
.mod
{string} product = ...;

 tuple ItemInfo {
   int width;
   float amps;
   int recipe;
   int demand;
}

int Width=10;
int MinAmps=0;
int MaxAmps=20;

range Bin=1..3;

ItemInfo Items[product] = ...;

{int} recipes={Items[i].recipe | i in product};

 dvar boolean x[Bin][product];
 dvar boolean y[Bin];

 minimize sum(b in Bin) y[b];

 subject to {

forall(b in Bin) sum(j in product) Items[j].width*x[b][j] <= Width*y[b];
forall(b in Bin) sum(j in product) Items[j].amps*x[b][j] >= MinAmps*y[b];
forall(b in Bin) sum(j in product) Items[j].amps*x[b][j] <= MaxAmps*y[b];
forall(j in product) sum(i in Bin) x[i][j] == Items[j].demand;

forall(b in Bin) 1>=sum(r in recipes) (1<=sum(p in product:Items[p].recipe==r) x[b][p]);

 }

and .dat
product={"A","B","C"};
Items=[<1,1,1,1>,<2,2,2,2>,<3,3,1,1>];


text:
Q: How to tell whether a Javascript error is 'blocking'? Is there such a thing as blocking vs non blocking Javascript errors?
What I mean is that I've seen my site report some errors, but the process involved still completes successfully (as far as I can tell). These errors include:
TypeError: undefined is not an object (evaluating 'e.nodeName.toLowerCase')
TypeError: e.nodeName is undefined
(these are always from my general JQuery library file)
These are what I mean by 'non-blocking' errors, since the scripts involved seem to complete successfully.
If there is such a thing as blocking v non-blocking, what is the correct terminology for it, and how can I tell the difference between the 2 (eg so that I can prioritise investigating blocking errors)?
Thanks

A: Whenever
throw Error;

The exception bubles up the function stack. If it reaches the end of it, it throws an uncaught (=unexpected) exception. This halts the complete program as its unlikely to work properly anymore.
However it can be catched  (=expected exception):
try{
 someerrorproducingfunc();
 //continue after success
}catch(e){
 //continue after error
 console.error(e);
}
//continue after error+success

So the code proceeds ( leaving out the continue after sucess part). However, if you use console.error it logs sth that looks like an error.
ressource: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/throw

Note that Error is just an object constructor in js:
new Error("test");

While throw throws an exception...

A: No. All un-caught error are blocking, they will end the execution of the entire call stack. However, an error that happens after various operation will not revert back to a situation like before. Making an AJAX call, and then having an undefined error will not cancel the call for example. Demo:

(function () {
    "use strict";
    let a  = 5;

    console.log(a); // 5

    setTimeout(function () {
        console.log(a); // 10
        // will execute because it is a fresh stack
        // the variable a is 10 despite and not 12 because it happened after
    }, 250);

    const withError2 = function () {
        a = 10;
        a.x.z = 2; // Error
        a = 12; // never executes because it comes after the error
    }

    withError2();
    console.log(a); // never executes because it comes after the error
}());


text:
Q: Совмещение анимации @keyframes и opacity Проблема в том, что opacity не работает...

#square {
  position: relative;
  margin: 0 auto;
  top: 20vh;
  width: 50px;
  height: 30px;
  background-color: red;
  animation: mymove 5s infinite;
}

@keyframes mymove {
  from {
    left: 0px;
  }
  to {
    left: 200px;
  }
}

#cloud-left {
  position: absolute;
  right: 10px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: black;
  animation: cloudmove 2s ease-out infinite;
}

@keyframes cloudmove {
  from {
    top: 0px;
    right: 10px;
    opacity: 0;
  }
  to {
    top: -30px;
    right: 30px;
    opacity: 50;
  }
}

A: Ну естественно не будет работать.Вы написал opacity 50
@keyframes cloudmove {
  from {
    top: 0px;
    right: 10px;
    opacity: 0;
  }
  to {
    top: -30px;
    right: 30px;
    opacity: 50; // Внимание на эту строку
  }
}

В качестве значения выступает число из диапазона [0.0; 1.0]. Значение 0 соответствует полной прозрачности элемента, 1, наоборот — его непрозрачности

#square {
  position: relative;
  margin: 0 auto;
  top: 20vh;
  width: 50px;
  height: 30px;
  background-color: red;
  animation: mymove 5s infinite;
}

@keyframes mymove {
  from {
    left: 0px;
  }
  to {
    left: 200px;
  }
}

#cloud-left {
  position: absolute;
  right: 10px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: black;
  animation: cloudmove 2s ease-out infinite;
}

@keyframes cloudmove {
  from {
    top: 0px;
    right: 10px;
    opacity: 0;
  }
  to {
    top: -30px;
    right: 30px;
    opacity: 1;
  }
}


text:
Q: Java memory mapped files and swap I'm looking at some memory mapped files in Java. Let's say I have a heap size set to 2gb, and I memory map a file that is 50gb - far more than the physical memory on the machine. The OS will cache parts of that 50gb file in the os file cache, the java process will have 2gb of heap space. What I'm curious about is how does the OS decide how much of the 50gb file to cache?
For instance, if I have another java process, also with a 2gb heap size, will that 2gb be swapped out to allow the os to cache parts of the memory mapped file? Will parts of the heap space of the first process be swapped out to allow the OS to cache?
Is there any way to tell the OS not to swap heap space for OS caching? If the OS doesn't swap out main processes, how does it determine how big its file cache should be?

A: Linux doesn't really distinguish between anonymous and memory-mapped pages. They all get demand-loaded anyway via page faults.
You can think of anonymous memory as if it was a private memory mapping of /dev/zero.
So you can map as much of anything as you want (address-space permititng, but I assume you are on a 64-bit box here). Linux only loads them in when the process touches them, via page faults.
Likewise, it keeps some records of how recently pages have been used so they get prioritised for being thrown away.
If your file mapping is a MAP_SHARED one, the only difference is that pages which are discarded to get more space for other things don't have to be written into a swap area, they can just be read back in from the original file.
So in answer to your question, no, mapping a large file will not take virtual memory away from anyone, provided you don't read or write the pages.


text:
Q: Similarity as edge attribute in iGraph Lets say we have some graph g and then we compute some similarity between each pair of nodes from g:
g <- graph.ring(10)
g_sim <- similarity.dice(g)

The question is: how to use data from g_sim to assign weights to the edges from g? In other words: if there is and edge A--B in g, I want to have an attribute for that edge that is equal to value that we have for the pair A,B in g_sim.

A: In theory you could do
g <- graph.ring(10)
g_sim <- similarity.dice(g)
el <- get.edgelist(g)
E(g)$weight <- g_sim[el]

But in this case similarity.dice isn't a good measure. If you compare adjacency (where edges actually exist) to the non-zero similarity values
get.adjacency(g)
#  [1,] . 1 . . . . . . . 1
#  [2,] 1 . 1 . . . . . . .
#  [3,] . 1 . 1 . . . . . .
#  [4,] . . 1 . 1 . . . . .
#  [5,] . . . 1 . 1 . . . .
#  [6,] . . . . 1 . 1 . . .
#  [7,] . . . . . 1 . 1 . .
#  [8,] . . . . . . 1 . 1 .
#  [9,] . . . . . . . 1 . 1
# [10,] 1 . . . . . . . 1 .

g_sim
#       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#  [1,]  1.0  0.0  0.5  0.0  0.0  0.0  0.0  0.0  0.5   0.0
#  [2,]  0.0  1.0  0.0  0.5  0.0  0.0  0.0  0.0  0.0   0.5
#  [3,]  0.5  0.0  1.0  0.0  0.5  0.0  0.0  0.0  0.0   0.0
#  [4,]  0.0  0.5  0.0  1.0  0.0  0.5  0.0  0.0  0.0   0.0
#  [5,]  0.0  0.0  0.5  0.0  1.0  0.0  0.5  0.0  0.0   0.0
#  [6,]  0.0  0.0  0.0  0.5  0.0  1.0  0.0  0.5  0.0   0.0
#  [7,]  0.0  0.0  0.0  0.0  0.5  0.0  1.0  0.0  0.5   0.0
#  [8,]  0.0  0.0  0.0  0.0  0.0  0.5  0.0  1.0  0.0   0.5
#  [9,]  0.5  0.0  0.0  0.0  0.0  0.0  0.5  0.0  1.0   0.0
# [10,]  0.0  0.5  0.0  0.0  0.0  0.0  0.0  0.5  0.0   1.0

You will see that all the edges will be given weight 0. The similarity.dice measure is twice the number of common neighbors divided by the sum of the degrees of the vertices. Apparently the vertices themselves are excluded from the calculation. So that means two connected vertices on a circle share no neighbors so they would have weights of 0. So everything is working properly, just similarity.dice isn't a good choice to weight the edges of this graph because all the weights would be 0.
Thanks to @user368090, here's one that looks better
g <- graph.famous("Krackhardt_Kite")
g_sim <- similarity.dice(g)
el <- get.edgelist(g)
E(g)$weight <- g_sim[el]
plot(g, edge.width=E(g)$weight*10)


text:
Q: Permissions in a shared server (chmod) I have recently been given an account on a Linux server. This server is shared with different members of a research institution and the standard permissions allow other users to access my directories and files.
I have decided to create a folder (let's call it private) in my home and to change the permissions with chmod 700 ~/private. I have noticed that the permissions of new files created in private might allow others to access them. I am fairly new with chmod and I don't understand whether having set the permissions of private as above prevent others to view and access what is within this folder, regardless of the files permissions.
Shall I use a similar approach as in this question to set the permissions of all files within private or having set the permissions of this folder is already enough?

A: It's already enough. The directory access limitations take precedence over its content's permissions.


text:
Q: Is it necessary to create classes for every single database query in order to work with TableView? In the last few days I went through some JavaFX tutorials explaining 'How to use TableViews?' Every single tutorial creates DataModel-Objects like Person for example. This is fine as long as you just want sql-statements like select Firstname, Lastname from Person.
But what if you don't want to create data models for every single select-query, because you join data with another objects for whatever reason? For example, select * from Person join City join Country. What I learned the last days is, if you create a tableview containing only List (representing the rows), it becomes horrible to handle formatting or even evaluating the tableview.
Is that really a javaFX thing? Or did I miss something?
Update
In order to make it more clear, see this question. I first found this question after reading answers and comments to my question, but I am not satisfied with the answer to the linked question.

A: Your question is mixing up two concepts here: javafx.scene.control.TableView on one hand, and SQL/ORM on the other hand. Let's forget about SQL queries and such as I think your concern is mostly on TableView.
TableView must be populated with a List. The inner type of this list must match the TableView's generic type. So for instance TableView<Person> will be populated with a List<Person>.
Other than that, the actual type of the objects representing rows can be anything. It doesn't even have to contain the data itself, or it can very-well be, for instance, a Map<String, Object>. In this case, you will map the keys of the row to each column by defining a CellValueFactory for each column, that will return the entry value for your chosen key.
Then you can convert this value to a String and/or a Nodeby defining a CellFactory for the column.
Objects with JavaFX properties can be mapped more easily, as there exists pre-made PropertyValueFactory that will require only the property name. But they're not the only way to go.
Example using a Map<String, Object> for each row:
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javafx.application.Application;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class App extends Application {

  private TableView<Map<String, Object>> tableView;
  private TableColumn<Map<String, Object>, String> nameCol;
  private TableColumn<Map<String, Object>, Integer> ageCol;

  private Stage stage;

  @Override
  public void start(Stage stage) {
    this.stage = stage;

    //Insert a TableView into scene
    this.tableView = new TableView<>();
    this.nameCol = new TableColumn<>("Name");
    this.nameCol.setPrefWidth(250);
    ageCol = new TableColumn<>("Age");
    tableView.getColumns().add(nameCol);
    tableView.getColumns().add(ageCol);

    nameCol.setCellValueFactory(param -> {
      Map<String, Object> v = param.getValue();
      return new SimpleStringProperty(v == null ? null : (String) v.get("name"));
    });

    ageCol.setCellValueFactory(param -> {
      Map<String, Object> v = param.getValue();
      return new SimpleObjectProperty<Integer>(v == null ? null : (Integer) v.get("age"));
    });
    ageCol.setCellFactory(param -> {
      return new TableCell<>() {
        @Override
        public void updateItem(Integer item, boolean empty) {
          if (empty || item == null)
            super.setText("");
          else
            super.setText(NumberFormat.getIntegerInstance().format(item));
          //Could also call setGraphic(Node)
        }
      };
    });

    final Scene scene = new Scene(new BorderPane(tableView), 640, 480);

    stage.setScene(scene);
    stage.setOnShown(event -> stageReady()); //Continue when stage is rendered
    stage.show();
  }

  private void stageReady() {
    //Generate data
    List<Map<String, Object>> data = new ArrayList<>();
    Map<String, Object> obj1 = new HashMap<>();
    obj1.put("name", "Name of Object 1");
    obj1.put("age", 42);
    data.add(obj1);
    Map<String, Object> obj2 = new HashMap<>();
    obj2.put("name", "OBJECT 2");
    obj2.put("age", 53);
    data.add(obj2);
    //Show data
    tableView.getItems().setAll(data);
  }

  public static void main(String[] args) {
    launch();
  }

}

ageCol.setCellFactory is only here for demonstration. If I had not set it, then the Integer cells would have been rendered calling Integer.toString() for the cells text property.

A: As shown here, a database query can be used to construct an ObservableList<Map> of attribute-value pairs. As shown in Adding Maps of Data to the Table, MapValueFactory is "A convenience implementation of the Callback interface," like PropertyValueFactory, "designed specifically for use within the TableColumn.
Inspired by this related example, the variation below displays a TableView containing the entries contained in the Map<String,String> returned by System.getenv(). Although that map is unmodifiable, simple editing support is shown.

import java.util.Map;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 * https://docs.oracle.com/javase/8/javafx/user-interface-tutorial/table-view.htm
 * https://stackoverflow.com/a/18620705/230513
 * https://stackoverflow.com/a/69781121/230513
 * https://stackoverflow.com/a/9134371/230513
 */
public class TableMapSample extends Application {

    private final String columnKey = "Key";
    private final String columnValue = "Value";

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        ObservableList<Map.Entry<String, String>> list
            = FXCollections.observableArrayList(System.getenv().entrySet());
        TableView<Map.Entry<String, String>> table = new TableView<>(list);
        table.setEditable(true);
        table.getSelectionModel().setCellSelectionEnabled(true);

        TableColumn<Map.Entry<String, String>, String> keyColumn = new TableColumn<>(columnKey);
        keyColumn.setCellValueFactory((TableColumn.CellDataFeatures<Map.Entry<String, String>, String> p)
            -> new SimpleStringProperty(p.getValue().getKey()));
        table.getColumns().add(keyColumn);
        keyColumn.setCellFactory(TextFieldTableCell.forTableColumn());

        TableColumn<Map.Entry<String, String>, String> valueColumn = new TableColumn<>(columnValue);
        valueColumn.setCellValueFactory((TableColumn.CellDataFeatures<Map.Entry<String, String>, String> p)
            -> new SimpleStringProperty(p.getValue().getValue()));
        valueColumn.setCellFactory(TextFieldTableCell.forTableColumn());
        valueColumn.setPrefWidth(800);
        table.getColumns().add(valueColumn);

        stage.setTitle("Table Map.Entry<K,V>");
        stage.setScene(new Scene(new StackPane(table)));
        stage.show();
    }
}


text:
Q: How to handle continuos recording of user geo-points in Android even with screen off? I have an app which is recording the position of the user continuously. The location updates are to be very frequent to get an exact mapping of the route the user has taken. To keep the application recording the geo points when the phone falls asleep I use a wake lock which is released when the user stops the recording or in onDestroy().
I now realize I am not removing the location listener from the location manager. This leads to the battery draining if the user forgets to press the "stop recording route" button before leacing the application. My initial thought was to remove it in onPause() but then I'm afraid onPause() might get called when the screen turns off although I have a wake lock (but not screen on).
My questions in this matter are:
When should I remove the location listener from the location manager?  Should I release the listener i onDestroy()? Or perhaps I do not need a wake lock at all as long as I am listening to the location manager? How should this be handled if so?
I've seen this discussed in other places like here:
Android - When using LocationManager.requestLocationUpdates, do I need a WakeLock?
But there doesn't seem to be an absolute answer.

A: You didn't mention how frequently you want to acquire locations which is relevant for the soluiton.
Acquisition frequency
If you want to acquire locations with a frequency bigger then 1 per 5 minutes, I suggest to leave the the listener registered. GPS devices as supposed to enter a energy save mode between acquisitions.
If the frequency is smaller that that, than you can consider removing the lister after you get the location and register it again using a timer task or the Alarmmanager, depending on your application design.
WakeLock
I've never tried it myself, but my expectation is that Android will enter sleep mode after some time of no user interaction, if no one request it to stay awake. It should be no different even if you register a listener.
Appliaction architecture
onPause() and onStop() are called when some other activity covers partially or totally you activity screen. So this are not suitable places to unregister the listener, if you want to keep continuous recording. Also, if the user leaves your application the recording will stop.
I suggest that you use a service to recorde the locations, if you have short period between acquisitions, or use the AlarmManager to schedule less frequent acqisitions.


text:
Q: How to prevent data shown in dev tool chrome in production env
If I go to devtools in chrome and go to Network tab and check Fetch/XHR , I can see data received from server. Well , following screen shot is from prod env :).
Kindly guide/advice.
I have developed my application in ionic/angular.

A: Short answer: You can't.
Long answer: Data you provide to the client application through HTTP(S) communication  will always be visible to the end user.  Client application cannot provide security of the data. If there's any data that should not be accessed by the end user, you have to implement the security measure on the server, not the client. Server must provide only the data the user is authorised to access. Devtools is only a convenient way to display the data, which the user still have access to by other means - you basically send the data to them, therefore consider them visible.


text:
Q: bad using of if instruction I have some situations using if sentence, It add aditional value to my request.. I'm doing a paper,stone,scissors game, there are another form instead if sentence?:
if ("stone".equals(movePlayer1) && "stone".equals(moveComputer)) {
        draw = draw + 1;

    }
    if ("paper".equals(movePlayer1) && "paper".equals(moveComputer)) {
        draw = draw + 1;
    }
    if ("Scissors".equals(movePlayer1) && "Scissors".equals(moveComputer)) {
        draw = draw + 1;
    }
    if ("paper".equals(movePlayer1) && "Scissors".equals(moveComputer)) {
        win = win + 1;

    }

    if ("paper".equals(movePlayer1) && "stone".equals(moveComputer)) {
        win = win + 1;

    }

    if ("Scissors".equals(movePlayer1) && "paper".equals(moveComputer)) {
        win = win + 1;

    }

    if ("stone".equals(movePlayer1) && "stone".equals(moveComputer)) {
        serverwin = serverwin + 1;

    }

    if ("paper".equals(movePlayer1) && "Scissors".equals(moveComputer)) {
        serverwin = serverwin + 1;

    }

    if ("Scissors".equals(movePlayer1) && "stone".equals(moveComputer)) {
        serverwin = serverwin + 1;

    }

There is another way to do that like switch, else or something like that?

A: In an implementation of Rock, Paper, Scissors, both the player and computer make a choice simultaneously, and then those choices are compared. Either the player wins, the computer wins, or the players draw. As soon as you have detected one of those conditions, it's no longer necessary to make further evaluation.
When you code many if statements as you have, each statement is independent of the others. Even if the first if statement evaluates to true, all the remaining if statements will still be evaluated.
Rather than using many if statements, you should be using if... else if... else which effectively ties many conditions together in a mutually exclusive fashion and will pass control back out of the code block as soon as one of those statements has evaluated to true.
if ("stone".equals(movePlayer1) && "stone".equals(moveComputer))
{
    draw = draw + 1;
}
else if ("paper".equals(movePlayer1) && "paper".equals(moveComputer))
{
    draw = draw + 1;
}
else if ("Scissors".equals(movePlayer1) && "Scissors".equals(moveComputer))
{
    draw = draw + 1;
}

// continue your code below

Please make sure you understand the fundamentals of flow control before proceeding further.

A: How about following approach?
    switch (movePlayer1) {
    case "stone":
        switch (moveComputer) {
        case "stone":
            draw++;
            break;
            // check rest of stone vs moveComputer value here
        }
        break;

    case "paper":
        switch (moveComputer) {
        case "paper":
            draw++;
            break;
            // check rest of paper vs moveComputer value here
        }
        break;

    case "Scissors":
        switch (moveComputer) {
        case "Scissors":
            draw++;
            break;
            // check rest of Scissors vs moveComputer value here
        }
        break;
    }


text:
Q: How to add a style to a particular column in EXTjs Editor Grid Panel which has column vars? /*
Need to have pointer cursor only on the particular column instead for whole grid or the row.
*/

this.testRenderer = function(v, m, r, ri, ci, ds) {
 var total = formatMoney(r.data["total"], cur);
 return total;
};

var columnsVar = [
 {
 header: getMsg('test', 'testp'),
 dataIndex: 'test.name',
 sortable: true
 },
 {
 header: getMsg('test', 'testtotal'),
 sortable: true,
 dataIndex: 'total',
 editor: new Ext.form.TextField({
 allowBlank: false,
 maxLength: 48
 }),
 render:this. testRenderer

 }, {
 header: getMsg('test', 'active'),
 sortable: true,
 dataIndex: 'test.Status'
 }
];

this.testGrid = new Ext.grid.EditorGridPanel({
 title:getMsg('test','Details'),
 flex: 3,
 cls: 'cnqr-shuttle-grid',
 border: false,
 header: true,
 clicksToEdit: 1,
 enableHdMenu: false,
 enableColumnHide: false,
 enableColumnMove: false,
 autoHeight: true,
 viewConfig: {
     getRowClass : function(record, rowIndex, p, store) {
      p.tstyle = ' cursor: pointer;'
     },
     forceFit: true,
     scrollOffset: 0 // the grid will never have scrollbars
 },
 tbar: new Ext.Toolbar({
     ctCls: 'grayButtonToolBar  border-toolbar'
 }),
 store: store1,
 selModel: new Ext.grid.RowSelectionModel(),
 columns: columnsVar

});

//testGrid is the Ext editor grid and column vars has 3 columns and I need have pointer cursor only on the 2nd column testtotal col. Have tried adding code at the testRenderer and did not work.

A: On the column you want the pointer on, add the following:
renderer: function(value, metadata) {
    metadata.tdCls = 'pointer-only';
    return value;
}

And in your CSS add the class:
.pointer-only {
    cursor: pointer;
}

Here's a fiddle illustrating this on the last column of a simple grid

A:

renderer: function (value, metadata) {
 metadata.style = 'cursor: pointer;';
 return value;
}


text:
Q: Trying to calculate angle of a pie chart slice created in svg and javascript I am creating dynamic pie chart slices via javascript and svg.  I need both sides of the slice to have a border.  I can't work out the math todo this on both borders (I can get it on the starting border, but not the final end border of the slice.
let size = 200
let slicePercentage = 33
let radius = size / 2
let circumference = Math.PI * radius * 2
let slice = ((slicePercentage / 2) * circumference) / 100 + ' ' + circumference

let line = ((size / 2) + radius) * Math.cos(slicePercentage)

I have included code here to show:
https://jsfiddle.net/yg210erv/1/

A: I have forked the fiddle to answer your question here, but you may also want to check on the geometry of what you want to accomplish. Basically, you had size as the y coordinate of the second line, which makes no sense. I set two variables, linex and liney for the x and y coordinates of line2. The expressions are pretty simple:
let finalAngle = 2 * Math.PI * (slicePercentage/100)
let linex = radius + (radius * Math.cos(finalAngle))
let liney = radius + (radius * Math.sin(finalAngle))

You could also write:
let linex = radius * (1 + Math.cos(finalAngle))

But that would only work if you are going to always create the slices with the same center at size/2.