问:
Accessing pointer variable of one .c file in another standalone .c file without using .h file
Firstly the scenario, my host environment is Linux, target is MAX10 FPGA and running RISCV soft processor and writing software for that. I am writing a simple bootloader in which I have one file main.c where all the functions are defined and another file led.c which is a standalone application. Now I want to go from main.c to led.c using some address say 0x08000000. This is achieved by using following code!

```<code>void (*func_ptr)(void);
func_ptr = (void*)0x08000000;  //starting address of led routine
func_ptr();
</code>```

In this main.c I have addresses of two LEDS which are declared at the top like this

```<code>volatile int* ledr = (volatile int*)(0x10000010);
volatile int* ledg = (volatile int*)(0x10000020);
</code>```

I am converting this led.c to .srec format and downloading it to FPGA RAM after parsing.

Till here it is working perfectly!! It is going to this application. But unfortunately in led.c, it doesn't know the address of leds where i have written blinking leds program. Although delay() function is working properly but as far as I can figure out till here is that led.c doesn't know addresses so that is why I am unable to see blinking leds on my FPGA. Blinking LEDS program is below which is complete led.c file

```<code>volatile int* led0 = (volatile int*)(0x10000010);
volatile int* led1 = (volatile int*)(0x10000020);

static void delay ()
{
  volatile int i;
  for(i=0; i<1000000; i++)
  {
  }

}

int main(void)
{

  *led0=0;
  *led1=0;
  while(1)
  {

     *led0=1;
     delay();
     *led0=0;
     *led1=1;
     delay();
     *led1=0;
  }

}
</code>```

Anyone here who can give me idea that what is wrong here and what should I do? Your help will be appreciated!!

P.S. When it goes in this application it remains in while loop and that means it is working properly, but not blinking leds. I have double checked this thing!

答:
no you will need a third party file either a peripheral "driver" file that both programs use, or a header file.  I assume by now you understand that main.c and led.c are not your whole program, there is a bootstrap at a minimum if not other code that the toolchain adds to make a complete program.

Either use a third common file or provide the same code/information both files.  this has nothing to do with arm or fpgas, elemetary C programming.

Body:
Firstly the scenario, my host environment is Linux, target is MAX10 FPGA and running RISCV soft processor and writing software for that. I am writing a simple bootloader in which I have one file main.c where all the functions are defined and another file led.c which is a standalone application. Now I want to go from main.c to led.c using some address say 0x08000000. This is achieved by using following code!

void (*func_ptr)(void);
func_ptr = (void*)0x08000000;  //starting address of led routine
func_ptr();

In this main.c I have addresses of two LEDS which are declared at the top like this

volatile int* ledr = (volatile int*)(0x10000010);
volatile int* ledg = (volatile int*)(0x10000020);

I am converting this led.c to .srec format and downloading it to FPGA RAM after parsing.

Till here it is working perfectly!! It is going to this application. But unfortunately in led.c, it doesn't know the address of leds where i have written blinking leds program. Although delay() function is working properly but as far as I can figure out till here is that led.c doesn't know addresses so that is why I am unable to see blinking leds on my FPGA. Blinking LEDS program is below which is complete led.c file

volatile int* led0 = (volatile int*)(0x10000010);
volatile int* led1 = (volatile int*)(0x10000020);

static void delay ()
{
  volatile int i;
  for(i=0; i<1000000; i++)
  {
  }

}

int main(void)
{

  *led0=0;
  *led1=0;
  while(1)
  {

     *led0=1;
     delay();
     *led0=0;
     *led1=1;
     delay();
     *led1=0;
  }

}

Anyone here who can give me idea that what is wrong here and what should I do? Your help will be appreciated!!

P.S. When it goes in this application it remains in while loop and that means it is working properly, but not blinking leds. I have double checked this thing!


来源: stackexchange

问:
Is there a windows utility similar to HTML Tidy for Javascript?
I want to cleanup some javascript files and reformat them with nice indents, etc,
Are there recommendations for utilities to do this under Windows?</p>

答: GNU indent tidies up C-style languages.  Perhaps Javascript could be used as a subject as well.</p>

OwnerDisplayName: Noah

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Noah

OwnerDisplayName: strager

ContentLicense: CC BY-SA 2.5


问:
lodash json group object costs
Please,
I have this JSON object and want to group values by type.

```<code>var costs = [
  { 'name': 'JON', 'flight':100, 'value': 12,  type: 'uns' },
  { 'name': 'JON', 'flight':100, 'value': 35,  type: 'sch' },
  { 'name': 'BILL', 'flight':200, 'value': 33,  type: 'uns' },
  { 'name': 'BILL', 'flight':200, 'value': 45,  type: 'sch' }
];
</code>```

I want something like this:

```<code>var costs = [
  { 'name': 'JON', 'flight':100, 'uns': 12,  'sch': 35 },
  { 'name': 'BILL', 'flight':200, 'uns': 33,  'sch': 45}
];
</code>```

I try use lodash but without sucess:

```<code>var compiled_costs = _.chain(costs)
                      .groupBy("flight")
                      .value();

{
"100":
    [    {"name":"JON","flight":100,"value":12,"type":"uns"},
         {"name":"JON","flight":100,"value":35,"type":"sch"}
    ],
"200":
    [
         {"name":"BILL","flight":200,"value":33,"type":"uns"},
         {"name":"BILL","flight":200,"value":45,"type":"sch"}
    ]
}
</code>```

答:
You can use native reduce() method:

const costs = [
  { 'name': 'JON', 'flight':100, 'value': 12,  type: 'uns' },
  { 'name': 'JON', 'flight':100, 'value': 35,  type: 'sch' },
  { 'name': 'BILL', 'flight':200, 'value': 33,  type: 'uns' },
  { 'name': 'BILL', 'flight':200, 'value': 45,  type: 'sch' }
];
const compiledCosts = costs.reduce((acc, { name, flight, value, type }) => {
  let obj = acc.find(x => x.name === name);
  if (typeof obj === 'undefined') {
    acc.push({ name, flight, [type]: value });
  } else {
    obj[type] = value;
  }
  return acc;
}, []);
console.log(compiledCosts);```

Title: lodash json group object costs

Body:
Please,
I have this JSON object and want to group values by type.

var costs = [
  { 'name': 'JON', 'flight':100, 'value': 12,  type: 'uns' },
  { 'name': 'JON', 'flight':100, 'value': 35,  type: 'sch' },
  { 'name': 'BILL', 'flight':200, 'value': 33,  type: 'uns' },
  { 'name': 'BILL', 'flight':200, 'value': 45,  type: 'sch' }
];

I want something like this:

var costs = [
  { 'name': 'JON', 'flight':100, 'uns': 12,  'sch': 35 },
  { 'name': 'BILL', 'flight':200, 'uns': 33,  'sch': 45}
];

I try use lodash but without sucess:

var compiled_costs = _.chain(costs)
                      .groupBy("flight")
                      .value();

{
"100":
    [    {"name":"JON","flight":100,"value":12,"type":"uns"},
         {"name":"JON","flight":100,"value":35,"type":"sch"}
    ],
"200":
    [
         {"name":"BILL","flight":200,"value":33,"type":"uns"},
         {"name":"BILL","flight":200,"value":45,"type":"sch"}
    ]
}


问:
Getting Modal to onload when page opens
Can someone help me, Im trying to get a Modal to load when the page does but having some serious issues about it.</p>

```<code><script>
   $('#overlay').modal('show');

setTimeout(function() {
    $('#overlay').modal('hide');
}, 5000);
</script>

</head>

<body>

<div class="modal fade" id="overlay">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>Context here</p>
      </div>
    </div>
  </div>
</div>
</code>```

答:
Two issues:

One .. You're not waiting until the DOM is fully loaded.  Use $( document ).ready() to achieve loading your script AFTER the DOM has loaded.

Two:  It's best practice to put your code AFTER the actual DOM elements, not before it.  That way the DOM is "almost" guaranteed to load before your script runs.

IE:

```<code><div class="modal fade" id="overlay">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>Context here</p>
      </div>
    </div>
  </div>
</div>

   <script>
     $(document).ready(function() {
       $('#overlay').modal('show');
       setTimeout(function() {
       $('#overlay').modal('hide');
       }, 5000);
     });
  </script>
</code>```

EDIT
I would use .show() and .hide()

```<code>   <script>
     $(document).ready(function() {
       $('#overlay').show();
       setTimeout(function() {
       $('#overlay').hide();
       }, 5000);
     });
  </script>
</code>```

Title: Getting Modal to onload when page opens

Body:
Can someone help me, Im trying to get a Modal to load when the page does but having some serious issues about it.

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal title

Context here

Body:
Two issues:

One .. You're not waiting until the DOM is fully loaded.  Use $( document ).ready() to achieve loading your script AFTER the DOM has loaded.

Two:  It's best practice to put your code AFTER the actual DOM elements, not before it.  That way the DOM is "almost" guaranteed to load before your script runs.

IE:

<div class="modal fade" id="overlay">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>Context here</p>
      </div>
    </div>
  </div>
</div>

   <script>
     $(document).ready(function() {
       $('#overlay').modal('show');
       setTimeout(function() {
       $('#overlay').modal('hide');
       }, 5000);
     });
  </script>

EDIT
I would use .show() and .hide()

   <script>
     $(document).ready(function() {
       $('#overlay').show();
       setTimeout(function() {
       $('#overlay').hide();
       }, 5000);
     });
  </script>


问:
Checking TeX syntax
so I'm currently working on a little application which basically consists of an editor and a preview. One writes LaTeX in the editor and the idea is that you get a live preview while you type. Like here in stackoverflow.
For doing that, I have to compile the TeX input at some point (because I need an image/pdf for displaying a preview) and since it isn't just some normal text, I better do it while there won't be any compiling errors.

So my question is: Using PyQT5, can I somehow keep checking the syntax and somehow know when the current Tex input could be compiled successfully?

答:
It is possible that you could compile the LaTeX code in the background whenever an edit is made, and only show the result based on if there were no errors from the compile.  You could even keep the previous successful compile in the preview until the next point that will compile is reached.  In this way, you would not have to check that the syntax itself was correct and ready to be displayed, but rather your viewer would only display useful previews.

I imagine this could be done by parsing the output files, or even just checking their modification times.  There are many points during the writing of LaTeX code where it may not compile, as well as a large variety of packages one could use, so it seems like an ambitious project to employ a complete syntax checker.  Additionally, you could even display compiler messages in real-time in the previewer while still providing a useful compiled view to work off of.  I could see both as being very useful to any LaTeX user.

I apologize if some of this seems better suited to a comment, but I am not yet able to on this site despite being able to on TeX.SX where this may also be relevant.  I do hope, however, that it is a useful idea.

Title: Checking TeX syntax


问:
webpack 2 dev server served from src
How should I set up my webpack config to run webpack-dev-server from src folder, not dist? I mean not only change path because then babel is not working. Now I have a problem that everything is served from bundle.js and I can't see for example where is an error. Here's my config file :

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist/'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [
          path.resolve(__dirname,'src')
        ]
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
      }
    ]
  },
  devServer: {
    compress: true,
    port: 8000
  }
}```

答:
You can specify the devserver.contentBase to define where the server will serve content from, but this shouldn't be necessary unless you're trying to serve static files. The default is the current working directory and will be served from memory rather than from the output.path. Also, if you're not aware of it, your output.publicPath is making the content be served at localhost:8000/dist/

References:

https://webpack.js.org/configuration/dev-server/#devserver-contentbase
http://webpack.github.io/docs/webpack-dev-server.html

Title: webpack 2 dev server served from src


问:
Xcode UI Tests Multiple Buttons Found
I'm having a problem where my UI Test says multiple buttons found when using the following code.

```<code>app.buttons["Upgrade"].tap()
</code>```

So I reran my unit test and set a breakpoint right before running that line and hit the record button and clicked the button and it generated the following code.

```<code>app.children(matching: .window).element(boundBy: 0).children(matching: .other).element(boundBy: 1).buttons["Upgrade"].tap()
</code>```

Of course at the top of the test I have let app = XCUIApplication().

Any idea why this would be happening?

Sometimes when running p UIApplication.shared.windows in the debugger it has 2 values in the array. I'm not sure why as I never have multiple windows. The only interactions I have with windows is setting UIApplication.shared.keyWindow?.rootViewController to different view controllers sometimes, and the following code in didFinishLaunchingWithOptions.

```<code>// Get view controllers ready
self.window = UIWindow(frame: UIScreen.main.bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController: ViewController = mainStoryboard.instantiateViewController(withIdentifier: "FirstView") as! ViewController
// Show view controller
self.window?.rootViewController = mainViewController
self.window?.makeKeyAndVisible()
</code>```

That is within an if statement and within the else statement I have pretty much the same code except instead of FirstView it's SecondView.

答:
I am seeing similar problems since updating to Xcode 8.3 where the XCUIElementQuery is returning multiple results when there should be only one.  There may be a bug introduced in this build.

https://forums.developer.apple.com/thread/75546
describes the bug and the radar is here:
https://openradar.appspot.com/31498932

I've tried the posted workaround by trying to coerce my queries to return the desired object as an XCUIElementQuery and then using element(boundBy:) and it worked for me.

It's upsetting how unstable the UI Tests are.

ContentLicense: CC BY-SA 4.0

Title: Xcode UI Tests Multiple Buttons Found

Body:
I'm having a problem where my UI Test says multiple buttons found when using the following code.

app.buttons["Upgrade"].tap()

So I reran my unit test and set a breakpoint right before running that line and hit the record button and clicked the button and it generated the following code.

app.children(matching: .window).element(boundBy: 0).children(matching: .other).element(boundBy: 1).buttons["Upgrade"].tap()

Of course at the top of the test I have let app = XCUIApplication().

Any idea why this would be happening?

Sometimes when running p UIApplication.shared.windows in the debugger it has 2 values in the array. I'm not sure why as I never have multiple windows. The only interactions I have with windows is setting UIApplication.shared.keyWindow?.rootViewController to different view controllers sometimes, and the following code in didFinishLaunchingWithOptions.

// Get view controllers ready
self.window = UIWindow(frame: UIScreen.main.bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController: ViewController = mainStoryboard.instantiateViewController(withIdentifier: "FirstView") as! ViewController
// Show view controller
self.window?.rootViewController = mainViewController
self.window?.makeKeyAndVisible()

That is within an if statement and within the else statement I have pretty much the same code except instead of FirstView it's SecondView.


问:
Implications of Wrapping Delayed Job in Transaction for Rails App
Can anyone explain what would happen in the code below if the delayed_job that's scheduled in two weeks fails?

My understand is that this entire transaction would sit in memory until the transaction runs successfully or exhausts the permitted number of attempts (i.e. transaction doesn't merely guarantee that the job itself is created). Am I correct? If anyone could also elaborate on implications of this structure (i.e. memory leakage, race conditions, performance, etc.) and potential improvements that would be greatly appreciated!

```<code>...

def process
  old_user.transaction(requires_new: true) do
    begin
      update_user_attributes

      TransferUserDataJob.new(old_user, new_user).delay(run_at: 14.days.from_now, queue: 'transfer_user_data_queue').perform

      raise ActiveRecord::Rollback if user.status.nil?
    rescue Exception => e
      raise ActiveRecord::Rollback
    end
end

...
</code>```

答:
That code isn't doing what you expect it to do.

This part:

```<code>TransferUserDataJob.new(old_user, new_user).delay(run_at: 14.days.from_now, queue: 'transfer_user_data_queue').perform
</code>```

Will schedule that job to performed by a separate process, typically on a separate server. So, it won't run in the context of your transaction.

Instead, you need to go into your TransferUserDataJob class and place that transaction inside the perform method.

Body:
Can anyone explain what would happen in the code below if the delayed_job that's scheduled in two weeks fails?

My understand is that this entire transaction would sit in memory until the transaction runs successfully or exhausts the permitted number of attempts (i.e. transaction doesn't merely guarantee that the job itself is created). Am I correct? If anyone could also elaborate on implications of this structure (i.e. memory leakage, race conditions, performance, etc.) and potential improvements that would be greatly appreciated!

...

def process
  old_user.transaction(requires_new: true) do
    begin
      update_user_attributes

      TransferUserDataJob.new(old_user, new_user).delay(run_at: 14.days.from_now, queue: 'transfer_user_data_queue').perform

      raise ActiveRecord::Rollback if user.status.nil?
    rescue Exception => e
      raise ActiveRecord::Rollback
    end
end

...

Body:
That code isn't doing what you expect it to do.

This part:

TransferUserDataJob.new(old_user, new_user).delay(run_at: 14.days.from_now, queue: 'transfer_user_data_queue').perform

Will schedule that job to performed by a separate process, typically on a separate server. So, it won't run in the context of your transaction.

Instead, you need to go into your TransferUserDataJob class and place that transaction inside the perform method.


问:
WSO2 Identity Server 5.0.0 Api for session management
Does WSO2 Identity Server has api for session management?

I have an app with SAML SSO.
What I would like to achieve is to check if for given saml token there is an active session.

答:
Validity of the SAML token has nothing to do with validity of the user session.

In theory - when user does "logout", the identity server should execute SLO (single logout), however based on our experience with WSO2IS 5.0.0 it works only for limited number of options.

Since version 5.2.0 there's OpenID Connect Session Management implemented using iframes, see http://malithiedirisinghe.blogspot.be/2016/03/openid-connect-session-management.html

But generally - you will have hard time to synchronize session between multiple service providers and WSO2 IS. With the claim based authentication (SAML, OAuth 2.0) the sessions between the IdP and SP are independent. (the only option I've see when the IdP is working as the pass-through-proxy for backend SP, but that's not what WSO2IS is intended for)

In version WSO2IS 5.3.0 there should be "user session management" implemented, but I haven't worked with that yet (managing session for WSO2IS, not external SPs)


问:
Calling C++ member functions with the thiscall convention
I have an application written in C++ that loads my DLL that is written in Delphi. The application calls an exported function of the DLL and passes it a pointer to an object of a class that has several member functions that I want to call from my Delphi DLL. I have written a Delphi class equivalent of the C++ class:

```<code>CClass = class
    procedure A(param : Integer); virtual; abstract;
    procedure B; virtual; abstract;
end
</code>```

and the C++ class looks the same

```<code>class CClass {
public:
    virtual void A(int) = 0;
    virtual void B() = 0;
};
</code>```

The member functions use the thiscall calling convention which does not have a Delphi equivalent. This probably means I need to use assembly. I have tried:

```<code>function exported_procedure(ptr : CClass) : Integer; cdecl;
begin
    asm
        push ebx;
        push esi;
        mov ecx, ptr;
        push 4;
        call CClass.A;
        pop esi;
        pop ebx;
    end;

    Result := 0;
end
</code>```

But I get a segmentation fault when the application calls this function. How do I properly call the member function?

答: The asm looks fine, that's how we call a thiscall interface. But this is a class. I don't think there's any reason to assume CClass.A actually calls void A(int). You'd have to figure out the correct offset. Having a Delphi class won't help I think: you should find out the offsets in C++, add that offset to ptr and call that address.</p>

Body:
I have an application written in C++ that loads my DLL that is written in Delphi. The application calls an exported function of the DLL and passes it a pointer to an object of a class that has several member functions that I want to call from my Delphi DLL. I have written a Delphi class equivalent of the C++ class:

CClass = class
    procedure A(param : Integer); virtual; abstract;
    procedure B; virtual; abstract;
end

and the C++ class looks the same

class CClass {
public:
    virtual void A(int) = 0;
    virtual void B() = 0;
};

The member functions use the thiscall calling convention which does not have a Delphi equivalent. This probably means I need to use assembly. I have tried:

function exported_procedure(ptr : CClass) : Integer; cdecl;
begin
    asm
        push ebx;
        push esi;
        mov ecx, ptr;
        push 4;
        call CClass.A;
        pop esi;
        pop ebx;
    end;

    Result := 0;
end

But I get a segmentation fault when the application calls this function. How do I properly call the member function?


问:
Find the differences between 2 Excel worksheets?
I have two excel files with the same structure:  they both have 1 column with data.  One has 800 records and the other has 805 records, but I am not sure which of the 5 in the 805 set are not in the 800 set.  Can I find this out using Excel?</p>

答:
With just one column of data in each to compare a PivotTable may provide much more information. In the image below ColumnA is in Sheet1 (with a copy in Sheet2 for the sake of the image) and ColumnC in Sheet2. In each sheet a source flag has been added (Columns B and D in the image). The PT has been created with multiple consolidation ranges (Sheet1!$A$1:$B$15 and Sheet2!$C$1:$D$10):

The left hand numeric column shows what is present in Sheet1 (including q twice) and the right what in Sheet2 (again with duplicates – of c and d). d-l are in Sheet1 but not Sheet2 and w and z are in Sheet2 (excluding those there just for the image) but not Sheet1. Add display Show grand totals for columns and control totals would appear.


问:
Parsing Json from JSP response with jquery
I have this String response from a JSP:

```<code>{"status":"ok","tipo":"orden","ordenes":"[{"numero":"15056","fecha":"2006-03-28","proveedor":"101","codigo":"15","orden":"5","fepago":"2006-03-29","marca":"1","razon":"XXXXXXX","importe":"1500.0"}]"}
</code>```

When I try to parse this result to JSON, I receive this error:

```<code>Uncaught SyntaxError: Unexpected token n in JSON at position 44
</code>```

This is how I do stringify the JSON (no, I cannot use any JSON libraries):

String ordenObtenida = "{\"status\":\"ok\",\"tipo\":\"" + tipo + "\",\"ordenes\":\"[";
while (rs.next()) {
    hasRow = true;
    if (rs.getString("razon") != null) {
        razon = rs.getString("razon").replaceAll("\"", "").trim();
    }
    ordenObtenida += "{\"numero\":\"" + rs.getInt("numero") + "\",\"fecha\":\"" + rs.getDate("fecha") + "\",\"proveedor\":\"" + rs.getInt("proveedor") + "\","
        + "\"codigo\":\"" + rs.getInt("codigo") + "\",\"orden\":\"" + rs.getInt("orden") + "\",\"fepago\":\"" + rs.getDate("fepago") + "\",\"marca\":\"" + rs.getInt("marca") + "\","
        + "\"razon\":\"" + razon + "\",\"importe\":\"" + rs.getFloat("importe") + "\"},";
}
ordenObtenida = ordenObtenida.substring(0, ordenObtenida.length() - 1) + "]\"}";
```

<p>And this is how I parse it (with jQuery):</p>

<pre class="lang-js prettyprint-override"><code>$.ajax({
    type: 'POST',
    url: 'TraePorOrden.jsp',
    data: dato
}).success(function (msg) {
    var msg = $.trim(msg);
    //msg = JSON.stringify(msg);
    var js = $.parseJSON(msg);
});
</code>```

If I uncomment the line msg = JSON.stringify(msg);, the JSON parses correctly but all the attributes are undefined.

Please advise.

答:
The response coming from your JSP is not a valid JSON, first of all.
You are including quotes around ordenes array, it should be like this:

```<code>{
  "status": "ok",
  "tipo": "orden",
  "ordenes": [
    {
      "numero": "15056",
      "fecha": "2006-03-28",
      "proveedor": "101",
      "codigo": "15",
      "orden": "5",
      "fepago": "2006-03-29",
      "marca": "1",
      "razon": "XXXXXXX",
      "importe": "1500.0"
    }
  ]
}
</code>```

I'm not a specialist on Java but on the JSON making function, you're sending ordenes array as a string.

My suggestion for you is to don't do string concatenation and use a Java library for JSON creation. Also, try to remove the quotes around the array response, like below.

```<code>String ordenObtenida = "{\"status\":\"ok\",\"tipo\":\"" + tipo + "\",\"ordenes\":\[;
    while (rs.next()) {
        hasRow = true;
        if (rs.getString("razon") != null) {
            razon = rs.getString("razon").replaceAll("\"", "").trim();
        }
        ordenObtenida += "{\"numero\":\"" + rs.getInt("numero") + "\",\"fecha\":\"" + rs.getDate("fecha") + "\",\"proveedor\":\"" + rs.getInt("proveedor") + "\","
                + "\"codigo\":\"" + rs.getInt("codigo") + "\",\"orden\":\"" + rs.getInt("orden") + "\",\"fepago\":\"" + rs.getDate("fepago") + "\",\"marca\":\"" + rs.getInt("marca") + "\","
                + "\"razon\":\"" + razon + "\",\"importe\":\"" + rs.getFloat("importe") + "\"},";
    }
    ordenObtenida = ordenObtenida.substring(0, ordenObtenida.length() - 1) + "]\"}";
</code>```

Body:
I have this String response from a JSP:

{"status":"ok","tipo":"orden","ordenes":"[{"numero":"15056","fecha":"2006-03-28","proveedor":"101","codigo":"15","orden":"5","fepago":"2006-03-29","marca":"1","razon":"XXXXXXX","importe":"1500.0"}]"}

When I try to parse this result to JSON, I receive this error:

Uncaught SyntaxError: Unexpected token n in JSON at position 44

This is how I do stringify the JSON (no, I cannot use any JSON libraries):

String ordenObtenida = "{\"status\":\"ok\",\"tipo\":\"" + tipo + "\",\"ordenes\":\"[";
while (rs.next()) {
    hasRow = true;
    if (rs.getString("razon") != null) {
        razon = rs.getString("razon").replaceAll("\"", "").trim();
    }
    ordenObtenida += "{\"numero\":\"" + rs.getInt("numero") + "\",\"fecha\":\"" + rs.getDate("fecha") + "\",\"proveedor\":\"" + rs.getInt("proveedor") + "\","
        + "\"codigo\":\"" + rs.getInt("codigo") + "\",\"orden\":\"" + rs.getInt("orden") + "\",\"fepago\":\"" + rs.getDate("fepago") + "\",\"marca\":\"" + rs.getInt("marca") + "\","
        + "\"razon\":\"" + razon + "\",\"importe\":\"" + rs.getFloat("importe") + "\"},";
}
ordenObtenida = ordenObtenida.substring(0, ordenObtenida.length() - 1) + "]\"}";

And this is how I parse it (with jQuery):

$.ajax({
    type: 'POST',
    url: 'TraePorOrden.jsp',
    data: dato
}).success(function (msg) {
    var msg = $.trim(msg);
    //msg = JSON.stringify(msg);
    var js = $.parseJSON(msg);
});

If I uncomment the line msg = JSON.stringify(msg);, the JSON parses correctly but all the attributes are undefined.

Please advise.

Body:
The response coming from your JSP is not a valid JSON, first of all.
You are including quotes around ordenes array, it should be like this:

{
  "status": "ok",
  "tipo": "orden",
  "ordenes": [
    {
      "numero": "15056",
      "fecha": "2006-03-28",
      "proveedor": "101",
      "codigo": "15",
      "orden": "5",
      "fepago": "2006-03-29",
      "marca": "1",
      "razon": "XXXXXXX",
      "importe": "1500.0"
    }
  ]
}

I'm not a specialist on Java but on the JSON making function, you're sending ordenes array as a string.

My suggestion for you is to don't do string concatenation and use a Java library for JSON creation. Also, try to remove the quotes around the array response, like below.

String ordenObtenida = "{\"status\":\"ok\",\"tipo\":\"" + tipo + "\",\"ordenes\":\[;
    while (rs.next()) {
        hasRow = true;
        if (rs.getString("razon") != null) {
            razon = rs.getString("razon").replaceAll("\"", "").trim();
        }
        ordenObtenida += "{\"numero\":\"" + rs.getInt("numero") + "\",\"fecha\":\"" + rs.getDate("fecha") + "\",\"proveedor\":\"" + rs.getInt("proveedor") + "\","
                + "\"codigo\":\"" + rs.getInt("codigo") + "\",\"orden\":\"" + rs.getInt("orden") + "\",\"fepago\":\"" + rs.getDate("fepago") + "\",\"marca\":\"" + rs.getInt("marca") + "\","
                + "\"razon\":\"" + razon + "\",\"importe\":\"" + rs.getFloat("importe") + "\"},";
    }
    ordenObtenida = ordenObtenida.substring(0, ordenObtenida.length() - 1) + "]\"}";


问:
Where is "select#" coming from?
I am going over an assignment for class. I have messed around with the code the class provided. I understand pretty much everything, but this userAnswer += parseInt($("select#" + blank).val());
where is the select# coming from It doesn't make senses to me, but it seems like it has to be there because whenever I change anything it, the code breaks. Thank you for your time!

```<code><!DOCTYPE html>
<html>
  <head>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/style.css" rel="stylesheet" type="text/css">
    <script src="js/jquery-3.2.0.js"></script>
    <script src="js/scripts.js"></script>
    <title>Vacation</title>
  </head>
  <body>
    <div class="jumbotron">
      <h1>Vacation's All I Ever Wanted</h1>
    </div>
    <div class="container">
      <div id="vaca">
      <br>
      <p>Not sure where you should go on your next vacation? Well hopefully this quiz will help! All languages must take Intro and Javascript :(</p>
      <hr>
      <div id="blanks">
        <form>
          <div class="form-group">
            <label for="fun">What do you like to do for fun while traveling?</label>
            <select class="form-control" id="fun">
              <option value="3">Going to latest hipster cafe's</option>
              <option value="2">Eating street food</option>
              <option value="1">Skiing</option>
              <option value="2">Explore the jungle</option>
            </select>
          </div>
          <div class="form-group">
            <label for="weather">What is your idea of perfect weather?</label>
            <select class="form-control" id="weather">
              <option value="1">Snow</option>
              <option value="2">Hot and humid</option>
              <option value="1">Cold</option>
              <option value="3">Sunny and perfect weather year round</option>
            </select>
          </div>
          <div class="form-group">
            <label for="food">What kind of food do you like?</label>
            <select class="form-control" id="food">
              <option value="3">Mexican</option>
              <option value="2">Thai</option>
              <option value="1">Scandinavian</option>
            </select>
          </div>
          <div class="form-group">
            <label for="language">How important is it that the place location English?</label>
            <select class="form-control" id="language">
              <option value="2">Not important</option>
              <option value="1">Somewhat important</option>
              <option value="3">Very</option>
            </select>
          </div>
          <div class="form-group">
            <label for="music">What kind of music do you like?</label>
            <select class="form-control" id="music">
              <option value="3">Everything</option>
              <option value="2">World</option>
              <option value="1">Folk</option>
            </select>
          </div>
          <br>
          <button type="submit" class="btn inthemiddle">Tell me where to go</button>
        </form>
        <hr>
      </div>
    </div>
      <div id="thai">
        <br>
        <button id="redoThai" type="button" class="btn inthemiddle">Try again</button>
        <hr>
        <h2>Miss Cleo says to go here</h2>
        <div class="row">
          <div class="col-lg-12">
            <h3>Thailand</h3>
            <p>You should go to Thailand where they have delicious and cheap street food. The language barrier and weather will not be an issue for you</p>
          </div>
        </div>
      </div>
      <div id="la">
        <br>
        <button id="redoLa" type="button" class="btn inthemiddle">Try again</button>
        <hr>
        <h2>Miss Cleo says to go here:</h2>
        <div class="row">
          <div class="col-lg-12">
            <h3>Los Angeles, California USA</h3>
            <p>You should go to sunny Los Angeles where the weather is always amazing and you can experience some of the best $1 Tacos. LA is a fantasic place for music, you will find that the music scene is very diverse.</p>
          </div>
        </div>
      </div>
      <div id="scand">
        <br>
        <button id="redoScand" type="button" class="btn inthemiddle">Try again</button>
        <hr>
        <h2>Miss Cleo says to go here:</h2>
        <div class="row">
          <div class="col-lg-12">
            <h3>Any Scandavian Country</h3>
            <p>You should go to any Scandavian country. You will enjoy the weather, outdoors activities, and food!</p>
          </div>
        </div>
      </div>
      <div id="none">
        <br>
        <button id="redoNone" type="button" class="btn inthemiddle">Try again</button>
        <hr>
        <h2>Miss Cleo says to go nowhere:</h2>
        <div class="row">
          <div class="col-lg-12">
            <h3>None</h3>
            <p>Miss Cleo can tell that you don't like to travel so just stay home</p>
            <img src="img/rapper.jpg">
          </div>
        </div>
      </div>
    </div>
  </body>
</html>
</code>```

JS

```<code>$(document).ready(function() {
  $("#blanks form").submit(function(event) {
    var topics = ["fun", "food", "music", "language", "weather"];
    var userAnswer = 0;

    topics.forEach(function(blank) {
      userAnswer += parseInt($("select#" + blank).val());
    });

    if (userAnswer <= 5) {
      $("#scand").show();
      $("#vaca").hide();
    }
    else if (userAnswer === 6 || userAnswer >= 8 && userAnswer <= 10) {
      $("#thai").show();
      $("#vaca").hide();
    }
    else if (userAnswer === 11 || userAnswer >= 13) {
      $("#la").show();
      $("#vaca").hide();
    }
    else if (userAnswer === 7 || userAnswer === 12) {
      $("#none").show();
      $("#vaca").hide();
    }

  $("#redoThai").click(function() {
    location.reload();
  });

  $("#redoLa").click(function() {
    location.reload();
  });

  $("#redoScand").click(function() {
    location.reload();
  });

  $("#redoNone").click(function() {
    location.reload();
  });

  event.preventDefault();

  });
});
</code>```

答:
select is a DOM element. # indicates that we're looking for a select with a given id attribute. The blank after this selector is simply the concatenation of the string and variable. Together, it creates a single selector.

Example:

```<code>// Javascript
var blank = "theid";
var obj = $("select#" + blank);

// HTML
<select id="theid"></select>
</code>```

Your script is doing this so it can select a variable select element based on an ID that corresponds with the variable blank.

This is a fairly basic concept, so I highly recommend reading the jQuery Selector Docs and CSS Selectors to learn more about how this all works.

Title: Where is "select#" coming from?

Body:
I am going over an assignment for class. I have messed around with the code the class provided. I understand pretty much everything, but this userAnswer += parseInt($("select#" + blank).val());
where is the select# coming from It doesn't make senses to me, but it seems like it has to be there because whenever I change anything it, the code breaks. Thank you for your time!

<!DOCTYPE html>

    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/style.css" rel="stylesheet" type="text/css">

    <title>Vacation</title>

Vacation's All I Ever Wanted

Not sure where you should go on your next vacation? Well hopefully this quiz will help! All languages must take Intro and Javascript :(

        <form>

            What do you like to do for fun while traveling?
            <select class="form-control" id="fun">
              <option value="3">Going to latest hipster cafe's</option>
              <option value="2">Eating street food</option>
              <option value="1">Skiing</option>
              <option value="2">Explore the jungle</option>
            </select>

            What is your idea of perfect weather?
            <select class="form-control" id="weather">
              <option value="1">Snow</option>
              <option value="2">Hot and humid</option>
              <option value="1">Cold</option>
              <option value="3">Sunny and perfect weather year round</option>
            </select>

            What kind of food do you like?
            <select class="form-control" id="food">
              <option value="3">Mexican</option>
              <option value="2">Thai</option>
              <option value="1">Scandinavian</option>
            </select>

            How important is it that the place location English?
            <select class="form-control" id="language">
              <option value="2">Not important</option>
              <option value="1">Somewhat important</option>
              <option value="3">Very</option>
            </select>

            What kind of music do you like?
            <select class="form-control" id="music">
              <option value="3">Everything</option>
              <option value="2">World</option>
              <option value="1">Folk</option>
            </select>

          <button type="submit" class="btn inthemiddle">Tell me where to go</button>
        </form>

        <button id="redoThai" type="button" class="btn inthemiddle">Try again</button>

Miss Cleo says to go here

Thailand

You should go to Thailand where they have delicious and cheap street food. The language barrier and weather will not be an issue for you

        <button id="redoLa" type="button" class="btn inthemiddle">Try again</button>

Miss Cleo says to go here:

Los Angeles, California USA

You should go to sunny Los Angeles where the weather is always amazing and you can experience some of the best $1 Tacos. LA is a fantasic place for music, you will find that the music scene is very diverse.

        <button id="redoScand" type="button" class="btn inthemiddle">Try again</button>

Miss Cleo says to go here:

Any Scandavian Country

You should go to any Scandavian country. You will enjoy the weather, outdoors activities, and food!

        <button id="redoNone" type="button" class="btn inthemiddle">Try again</button>

Miss Cleo says to go nowhere:

None

Miss Cleo can tell that you don't like to travel so just stay home

JS

$(document).ready(function() {
  $("#blanks form").submit(function(event) {
    var topics = ["fun", "food", "music", "language", "weather"];
    var userAnswer = 0;

    topics.forEach(function(blank) {
      userAnswer += parseInt($("select#" + blank).val());
    });

    if (userAnswer <= 5) {
      $("#scand").show();
      $("#vaca").hide();
    }
    else if (userAnswer === 6 || userAnswer >= 8 && userAnswer <= 10) {
      $("#thai").show();
      $("#vaca").hide();
    }
    else if (userAnswer === 11 || userAnswer >= 13) {
      $("#la").show();
      $("#vaca").hide();
    }
    else if (userAnswer === 7 || userAnswer === 12) {
      $("#none").show();
      $("#vaca").hide();
    }

  $("#redoThai").click(function() {
    location.reload();
  });

  $("#redoLa").click(function() {
    location.reload();
  });

  $("#redoScand").click(function() {
    location.reload();
  });

  $("#redoNone").click(function() {
    location.reload();
  });

  event.preventDefault();

  });
});

Body:
select is a DOM element. # indicates that we're looking for a select with a given id attribute. The blank after this selector is simply the concatenation of the string and variable. Together, it creates a single selector.

Example:

// Javascript
var blank = "theid";
var obj = $("select#" + blank);

// HTML
<select id="theid"></select>

Your script is doing this so it can select a variable select element based on an ID that corresponds with the variable blank.

This is a fairly basic concept, so I highly recommend reading the jQuery Selector Docs and CSS Selectors to learn more about how this all works.


问:
Convert a list of objects to an xml string
Hello I have a list of object i want to convert into an xml. Here is what the final xml should look like.

```<code><ArrayOfTweet>
    <Tweet>
        <Photos>
            <Photo>
                <PhotoHeight>FOO</PhotoHeight>
                <PhotoUri>a/random/ur/path</PhotoUri>
                <PhotoWidth>923</PhotoWidth>
                <SourcePhotoUri>a/random/path</SourcePhotoUri>
            </Photo>
        </Photos>
        <ProfileImage>a/random/path</ProfileImage>
        <ScreenName>FOO</ScreenName>
        <Text>some text</Text>
        <TweetId>1234</TweetId>
        <UserId>1234</UserId>
        <Username>BAR</Username>
    </Tweet>
    <Tweet>
        <Photos>
            <Photo>
                <PhotoHeight>FOO</PhotoHeight>
                <PhotoUri>a/random/ur/path</PhotoUri>
                <PhotoWidth>923</PhotoWidth>
                <SourcePhotoUri>a/random/path</SourcePhotoUri>
            </Photo>
        </Photos>
        <ProfileImage>a/random/path</ProfileImage>
        <ScreenName>FOO</ScreenName>
        <Text>some text</Text>
        <TweetId>1234</TweetId>
        <UserId>1234</UserId>
        <Username>BAR</Username>
    </Tweet>
</ArrayOfTweet>
</code>```

I have converted each of the objects in the list into an xml string like so

```<code>//TweetList is the list of tweet objects

List<string> xmlStringTweetList = new List<string>();
foreach (var tl in TweetList)
{
    xmlStringTweetList.Add(toXML(tl));
}

private string toXML(Tweet t)
{
    var stringwriter = new System.IO.StringWriter();
    var serializer = new XmlSerializer(t.GetType());
    serializer.Serialize(stringwriter, t);
    return stringwriter.ToString();
}
</code>```

I tried converting that list into the format above using

```<code>XElement xmlElements = new XElement("ArrayOfTweet", xmlStringTweetList.Select(i => new XElement("Tweet", i)));
</code>```

But there is the extra <Tweet></Tweet>  That i dont need. Is there a way of doing this?

答: I think XElement xmlElements = new XElement("ArrayOfTweet", xmlStringTweetList.Select(i => XElement.Parse(i))); should do.

Body:
Hello I have a list of object i want to convert into an xml. Here is what the final xml should look like.

<ArrayOfTweet>
    <Tweet>
        <Photos>
            <Photo>
                <PhotoHeight>FOO</PhotoHeight>
                <PhotoUri>a/random/ur/path</PhotoUri>
                <PhotoWidth>923</PhotoWidth>
                <SourcePhotoUri>a/random/path</SourcePhotoUri>
            </Photo>
        </Photos>
        <ProfileImage>a/random/path</ProfileImage>
        <ScreenName>FOO</ScreenName>
        <Text>some text</Text>
        <TweetId>1234</TweetId>
        <UserId>1234</UserId>
        <Username>BAR</Username>
    </Tweet>
    <Tweet>
        <Photos>
            <Photo>
                <PhotoHeight>FOO</PhotoHeight>
                <PhotoUri>a/random/ur/path</PhotoUri>
                <PhotoWidth>923</PhotoWidth>
                <SourcePhotoUri>a/random/path</SourcePhotoUri>
            </Photo>
        </Photos>
        <ProfileImage>a/random/path</ProfileImage>
        <ScreenName>FOO</ScreenName>
        <Text>some text</Text>
        <TweetId>1234</TweetId>
        <UserId>1234</UserId>
        <Username>BAR</Username>
    </Tweet>
</ArrayOfTweet>

I have converted each of the objects in the list into an xml string like so

//TweetList is the list of tweet objects

List<string> xmlStringTweetList = new List<string>();
foreach (var tl in TweetList)
{
    xmlStringTweetList.Add(toXML(tl));
}

private string toXML(Tweet t)
{
    var stringwriter = new System.IO.StringWriter();
    var serializer = new XmlSerializer(t.GetType());
    serializer.Serialize(stringwriter, t);
    return stringwriter.ToString();
}

I tried converting that list into the format above using

XElement xmlElements = new XElement("ArrayOfTweet", xmlStringTweetList.Select(i => new XElement("Tweet", i)));

But there is the extra <Tweet></Tweet>  That i dont need. Is there a way of doing this?


问:
Button with handler and bound tag attributes
I want to define in a jsviews template a button that have both click handler and data bound property.

Assuming I have this data:

```<code>var data = {
    Enable : true,
    DisplayName : "foo",
    SomeData : 42
};
</code>```

This helpers :

```<code>var handlers = {
    fooClicked : function(data, evt) {
        console.log(arguments);
    }
};
</code>```

How to add a button in my template to plumb the event handler and the properties of the button ?

I tried :

<button data-link="{on ~onAvailabilityClick SomeData disabled:^{!Enable}}">
     {^{>DisplayName}}
</button>

<button data-link="{on ~onAvailabilityClick SomeData} disabled:^{!Enable}">
     {^{>DisplayName}}
</button>

{^{on ~onAvailabilityClick SomeData}}<button data-link="disabled:^{!Enable}">
     {^{>DisplayName}}
</button>{{/on}}

But none of these works (either template syntax error or incomplete button, like having no text, or no handler).

I'm using jsViews 0.98.4.

PS: I don't know if it matters, but actually, my template is fed within a for loop, for an deep object structure.

答:
You can find documentation on setting multiple data-link bindings, and other related topics here:

http://www.jsviews.com/#linked-elem-syntax@fullsyntax

http://www.jsviews.com/#link-elemattribs

http://www.jsviews.com/#link-tags

http://www.jsviews.com/#link-events

In your case, you need to write

```<code><button data-link="disabled{:!Enable} {on ~onAvailabilityClick SomeData}">
     {^{>DisplayName}}
</button>
</code>```

or if you prefer:

```<code><button
  data-link="disabled{:!Enable} {on ~onAvailabilityClick SomeData} {:DisplayName}">
</button>
</code>```

Body:
I want to define in a jsviews template a button that have both click handler and data bound property.

Assuming I have this data:

var data = {
    Enable : true,
    DisplayName : "foo",
    SomeData : 42
};

This helpers :

var handlers = {
    fooClicked : function(data, evt) {
        console.log(arguments);
    }
};

How to add a button in my template to plumb the event handler and the properties of the button ?

I tried :

<button data-link="{on ~onAvailabilityClick SomeData disabled:^{!Enable}}">
     {^{>DisplayName}}
</button>

<button data-link="{on ~onAvailabilityClick SomeData} disabled:^{!Enable}">
     {^{>DisplayName}}
</button>

{^{on ~onAvailabilityClick SomeData}}<button data-link="disabled:^{!Enable}">
     {^{>DisplayName}}
</button>{{/on}}

But none of these works (either template syntax error or incomplete button, like having no text, or no handler).

I'm using jsViews 0.98.4.

PS: I don't know if it matters, but actually, my template is fed within a for loop, for an deep object structure.

Body:
You can find documentation on setting multiple data-link bindings, and other related topics here:

http://www.jsviews.com/#linked-elem-syntax@fullsyntax

http://www.jsviews.com/#link-elemattribs

http://www.jsviews.com/#link-tags

http://www.jsviews.com/#link-events

In your case, you need to write

<button data-link="disabled{:!Enable} {on ~onAvailabilityClick SomeData}">
     {^{>DisplayName}}
</button>

or if you prefer:

<button
  data-link="disabled{:!Enable} {on ~onAvailabilityClick SomeData} {:DisplayName}">
</button>


答:
TeX syntax is very complex, and it's very hard to predict if it will compile successfully. I'm not aware of any previewers that try it.

Instead, they try to compile the source. If it fails, they quit and keep the previously-generated PDF. After some input, they try again.
Or, they allow the user to trigger rendering with a key shortcut.

Some things you may or may not want to be aware of: QTeXEngine; KLFBackend; and PyLaTeX.

Title: Checking TeX syntax

Body:
so I'm currently working on a little application which basically consists of an editor and a preview. One writes LaTeX in the editor and the idea is that you get a live preview while you type. Like here in stackoverflow.
For doing that, I have to compile the TeX input at some point (because I need an image/pdf for displaying a preview) and since it isn't just some normal text, I better do it while there won't be any compiling errors.

So my question is: Using PyQT5, can I somehow keep checking the syntax and somehow know when the current Tex input could be compiled successfully?


问:
How to prevent attacks on WordPress wp-login.php page
On my website, the highest GPU usage is actually on the WordPress login page, not the home page. I have basically come to the conclusion that it is being attacked by a brute force attack, or something similar.

I have installed a plugin that prevents password attacks from bots, but it doesn't prevent the bots from actually visiting the page in the first place.

I want to change the location of the login page to something like wp-login-here.php, or perhaps there is a better solution. The Stealth Plugin seems like it would do the trick, but it is not compatible with recent versions of WordPress. Any ideas?

EDIT: The real solution to this problem was for me to do a clean install of WordPress, this time in a version that was supported by the Stealth plugin. After installing WP and the Stealth plugin on this earlier version of WP, I used the .htaccess file that the plugin created and copied it over (after making a few modifications) to the production site. The reason I accepted the answer I did was because Bad Behavior ended up being a good plugin, and the other advice was useful.

答: create a .htaccess rule for the wp-admin directory and set it to either a set list of IP's or a user/pass combo. You don't want to start hacking wordpress if you can avoid it as the next upgrade will just undo your changes, and setting it at the Apache .htaccess level will be a lot more effective than trying to patch wordpress.</p>


问:
PHP var and javascript function
I have a PHP var with a multidimensional array. I want to access that var in a javascript function and iterate over an element of the array (belongs_to). How can I do this?

This is the php var:

```<code><?php

    $q1 =[1=>['old_id'=>1,'belongs_to'=>null],
          2=>['old_id'=>2,'belongs_to'=>null],
          3=>['old_id'=>3,'belongs_to'=>null],
          4=>['old_id'=>4,'belongs_to'=>null],
          5=>['old_id'=>5,'belongs_to'=>null],
          6=>['old_id'=>6,'belongs_to'=>null];
          1030=>['id'=>1030,'belongs_to'=>1],
          1031=>['old_id'=>1031,'belongs_to'=>1],
          1032=>['old_id'=>1032,'belongs_to'=>2],
          1033=>['old_id'=>1033,'belongs_to'=>2];
?>
</code>```

答:
Php runs on server, javascript runs on browser. Because of this reason you can not reach the php variable from the javascript file.

The most easiest way to access your array is AJAX. You can write an ajax call from the script and server returns the json encoded php array.

After that you can use your php array in your script with decoding json to javascript object. To decoding encoded json to javascript array parseJSON() function.

Title: PHP var and javascript function

Body:
I have a PHP var with a multidimensional array. I want to access that var in a javascript function and iterate over an element of the array (belongs_to). How can I do this?

This is the php var:

<?php

    $q1 =[1=>['old_id'=>1,'belongs_to'=>null],
          2=>['old_id'=>2,'belongs_to'=>null],
          3=>['old_id'=>3,'belongs_to'=>null],
          4=>['old_id'=>4,'belongs_to'=>null],
          5=>['old_id'=>5,'belongs_to'=>null],
          6=>['old_id'=>6,'belongs_to'=>null];
          1030=>['id'=>1030,'belongs_to'=>1],
          1031=>['old_id'=>1031,'belongs_to'=>1],
          1032=>['old_id'=>1032,'belongs_to'=>2],
          1033=>['old_id'=>1033,'belongs_to'=>2];
?>


问:
smartgit compare remote repository with local repository before pull or push
I'm very new to using git so I'm probably just missing something simple here.  I have a remote repository (Bonobo, windows git) and a local repository.  There is only 1 branch called master.  I'm only working with 1 other developer, Bob.

Let's start with both Bob and I have smartgit (Windows client) and we have a test.txt file in our repos and in the remote origin repo.  The file is exactly the same.

Bob edits his local test file with "superduper", commits locally, and pushes.

I hit refresh, nothing changes, hm.. I wait a minute or two and a green arrow shows up.  OK great there is a change!

Now I view the log (right click on repo), no changes, no comments? I right click the rep and hit refresh, nothing. I log directly into the remote origin, yep, there are the changes "superduper".  I wait around for 10 minutes, my Journal area updates with the log of his commit changes "superduper" and can even see the actual change in the file compare view.  Great, it's all working!  But there seems to be a lot of waiting.

So, my 2 questions are:

1 - How can I make the little green arrow show up faster so I know the repo changed (or by manually forcing a check)

2 - How can I make the Journal update faster (or manually force) once I have the green arrow.  Sitting around for 10 minutes for the Journal to update so I can see the changed w/o pulling and overwriting seems like a long time.

Thank you very much for any input.

答:
Answer for both questions is pull. It will pull all new changes from remote to your local repository. Refresh looks only for changes made locally.

Since you are new to git, I think it is worth mentioning that pull comes in two forms: pull and fetch. Fetch looks for any new commits on the remote and brings them to your local repository, but it does not change your HEAD. Pull does two things: 1. Fetch, 2. look whether there are new commits in your current branch. If there are, it tries to incorporate those new commits with your local commits either with merge or with rebase. If you did not do any local commits, it just fast-forwards your current HEAD to the latest state came from the remote.

Note that green arrow occurs only when you did fetch (either manually or in background), it shows that there are new commits that you can pull.


问:
kafka streaming reading all data in the first batch itself
I have inserted 50 records in Kafka topic with 1 second latency between each record, so 50 records in 50+ seconds.

While consuming the records from this topic, as you can see in below code, i am keeping the batch interval to 1 second. So ideally i should be getting ~50 RDDs.
I am using foreachRDD to get the data in batches , and then process data for each RDD.
In below code, each time "call" method is called, i am counting records in each RDD. The surprising thing is that the first RDD itself is showing 50 records , and obviously subsequent RDD are showing 0 records.
I don't understand this behaviour, it should be ideally 1 record per RDD.

Can anyone suggest if my understanding is wrong?

JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, Durations.seconds(1));

```<code>messages.foreachRDD(new VoidFunction<JavaRDD<ConsumerRecord<K, String>>>() {
            public void call(JavaRDD<ConsumerRecord<K, V>> rdd) {
                System.out.println("NUmber of elements in RDD : "+ rdd.count());

                List<Row> rows = rdd.map(record -> processData(record))
                        .reduce((rows1, rows2) -> {
                            rows1.addAll(rows2);
                            return rows1;
                        });

                StructType schema = DataTypes.createStructType(fields);
                Dataset ds = ss.createDataFrame(rows, schema);
                ds.createOrReplaceTempView("trades");
                ds.show();
            }
        });
</code>```

答:
Spark Streaming uses "micro batching" that is, during the batch interval data arrives or is collected.

At each batch interval deadline, the data that arrived up to that moment is sent for processing to Spark. If when the streaming process starts, all data has already been received on Kafka, all that data will be processed at once in the first interval.

Eventual new data arriving after that moment will be processes in further intervals.

Body:
I have inserted 50 records in Kafka topic with 1 second latency between each record, so 50 records in 50+ seconds.

While consuming the records from this topic, as you can see in below code, i am keeping the batch interval to 1 second. So ideally i should be getting ~50 RDDs.
I am using foreachRDD to get the data in batches , and then process data for each RDD.
In below code, each time "call" method is called, i am counting records in each RDD. The surprising thing is that the first RDD itself is showing 50 records , and obviously subsequent RDD are showing 0 records.
I don't understand this behaviour, it should be ideally 1 record per RDD.

Can anyone suggest if my understanding is wrong?

JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, Durations.seconds(1));

messages.foreachRDD(new VoidFunction<JavaRDD<ConsumerRecord<K, String>>>() {
            public void call(JavaRDD<ConsumerRecord<K, V>> rdd) {
                System.out.println("NUmber of elements in RDD : "+ rdd.count());

                List<Row> rows = rdd.map(record -> processData(record))
                        .reduce((rows1, rows2) -> {
                            rows1.addAll(rows2);
                            return rows1;
                        });

                StructType schema = DataTypes.createStructType(fields);
                Dataset ds = ss.createDataFrame(rows, schema);
                ds.createOrReplaceTempView("trades");
                ds.show();
            }
        });


问:
How to get internal eslint plugins without the eslint-plugin-* prefix to work
I have finished making an internal eslint plugin, but unfortunately our company requires us to prefix all of our internal npm packages with companyName-. This is causing issues with eslint looking for packages with eslint-plugin- prefix since my package is prefixed with companyName-*.

in my .eslintrc I have

```<code>"plugins": [
  "react",
  "babel",
  "lodash",
  "companyName-eslint-plugin-projectName"
],
</code>```

eslint appends eslint-plugin to companyName-eslint-plugin-teamName and tries to look for eslint-plugin-companyName-eslint-plugin-teamName

is there anyway to bypass this in .eslintrc?

答: figured it out myself. You could set up an npm scope with your company name, and then publish the plugin under that scope: @companyName/eslint-plugin-something.</p>

Body:
I have finished making an internal eslint plugin, but unfortunately our company requires us to prefix all of our internal npm packages with companyName-. This is causing issues with eslint looking for packages with eslint-plugin- prefix since my package is prefixed with companyName-*.

in my .eslintrc I have

"plugins": [
  "react",
  "babel",
  "lodash",
  "companyName-eslint-plugin-projectName"
],

eslint appends eslint-plugin to companyName-eslint-plugin-teamName and tries to look for eslint-plugin-companyName-eslint-plugin-teamName

is there anyway to bypass this in .eslintrc?


问:
Java ASN.1 compiler
Right now I'm using BinaryNotes to parse ASN.1 files for use in a Java project. It takes an ASN.1 definition and produces Java class(s) that let me manipulate ASN.1 files.

I've hit a wall with extension markers (...) because it doesn't support them. The source forge project page says they're coming in the next release, but the last release was nearly 2 years ago so I fear the project is dead.

Can anyone recommend an easy (and $free) replacement that does a similar thing and does support extension markers?

答: Binary Notes is unsupported, but you can try jASN1 from OpenMuc. It appears to be based in part on Binary Notes and is currently active. The jASN1 libraries are available for download on their home page, and on JCenter and Maven Central under the group org.openmuc

Title: Java ASN.1 compiler


问:
Move Child Node to Parent Node On Condition
I have an xml file from which I need to move/copy specific child node which has trade item id like childA to parent node by creating an empty parent node.

Like  Input XML :

```<code><root>
<Payload>
        <TradeItemVersion>
            <TradeItemID>A</TradeItemID>
            <TradeItemTitle>B</TradeItemTitle>
            <ProductID>C</ProductID>
       <TradeItemVersion>
     <Child>
            <TradeItemID>ChildA</TradeItemID>
            <TradeItemTitle>Child</TradeItemTitle>
            <ProductID>Child</ProductID>
       <Child>
<Child>
            <TradeItemID>ChildB</TradeItemID>
            <TradeItemTitle>Child</TradeItemTitle>
            <ProductID>Child</ProductID>
       <Child>
<Payload>
<root>
</code>```

Final Output :

```<code><root>
<Payload>
<TradeItemVersion>
            <TradeItemID>ChildA</TradeItemID>
            <TradeItemTitle>Child</TradeItemTitle>
            <ProductID>Child</ProductID>
       <TradeItemVersion>
        <TradeItemVersion>
            <TradeItemID>A</TradeItemID>
            <TradeItemTitle>B</TradeItemTitle>
            <ProductID>C</ProductID>
       <TradeItemVersion>
<Child>
            <TradeItemID>ChildB</TradeItemID>
            <TradeItemTitle>Child</TradeItemTitle>
            <ProductID>Child</ProductID>
       <Child>

<Payload>
<root>
</code>```

I was able to copy child at top but all childs are getting copied and I am not able to select specific child, Also I couldn't create new empty parent tag to put child inside it.

My code is below :

```<code> <xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

<xsl:template match="node()|@*" name="identity">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="TradeItemVersion">
        <xsl:apply-templates mode="search"/>
        <xsl:call-template name="identity"/>
    </xsl:template>
    <xsl:template match="Child"/>
    <xsl:template match="Child" mode="search">
        <xsl:call-template name="identity"/>
    </xsl:template>
    <xsl:template match="text()" mode="search"/>

</xsl:stylesheet>
</code>```

Please suggest.

答:
I have found the answer myself after lots of hit and trial.

Following XSL would convert :

```<code>   <xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

<xsl:template match="node()|@*" name="identity">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="TradeItemVersion">
        <xsl:apply-templates mode="search"/>
        <xsl:call-template name="identity"/>
    </xsl:template>

<xsl:template match="Child"/>
    <xsl:template match="Child[contains(TradeItemID,'ChildA')]" mode="search">
        <TradeItemVersion>
<xsl:call-template name="identity"/>
</TradeItemVersion>
    </xsl:template>
    <xsl:template match="text()" mode="search"/>

</xsl:stylesheet>
</code>```

Input XML :

```<code><root>
<Payload>
        <TradeItemVersion>
            <TradeItemID>A</TradeItemID>
            <TradeItemTitle>B</TradeItemTitle>
            <ProductID>C</ProductID>

     <Child>
            <TradeItemID>ChildA</TradeItemID>
            <TradeItemTitle>Child</TradeItemTitle>
            <ProductID>Child</ProductID>
       </Child>
<Child>
            <TradeItemID>ChildB</TradeItemID>
            <TradeItemTitle>Child</TradeItemTitle>
            <ProductID>Child</ProductID>
       </Child>
</TradeItemVersion>
</Payload>
</root>
</code>```

Output XML :

```<code><root>
  <Payload>
    <TradeItemVersion>
      <Child>
        <TradeItemID>ChildA</TradeItemID>
        <TradeItemTitle>Child</TradeItemTitle>
        <ProductID>Child</ProductID>
      </Child>
    </TradeItemVersion>
    <TradeItemVersion>
      <TradeItemID>A</TradeItemID>
      <TradeItemTitle>B</TradeItemTitle>
      <ProductID>C</ProductID>
    </TradeItemVersion>
  </Payload>
</root>
</code>```

Body:
I have an xml file from which I need to move/copy specific child node which has trade item id like childA to parent node by creating an empty parent node.

Like  Input XML :

<root>
<Payload>
        <TradeItemVersion>
            <TradeItemID>A</TradeItemID>
            <TradeItemTitle>B</TradeItemTitle>
            <ProductID>C</ProductID>
       <TradeItemVersion>
     <Child>
            <TradeItemID>ChildA</TradeItemID>
            <TradeItemTitle>Child</TradeItemTitle>
            <ProductID>Child</ProductID>
       <Child>
<Child>
            <TradeItemID>ChildB</TradeItemID>
            <TradeItemTitle>Child</TradeItemTitle>
            <ProductID>Child</ProductID>
       <Child>
<Payload>
<root>

Final Output :

<root>
<Payload>
<TradeItemVersion>
            <TradeItemID>ChildA</TradeItemID>
            <TradeItemTitle>Child</TradeItemTitle>
            <ProductID>Child</ProductID>
       <TradeItemVersion>
        <TradeItemVersion>
            <TradeItemID>A</TradeItemID>
            <TradeItemTitle>B</TradeItemTitle>
            <ProductID>C</ProductID>
       <TradeItemVersion>
<Child>
            <TradeItemID>ChildB</TradeItemID>
            <TradeItemTitle>Child</TradeItemTitle>
            <ProductID>Child</ProductID>
       <Child>

<Payload>
<root>

I was able to copy child at top but all childs are getting copied and I am not able to select specific child, Also I couldn't create new empty parent tag to put child inside it.

My code is below :

 <xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

<xsl:template match="node()|@*" name="identity">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="TradeItemVersion">
        <xsl:apply-templates mode="search"/>
        <xsl:call-template name="identity"/>
    </xsl:template>
    <xsl:template match="Child"/>
    <xsl:template match="Child" mode="search">
        <xsl:call-template name="identity"/>
    </xsl:template>
    <xsl:template match="text()" mode="search"/>

</xsl:stylesheet>

Please suggest.

Body:
I have found the answer myself after lots of hit and trial.

Following XSL would convert :

   <xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

<xsl:template match="node()|@*" name="identity">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="TradeItemVersion">
        <xsl:apply-templates mode="search"/>
        <xsl:call-template name="identity"/>
    </xsl:template>

<xsl:template match="Child"/>
    <xsl:template match="Child[contains(TradeItemID,'ChildA')]" mode="search">
        <TradeItemVersion>
<xsl:call-template name="identity"/>
</TradeItemVersion>
    </xsl:template>
    <xsl:template match="text()" mode="search"/>

</xsl:stylesheet>

Input XML :

<root>
<Payload>
        <TradeItemVersion>
            <TradeItemID>A</TradeItemID>
            <TradeItemTitle>B</TradeItemTitle>
            <ProductID>C</ProductID>

     <Child>
            <TradeItemID>ChildA</TradeItemID>
            <TradeItemTitle>Child</TradeItemTitle>
            <ProductID>Child</ProductID>
       </Child>
<Child>
            <TradeItemID>ChildB</TradeItemID>
            <TradeItemTitle>Child</TradeItemTitle>
            <ProductID>Child</ProductID>
       </Child>
</TradeItemVersion>
</Payload>
</root>

Output XML :

<root>
  <Payload>
    <TradeItemVersion>
      <Child>
        <TradeItemID>ChildA</TradeItemID>
        <TradeItemTitle>Child</TradeItemTitle>
        <ProductID>Child</ProductID>
      </Child>
    </TradeItemVersion>
    <TradeItemVersion>
      <TradeItemID>A</TradeItemID>
      <TradeItemTitle>B</TradeItemTitle>
      <ProductID>C</ProductID>
    </TradeItemVersion>
  </Payload>
</root>


问:
Keras 2.0.3 compatibility
Is keras 2.0.3 (latest version) compatible with latest Anaconda version (4.3.1, python version 3.6) ? Or keras is only compatible with python 3.5, so I must choose older version of Anaconda?

EDIT: I have some problems when I use this method:

```<code>prediction = np_utils.categorical_probas_to_classes(prediction)
</code>```

Error: "keras.utilis.np_utilis" has no attribute "categorical_probas_to_classes"

Also I have other errors with keras's methods. So I thought that problem is python version, that is incompatible with keras's version

答:
if you used activation="softmax",
use:</p>

```<code>prediction = model.predict(x_test)
prediction = ***prediction.round(0)***
print(prediction[:15])
</code>```

Title: Keras 2.0.3 compatibility

Body:
Is keras 2.0.3 (latest version) compatible with latest Anaconda version (4.3.1, python version 3.6) ? Or keras is only compatible with python 3.5, so I must choose older version of Anaconda?

EDIT: I have some problems when I use this method:

prediction = np_utils.categorical_probas_to_classes(prediction)

Error: "keras.utilis.np_utilis" has no attribute "categorical_probas_to_classes"

Also I have other errors with keras's methods. So I thought that problem is python version, that is incompatible with keras's version

Body:
if you used activation="softmax",
use:

prediction = model.predict(x_test)
prediction = ***prediction.round(0)***
print(prediction[:15])


答:
You have 2 ways to do this.

The most straightforward would be to output that array in some format (preferably JSON) as the value of a hidden <input> in your HTML:

```<code><?php
   $q1 = [ /* stuff here */ ];
   $json = json_encode($q1);
   echo '<input id="arrayData" value="' . htmlentities($json) . '"/>';
</code>```

You can then read the value of that input, parse it, and then use it from the JavaScript side:

```<code>const q1 = JSON.parse(document.querySelector('#arrayData').value);
</code>```

Note the id of the input is the same as the selector in querySelector (though it can be any value).

The other method, which is cleaner but involves more work, is to create a new PHP endpoint that would return the array as JSON, then use one of the many AJAX methods to read it.

A code example would be a bit long, but there are plenty of examples of it out there.

Title: PHP var and javascript function

Body:
You have 2 ways to do this.

The most straightforward would be to output that array in some format (preferably JSON) as the value of a hidden <input> in your HTML:

<?php
   $q1 = [ /* stuff here */ ];
   $json = json_encode($q1);
   echo '<input id="arrayData" value="' . htmlentities($json) . '"/>';

You can then read the value of that input, parse it, and then use it from the JavaScript side:

const q1 = JSON.parse(document.querySelector('#arrayData').value);

Note the id of the input is the same as the selector in querySelector (though it can be any value).

The other method, which is cleaner but involves more work, is to create a new PHP endpoint that would return the array as JSON, then use one of the many AJAX methods to read it.

A code example would be a bit long, but there are plenty of examples of it out there.


问:
Why does a closure introduce a borrow when the same code inlined does not?
This code works:

```<code>extern crate num;

use num::{BigInt, FromPrimitive, Zero};

fn sample() {
    let mut to_factor = "600851475143".parse::<BigInt>().unwrap();

    let mut prime = BigInt::from_i32(2).unwrap();

    let zero = BigInt::zero();

    //let is_div = |n, p| { n % p == zero};

    loop {
        if &to_factor % &prime == zero {
            to_factor = &to_factor / ′
        } else {
            break;
        }
    }

    println!("{}", to_factor);
}
</code>```

but if I try to replace the condition in the loop with a closure, it doesn't compile anymore:

```<code>fn sample() {
    let mut to_factor = "600851475143".parse::<BigInt>().unwrap();

    let mut prime = BigInt::from_i32(2).unwrap();

    let zero = BigInt::zero();

    let is_div = |n, p| { n % p == zero};

    loop {
        if is_div(&to_factor, &prime) {
            to_factor = &to_factor / ′
        } else {
            break;
        }
    }

    println!("{}", to_factor);
}
</code>```

The error is as follows:

error[E0506]: cannot assign to `to_factor` because it is borrowed
  --> src/main.rs:16:13
   |
15 |         if is_div(&to_factor, &prime) {
   |                    --------- borrow of `to_factor` occurs here
16 |             to_factor = &to_factor / ′
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `to_factor` occurs here
```

<p>It seems fine to me -- the borrow should be "over" by the time we alter <code>to_factor</code>, certainly?</p>

<p>To increase the confusion, if I replace <code>is_div</code> with an actual function:</p>

```fn is_div(n: &BigInt, p: &BigInt) -> bool {
    return to_factor % p == BigInt::zero()
}
```

it works fine.

I am a beginner in Rust, but not to programming generally. I'm pretty sure this has to do with ownership, but it might also have to do with how closures are implemented?

These examples are a MWE from the actual code I was trying to write. They're not really meaningful at this point but they demonstrate the same compile error.

答:
As you've written it, the is_div closure does not borrow to_factor, it takes it forever.  If you change the closure signature to borrow to_factor it works.

```<code>let is_div = |&n, p| { n % p == zero};
</code>```

Can't use crates on the playground but this illustrates it.

```<code>fn main() {
    let mut to_factor = "654684234".parse::<i32>().unwrap();

    let prime = 2;

    let zero = 0;

    let is_div = |&n, p| n % p == zero;

    loop {
        if is_div(&to_factor, &prime) {
            to_factor = &to_factor / ′
        } else {
            break;
        }
    }

    println!("{}", to_factor);
}
</code>```

Body:
This code works:

extern crate num;

use num::{BigInt, FromPrimitive, Zero};

fn sample() {
    let mut to_factor = "600851475143".parse::<BigInt>().unwrap();

    let mut prime = BigInt::from_i32(2).unwrap();

    let zero = BigInt::zero();

    //let is_div = |n, p| { n % p == zero};

    loop {
        if &to_factor % &prime == zero {
            to_factor = &to_factor / ′
        } else {
            break;
        }
    }

    println!("{}", to_factor);
}

but if I try to replace the condition in the loop with a closure, it doesn't compile anymore:

fn sample() {
    let mut to_factor = "600851475143".parse::<BigInt>().unwrap();

    let mut prime = BigInt::from_i32(2).unwrap();

    let zero = BigInt::zero();

    let is_div = |n, p| { n % p == zero};

    loop {
        if is_div(&to_factor, &prime) {
            to_factor = &to_factor / ′
        } else {
            break;
        }
    }

    println!("{}", to_factor);
}

The error is as follows:

error[E0506]: cannot assign to `to_factor` because it is borrowed
  --> src/main.rs:16:13
   |
15 |         if is_div(&to_factor, &prime) {
   |                    --------- borrow of `to_factor` occurs here
16 |             to_factor = &to_factor / ′
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `to_factor` occurs here

It seems fine to me -- the borrow should be "over" by the time we alter to_factor, certainly?

To increase the confusion, if I replace is_div with an actual function:

fn is_div(n: &BigInt, p: &BigInt) -> bool {
    return to_factor % p == BigInt::zero()
}

it works fine.

I am a beginner in Rust, but not to programming generally. I'm pretty sure this has to do with ownership, but it might also have to do with how closures are implemented?

These examples are a MWE from the actual code I was trying to write. They're not really meaningful at this point but they demonstrate the same compile error.

Body:
As you've written it, the is_div closure does not borrow to_factor, it takes it forever.  If you change the closure signature to borrow to_factor it works.

let is_div = |&n, p| { n % p == zero};

Can't use crates on the playground but this illustrates it.

fn main() {
    let mut to_factor = "654684234".parse::<i32>().unwrap();

    let prime = 2;

    let zero = 0;

    let is_div = |&n, p| n % p == zero;

    loop {
        if is_div(&to_factor, &prime) {
            to_factor = &to_factor / &prime;
        } else {
            break;
        }
    }

    println!("{}", to_factor);
}


问:
How to include resource files like css and js files in jhipster's angular app?
I have been trying to include resource files in my jhipster angular 2 app but stuck in the issue for 3 days. So far i have found, angular 2 is webpack based configured in this app. i tried implementing through angular-cli.json and vendor.ts too. i even tried to include the files in index.html file. unfortunately, there's no any change in my dumb app. Responses are appreciable. Thanks!</p>

答:
Assuming you are running a working setup and launched hot reloader using yarn start, there are several use cases to include "assets", as CSS/JS

a global stylesheet

All global stylesheets can be placed in the file global.(s)css and changes immediately trigger a hot reload.

a component stylesheet

You might want to give a certain angular component a stylesheet, which is encapsulated to that component. Then you add a some.component.css (or scss) next to some.component.ts and embed it this way:

```<code>@Component({
    selector: 'jhi-some-component',
    templateUrl: './some.component.html',
    styleUrls: [
        'some.component.scss'
    ]
})
export class SomeComponent
//...
</code>```

as global styles, component styles trigger a hot reload on change.

vendor stylesheets

you can place them into vendor.(s)css. To make changes to that file take effect, a restart of the yarn start is needed

assets in general

Webpack tries to resolve all mentioned assets relatively to their files to include them. That way you can use any asset you want. If Webpack will have problems to resolve any asset, it will let you know that.

You mentioned also JS, but I don't get the sense of using JS resource, as Typescript is used in the angular client.

Body:
Assuming you are running a working setup and launched hot reloader using yarn start, there are several use cases to include "assets", as CSS/JS

a global stylesheet

All global stylesheets can be placed in the file global.(s)css and changes immediately trigger a hot reload.

a component stylesheet

You might want to give a certain angular component a stylesheet, which is encapsulated to that component. Then you add a some.component.css (or scss) next to some.component.ts and embed it this way:

@Component({
    selector: 'jhi-some-component',
    templateUrl: './some.component.html',
    styleUrls: [
        'some.component.scss'
    ]
})
export class SomeComponent
//...

as global styles, component styles trigger a hot reload on change.

vendor stylesheets

you can place them into vendor.(s)css. To make changes to that file take effect, a restart of the yarn start is needed

assets in general

Webpack tries to resolve all mentioned assets relatively to their files to include them. That way you can use any asset you want. If Webpack will have problems to resolve any asset, it will let you know that.

You mentioned also JS, but I don't get the sense of using JS resource, as Typescript is used in the angular client.


问:
Doctrine and composite unique keys
I want to do composite unique key in doctrine.
Those are my fields:

/**
 * @var string $videoDimension
 *
 * @Column(name="video_dimension", type="string", nullable=false)
 */
private $videoDimension;

/**
 * @var string $videoBitrate
 *
 * @Column(name="video_bitrate", type="string", nullable=false)
 */
private $videoBitrate;
```

How can I show doctrine, that those combined together are composite unique key?

答:
I know this is an old question, but I came across it while looking for a way to create composite PK and thought it could use some update.

Things are actually much simpler if what you need is a Composite Primary Key. (Which, of course, guarantees uniqueness) Doctrine documentation contains some nice examples by this url: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/composite-primary-keys.html

So the original example could look something like this:

```<code>/**
 * @var string $videoDimension
 *
 * @ORM\Id @ORM\Column(type="string")
 */
private $videoDimension;

/**
 * @var string $videoBitrate
 *
 * @ORM\Id @ORM\Column(type="string")
 */
private $videoBitrate;
</code>```

A few notes here:

Column "name" is omitted since Doctrine is able to guess it based on
the property name

Since videoDimension and videoBitrate are both parts of the PK - there is no need to specify nullable = false

If required - the Composite PK may be composed of foreign keys, so feel free to add some relational mappings

Title: Doctrine and composite unique keys

Body:
I want to do composite unique key in doctrine.
Those are my fields:

/**
 * @var string $videoDimension
 *
 * @Column(name="video_dimension", type="string", nullable=false)
 */
private $videoDimension;

/**
 * @var string $videoBitrate
 *
 * @Column(name="video_bitrate", type="string", nullable=false)
 */
private $videoBitrate;

How can I show doctrine, that those combined together are composite unique key?

Body:
I know this is an old question, but I came across it while looking for a way to create composite PK and thought it could use some update.

Things are actually much simpler if what you need is a Composite Primary Key. (Which, of course, guarantees uniqueness) Doctrine documentation contains some nice examples by this url: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/composite-primary-keys.html

So the original example could look something like this:

/**
 * @var string $videoDimension
 *
 * @ORM\Id @ORM\Column(type="string")
 */
private $videoDimension;

/**
 * @var string $videoBitrate
 *
 * @ORM\Id @ORM\Column(type="string")
 */
private $videoBitrate;

A few notes here:

Column "name" is omitted since Doctrine is able to guess it based on
the property name

Since videoDimension and videoBitrate are both parts of the PK - there is no need to specify nullable = false

If required - the Composite PK may be composed of foreign keys, so feel free to add some relational mappings


问:
Data encapsulation and security in Swift
I'm currently studying iOS development in Swift and came across the concept of data encapsulation and security. Let's start with an example:

```<code>Class Person {
    private var _weight: Int!

    var weight: Int {
        get {
            return _weight
        }
        set {
            _weight = newValue
        }
    }
}
</code>```

In the tutorial, I was taught to always make a private var for the purpose of security so the variable cannot be excessed externally and mutate the data. And the instructor also emphasized to explicitly set the getter and setter like above. Writing getter and setter seems very cumbersome to me and it seems like I only need to utilize getter and setter when they are needed. (i.e. getter could be used for read-only property and setter could be used for the purpose of Computed Property).

I wonder if I need to follow this practice all the time or whether I can simply define the property like following:

```<code>Class Person {
    var _weight: Int!
}
</code>```

答:
In Swift, you don't need to declare explicit getters and setters for all of your properties, unless you want to customize their behavior.

Most of the time, this will work just fine:

```<code>class Person {
    var weight: Int
}
</code>```

You can even make a variable read-only publicly, and read-write privately:

```<code>class Person {
    public private(set) var weight: Int
}
</code>```

Your instructor's example is useful when you want to customize the behavior of the getters and setters, for example lazily fetching the data from some external source:

```<code>class Person {
    private var _weight: Int!

    var weight: Int {
        get {
            if _weight == nil {
                //fetch _weight from somewhere
            }
            return _weight!
        }
        set {
            _weight = newValue
        }
    }
}
</code>```

Private variables are not a security feature. It's trivial to dump the memory of an object and extract private variables from that, and in many languages you can access them even more easily using features like reflection.

Rather, private variables are for encapsulation.  A variable being marked private means "This is an internal interface so do not use it.  If you do use it, it's not guaranteed to work, and even if it works now, it might not work in the future."  Private variables can also allow the compiler to perform some extra optimizations in some cases, since it knows that the variable will never be accessed anywhere except in this class declaration.

Body:
I'm currently studying iOS development in Swift and came across the concept of data encapsulation and security. Let's start with an example:

Class Person {
    private var _weight: Int!

    var weight: Int {
        get {
            return _weight
        }
        set {
            _weight = newValue
        }
    }
}

In the tutorial, I was taught to always make a private var for the purpose of security so the variable cannot be excessed externally and mutate the data. And the instructor also emphasized to explicitly set the getter and setter like above. Writing getter and setter seems very cumbersome to me and it seems like I only need to utilize getter and setter when they are needed. (i.e. getter could be used for read-only property and setter could be used for the purpose of Computed Property).

I wonder if I need to follow this practice all the time or whether I can simply define the property like following:

Class Person {
    var _weight: Int!
}

Body:
In Swift, you don't need to declare explicit getters and setters for all of your properties, unless you want to customize their behavior.

Most of the time, this will work just fine:

class Person {
    var weight: Int
}

You can even make a variable read-only publicly, and read-write privately:

class Person {
    public private(set) var weight: Int
}

Your instructor's example is useful when you want to customize the behavior of the getters and setters, for example lazily fetching the data from some external source:

class Person {
    private var _weight: Int!

    var weight: Int {
        get {
            if _weight == nil {
                //fetch _weight from somewhere
            }
            return _weight!
        }
        set {
            _weight = newValue
        }
    }
}

Private variables are not a security feature. It's trivial to dump the memory of an object and extract private variables from that, and in many languages you can access them even more easily using features like reflection.

Rather, private variables are for encapsulation.  A variable being marked private means "This is an internal interface so do not use it.  If you do use it, it's not guaranteed to work, and even if it works now, it might not work in the future."  Private variables can also allow the compiler to perform some extra optimizations in some cases, since it knows that the variable will never be accessed anywhere except in this class declaration.


问:
Autocomplete textbox freezes while executing query. Must be a better way!
everyone! I searched the best I could and did not find exactly the help I was looking for.

Problem

AutoCompleteTextbox FREEZES and "eats" characters while query is performed

Asking for

Mimic Google Instant functionality

Background

First things first: C#, WPF, .NET 4.0

Ok, now that's out of the way, I'm trying to find the best way to implement a dynamic AutoComplete Textbox, which queries a database for results after each letter typed.

The following code gets executed when the AutoCompleteTextBox's TextChanged event is fired:

```<code>    public void Execute(object sender, object parameter)
    {
        //removed some unnecessary code for the sake of being concise

        var autoCompleteBox = sender as AutoCompleteTextBox;
        var e = parameter as SearchTextEventArgs;

        var result = SearchUnderlyings(e.SearchText);

        autoCompleteBox.ItemsSource = result;
    }
</code>```

Now, let's say that SearchUnderlyings(e.SearchText) takes an average of 600-1100ms - during that time, the textbox is frozen and it "eats" any keys pressed. This is an annoying problem I've been having. For some reason, the LINQ in SearchUnderlyings(e.SearchText) is running in the GUI thread. I tried delegating this to a background thread, but still same result.

Ideally, I would like the textbox to work the way Google Instant does - but I don't want to be "killing" threads before the server/query can return a result.

Anyone have experience or can offer some guidance which will allow me to query as I type without freezing the GUI or killing the server?

Thank you guys!

答:
So, we kind of hacked something quick. By making the calls to SearchUnderlyings(e.SearchText) asynchronous, my GUI thread is no longer blocked and the textbox is no longer "eating" key presses. By adding the lastQueryTag == _lastQuery check, we are trying to ensure some thread-safety, allowing only the most recent query to set the ItemsSource.

Perhaps not the most ideal or elegant solution. I am still open to further critiques and suggestions. Thank you!

```<code>private long _lastQuery = DateTime.Now.Ticks;

public void Execute(object sender, object parameter)
{
    var autoCompleteBox = sender as AutoCompleteTextBox;
    var e = parameter as SearchTextEventArgs;

    // removed unecessary code for clarity

    long lastQueryTag = _lastQuery = DateTime.Now.Ticks;
    Task.Factory.StartNew(() =>
    {
        var result = SearchUnderlyings(e.SearchText);

         System.Windows.Application.Current.Dispatch(() =>
         {
             if (lastQueryTag == _lastQuery)
                  autoCompleteBox.ItemsSource = result;
         });
    });
}
</code>```

Body:
everyone! I searched the best I could and did not find exactly the help I was looking for.

Problem

AutoCompleteTextbox FREEZES and "eats" characters while query is performed

Asking for

Mimic Google Instant functionality

Background

First things first: C#, WPF, .NET 4.0

Ok, now that's out of the way, I'm trying to find the best way to implement a dynamic AutoComplete Textbox, which queries a database for results after each letter typed.

The following code gets executed when the AutoCompleteTextBox's TextChanged event is fired:

    public void Execute(object sender, object parameter)
    {
        //removed some unnecessary code for the sake of being concise

        var autoCompleteBox = sender as AutoCompleteTextBox;
        var e = parameter as SearchTextEventArgs;

        var result = SearchUnderlyings(e.SearchText);

        autoCompleteBox.ItemsSource = result;
    }

Now, let's say that SearchUnderlyings(e.SearchText) takes an average of 600-1100ms - during that time, the textbox is frozen and it "eats" any keys pressed. This is an annoying problem I've been having. For some reason, the LINQ in SearchUnderlyings(e.SearchText) is running in the GUI thread. I tried delegating this to a background thread, but still same result.

Ideally, I would like the textbox to work the way Google Instant does - but I don't want to be "killing" threads before the server/query can return a result.

Anyone have experience or can offer some guidance which will allow me to query as I type without freezing the GUI or killing the server?

Thank you guys!

Body:
So, we kind of hacked something quick. By making the calls to SearchUnderlyings(e.SearchText) asynchronous, my GUI thread is no longer blocked and the textbox is no longer "eating" key presses. By adding the lastQueryTag == _lastQuery check, we are trying to ensure some thread-safety, allowing only the most recent query to set the ItemsSource.

Perhaps not the most ideal or elegant solution. I am still open to further critiques and suggestions. Thank you!

private long _lastQuery = DateTime.Now.Ticks;

public void Execute(object sender, object parameter)
{
    var autoCompleteBox = sender as AutoCompleteTextBox;
    var e = parameter as SearchTextEventArgs;

    // removed unecessary code for clarity

    long lastQueryTag = _lastQuery = DateTime.Now.Ticks;
    Task.Factory.StartNew(() =>
    {
        var result = SearchUnderlyings(e.SearchText);

         System.Windows.Application.Current.Dispatch(() =>
         {
             if (lastQueryTag == _lastQuery)
                  autoCompleteBox.ItemsSource = result;
         });
    });
}


问:
Can Assets/Resoures be shared between iOS + Droid projects?
I have a Xamarin based Visual Studio 2015 project that has the following structure.

MyApp (Portable)
MyApp.Droid
MyApp.iOS

Currently I include assets / resources in the MyApp.Droid project and the MyApp.iOS project.

So for example myhtml.html is duplicated as both MyApp.Droid/Asserts/myhtml.html and MyApp.iOS/Resources/myhtml.html

Are there any ways I can avoid this duplication?

答:
Assuming you are using Xamarin Forms, yes, you can use .net resource files.

You can create a folder in the portable project, add there the content files and set the Compilation Action to Embedded Resource for all of those, then you can use the .net provided mechanism to acces the resources, per example (in this example I assume the code is being executed in a class contained in the portable project and the files are stored in a folder called ResourceFiles):

```<code>var htmlFile = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("MyNamespace.ResourceFiles.myhtml.html");
</code>```

In this way you have the stream with the file's content.

Also, as a hint, you can load these files from XAML using a custom markup extension, per example, here is a markup extension to load images from .net resources:

```<code>[ContentProperty ("Source")]
public class ImageResourceExtension : IMarkupExtension
{
    public string Source { get; set; }

    public object ProvideValue (IServiceProvider serviceProvider)
    {
        if (Source == null)
            return null;

        var imageSource = new StreamImageSource { Stream = async (ct) => this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream(Source) };

        return imageSource;
    }
}
</code>```

Then, to use this extension in XAML you will do (local is the XAML namespace definition of your own namespace):

```<code><Image Source="{local:ImageResource MyNamespace.ResourceFiles.MyImage.png}" />
</code>```

Body:
Assuming you are using Xamarin Forms, yes, you can use .net resource files.

You can create a folder in the portable project, add there the content files and set the Compilation Action to Embedded Resource for all of those, then you can use the .net provided mechanism to acces the resources, per example (in this example I assume the code is being executed in a class contained in the portable project and the files are stored in a folder called ResourceFiles):

var htmlFile = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("MyNamespace.ResourceFiles.myhtml.html");

In this way you have the stream with the file's content.

Also, as a hint, you can load these files from XAML using a custom markup extension, per example, here is a markup extension to load images from .net resources:

[ContentProperty ("Source")]
public class ImageResourceExtension : IMarkupExtension
{
    public string Source { get; set; }

    public object ProvideValue (IServiceProvider serviceProvider)
    {
        if (Source == null)
            return null;

        var imageSource = new StreamImageSource { Stream = async (ct) => this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream(Source) };

        return imageSource;
    }
}

Then, to use this extension in XAML you will do (local is the XAML namespace definition of your own namespace):

<Image Source="{local:ImageResource MyNamespace.ResourceFiles.MyImage.png}" />