text:
Q: Are nested child routes in combination with named router outlets not supported in Angular 2 Fellow-coders,
I have the following routing table:
const routes: Routes = [
    { path: '', redirectTo: 'main', pathMatch: 'full' },
    {
        path: 'main', component: MainComponent,
        children: [
            { path: 'spaceoverview', component: SpaceOverviewComponent, outlet: 'mainview' },
            { path: 'create-menu', component: CreateMenuComponent, outlet: 'sidebar' },
            { path: 'create-space', component: CreateSpaceComponent, outlet: 'mainview' },
            { path: 'update-menu/:id', component: UpdateMenuComponent, outlet: 'sidebar' },
            { path: 'update-space/:id', component: UpdateSpaceComponent, outlet: 'mainview' },
            { path: 'empty-menu', component: EmptyMenuComponent, outlet: 'sidebar' },
            { path: 'empty-main', component: EmptyMainComponent, outlet: 'mainview' },
            { path: 'update-categories', component: ChangeCategoriesComponent, outlet: 'mainview' },
            {
                path: 'permissions/:id', component: TestComponent, outlet: 'mainview',
                children: [
                    { path: 'create-reader/:id', component: CreateReaderComponent, outlet: 'top' },
                    { path: 'reader-overview/:id', component: ReaderOverviewComponent, outlet: 'bottom' },
                    { path: 'empty-top', component: EmptyTopComponent, outlet: 'top' },
                    { path: 'empty-bottom', component: EmptyBottomComponent, outlet: 'bottom' }
                ]
            }
        ]
    },
    { path: '**', component: PageNotFoundComponent }
];

They are all child routes of main, permissions also, except it has it's own child routes.
Unfortunately I can't seem to get it to work. I tried so many things already...
Loading a non-nested child with:
this.router.navigate(['/main', { outlets: { 'sidebar': ['update-menu', id], 'mainview': ['update-space', id] } }]);

is no problem, the corresponding url becomes:
http://localhost:4200/main/(sidebar:update-menu/123//mainview:update-space/123)

But when I try to load the permissions child route, with named router outlets, like:
this.router.navigate(['/main', { outlets: { 'mainview': ['/permissions', this.id, { outlets: { 'top': ['create-reader'], 'bottom': ['reader-overview'] } }], 'sidebar': ['update-menu', this.id] } }]);

It just won't load...
Does the Angular 2 router support nested routes using named router outlets, or am I bumping against the boundaries of it?
Please help a frustrated Angular 2 coder...


text:
Q: what is the motivation for the existence of specific clang versions (like the emscripten one)? I recently started to do some work with the emscripten c/c++ to javascript compiler, and when trying to build the compiler from source, i saw that it have a specific version of clang for itself.
Until now, I couldn't find anywhere a reason why there is a separate version of the compiler. I was under the impression that every backend could get input from every frontend, if you follow llvm specs, and use the same llvm version for both. I can imagine that one could use this approach to use specific command line options, but can't see advantages of rebuilding the entire thing, over a script to do that job and connecting the dots, instead.
So, what exactly are the advantages of doing a specific clang build, over just implementing a backend?

A: Implementing a backend is exactly what we're doing for WebAssembly, and Emscripten will eventually be able to use that backend for both WebAssembly and asm.js.
Emscripten as well as PNaCl were started as unsure experiments, without sufficient experience with LLVM. It was easier for the authors to write their own thing in a way that they though sensible, versus meeting the constraints of LLVM. As these things usually go, those experiments haven't fully gone away... But over time WebAssembly should make everything right.
LLVM's constraints are entirely sensible: keep a high code quality, don't raise maintenance burden, avoid creating needless dependencies between layers of the code. That allows LLVM to be successful: when it accepts new backends LLVM wants to be better as a whole, not be burdened by a new backend, or have a backend which exists in isolation, or becomes unmaintained. Others constraints are more historic: when PNaCl started in ~2010 (video) LLVM didn't have great support for x86 instruction bundling which NaCl's x86 sandboxes relies on, or for x32 which NaCl relies on for its x86-64 sandbox, and both for PNaCl and Emscripten it wasn't clear how virtual ISAs could be supported at the time. I'm oversimplifying, many other factors went into those decisions, and I'm sure that were they made today things would go differently.
PNaCl still has substantial changes (LLVM and clang forks), despite many of them making it to upstream LLVM and PNaCl developers participating in code reviews which made LLVM friendlier for PNaCl's usecases. These changes live in three categories: backend changes necessary for NaCl sandboxing (which subzero intends to replace), bitcode "simplification" passes which stand in for a backend done "the LLVM way" (and which Emscripten uses), and other random changes many of which could be upstreamed.
Emscripten saw a substantial approach change when it moved to fastcomp instead of its previous approach.
Note that there's much more than LLVM and clang: these compilers also rely on C++ standard libraries (both have libc++ / libc++abi, mostly unchanged, PNaCl used to support libstdc++), C standard libraries (both have musl, PNaCl also has newlib, bionic, some form of glibc), compiler runtime (compiler-rt), linker, and general user libraries such as SDL (part of Emscripten, and for PNaCl in webports).
In both cases the compilers are rebased to trunk LLVM semi-frequently, though Emscripten's changes are much easier to rebase than PNaCl's. There's a huge cost to maintaining a fork!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to center my "inputPane" using JavaFX How can I center my panel inputPane in a BorderPane, in JavaFX?
Here's my code.
public class MainStage {
    private Scene mainScene;
    private InputPane inputPane;
    private DisplayPane displayPane;
    private EditPane editPane;
    private BorderPane borderPane;

    private VBox mainPane;

    public MainStage(){
        borderPane = new BorderPane();
        inputPane=new InputPane();
        displayPane=new DisplayPane();
        editPane=new EditPane();

        mainPane=new VBox();
        mainPane.getChildren().addAll(inputPane.getPane(),displayPane.getTable(),editPane.getPane());
        mainPane.setSpacing(10);

        mainScene=new Scene(mainPane,800,480);
        mainScene.getStylesheets().add("styleSheet.css");
    }
    public Scene getMainScene() {
        return mainScene;
    }
    public InputPane getInputPane() {
        return inputPane;
    }
    public DisplayPane getDisplayPane() {
        return displayPane;
    }
    public EditPane getEditPane(){
        return editPane;
    }
}

I'm trying to modify InputPane class.
public class InputPane {

    private Text server;
    private Text textNumber;
    private TextField tfNumber;

    private Button addButton;
    private GridPane griglia;

    public InputPane() {

        textNumber=new Text("Insert Port Number: ");
        server = new Text("SERVER");
        server.setStyle("-fx-font-weight:bold;"
                       +"-fx-color: black;"
                       +"-fx-font-size: 18;");
        tfNumber = new TextField();
        tfNumber.setTextFormatter(new TextFormatter<>(new NumberStringConverter()));

        griglia=new GridPane();

        griglia.add(server,1,0);
        griglia.add(textNumber,0,1);
        griglia.add(tfNumber,1,1);
        griglia.setVgap(5);
        griglia.setHgap(10);

        GridPane.setHalignment(server, HPos.CENTER);
        GridPane.setHalignment(textNumber, HPos.CENTER);

    }

    public GridPane getPane() {
        return griglia;
    }
    public Button getAddButton() {
        return addButton;
    }
}

I give you some ideas of how you can see now my GUI:
This is the result

And I would like to make somethink like this

Thank you

A: Your question is not really clear as you ask :

How can I center my panel inputPane in a BorderPane, in JavaFX?

But in your example, you never use your BorderPane, you only use VBox
To answer to your question, simply use an HBox as parent of your GridPane with alignment property set to Pos.CENTER.
public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        BorderPane bord = new BorderPane();
        HBox hb = new HBox();
        GridPane griglia = new GridPane();
        Text server = new Text("SERVER");
        griglia.add(server, 1, 0);
        griglia.add(new Text("Numero Porta"), 0, 1);
        griglia.add(new TextField(), 1, 1);
        griglia.setVgap(5.0);
        griglia.setHgap(5.0);
        GridPane.setValignment(server, VPos.CENTER);
        GridPane.setHalignment(server, HPos.CENTER);
        hb.getChildren().add(griglia);
        hb.setStyle("-fx-border-color:red");
        hb.setAlignment(Pos.CENTER);
        bord.setTop(hb);
        primaryStage.setScene(new Scene(bord, 800, 500));
        primaryStage.show();
    }

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


text:
Q: focus textfield if javascript validation failed I've this code:
<html>
    <head>
        <script type="text/javascript">
            function validate(){
                var name=document.frm.name.value;
                if(name.indexOf("A")==0){
                    alert(name);
                }
            }
        </script>
    </head>
    <body>
        <form name="frm" action="test.php">
            Enter name:<input type="text" name="name" onblur="validate()"/>
            Enter e-Mail:<input type="text" name="email" onblur=""/>
            <input type="submit"/>
        </form>
    </body>
</html>

In above code, I'd tried to validate textfields when they lose focus. The script working fine if the name starts with A. But I want if the user enter different name which doesn't start with A it will return the focus to the textfield name. For that I'd written this script:
<script type="text/javascript">
    var name = document.frm.name.value;
    if(name.indexOf("A") == 0){
        alert(name);
    }else{
        document.frm.name.focus();
    }
</script>

then it doesn't works.
Anybody could help with that what should I do to request focus of textfield name?
I've only a little knowledge of javascript.

A: modifiy your script like this
   <html>
    <head>
        <script type="text/javascript">
            function validate(){
                var name=document.frm.name.value;
                if(name.indexOf("A")==0){
                    alert(name);
                }
            }
        </script>
    </head>
    <body >
        <form id="frm" action="test.php">
            Enter name:<input type="text" name="username" onblur="validate()"/>
            Enter e-Mail:<input type="text" name="email" onblur=""/>
            <input type="submit" onclick="check()"/>
        </form>
        <SCRIPT LANGUAGE="JavaScript">
        <!--
        function validate()
        {
            var name = document.getElementById('frm').username.value;
            if(name.indexOf("A") == 0){
                alert(name);
                        document.getElementById('frm').email.focus();
             }else{
                document.getElementById('frm').username.focus();
            }
        }
        function check()
        {
            var name = document.getElementById('frm').username.value;
            if(name.indexOf("A") == 0){
             }else{
                alert("Please enter a name starting with 'A'");
                     document.getElementById('frm').username.focus();
            }
        }
        //-->
        </SCRIPT>
    </body>
</html>

You want to execute function validate() on event onblur. in the script you have written the code for focusing, but not added it in a function.

A: Just give an id for you form and refer it with document.getElementById('form_id'). Use of name attribute in this context has been deprecated over a decade ago. Also name for input should be something else than "name", rather use username or sth.
HTML:
<form id="frm" action="test.php">
    Enter name:<input type="text" name="username" id="username" onblur="validate()"/>
    Enter e-Mail:<input type="text" name="email" id="email" onblur=""/>
</form>

JavaScript:
function validate(){
    var form = document.getElementById('frm');
    if (form.username.value.indexOf("A") === 0) {
        alert(name);
    } else {
        form.username.focus();
    }
}

Instead of retrieving the id of the form, you can also pass the form to validate() as an argument: onblur="validate(this);". Then use that argument as a form in the eventhandler:
function validate(form){
    if (form.username.value.indexOf("A") === 0) {
        alert(name);
    } else {
        form.username.focus();
    }
}

EDIT
Focus doesn't seem to work without a delay, you can try this (the inputhas an id="username"):
function focusTo (elm) {
    elm.focus();
    return;
}

function validate(){
    var form = document.getElementById('frm');
    if (form.username.value.indexOf("A") === 0) {
        alert(name);
    } else {
        alert('error');
        setTimeout(function () {focusTo(form.username);}, 10);
    }
}

A: try this document.frm.username.focus(); . i hope it will work.


text:
Q: adding font awesome icon to css panel I have this CSS3 based panel that slides out vertically. How can I add a 2x fontawesome icon or any icon to the close /open panel button, which will display one icon for open and another  close icon for close?really appreciate your help.

* {
  margin:0;
  padding:0;
  font-family:"Helvetica Neue", Helvetica, Sans-serif;
  word-spacing:-2px;
}

h1 {
  font-size:40px;
  font-weight:bold;
  color:#191919;
  -webkit-font-smoothing: antialiased;
}

h2 {
  font-weight:normal;
  font-size:20px;
  color:#888;
  padding:5px 0;
}

.message {
  background:#181818;
  color:#FFF;
  position: absolute;
  top: -250px;
  left: 0;
  width: 100%;
  height: 250px;
  padding: 20px;
  transition: top 300ms cubic-bezier(0.17, 0.04, 0.03, 0.94);
  overflow: hidden;
  box-sizing: border-box;
}

.message h1 {
  color:#FFF;
}

#toggle {
  position:absolute;
  appearance:none;
  cursor:pointer;
  left:-100%;
  top:-100%;
}

#toggle + label {
  position:absolute;
  cursor:pointer;
  padding:10px;
  background: #26ae90;
  width: 100px;
  border-radius: 3px;
  padding: 8px 10px;
  color: #FFF;
  line-height:20px;
  font-size:12px;
  text-align:center;
  -webkit-font-smoothing: antialiased;
  cursor: pointer;
  margin:20px 50px;
  transition:all 500ms ease;
}

#toggle + label:after {
  content:"Open"
}

.container {
  transition: margin 300ms cubic-bezier(0.17, 0.04, 0.03, 0.94);
  padding:5em 3em;
}

#toggle:checked ~ .message {
  top: 0;
}

#toggle:checked ~ .container {
  margin-top: 250px;
}

#toggle:checked + label {
  background:#dd6149;
}

#toggle:checked + label:after {
  content:"Close"
}
<input type="checkbox" name="toggle" id="toggle"/>

Pure CSS3 Slide Down Toggle Demo

Click the Open button to see content

Hidden message here

CSS3 slide out menu

A: I think this is what you want:
Open:
#toggle + label:before {
    font-family: 'FontAwesome';
    content:"\f054";
}
#toggle + label:after {
  content:"Open"
}

Close:
#toggle:checked + label:before{
    font-family: 'FontAwesome';
    content:"\f0c9";
}
#toggle:checked + label:after {
  content:"Close"
}

https://jsfiddle.net/z57b2e2c/1/


text:
Q: Python: get text from tkinter scrolledtext and read line by line I'm currently working on a simple txt converter. The data is loaded from a txt file into a scrolledtext widget. Now I want to read this text line by line (since I'd like to have the opportunity to edit the original data) and do the conversion based on the scrolledtext data. However, I can't get satisfying results.
If I simply print the text I got by using .get('1.0', 'end-1c') it looks exactly like the scrolledtext data. Now I want to read it line by line with a for loop and seperate it with the strip and split command. Basically the same way I was doing when reading directly from the file, but it's not working.
Input data contains a lot of spaces:
"                  1267    33311225.807"
"                  1268    33311224.395"

I would expect ['1267', '33311225.807']. Instead I get a new line for every digit:
[1]
[2]
[6]
[8]
...

and so on.
import tkinter.scrolledtext as tkst
from tkinter import filedialog
from tkinter import ttk

root = tk.Tk()
root.title("Converter")
root.geometry('1000x690+200+50')
tab_parent = ttk.Notebook(root)

tab1 = ttk.Frame(tab_parent)
tab_parent.add(tab1, text="  convert  ")

frame1 = tk.Frame(tab1)
textPad_top = tkst.ScrolledText(master=frame1)

coordinates_text = textPad_top.get('1.0', 'end-1c')
for line in coordinates_text:
    line_splitted = line.strip().split(" ")
    read_coordinates = [ele for ele in line_splitted if ele.strip()]
    point_id.append(read_coordinates[0])
    r_value.append(read_coordinates[1])

root.mainloop()

Eventually I want to have several lists. One for every column given in the source file.
I'm an absolute beginner in programming and would really appreciate your help.

A: When you iterate over a string, it will iterate over each character which is exactly what you're reporting.
If you want to iterate over each line, you need to split the data on newlines
for line in coordinates_text.split("\n"):
    ...


text:
Q: Node.js - How to Backup Variables to a file and reobtain it on server relaunch? I think the title says it all. But I want to explain further.
Let's say, I have a running nodejs server which contains a variable that will contain
(almost) all data that the server will store. If I want to do a server restart (due to
some reasons), how do I backup the variables so that it's safe to close the nodejs server,
and to relaunch it with the variables that contains the data when I closed it?
Regards,
JoshuaLangit123

A: Here's some pseudo code to achieve what you want to do:

*

*At startup, read data.json and assign the value of it to your single data variable:
var data = JSON.parse(fs.readFileSync('data.json'));

*When the app is closed using Ctrl-C you can use this handler to write the single data variable back to data.json.
process.on( 'SIGINT', function() {
  fs.writeFileSync('data.json', JSON.stringify(data));
  process.exit();
})

A: This depends on so many things. Usually what you do is use a database (mongodb, mysql, whatever) to store application state.. Users, session, etc
If you really do want to dump all the variables to a file that can be read/written to (which I think sounds like a really, really, really bad idea, but hard to know for sure unless I knew what you were doing) you could make a single object that you put all the variables into, which you can json-ify and write to disk.
and then you read that file again (or require it even) when the node instance is started again.


text:
Q: What is the best way of organizing the loopings? I have data for 12 instruments grouped as 3x4 (4 instruments for each group: N1, N2, N3, N4; C1, C2, C3, C4; S1, S2, S3, S4;). Each instrument has 2 sets of data: H and T. The dataset comes from different excel spreadsheets.
What is the best way to perform this interaction? Creating a dictionary, a matrix, using the lists...? In Matlab I would create 3 matrices with 4 columns each, but I don't know how to do this on Python (just started using it).
First I am trying to create the variables described above (N1, C3, S4...) and appending the values from different excel spreadsheets:
sheets = ['S_WH', 'C_WH', 'N_WH']
for i in sheets:
    path = r"\\uniwa.uwa.edu.au\userhome\students2\22371812\My Documents\Documents\FieldTechniques"
    filename = i + '.xlsx'
    sheetHeights = openpyxl.load_workbook(os.path.join(path,filename), data_only=True)
    heights = sheetHeights.get_sheet_by_name("Sheet1")

    Time=[]
    H1=[]
    H2=[]
    H3=[]
    H4=[]

    for row in range (2, heights.max_row+1):
        Time.append(heights['A' + str(row)].value)
        H1.append(heights['B' + str(row)].value)
        H2.append(heights['C' + str(row)].value)
        H3.append(heights['D' + str(row)].value)
        H4.append(heights['E' + str(row)].value)

First of all, how do I get those lists (H1, H2...) and append to a dictionary (that's how I thought it could be the best way) for each one of the sheets?
Secondly, I have to do the same for T values, so all the stations will have H and T related to it. A third value would be S, that is the sum of H and T. I don't know how to do this either. If someone could help me (even giving some hints) it would be great.

A: Best is a bit ambiguous here. Lists have their pros & cons, and so do dictionaries, arrays, and every other data structure.
The best structure depends on what you need (minimal memory, minimal search time and so on).
As long as no major constraint is introduced, I would go with what I think is the simplest solution - dictionary that holds a key and a 3-values list as its value - {instrument : [H,T,S]}
Toy example:
N1,N2 = 'a','b'
H_N1, H_N2 = 1,2
T_N1, T_N2 = 10,20

instruments = [N1, N2]
# assuming you already have H,T saved
H = [H_N1, H_N2]
T = [T_N1, T_N2]

# create an list S, and fill it using list comprehension
S = [H[i] + T[i]  for i in range(len(T))]

# can also be done by a loop
S = []
for i in range(len(T)):
    S.append(T[i] + H[i])

# add the lists together so they would all be stored together as a dictionary value
zip1 = zip(H,T,S)
zip2 = zip(instruments, zip1)
d = dict((key,value) for (key,value) in zip2)
print d

Output = {'a': (1, 10, 11), 'b': (2, 20, 22)}


text:
Q: Flume in EC2 and sink as HDFS in EMR. Is it possible? I have a hadoop cluster in EMR and I have a EC2 instance. I need to install flume in EC2 node and use HDFS in EMR as sink. I have been trying this for sometime, but not being able to do so. I get the following exception:
 2017-12-19 10:50:32,428 (SinkRunner-PollingRunner-DefaultSinkProcessor) [WARN - org.apache.flume.sink.hdfs.HDFSEventSink.process(HDFSEventSink.java:443)] HDFS IO error
org.apache.hadoop.ipc.RemoteException: Server IPC version 9 cannot communicate with client version 3
     at org.apache.hadoop.ipc.Client.call(Client.java:740)
     at org.apache.hadoop.ipc.RPC$Invoker.invoke(RPC.java:220)
     at com.sun.proxy.$Proxy4.getProtocolVersion(Unknown Source)
     at org.apache.hadoop.ipc.RPC.getProxy(RPC.java:359)
     at org.apache.hadoop.hdfs.DFSClient.createRPCNamenode(DFSClient.java:106)
     at org.apache.hadoop.hdfs.DFSClient.<init>(DFSClient.java:207)
     at org.apache.hadoop.hdfs.DFSClient.<init>(DFSClient.java:170)
     at org.apache.hadoop.hdfs.DistributedFileSystem.initialize(DistributedFileSystem.java:82)
     at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:1378)
     at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:66)
     at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:1390)
     at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:196)
     at org.apache.hadoop.fs.Path.getFileSystem(Path.java:175)
     at org.apache.flume.sink.hdfs.BucketWriter$1.call(BucketWriter.java:260)
     at org.apache.flume.sink.hdfs.BucketWriter$1.call(BucketWriter.java:252)
     at org.apache.flume.sink.hdfs.BucketWriter$9$1.run(BucketWriter.java:701)
     at org.apache.flume.auth.SimpleAuthenticator.execute(SimpleAuthenticator.java:50)
     at org.apache.flume.sink.hdfs.BucketWriter$9.call(BucketWriter.java:698)
     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
     at java.lang.Thread.run(Thread.java:748)


text:
Q: CNN+LSTM OCR model not predicting "is" correctly I have made a model in tensorflow with the following structure for OCR. I trained it on a significantly large dataset(250K images) and also getting around 94% accuracy. But the model predicts "is" as "1s" or "1S" most of the times. I checked the dataset and it contains quite a lot of instances of "is" so I dont think dataset is the problem. Also the model predicts correctly when it is a part of another word such as "this" or "christian". What could possibly be the reasons for this behaviour how can I improve the model to detect "is".
Things I tried
Decrease number of maxpool layers.
Use 2x1 kernels for maxpool layers
Input: (?, 64, 1024, 1)
cnn-1: [None, 64, 1024, 64]
relu-1: [None, 64, 1024, 64]
bn-1: [None, 64, 1024, 64]
maxpool-1: [None, 32, 512, 64]
cnn-2: [None, 32, 512, 128]
relu-2: [None, 32, 512, 128]
bn-2: [None, 32, 512, 128]
maxpool-2: [None, 16, 256, 128]
cnn-3-1: [None, 16, 256, 256]
relu-3-1: [None, 16, 256, 256]
cnn-3-1: [None, 16, 256, 256]
relu-3: [None, 16, 256, 256]
bn-3: [None, 16, 256, 256]
maxpool-3: [None, 8, 128, 256]
cnn-4-1: [None, 8, 128, 512]
relu-4-1: [None, 8, 128, 512]
bn-4-1: [None, 8, 128, 512]
cnn-4-2: [None, 8, 128, 512]
relu-4-2: [None, 8, 128, 512]
bn-4-2: [None, 8, 128, 512]
maxpool-4: [None, 4, 64, 512]
cnn-5: [None, 4, 64, 512]
relu-5: [None, 4, 64, 512]
lstm-input: [None, 64, 2048]
lstm-output: [None, 64, 256]
lstm-output-reshaped: [None, 256]
fully-connected: [None, 94]
reshaped_logits: [None, None, 94]
transposed_logits: [None, None, 94]

A: Since probably most numbers in your dataset are preceded by spaces, and "1" and "i" look similar, it is somewhat of an understandable error.
I do not thing changing the architecture of the network will help at all.
What I would do is to artificially oversample the "is" instances. You say there are already many instances of it - but probably not enough. So with some probability of 5% - 10% force the text sample at a location that will contain an "is". You don't even need to restart the whole training, you can continue training an already trained network like this, and it will force the network to be biased towards "is".
If it now starts to misidentify "15" as "is" then with some smaller probability, like 2%-5%, add stretches that contain numbers like that as well. So like teaching a person, show it examples to allow it to learn the difference.
Don't raise the probabilities too high, though, because you will ruin the general accuracy. It will very quickly learn to tell 15 from is but will forget everything else...

A: You will need a language model to correct spellings in ocr output. I think you can find one spell checker in nltk. More sophisticated spell checkers can be built using seq2seq autoencoders.


text:
Q: Where do I look for cron errors I have 2 cron jobs that were running fine but now stopped running. I looked through my crontab and everything looks OK. How can I tell if these jobs are running? is there a place where cron stores errors? Where do I look for cron specific errors, or even a record of the cron jobs that ran prior.

A: Try directing the output to a log file.  Just make sure that it exists and is writable by whatever user the cronjob is running as.  (In my example, this would be cyphertite)
I also recommend running date somewhere at the beginning of your script so that you get the date in the log file.
 0 15 * * *    /home/andrew/daily-backup.sh >> /var/log/cyphertite.log

Additionally, cron logs are directed to /var/log/syslog if that helps


text:
Q: Does right-click Format option remove MBR from USB flash drive? As I can understand, if we format a USB flash drive by Rufus and copy to the drive Windows ISO files by Rufus, later delete all the ISO files from the drive by Del key, the drive would be still bootable with MBR. Is it correct?
If so, what if we later would format the drive by the "Format" option of the Windows right-click context menu? Does this operation remove MBR from the drive and make it non-bootable?

A: Let's get our terms right :

*

*MBR and GPT are two partition styles

*Formatting the partition creates a file-system such as NTFS or FAT32.
The two terms are distinct and one has no relation to the other
(beside some inherent limitations).
In addition, deleting all the files in the partition will make the disk
unbootable if the boot uses data that is in the partition.
The small initial bootstrap code that is placed by Rufus inside the first
few sectors of the disk will stay, so the disk may possibly look as
bootable to the BIOS, but the boot will fail in this case.

A:
As I can understand, if we format a USB flash drive by Rufus and copy to the drive Windows ISO files by Rufus, later delete all the ISO files from the drive by Del key, the drive would be still bootable with MBR. Is it correct?

No.
First, there is just one ISO file system that you copy to a USB flash drive using Rufus. If you later delete files in the partition that won't affect the MBR and the boot sector of the partition so "bootability" will still be there. But without any files in a partition the remaining boot code in the boot sector will fail. It really depends on what you consider "bootable".

If so, what if we later would format the drive by the "Format" option of the Windows right-click context menu? Does this operation remove MBR from the drive and make it non-bootable?

No, the MBR will not be removed and the format operation does not affect the flag within the MBR that marks a bootable partition.
The MBR will only be affected if your format operation changes the file system. That would require changing the file system type identifier in the MBR.


text:
Q: What are the differences between Pokémon Sun & Pokémon Moon? Are there any differences between Pokémon Sun & Moon? Obviously there are changes in the Pokémon you can catch in either version as well as the legendaries, so including those are there also additional changes such as NPC changes, areas you can visit, specific mechanics?

A: In terms of gameplay, the difference is that whilst playing Pokémon Sun, the in-game weather will be day, during real life daytime. Playing Moon during the day however will have a night weather effect.
Before you buy one, you should conisder two things:
1. When you are going to be playing the game.
2. Which lighting you prefer, light/dark.
Hope this helps.

A: Serebii has a summary of all of the differences between the two versions.

In Pokemon Sun the first totem pokemon you encounter is Gumshoos whilst in Moon you encounter an aloan Raticate.
In Pokemon Sun you have the ability to meet and battle Kiawe whilst in Moon you can meet and battle Mallow.
You can also get different stores in the festival plaza. You can usually get them in both games to begin with but the higher level versions of them are only available in one version.
In the Battle Tree you have the ability to scout trainers. You can only scout Plumeria, Sina and Kiawe in Sun and you can only scout Guzma, Dexio, Malloww.
As far as I know other characters can be scouted in both games.

source

A: Apart from the specific pokémon and legendaries, the main difference is the shift in time. The time of the clock would be exactly the same as the in-game time in Pokémon Sun, while it is shifted by 12 hours (i.e., AM would turn to PM and vice versa) in Pokémon Moon.
Apart from that, there are other differences such as the different Totem pokémon and ally pokémon, and a specific pokémon has a different evolution depending on the game.


text:
Q: Magento category tree not showing all sub categories when adding a new product Hello Everyone I hope you are doing well. I have an issue I need help with Please.
I'm trying to add products to specific sub categories using Magento ver. 1.9.0.1  I've been able to do it with no major problems until recently. I am not sure why. Now when I get to the point in which I am to select a category it does not give me the ability to expand the category tree (folder tree) to show sub categories to choose from.
Could you please help me to solve this problem.
Here is a picture of what it looks like:

In my particular situation the books category should be able to expand to show sub categories, but it is not doing so. That is my problem.
I'd like to have the sub categories of the books category show up in the category tree.
on a side note if I were to save the products to the books category then later on go back to change the category only the root and workshops folders are visible.
on another side note sometimes when I save and continue when adding a product it does not save properly and it redirects me to the dashboard.
Please help me

A: I also ran into this situation. The problem was in the negative value of the field "children_count" in the table "catalog_category_entity".

A: I figured out at least a temporary solution.
I basically created a new root category, moved all the sub categories to the new root category then moved the root category into where the original category was and deleted the old books category. I also had to readjust the subcategories so that they would get reindexed or something like that. I feel like I may have done more than necessary though.
I'm thinking it may have worked if you had taken the main subcategory and just moved it from one location to another (for example a root category) and back so that it could rerecognize it or something like that.
Not a very coding solution, but it seems to be working again.

A: I just ran into this problem right after upgrading from 1.7.0.2 to 1.9.1.0.
I tried a bunch of suggestions (e.g. run a query to change the level, create a new root dir and move the old stuff into it, blah, blah, blah) and they only made things worse.
Fortunately, I used PHPMyAdmin to backup the magento MySQL database before doing the upgrade.  I deleted the live(!) catalog_category_entity table (and all its related tables' data!) then copied all their data back the from the backup tables. It was still messed up, but at least the website was displaying things correctly. Then I decided to reindex everything before taking a break this time it fixed it. (so, for me, the upgrade hosed it, restoring the backup tables and reindexing fixed it)
BTW, I also found that the js/scriptaculous directory got deleted during the upgrade (why?!?!? NOT cool Magento) and I put an old copy back to fix the picture zoom not working.


text:
Q: Validation of Payload in ESB I have a HTTP POST REQUEST which sends a payload as follows:

{  "key1" : "value1", "key2" : "value2" ,"key3": "value3" }

I was able to validate all the values but I had to use a component everytime.
In this case , I used the validator "Not a blank string" 3 times.
1. Is there any way that I can validate all the three values in a single validator ?
 2. Should I use Scatter-Gather for validating all the values in parallel(according to best-practices) ?
 3. How can I validate the key set(the key set should only contain "key1", "key2" and "key3"  ?

Update:
I have fetched the key set by using the connector setVariable

EDIT:
JSON validator can be downloaded from exchange. search for JSON MODULE

A: i did a small sample to demonstrate how json validator works. you can use the same

*

*go to https://jsonschema.net/ or any online json schema generator and generate json schema for your json file.

*same this schema into a file with .json extension and place it in src/main/resources folder.

*implement the schema validate and refer to your schema and your incoming json will get validated against the schema automatically so you dont have to use any of the scatter-gather or each individual key-value pair validations.

here are some of the responses with different json inputs against my flow

*

*

*

*
you can always enhance your schema to suite your needs. you can define data type for each key. lets say key3 should contain only numeric values, key2 should be an array. anything like that all can be achieved by modifying your schema and the validator will validate the incoming json accordingly.
update: here is the xml content of the mule flow
<flow name="stackoverflowFlow1" doc:id="c24d34aa-ce1d-4bbb-b3fd-d73007dad60b" >
        <http:listener doc:name="Listener" doc:id="80ab5db5-1d3e-409f-9990-cebf1fc07dd5" config-ref="HTTP_Listener_config" path="/valid"/>
        <json:validate-schema doc:name="Validate schema" doc:id="0a51cde0-5175-4f11-b972-3d5d708094c6" schema="schema.json"/>
        <logger level="INFO" doc:name="Logger" doc:id="2d95a6f0-8f88-4608-bdb8-7fae8abc0e6d" message="valid json"/>
    </flow>


text:
Q: iPhone Alternate View for Landscape Mode on Rotation I'm looking to have an alternate view for one of my ViewControllers when the user rotates the device to landscape (think CoverFlow in iPod) I have implemented this using the AlternateViews sample code (listening for a device rotation notification).
However, I've noticed a bug. I have a rather complicated UI - TabViewController/UINavigationController. When on one ViewController that uses the AlternateViews code and switch to another tab that also has an AlternateView the notifications seem to compete. Meaning it will show the AlternateView, but the one for the first tab's view controller not the second. If I back out of the navigation hierarchy so only one AlternateView exists, then it's fine.
In the end, I don't need an entirely separate ViewController for landscape mode. In fact, this is actually making things more complicated as I need it to have the same navigation bar and IBActions. What I need is to load in a UIWebView on device rotation (if not already loaded) and hide the current view (UITableView). This would also alleviate the bug above.
I can setup the code to create/show/hide the UIWebView and UITableView. However, I don't know exactly where or when to do that - willAutoRotateToOrientation? Any reference to the delegate method and psuedo code would be greatly appreciated.
Of course, if anyone has a fix for the AlternateViews sample code, given my UI hierarchy, I would appreciate that as well.

A: I would recommend putting your code that swaps out the views into -didAnimateFirstHalfOfRotationToInterfaceOrientation:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html
That way, your existing view starts to visibly rotate, then the new view gets swapped in and completes the rotation.


text:
Q: Как сделать перенаправление на другую локальную страницу при получении JWT-токена? Использую авторизацию с помощью JWT токенов, и при проверке логина и пароля токен выдается, но как сделать чтобы после успешного получения токена пользователя перенаправляли на другую страницу?
вот код получения токена:
<script type="text/javascript">

    var tokenKey = "accessToken";

    // отпавка запроса к контроллеру AccountController для получения токена
    async function getTokenAsync() {

        // получаем данные формы и фомируем объект для отправки
        const formData = new FormData();
        formData.append("grant_type", "password");
        formData.append("username", document.getElementById("emailLogin").value);
        formData.append("password", document.getElementById("passwordLogin").value);

        // отправляет запрос и получаем ответ
        const response = await fetch("/token", {
            method: "POST",
            headers: { "Accept": "application/json" },
            body: formData
        });
        // получаем данные
        const data = await response.json();

        // если запрос прошел нормально
        if (response.ok === true) {

            // сохраняем в хранилище sessionStorage токен доступа
            sessionStorage.setItem(tokenKey, data.access_token);
            console.log(data.access_token);
        }
        else {
            // если произошла ошибка, из errorText получаем текст ошибки
            console.log("Error: ", response.status, data.errorText);
        }
    };
    // отправка запроса к контроллеру ValuesController
    async function getData(url) {
        const token = sessionStorage.getItem(tokenKey);

        const response = await fetch(url, {
            method: "GET",
            headers: {
                "Accept": "application/json",
                "Authorization": "Bearer " + token  // передача токена в заголовке
            }
        });
        if (response.ok === true) {

            const data = await response.json();
            alert(data)
        }
        else
            console.log("Status: ", response.status);
    };

    // получаем токен
    document.getElementById("submitLogin").addEventListener("click", e => {

        e.preventDefault();
        getTokenAsync();
    });

</script>

getData и getDataAsync пробовал

A: Для редиректа используется location.assign(url)


text:
Q: How to extract a specific string in SQL Server? I have an NVARCHAR string in SQL Server 2012 like so:
declare @syncData   nvarchar(4000)
set @syncData = 'MyCol1="ABC" MyCol2="DEF" SiteCode="LA123"

I want to get the value after SiteCode=" (i.e. 'LA123').
I'm trying to use SUBSTRING with CHARINDEX but no luck (like whats suggested here).
I'm sure there is an easy way to do this?

A: Here is the way:
DECLARE @syncData AS nvarchar(4000), @vSiteCodeStartIndex AS INT, @vSiteCodeEndIndex AS INT;
SET @syncData = 'MyCol1="ABC" MyCol2="DEF" SiteCode="LA123"';

SELECT @vSiteCodeStartIndex = CHARINDEX('SiteCode="',@syncData)+LEN('SiteCode="')
SELECT @vSiteCodeEndIndex = CHARINDEX('"',@syncData,@vSiteCodeStartIndex);

SELECT @syncData,SUBSTRING(@syncData, @vSiteCodeStartIndex, @vSiteCodeEndIndex-@vSiteCodeStartIndex );

A: This works, even on dynamic string:
declare @syncData   nvarchar(4000)
set @syncData = 'MyCol1="ABC" MyCol2="DEF" SiteCode="LA123" xqwxqxqxqxq  dqw qdqw qw d'

select substring(@syncData,
    charindex('SiteCode="',@syncData)+len('SiteCode="'),
    (charindex('"',@syncData,charindex('SiteCode="',@syncData)+len('SiteCode="'))) - (charindex('SiteCode="',@syncData)+len('SiteCode="')))

A: You can try this:
declare @syncData   nvarchar(4000)
set @syncData = 'MyCol1="ABC" MyCol2="DEF" SiteCode="LA123"'
select RIGHT(@syncData,LEN(@syncData)-(LEN(@syncData) - CHARINDEX('=', REVERSE(@syncData)) + 1))

SQL FIDDLE DEMO
If you want to get rid of double quotes then you can use
declare @syncData   nvarchar(4000)
set @syncData = 'MyCol1="ABC" MyCol2="DEF" SiteCode="LA123"'
select REPLACE(RIGHT(@syncData,LEN(@syncData)-(LEN(@syncData) - CHARINDEX('=', REVERSE(@syncData)) + 1)),'"', '')

SQL FIDDLE DEMO
or you can use REPLACE(column,'"', '''') to put the value in single quotes.

A: declare @syncData   nvarchar(4000)
set @syncData = 'MyCol1="ABC" MyCol2="DEF" SiteCode="LA123"'
select Left(RIGHT(@syncData,LEN(@syncData)-CHARINDEX('SiteCode="',@syncData)-9),5)

A: you can create a function Reference
CREATE FUNCTION [dbo].[fnSplitValues]
(
    @IDs nvarchar(max)
)
RETURNS
@SplitValues TABLE
(
    val nvarchar(max)
)
AS
BEGIN
    -- Fill the table variable with the rows for your result set
    DECLARE @xml xml
    SET @xml = N'<root><r>' + replace(@IDs,' ','</r><r>') + '</r></root>'

    INSERT INTO @SplitValues(val)
    SELECT r.value('.','nvarchar(max)')
    FROM @xml.nodes('//root/r') as records(r)

    RETURN
END

Code Implementation
declare @syncData   nvarchar(4000)
set @syncData = 'MyCol1="ABC" MyCol2="DEF" SiteCode="LA123" MyCol3="GHI"'

SELECT SUBSTRING(REPLACE(val,'"',''), CHARINDEX('=', REPLACE(val,'"','')) + 1, LEN(REPLACE(val,'"','')))
FROM [dbo].[fnSplitValues](@syncData)
where val like '%sitecode%'

A: Notice how this only refers to @search once and @syncData twice and uses a minimum of functions to optimise performance.
To find the substring in a varchar.
DECLARE @search nvarchar(2000)= 'SiteCode'
DECLARE @syncData nvarchar(4000)='MyCol1="ABC" MyCol2="DEF" SiteCode="LA123"'
SET @search += '="'

SELECT SUBSTRING(x.x, 0, CHARINDEX('"', x.x))
FROM
  (SELECT RIGHT(@syncData,
   NULLIF(CHARINDEX(REVERSE(@search), REVERSE(@syncData)), 0) - 1) x) x

To find the substring in a table:
DECLARE @search nvarchar(2000)= 'MyCol2'
SET @search += '="'

DECLARE @t table(syncData nvarchar(4000))
INSERT @t values
('MyCol1="ABC" MyCol2="DEF" SiteCode="LA123"'),
('MyCol1="ABD" MyCol2="DEG" SiteCode="LA321"')

SELECT SUBSTRING(x.x, 0, CHARINDEX('"', x.x))
FROM @t t
CROSS APPLY
  (SELECT RIGHT(syncData,
   NULLIF(CHARINDEX(REVERSE(@search), REVERSE(syncData)), 0) - 1) x) x


text:
Q: NHibernate Linq Like Query Question Is there any way to make NHibernate.Linq generate a like query on an integer field?  The SQL that I want it to generate is:
select IntegerColumn
from Table
where IntegerColumn like '%StringValue%'

I've tried something like:
from entity in _session.Linq<Entity>
where entity.IntegerColumn.ToString().Contains(StringValue)
select entiry.IntegerColumn

This produces an ArgumentOutOfRange exception when it evaluates the query.
Does anyone have an idea how I can accomplish this?
Thanks,
Nathan

A: See this thread on nhusers


text:
Q: Implementing Queue in Java but cannot override the iterator() method I am trying to develop my knowledge of the Queue interface by implementing it in my own "MyQueue" class. However, I want to override the iterator() method. Since I can't implement both the Iterator and Queue interfaces at the same time, I am at a loss.
On my iterator() method Eclipse is giving me the error, cannot convert from MyQueue<E>.QueueIterator to Iterator<E> when I mouse over the red underline below the words new QueueIterator().
Also, when I try to implement my "QueueIterator" inner class, Eclipse gives me the error, syntax error on token "class", @ expected when I mouse over the red underline below the word class.
In the code examples below, I have removed all methods that have nothing to do with my question. I know I have to implement these methods to implement Queue. I'm just trying to make the problem clearer.
How can I override the iterator() method?
MyQueue class:
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Queue;

/**
 * A custom queue class. Uses a singly-linked list.
 */
public class MyQueue<E> implements Queue {
   // the top of the queue
   private Node<E> first;
   private int size;

   /**
    * Creates new myQueue object
    */
   public MyQueue() {
      first = null;
      current = null;
      size = 0;
   }

   @Override
   public Iterator<E> iterator() {
      return new QueueIterator();
   }

  /**
   * Holds Objects and points to the next one.
   *
   */
  private class Node<E> {
     private E data;
     private Node<E> next;

     /**
      * Creates a Node object
      * @param data The Object to be held by the Node
      */
     Node(E data) {
        this.data = data;
        this.next = null;
     }

     private Node<E> getNext() {
        return this.next;
     }

     private E getData() {
        return this.data;
     }
  }

  /**
   * Iterator implementation
   */
  private class QueueIterator() {

     private Node<E> curNode;

     public QueueIterator() {
        curNode = null;
     }

     public boolean hasNext() {
        if(curNode == null && first != null) {
           return true;
        } else if (curNode.getNext() != null) {
           return true;
        } else {
           return false;
        }
     }

     public E next() {
        if(curNode == null && first != null) {
           curNode = first;
           return curNode.getData();
        }

        if(!hasNext()) {
           throw new NoSuchElementException();
        }

        curNode = curNode.getNext();
        return curNode.getData();
     }
  }

A: QueueIterator needs to implement Iterator<E>.
You shouldn't have the parentheses on this line:
  private class QueueIterator() {

It should be just:
  private class QueueIterator {

Actually:
  private class QueueIterator implements Iterator<E> {


text:
Q: Flatten array of objects I have an array of objects coming from a formData serializeArray function. For example:
[
        0 : {name: 'animal_monkey', value: 'banana'}
        1 : {name: 'animal_horse', value: 'radishes'}
        2 : {name: 'fruit_banana', value: 'yellow'}
        3 : {name: 'fruit_apple', value: 'red'}
]

I am looking for a way to get these different elements into a single object, split by category with their appropriate value assigned, like so:
{
        animal: {
                        monkey : banana,
                        horse : radishes
                },
        fruit: {
                        banana : yellow,
                        apple : red
               }
}

I have tried doing this with reduce and Object assign, like so
obj = keys.map((k, i) => k.reduceRight((value, key) => ({[key]: value}), vals[i]) )
result = Object.assign({}, ...obj)

where keys is an array of ['animal_monkey', 'animal_horse', 'fruit_banana', 'fruit_apple'] and vals is a list with values: ['banana', 'radishes', 'yellow', 'red']. However, perhaps as expected, the values are overwritten and I end up with:
{
        animal: {
                        horse : radishes
                },
        fruit: {
                        apple : red
               }
}

The first value(s) don't survive the assignment. Does anyone have a good idea how to make this work?
Thanks!

A: You can split each name on _ and then create an object with the category and animal name using array#reduce.

const data = [ {name: 'animal_monkey', value: 'banana'}, {name: 'animal_horse', value: 'radishes'}, {name: 'fruit_banana', value: 'yellow'}, {name: 'fruit_apple', value: 'red'} ],
      result = data.reduce((r,o) => {
            const [category, name] = o.name.split('_');
            r[category] ??= {};
            r[category][name] = o.value;
            return r;
      }, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You can set a variable that will hold the final combined object, then add to it for each element in the array using array.forEach
let single = {};
arr.forEach(obj => {
  let [catagory, name] = obj.name.split('_'); // catagory = before the _, name = after the _
  single[catagory] ??= {}; // make sure the catagory exists as an object in single
  single[catagory][name] = obj.value;
}


text:
Q: Get Android contacts with type-to-filter functionality, restricted to a specific account I'm trying to:

*

*Display a list of contacts

*Let the user search through them by typing a query

*Limit search results only to a specific Google/Gmail account.

This is how I build the URI for the cursor:
// User is searching for 'jo'
String query = "jo";
Uri uri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(query));

// Restrict the query to contacts from 'example@gmail.com'
Uri.Builder builder = uri.buildUpon();
builder.appendQueryParameter(
    ContactsContract.DIRECTORY_PARAM_KEY, String.valueOf(ContactsContract.Directory.DEFAULT));
builder.appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, "example@gmail.com");
builder.appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.google");

uri = builder.build();

This is the final URI:
content://com.android.contacts/contacts/filter/jo?directory=0&account_name=example%40gmail.com&account_type=com.google

Currently, this shows search results from all accounts on the phone.

NOTE: If I use Contacts.CONTENT_URI instead of Contacts.CONTENT_FILTER_URI, then specifying the directory/account works as expected, but I can no longer use 'type-to-filter' style search.
The documentation does state:

The most important use case for Directories is search. A Directory
  provider is expected to support at least Contacts.CONTENT_FILTER_URI.

Could anyone help point out what I might be doing wrong?

A: I added your code in Google's example for contact retrieving, and with a couple of changes it worked perfectly with my Google for Work account.
The changes I made were:

*

*remove the line with DIRECTORY_PARAM_KEY, as I didn't find it to make any difference

*removed ContactsQuery.SELECTION from the return statement, because that constant prevents "invisible" contacts from being displayed.

The changes were made to ContactsListFragment.java
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    // If this is the loader for finding contacts in the Contacts Provider
    // (the only one supported)
    if (id == ContactsQuery.QUERY_ID) {
        Uri contentUri;

        // There are two types of searches, one which displays all contacts and
        // one which filters contacts by a search query. If mSearchTerm is set
        // then a search query has been entered and the latter should be used.

        if (mSearchTerm == null) {
            // Since there's no search string, use the content URI that searches the entire
            // Contacts table
            contentUri = ContactsQuery.CONTENT_URI;
        } else {
            // Since there's a search string, use the special content Uri that searches the
            // Contacts table. The URI consists of a base Uri and the search string.
            contentUri = Uri.withAppendedPath(ContactsQuery.FILTER_URI, Uri.encode(mSearchTerm));
        }

        // HERE COMES YOUR CODE (except the DIRECTORY_PARAM_KEY line)
        Uri.Builder builder = contentUri.buildUpon();
        builder.appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, "example@mycompany.com");
        builder.appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.google");
        contentUri = builder.build();

        // Returns a new CursorLoader for querying the Contacts table. No arguments are used
        // for the selection clause. The search string is either encoded onto the content URI,
        // or no contacts search string is used. The other search criteria are constants. See
        // the ContactsQuery interface.

        return new CursorLoader(getActivity(),
                contentUri,
                ContactsQuery.PROJECTION,
                null, // I REMOVED SELECTION HERE
                null,
                ContactsQuery.SORT_ORDER);
    }

    Log.e(TAG, "onCreateLoader - incorrect ID provided (" + id + ")");
    return null;
}


text:
Q: Problems transferring data from Android Phone to Serial Device using Bluetooth component sorry if my Title is not particularly precise.
I am trying to transfer byte Data from an Android Phone to a Serial Device.
As you can see below, the data I want to send is a Byte Array with Hex values.
if I send them the way I do right now, RealTerm the Serial port monitor display different Values than the ones I Sent (F0 F0 FC F3).
void __fastcall Blue::send(Byte * data, int len)
{
    TBytes DataToSend;
    DataToSend.set_length(1);

    for(int i = 0; i < len; i++)
    {
        DataToSend= ToBytes(data[i]);
        if(!btSocket->Connected)
            btSocket->Connect();
        btSocket->SendData(toSend);
    }
}

int Bluetooth::sendMessage(void *data, unsigned short len)
{
    Byte bff[4] = {'\AA', '\x55', '\xA5', '\x5A'};
    unsigned short crc;

    crc = util->calcCRC((unsigned long)data, len / 2);

    send(bff, 4);
    send((Byte *)data, len);
    return 0;
}

That is how I get the Connection
TBluetoothSocket* Bluetooth::getBtSocket()
{
    if(btSocket == NULL)
    {
        TBluetoothDevice * lDevice = fPairedDevices->Items[Form1->ComboBoxPairedDevices->ItemIndex];
        btSocket = lDevice->CreateClientSocket(StringToGUID(ServiceGUI), false);
    }
    return btSocket;
}

so the first thing I do is to send the bff as a start sequence and then I want to send the rest of the data using the serial communication. btSocket is just a TBluetoothSocket.
Well as stupid as it might sound, it was actually the Baud Rate.

A: Set correct baud rate on your RealTerm ;)


text:
Q: TestNG-Selenium - Unable to convert string value to Integer read from a Excel file I am trying to read data from an excel file using POI framework in TestNG, Selenium. I am able to read String data from the cells. When there in Integer data in the cell, it throws an error saying it can't convert String data into Integer.
I tried getStringCellValue, getRawvalue methods but it doesnt work.
Last line of the code is where I have issue. There should be a way to read integer data from the excel cells. Not just text/string only.
Any suggestions please
import org.testng.annotations.Test;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeClass;

import java.io.FileInputStream;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.testng.Assert;

import org.testng.annotations.AfterClass;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.Parameters;

import org.testng.annotations.AfterTest;

import org.testng.annotations.BeforeSuite;

import org.testng.annotations.AfterSuite;

import org.apache.poi.xssf.usermodel.XSSFCell;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

@Test
public void test(

   FileInputStream aTestDataExcelFile = new FileInputStream(TestDataFile);
   XSSFWorkbook aExcelWBook = new XSSFWorkbook(aTestDataExcelFile);
   XSSFSheet aXSSFSheet = aExcelWBook.getSheet(SheetName);
   XSSFCell aCell = aXSSFSheet.getRow(i).getCell(0);

   int aReasoncode= aCell.getStringCellValue();
}

A: You have to cast it into integer like this
int aReasoncode = Integer.parseInt(aCell.getStringCellValue());


text:
Q: Failure to build a project using NDK I'm trying out NDK for the first time, and I'm stuck with building this project. I'm attempting to use the libraries used in Android's screencap recording program to read data from my screen. I understand that I need to use LibGUI, which I've pulled from my phone. Whenever I compile, however, I get this as an error message:
C:/Users/Kevin/Desktop/ScreenCapture//jni/main.cpp:2:34: fatal error: gui/ISurfaceComposer.h: No such file or directory

Which is odd, considering that I have libgui.so included.
What my main file looks like:
#include <stdio.h>
#include <gui/ISurfaceComposer.h>

int main() {
    printf("Started!");
    return 0;
}

What my Android.mk looks like:
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := libgui-prebuilt
LOCAL_SRC_FILES := libgui.so

include $(PREBUILT_SHARED_LIBRARY)

include $(CLEAR_VARS)

LOCAL_MODULE    := screencapture
LOCAL_SRC_FILES := main.cpp
LOCAL_SHARED_LIBRARIES := libgui-prebuilt

include $(BUILD_EXECUTABLE)

And I have both the main file and libgui.so in the same folder.

A:
main.cpp:2:34: fatal error: gui/ISurfaceComposer.h: No such file or directory

Your error message indicates that the compiler is unable to find a header file, but your attempted solution is to provide a shared object (.so) library from the phone.
Libraries might help at link time, but before you can link you must successfully compile, and to do that you are going to have to obtain the missing header (perhaps from AOSP sources, as source code it will not be found on the phone) or else recreate it by deducing its contents from clues you collect.  Unfortunately, it often isn't possible to take just one internal header out of AOSP, as it will likely depend on many others.
Linking against private system internals also introduces a risk of your program breaking if the private interface between internal components changes between Android versions.
(Normally I would also mention that you are unlikely to be able to record a screen with the NDK in it's normal usage of making a shared library to link into an application process, however your Android.mk seems to indicate you are building an executable - that might work if you can succesfully build it and you run it as a user with sufficient permission such as adb's shell userid or using a root hack)

A: Add one line for module screencapture:
LOCAL_C_INCLUDES := $(LOCAL_PATH)/

If you haven't folder gui, you need to copy&paste includes headers *.h into folder jni/gui. Always such a requirement about using like that for ndk...

Or second case - using other location of this source for ldlibs:
LOCAL_LDLIBS := -L/full_path_to_source_gui/gui/


text:
Q: How does my projector downsample the input resolution into its native resolution? I have a projector that has a maximum input resolution of 1920x1080 and a native resolution of 800x480.
If I plug it into my computer which is sending it a 1920x1080 signal, what is it doing to display it at 800x480? The two aspect ratios are not multiples of each other so simply downscaling the images coming from the input doesn't make sense.
The main reason I ask is that I want to display an image of size exactly 800x480 through my computer, on the projector. But I'm unable to achieve this because my computer is outputting a 1920x1080 signal.
Thanks for any clarification.

A: Your projector uses an algorithm to reduce the larger image size it is being sent to the lower resolution.  It can achieve this be dropping lines of resolution and/or blending colors together.  This will result in loss of image quality.  As for the aspect ratio, depending on the projector's algorithm, it will wither fit the image to the projectors max, or simply give you a letterbox version - like movies on a TV.  You would need to check your projector's manual to see what options are available.
You didnt say what operating system you are using, so I am going to assume Windows 10.  Windows has a minimum height of 800 x 600 pixels.  As far as I know, you cannot go below that minimum.
However, you might be able to do a resolution of 1000 x 600, which is a multiple of 1.25 of the projectors resolution.  This should scale easily, with minimum loss of quality.  Again, you didnt mention your OS or GPU, however you can simply google for how to create custom resolutions for your OS and GPU and you should be good to go.


text:
Q: Which are the steps for crafting an Celestial (Exotic) armor? In Guild Wars 2, there are armors with a Celestial bonus (which have all stats as a bonus), which were introduced some time ago, during an event. I know those are still craftable, but i can't seem to find an organized step-by-step guide to craft an Celestial Ascended piece of armor.
Also, as a bonus, i would like a "Price Comparison" to craft an Exotic Celestial Armor vs a Ascended Celestial Armor (assuming the character already has a leve 500 Armorsmith)

A: Exotic
Important: This requires Armorsmith, Leatherworker, or Tailor crafting level 400, depending on which type of armor you want. I will use X / Y / Z format from here on to indicate different values for Armorsmith / Leatherworker / Tailor.

*

*Obtain a Celestial Intricate Gossamer Insignia recipe and one recipe for each of the six armor pieces, all of which can be purchased on the trading post. Search for "Celestial" and Draconic / Emblazoned / Exalted.

*Use those recipes on the appropriate character.

*You'll now need to gather the materials. Let's start with Charged Quartz Crystals, because those are the tricky part. You'll need 750 Quartz Crystals in total, of which you can fuse 25 into one Charged Quartz Crystal (at a "point of power", aka commune skill point challenge) once per day. This means that you'll need at least 30 days to get all of the required materials.

*Once you have your 30 Charged Quartz Crystals, you'll need to refine your raw crafting materials to craft 6 Celestial Intricate Gossamer Insignias and the tier 6 (Orichalcum / Hardened / Gossamer) crafting components for one of each piece of armor.
This will require the following materials:

*

*30 Charged Quartz Crystals

*30 Globs of Ectoplasm

*130 Spools of Gossamer Thread

*74 / 72 / 96 Gossamer Scraps

*32 / 0 / 0 Orichalcum Ore

*0 / 36 / 12 Hardened Leather Sections
Ascended
Important: This requires Armorsmith, Leatherworker, or Tailor crafting level 500, depending on which type of armor you want. I will use X / Y / Z format from here on to indicate different values for Armorsmith / Leatherworker / Tailor.

*

*Obtain a Celestial Intricate Gossamer Insignia recipe (unless you already unlocked it to craft your exotic armor).

*Purchase and use an Ascended Insignia recipe from the master craftsman. Select "Recipe: Wupwup Celestial Insignia" from the list. Then purchase and use each of the six ascended armor piece recipes from the last tab of the master craftsman. Use each of those, selecting the "WupWup" option for each.

*Consume all of the above recipes on the appropriate character.

*(same as exotic step #3 above)

*Once you have your 30 Charged Quartz Crystals, you'll need to refine your raw crafting materials to craft 6 Celestial Intricate Gossamer Insignias, which you will then use to craft six Wupwup Celestial Insignias. You will also need to craft Ectoplasm Refinement materials, which are limited to one per day, but you can bypass the time gate by buying the refined materials. You'll finally need to craft tier 7 (Deldrimor Steel / Elonian / Damask) crafting components for one of each piece of armor.
This will require the following materials. The ones marked with a * can be bought on the trading post to bypass the time gated materials required to craft them.

*

*30 Charged Quartz Crystals

*30 Globs of Ectoplasm

*30 Globs of Dark Matter

*120 Piles of Crystalline Dust

*6 Augur's Stones

*1500 Piles of Bloodstone Dust

*1500 Empyreal Fragments

*1500 Dragonite Ore

*150 Thermocatalytic Reagents

*480 Spools of Gossamer Thread

*60 / 60 / 60 Gossamer Scraps

*16 / 0 / 0 Deldrimor Steel Ingots*

*0 / 18 / 5 Elonian Leather Squares*

*25 / 24 / 36 Bolts of Damask*
If you are not looking to bypass the time gate, here are the total materials for each refined ascended material.
Deldrimor Steel Ingot:

*

*1 Glob of Ectoplasm

*10 Thermocatalytic Reagents

*100 Mithril Ore

*90 Iron Ore

*10 Lumps of Coal

*40 Platinum Ore

*20 Lumps of Primordium
Elonian Leather Square:

*

*1 Glob of Ectoplasm

*10 Thermocatalytic Reagents

*150 Thick Leather Sections

*40 Thin Leather Sections

*20 Coarse Leather Sections

*40 Rugged Leather Sections
Bolt of Damask:

*

*1 Glob of Ectoplasm

*25 Spools of Gossamer Thread

*300 Silk Scraps

*40 Wool Scraps

*20 Cotton Scraps

*40 Linen Scraps
As for a price comparison, it's impossible to be exact. The market fluctuates constantly, so the prices of the materials shift. In terms of coins, ascended armor is many times more expensive than exotic. In addition to the monetary cost, a full set of ascended armor costs 120 skill points, and the recipes cost an additional 21,000 karma and 30 laurels.


text:
Q: No puedo acceder a phpmyadmin y el contenedor me da un error Esta es la imagen de mi contenedor actual https://gyazo.com/ae7423468c16664cd90bc774235f6dbf
como veis, abajo me da un extraño error que no sé si es normal que salga... en cualquier caso, no puedo acceder a phpmyadmin (problema del cual, creé un post anteriormente, pero me dieron una solución que corrigiera el error).
Esta es la imagen de mi archivo config:
https://gyazo.com/bb43bf7c30410105fbc3e2a86c8d9821

A: El archivo php no influye en lo siguiente que comentaré.
Tienes alguna aplicación que trabaja en puerto 80 sin saberlo y está bloqueando que a apache para que no pueda iniciarse sobre ese puerto.
Usa la comanda siguiente en un terminal en modo administrador
netstat -anob esto te ayudará a saber que app te ocupa el puerto 80. Si no fuera el puerto 80 publica el resultado editando la pregunta.
Para la segunda pregunta obtienes un error por culpa del primero, un saludo


text:
Q: How to catch error I was using function Float.of_string to convert an input obtained by a formular.
Surely the user could be a bad guys and write a sentence instead of a float number in the input :)
There is lot of solution, to test the string input... But In my mind the function float.of_string, should test, it's obligatory to transform into a float. And as an evidence when the string is not a float... The server will reach an error which kill the server (or at minimum the session).
Then I think, the best will be (choice) :

*

*Return an option

*A way to catch error before it kill the session...

Then the true question of this post, is :
Is there a way to do something like try/catch block for the OPA uncaught exception.
And if yes how it works, and is it possible to throw an error in our own function ?
Thanks for your answer,
Matthieu

A: Ok, first concerning Float.of_string. It's a low-level function that does assume a well-formed input, so should not be called on anything coming from the user (or indeed anything that may fail). But you're not the first one asking that so maybe indeed we should change this function to return an option type.
For that kind of scenarios (when things can go wrong) one should instead use parsing and the Rule.float function. To learn more about parsing in Opa you can check the recent blog post and there will be a follow-up one coming tomorrow, I hope.
Now, concerning exception handling: we were (are?) planning to add it to Opa but as of today it's not available yet. So... be patient :)


text:
Q: How to sum integer inputs in Java, and display the results in an array at the end of the program? I am trying to create a "calculator", except it needs to print each element that was used to compose the sum total. This printing of the array elements needs to happen at the end of the program, when the user inputs 0 twice in a row.
Upon entering an input, the integer values will be stored in an array. Once the end of the program has been reached, the contents of this array will be printed. However, if the end of the program has not been reached, the program continues while the user adds consecutive inputs.
Currently, the program will only print one element at a time, instead of every element that was used to calculate the total. I've spent hours trying to debug, and any guidance would be greatly appreciated!
import java.util.*;

public class AddingMachine {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    boolean justStarting = true;
    int total = 0;
    int subtotal = 0;
    int input;
    int last = 1;
    int MAXIMUM_NUMBER_OF_INPUTS = 100;
    while (true) {
        input = scanner.nextInt();
        if (input == 0) {
            if (last == 0) {
                System.out.println("total " + total);
                return;
            }
            System.out.println("subtotal " + subtotal);
            total += subtotal;
            subtotal = 0;
        }
        subtotal += input;
        last = input;
        int[] numbers = new int[args.length];
        for (int i = 0; i < args.length; i++) {
            numbers[i] = last;
        }
        System.out.println(Arrays.toString(numbers));
    }
}

A: When summing the input in your loop, you could store the users input into a List of integers. Once you need to reprint them, you can iterate over the List and print the elements you stored.
Example:
List<Integer> storedUserInput = new ArrayList<>();
while (true) {
        input = scanner.nextInt();
        storedUserInput.add(input);
    if (input == 0) {
        if (last == 0) {
            for(Integer i : storedUserInput){
                 System.out.print(i + " + ");
            }
            System.out.println("total " + total);
            return;
        }
        System.out.println("subtotal " + subtotal);
        total += subtotal;
        subtotal = 0;
    }

}

A: Within the while loop, the array is re-initialized each time:
int[] numbers = new int[args.length];

so any previously entered value is lost.  Also, the purpose of the for loop within the while is not clear.
Also, unless using an array is a requirement, you really don't need an array.  You could just use a StringBuffer and append the entered values.


text:
Q: Run a program in a program So, I'm wondering if there's a way that I could have a program run in c, and when it finishes, to call and run a second program right after.
Basically, this is for a text-adventure thing, and I'd like it to run in segments, partly so that the code doesn't get huge with a ton if if-statements and all that, and partly so that I can have like a faux checkpoint system so that you can pick up sorta where you left off.
That, or a way to save your progress somehow. I couldn't come up with anything on exactly how to do that, but I know it's possible. I just don't really know what I'm doing yet. Forgive me if the above question(s) are really simple.


text:
Q: Unity 3D Mesh Find aligning vertices on the same Y axis Height I'm trying to find adjacent vertices from just one selected vertex. One condition these neighboring vertices have to fulfill is that they must be on the same height as the selected original vertex.
I have an int[] vertices array, and a Dictionary<int, float> plateauDictionary.
The vertices array holds all vertices of the entire mesh.
The Dictionary holds a collection of vertices that have a height(y-Axis) greater than 0.2f.
Im creating big flat plateaus, so finding adjacent vertices at the same height should be easy as most vertices are adjacent to each other at the same height.
Heres what I wrote so far:
    Matrix4x4 localToWorld = transform.localToWorldMatrix;
    Vector3[] worldVectors = new Vector3[totalVertices];

    foreach (KeyValuePair<int, float> u in plateauDictionary)
        worldVectors[u.Key] = localToWorld.MultiplyPoint3x4(mesh.vertices[u.Key]);

This returns an array of Vector3s consisting of all the world position of each vertex.
Now I want to pick one or a few randomly, and then get the amount of adjacent vertices at the same height, maybe in an assigned radius or maybe in a list of neighbors? How do I solve this? I'm a newb with LINQ but Im thinking that might be the way to go?
Thanks in advance!
My other code(Not really important for this question but for the sake of completeness):
    plateauDictionary = new Dictionary<int, float>();

    for (int j = 0; j < plateaus; j++)
    {
        var rndSize = plateauSizes[Random.Range(0, plateauSizes.Length)];
        var rndHeight = plateauHeights[Random.Range(0, plateauHeights.Length)];
        var rndVertex = ((xSize + 2) + (Random.Range(0, xSize - rndSize - 1) * (xSize + 1))) +
                                        Random.Range(0, xSize - rndSize - 1);

        plateauVertexArray = new int[rndSize * rndSize];

        for (int k = 0, i = 0; k < rndSize; k++)
        {
            for (int l = 0; l < rndSize; l++, i++)
            {
                plateauVertexArray[i] = (rndVertex + ((xSize + 1) * k)) + l;

                if (!plateauDictionary.ContainsKey(plateauVertexArray[i]))
                    plateauDictionary.Add(plateauVertexArray[i], rndHeight);

A: You could compare the remaining worldVectors.y value with your selected selectedWorldVector.y. I have no idea about linq but i think its a good option if you want to avoid if else spaghetti code.
Aside from that you could also instantiate an empty object at each vertex world position, add an empty box collider to each, and then use a Raycast.SphereCastAll() from your selectedWorldVector position. Set your radius in SphereCast to see each close vertex and then filter out ones that are too low/high.


text:
Q: How to avoid "cannot load such file -- utils/popen" from homebrew on OSX I'm getting an error when I run  brew in the terminal:
 /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- utils/popen (LoadError)
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /usr/local/Library/Homebrew/utils.rb:6:in `<top (required)>'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /usr/local/Library/Homebrew/global.rb:9:in `<top (required)>'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /usr/local/Library/brew.rb:16:in `<main>'

These are my gem settings:
- RUBYGEMS VERSION: 2.0.14
- RUBY VERSION: 2.0.0 (2014-02-24 patchlevel 451) [universal.x86_64-darwin13]
- INSTALLATION DIRECTORY: /Library/Ruby/Gems/2.0.0
- RUBY EXECUTABLE: /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby
- EXECUTABLE DIRECTORY: /usr/bin
- RUBYGEMS PLATFORMS:
  - ruby
  - universal-darwin-13
- GEM PATHS:
  - /Library/Ruby/Gems/2.0.0
  - /Users/ronaldkwan/.gem/ruby/2.0.0
  - /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/gems/2.0.0
- GEM CONFIGURATION:
  - :update_sources => true
  - :verbose => true
  - :backtrace => false
  - :bulk_threshold => 1000

A: Uninstall homebrew:
 ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Then reinstall
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Warning: This script will remove: /Library/Caches/Homebrew/ - thks benjaminsila

A: Original Answer
The problem mainly occurs after updating OS X to El Capitan (OS X 10.11) or macOS Sierra (macOS 10.12).
This is because of file permission issues with El Capitan's or later macOS's new SIP process. Try changing the permissions for the /usr/local directory:
$ sudo chown -R $(whoami):admin /usr/local

If it still doesn't work, use these steps inside a terminal session and everything will be fine:
cd /usr/local/Homebrew
git reset --hard origin/master
brew update

If /usr/local/Library/Homebrew doesn't work, try /usr/local/Homebrew. The problem might be that Homebrew is outdated.
Apr 2021 Update
The command above doesn't work for macOS High Sierra or above, as explained in this GitHub issue. You have to run this instead:
sudo chown -R $(whoami) $(brew --prefix)/*

A: First I executed:
sudo chown -R $(whoami):admin /usr/local

Then:
cd $(brew --prefix) && git fetch origin && git reset --hard origin/master

A: First, open a terminal session and run:
cd /usr/local/
git status

to see if Homebrew is clean.
If it's dirty, run:
git reset --hard && git clean -df

then
brew doctor
brew update

If it's still broken, try this in your session:
sudo rm /System/Library/Frameworks/Ruby.framework/Versions/Current
sudo ln -s /System/Library/Frameworks/Ruby.framework/Versions/1.8 /System/Library/Frameworks/Ruby.framework/Versions/Current

This will force Homebrew to use Ruby 1.8 from the system's installation.

A: This issue should be fixed in the newest version of Homebrew. Try reinstalling it, which is described on the Homebrew home page.

A: In my case I just needed to remove Homebrew's executable using:
sudo rm -f `which brew`

Then reinstall Homebrew:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

A: After updating to El Capitan, /usr/local has root:wheel rights.
Change the rights back to the user using:
sudo chown -R $(whoami):admin /usr/local

and:
brew doctor && brew update

This helped me to get Homebrew working again.

A: To me it feels like you have missing header files for popen, which is a C system library.
Check if you have installed xcode successful with the command line tools and have accepted the license.
See this thread for more information: How to install Xcode Command Line Tools

A: To restore your Homebrew setup try this:
cd /usr/local/Homebrew/Library && git stash && git clean -d -f && git reset --hard && git pull


text:
Q: Grub menu appears even if i have hibernated Windows 10 I had Windows 10 installed and then i installed latest version of Ubuntu 18.04.2, both works fine (first GRUB menu show up and then i can select which to boot up and if i select win then it takes me to windows OS selection screen where i can choose between Remix OS and Windows 10), the problem is that if I hibernate the Windows (which I always do), then also the GRUB menu shows up and I don't want that as you know that booting into the other OS while other is hibernated can result in huge loss of data.
Current : Grub shows up even if windows is hibernated.
What I want : Grub should only show up if all other OS are shutdown properly..that is Grub should not appear if windows is hibernated.

A: That is normal behavior for Linux. Modern Linux distros are able to mount the Windows partition read-only if it was hibernated (i.e., hiberfil.sys exists), so Windows OS and data should be safe.
This allows you to run a Windows executable in wine, without need to copy to the extx partition, even when hibernated, or to share data as read-only.
That said, as you state, it is good practice to perform a full shutdown, without hibernation, if dual-booting to Linux.


text:
Q: Python - make a list How can I turn something like this: (not a file)
Edit: It's what I get when I print this:
adjusted_coordinate_list = str(adjusted_X_coordinate) + ',' + str(Y_coordinate)

1,1
1,2
1,3
1,4
1,5

into this:
['1,1','1,2','1,3','1,4',1,5']

A: Use str.splitlines to split over boundaries of string and needed a list.
s = """1,1
1,2
1,3
1,4
1,5"""
print s.splitlines()

['1,1', '1,2', '1,3', '1,4', '1,5']

A: It looks to me like you are looping over this command to get the input you described. I'm assuming something like this:
for foo in bar:
    adjusted_coordinate_list = str(adjusted_X_coordinate) + ',' + str(Y_coordinate)
    print adjusted_coordinate_list

In order to get all the results in a clean list, you would do something like this:
adjusted_coordinate_list = []
for foo in bar:
    new_elem = "%s,%s" % ( adjusted_X_coordinate, Y_coordinate )
    adjusted_coordinate_list.append( new_elem )

Your adjusted_coordinate_list will now contain a list of all the adjusted coordinates.

A: Can try this pseudo code
ans_list = []
for each row:
    row = row.strip()
    ans_list.append(row)

A: you try this:
my_cor =[]
#some loop
    my_cor.append(str(adjusted_X_coordinate) + ',' + str(Y_coordinate))
print my_cor


text:
Q: Debugging Related : Why does this PHP code not working with desired behavior? I was trying to understand use of Aliasing/Importing in php namespaces from  php.net/manual sample example.
I slightly modified the sample example to explore all the features of php namespace  Aliasing/Importing in a single code file.
I also added multiple namespaces in the same file to observe all the features.
Here is the php source code:
<?php
namespace foo{
echo "1-Inside namespace foo \n";
use My\Full\Classname as Another;
use ArrayObject; // importing a global class
echo "2-After using  ArrayObject line: ".__LINE__."\n";
    class Another {
  public function cname() {
        echo "line".__LINE__."Method".__METHOD__."\n";
   }
   static function  method(){echo "line".__LINE__."Method: ".__METHOD__."\n";}
}
//This line below is Not working.
$obj1 = new namespace\Another; // instantiates object of foo\Another
echo "3-After namespace\Another object line: ".__LINE__."\n";
//This line below is Not working.
echo "4-".$obj1->method()."\n";
//This line below is Not working.
$obj2 = new Another; // instantiates object of class My\Full\Classname
echo "5-After Another object line: ".__LINE__."\n";
//This line below is Not working.
echo "6-".$obj2->method()."\n";
echo "7-After Another object line: ".__LINE__."\n";
//This line below is Not working.
$a = new ArrayObject(array(1)); // instantiates object of ArrayObject
echo "8-After ArrayObject line: ".__LINE__."\n";
}

namespace My\Full{

class Classname{
    public function cname() {
        echo "line".__LINE__."Method".__METHOD__."\n";
   }
   static function  method(){echo "line".__LINE__."Method: ".__METHOD__."\n";} } }
?>

I expected & wanted these desired behavior/output to be printed given below:
1-Inside namespace foo
2-After using ArrayObject line: x
3-After namespace\Another object line: x
4-line: x Method: foo\Another:method()
5-After Another object line: x
6-line: x Method: My\Full\Classname:method()
7-After Another object line: x
8-After ArrayObject line: x

But Instead of desired output, I got only few outputs with errors given below:
PHP Fatal error:  Cannot declare class foo\Another because the name is already in use in /home/himadree/ php workspace/ZCE/TOPIC1:BASICS/Namespaces/Using-namespaces-Aliasing-Importing.php on line 8

So, it looks like there might be any identical naming conflicts with the class name Another
Moreover i noticed that class 'Another' has 2 versions: foo\Another & My\Full\Classname as Another.After some useful comments i added extra class'Another'within namespace foo.But still its not working.Is this any the only error! i don't know.
Therefore in order to get my desired behavior/output,  what changes are needed in this code? I used eclipse php pdt tools, php version 5.5.
Since it is debug issue, so let me know if more specific information required.Thanks

A: The specific problem is that there is no class foo/Another defined. You're missing this within namespace foo:
class Another {}

Without it or something like it, foo\Another does not exist and attempting to instantiate it, as you are, will lead to a fatal error, as it does.

Moreover i noticed that class 'Another' has 2 versions: foo\Another & My\Full\Classname as Another.

That's the point this code is trying to demonstrate. Just Another would be ambiguous, since it could refer to the aliased as Another or to foo\Another. Hence why namespace\Another is used to explicitly refer to foo\Another. As opposed to the new Another, which refers to the aliased as Another.


text:
Q: Tic Tac Toe game by michael dawson the computer_move function I'll try my best to describe the question, but I am very confused already! So this is the winning function:
def winner(board):
    WAYS_TO_WIN = ((0, 1, 2),
                   (3, 4, 5),
                   (6, 7, 8),
                   (0, 3, 6),
                   (1, 4, 7),
                   (2, 5, 8),
                   (0, 4, 8),
                   (2, 4, 6))

    for row in WAYS_TO_WIN:
        if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
            winner = board[row[0]]
            return winner

And this is the loop inside computer_move function to see if a computer can win, if so then take that move:
for move in legal_moves(board):
    board[move] = computer
    if winner(board) == computer:
        print(move)
        return move

My question is, the winner function checks all the combinations to win, and only returns the first piece of the winning match i.e. a (3, 4, 5) win will only return '3' as winner because winner = board[row[0]]
What if the winning computer move is at board[row[2]], and the winner function returns board[row[0]] so that wouldn't match the condition if winner(board) == computer even if it is a win move?

A: The first function is checking if the 3 cells of any of the winning combinations hold the same value and this is not EMPTY and returns the value, which can be a player or the computer.
The computer simulates a every legal move and see if he wins with this move, and if he finds a move that makes him win he does it.
For example:
player computer EMPTY
EMPTY  computer player
EMPTY  EMPTY    player

computer will check if any of the EMPTY cell makes him win, what happens when he fills the centered EMPTY cell, and thus makes the move he had to do to get to that winning position.


text:
Q: Deseasonalize the data of traffic growth for the past data In another question (Using TimeSeriesForecast for forecasting the traffic growth) I asked to use the TimeSeriesForecast on this set of data the answer provided the plot with and without the seasonalization for the future value.
Is it possible to get the same plot (without seasonalization) for data which are already available (now this is only for the forecasted one)?
EDIT
The SARIMA model has the seasonal peaks. Is it possible to calculate the same model also for the range of dates on which I provided the data?
If that is possible maybe I could use the model of the periodic peaks to modulate the real data getting rid of the data seasonality.
What I would be curious to get is not a regression (which would be a flat line) but the deseasonalized data.

A: Your description of what you want to do is quite vague and the "not a regression" part is kind of contradictory. Therefore I'll take

"Is it possible to calculate the same model also for the range of dates on which I provided the data?"

part to formulate an answer.
Importing your data saved in TSV format
data = MapAt[DateString[{#, {"Day", "/", "Month", "/", "Year"}}] &,
 Import["D:\\Analytics www.superinformati.com Panoramica del pubblico 20141201-20150303 - Sheet 1.tsv"][[3 ;;, {1, 2}]]
 , {All, 1}]

Finding the SARIMA process
tsm = TimeSeriesModelFit[data]

One can use RandomFunction to create multiple simulations assuming a random process. The following code produces 5 simulations. I use Length@data - 30 because your data looks like the real trend starts somewhere after 30 days.
rf1 = RandomFunction[tsm["BestFit"], {Length@data - 30}, 5]

Creating a plot of these simulations and of their mean
randomP1 =
 DateListPlot[Transpose[{data[[30 ;;, 1]], #}] & /@ rf1["States"],
  PlotStyle -> Opacity[1/2],
  PlotRange -> {{data[[1, 1]], data[[-1, 1]]}, Automatic}]

meanP1 = DateListPlot[
  Transpose[{data[[30 ;;, 1]], TimeSeriesThread[Mean, rf1]["PathStates"]}],
  PlotStyle -> Red, PlotRange -> {{data[[1, 1]], data[[-1, 1]]}, Automatic}]

Putting everything into one plot
Show[{randomP1,
 DateListPlot[data, PlotStyle -> Directive[Black, Thick]],
 meanP1}]

Doing the same using a ARIMA model
tsm2 = TimeSeriesModelFit[data, "ARIMA"]

rf2 = RandomFunction[tsm2["BestFit"], {Length@data - 30}, 5]

randomP2 =
 DateListPlot[Transpose[{data[[30 ;;, 1]], #}] & /@ rf2["States"],
  PlotStyle -> Opacity[1/2],
  PlotRange -> {{data[[1, 1]], data[[-1, 1]]}, Automatic}]

meanP2 = DateListPlot[
  Transpose[{data[[30 ;;, 1]], TimeSeriesThread[Mean, rf2]["PathStates"]}],
  PlotStyle -> Red, PlotRange -> {{data[[1, 1]], data[[-1, 1]]}, Automatic}]

Show[{randomP2,
 DateListPlot[data, PlotStyle -> Directive[Black, Thick]],
 meanP2}]

A: Removing seasonality by using MeanFilter:
data = MapAt[DateString[{#, {"Day", "/", "Month", "/", "Year"}}] &,
 Import["D:\\Analytics www.superinformati.com Panoramica del pubblico 20141201-20150303 - Sheet 1.tsv"][[3 ;;, {1, 2}]]
 , {All, 1}]

DateListPlot[{data,
 Transpose[{data[[All, 1]], MeanFilter[data[[All, 2]], 7]}]}]


text:
Q: Disabling "View" mentions from backend? I'm using wordpress as a content manager or something, so i'm using backend only (and i've disabled the frontend with a ghost theme which redirect to the admin panel).
The question is: how could i disable the "view" post button and generally every mention to "preview" posts, view categoryes, pages etc?

Solved!
Thank you cristian.raiber! It worked perfectly.
I've also put this lines to hide the previews in single posts:

function posttype_admin_css() {
global $post_type;
$post_types = array(
                        /* set post types */
                        'progetti',
                        'post',
                        'page',
                  );
    if(in_array($post_type, $post_types))
    echo '#post-preview, #view-post-btn{display: none;}';
}
add_action( 'admin_head-post-new.php', 'posttype_admin_css' );
add_action( 'admin_head-post.php', 'posttype_admin_css' );

add_action('admin_head', 'hide_quick_view');

function hide_quick_view() {
  echo '
    span.view {display: none !important; visibility: hidden !important; opacity: 0 !important;}
  ';
}

A: Instead of disabling it, you'd be better off by hiding it using a bit of CSS trickery.
Try this and let me know if it works:
    add_action('admin_head', 'hide_quick_view');

function hide_quick_view() {
  echo '<style>
    span.view {display: none !important; visibility: hidden !important; opacity: 0 !important;}
  </style>';
}

This should be placed in your functions.php file.


text:
Q: how to print well formatted java code in JSP or consol form database? database using MYSQL.
IDE using eclipse .
server using Tomcat.
 problem scenario is facing difficulty in print the formatted java code on jsp or console
 java code example[
1. class One {
2. public static void main(String[] args) {
3. int assert = 0;
4. }
5. }
1. class Two {
2. public static void main(String[] args) {
3. assert(false);
4. }
5. }

] is stored in the database when retrieved that java code is printing in a single line on the console or jsp .
how to print it in a proper formatted  java code
 please give an appropriate solution...

A: Use the
 HTML tag:

<c:out value="${theJavaCode}"/>


text:
Q: How to assign non-null property to button? I am declaring an action for UIButton in myviewcontroller.h file like this
- (IBAction)loginClicked:(id)sender;

but I can see warning like Pointer is missing a nullability type specifier (_Nonnull, _Nullable, or _Null_unspecified).
How can I resolve this issue?
thanks

A: Replace
- (IBAction)loginClicked:(id)sender

With
-(IBAction) loginClicked:(nonnull id)sender

Read more at: https://developer.apple.com/swift/blog/?id=25


text:
Q: Create class if class not exist with PhpOrient Is it possible to create a class only if the class doesn't exists yet,
in PhpOrient for OrientDB 2.1.13?
So something like this:
$client->command('create class Thing extends V if class Thing != exist');

A: That behaviour is built in. If you try to create a class that already exists OrientDB will return an error (if you are doing it through the console). If you are using PhpOrient, it will throw an exception.
If the class does exist it will return the number of total classes in the db after creation
So just check the response, but catch the exception as well.:
$response=false;
try {
    $response = $client->command('create class Thing extends V);
} catch (Exception $e) {
    print "Error: " . $e->getMessage() ."\n";
    //class was most likely already created
}
//check $response
if ($response) {
    //class created scuccessfully
    print"Number of claasses $response \n";
}

You can of course set flags as you need them inside the blocks so you can do whatever you need depending on the outcome.
Hope this helps


text:
Q: IOException with URLConnection and getInputStream I'm trying to get data from a website with an android application.
Here is my code :
URL url = new URL("http://www.google.com/ig/api?weather=Schriesheim,Germany");
URLConnection uCon = url.openConnection();
iStream = uCon.getInputStream();

The method getInputStream() returns me an IOException, I already tried lots of things find on Internet, but nothing is working.
By the way, I tried this code in a Java application and it worked so I assume this the problem is in my Android settings.
I already add these lines in my Manifest.xml :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

I'm using Eclipse and running Archlinux x64.
Any idea ?
Thank you.

A: You can try this function for get data from internet
        public static String get(String from) {
            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(from);
                HttpResponse responseGet = client.execute(get);
                HttpEntity resEntityGet = responseGet.getEntity();
                if (resEntityGet != null) return EntityUtils.toString(resEntityGet);
                } catch (Exception e) {
                    Log.e("GET", e.toString());
                }
            return null;
        }

A: Try
uCon.setDoInput(true);

before
uCon.getInputStream();

A: Faced the same problem, copied all the code to a new project and it helped, the old one did not work. I think it's a curse or demon powers guys


text:
Q: Is the subextension of a cyclotomic extension Galois? If $\alpha$ is a root of the polynomial $f(X)=X^p-a$ over field $F$ of characteristic not $p$, where $p$ is a prime and $a$ is not a $p$-th power. Assume that $F(\alpha) \subset F(\zeta_p)$, do we have $F(\alpha)/F$ is Galois?

A: @DonAntonio essentially answered this in his comment. The extension $F(\zeta_p)/F$ is Galois with abelian Galois group, hence every intermediate subfield $E$ (i.e. field $E$ with $F\subset E \subset F(\zeta_p)$) is Galois over F by the Fundamental Theorem of Galois Theory. Here we've used the fact that every subgroup of an abelian group is normal.