问:
Conditional wont be read in do while statement
For my program I am trying to have the loop run until the letter n is entered. But for some reason i keep receiving the error cannot find symbol in the condition for my loop. All help is greatly appreciated. </p>

```<code>import java.io.*;
import java.util.*;
public class Prog213c
{
  public static void main(String[] args) {

        Scanner kbReader=new Scanner(System.in);

        do{
            System.out.println( "Enter student number");
            int studentNumber = kbReader.nextInt();
            System.out.println(" Enter credits ");
            int credits = kbReader.nextInt();

            switch (credits)
            {
            case 30:
                System.out.println("Grade Level code = 2");
                break;
            case 29:
                System.out.println("Grade Level code = 1");
                break;
            case 70:
                System.out.println("Grade Level code = 3");
                break;
            case 103:
                System.out.println("Grade Level code = 4");
                break;

            default: System.out.println("invalid number");
            }
            System.out.print("Do again(y/n)");
            String answer = kbReader.next();
        } while (answer == 'y'); // error received here
</code>```

答:
Change your while condition to:</p>

```<code>while ("y".equals(kbReader.next()));
</code>```

Body:
For my program I am trying to have the loop run until the letter n is entered. But for some reason i keep receiving the error cannot find symbol in the condition for my loop. All help is greatly appreciated.

import java.io.*;
import java.util.*;
public class Prog213c
{
  public static void main(String[] args) {

        Scanner kbReader=new Scanner(System.in);

        do{
            System.out.println( "Enter student number");
            int studentNumber = kbReader.nextInt();
            System.out.println(" Enter credits ");
            int credits = kbReader.nextInt();

            switch (credits)
            {
            case 30:
                System.out.println("Grade Level code = 2");
                break;
            case 29:
                System.out.println("Grade Level code = 1");
                break;
            case 70:
                System.out.println("Grade Level code = 3");
                break;
            case 103:
                System.out.println("Grade Level code = 4");
                break;

            default: System.out.println("invalid number");
            }
            System.out.print("Do again(y/n)");
            String answer = kbReader.next();
        } while (answer == 'y'); // error received here

Body:
Change your while condition to:

while ("y".equals(kbReader.next()));


来源: stackexchange

问:
How to send push notifications to web application and browser?
I have a database in which I insert and send data using java.So I want to send push notifications using java to my web application and getting them in javascript.

I also want to send push notification to my browser.Is there an easy way to do these two things? I have been trying for days but I have not found a well explained tutorial that I can understand.

Thank you in advance.

答:
It sounds like you may want to try websockets which any modern browser will support.

Effectively, it opens a TCP channel between the browser (javascript) and the server.  Messages can be written to the socket and received and handled by the browser.

An old but good introduction is: https://www.html5rocks.com/en/tutorials/websockets/basics/

The only other alternative would be to perform either polling at various intervals using javascript, or long polling.  Both have issues, particularly at high volume.  Websockets make more efficient use of network.

ContentLicense: CC BY-SA 3.0


问:
An enumerable sequence of parameters (arrays, lists, etc) is not allowed in this context in Dapper
I have the following code:

```<code>static void Main(string[] args){
        string sql= "SELECT * FROM Posts WHERE 1=1 ";
        SqlParameter[] @params= SetDynamicParameter(ref sql, "Param=Value", "Param2=Value2", "ParamN=ValueN");

        IDbConnection connection = new SqlConnection(connectionString);
        IEnumerable<Posts> en = connection.Query<Posts>(sql,param:@params);

        Console.ReadKey(true);
}
 static SqlParameter[] SetDynamicParameter(ref string sql,params string[] sarr) {
        string condition = string.Empty;
        List<SqlParameter> list = new List<SqlParameter>();
        foreach (var item in sarr)
        {
            condition += " AND "+item.Split('=')[0] + "=@" + item.Split('=')[0];
            list.Add(new SqlParameter("@" + item.Split('=')[0], item.Split('=')[1]));
        }
        sql += condition;
        return list.ToArray() ;
  }
</code>```

The output error:An enumerable sequence of parameters (arrays, lists, etc) is not allowed in this context.

How can it be?Is there an equivalent solution?

答:
Try to use Dapper.DynamicParameters instead of SqlParameter array:

```<code>var parameters = new DynamicParameters();
parameters.Add("@ParameterName", parameterValue);
</code>```

Body:
I have the following code:

static void Main(string[] args){
        string sql= "SELECT * FROM Posts WHERE 1=1 ";
        SqlParameter[] @params= SetDynamicParameter(ref sql, "Param=Value", "Param2=Value2", "ParamN=ValueN");

        IDbConnection connection = new SqlConnection(connectionString);
        IEnumerable<Posts> en = connection.Query<Posts>(sql,param:@params);

        Console.ReadKey(true);
}
 static SqlParameter[] SetDynamicParameter(ref string sql,params string[] sarr) {
        string condition = string.Empty;
        List<SqlParameter> list = new List<SqlParameter>();
        foreach (var item in sarr)
        {
            condition += " AND "+item.Split('=')[0] + "=@" + item.Split('=')[0];
            list.Add(new SqlParameter("@" + item.Split('=')[0], item.Split('=')[1]));
        }
        sql += condition;
        return list.ToArray() ;
  }

The output error:An enumerable sequence of parameters (arrays, lists, etc) is not allowed in this context.

How can it be?Is there an equivalent solution?

Body:
Try to use Dapper.DynamicParameters instead of SqlParameter array:

var parameters = new DynamicParameters();
parameters.Add("@ParameterName", parameterValue);

ContentLicense: CC BY-SA 4.0


问:
Get the mouse coordinates when clicking on canvas
A common question, but I still need help. I'm trying to get and store the mouse coordinates when someone clicks within the canvas.

my HTML

```<code><canvas id="puppyCanvas" width="500" height="500" style="border:2px solid black" onclick = "storeGuess(event)"></canvas>
</code>```

and my javascript

```<code>//setup canvas
var canvasSetup = document.getElementById("puppyCanvas");
var ctx = canvasSetup.getContext("2d");

guessX = 0;//stores user's click on canvas
 guessY = 0;//stores user's click on canvas

function storeGuess(event){
    var x = event.clientX - ctx.canvas.offsetLeft;
    var y = event.clientY - ctx.canvas.offsetTop;
    /*guessX = x;
    guessY = y;*/

    console.log("x coords:" + x + ", y coords" + y);
</code>```

I've read loads of forums, w3schools, and videos on this. I'm close to figuring it out, but I'm missing something. I can get the coordinates of the page if I delete the ctx.canvas.offsetLeft and ctx.canvas.offsetTop. But i need to incorporate those somehow to get the coordinates of the canvas, and then store then into the variables guessX and guessY.

答:
I am using this piece of code.

var myCanvas = document.querySelector('#canvas');

myCanvas.addEventListener('click', function(event) {
    var rect = myCanvas.getBoundingClientRect();
    var x = event.clientX - rect.left;
    var y = event.clientY - rect.top;
    console.log("x: " + x + " y: " + y);
}, false);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas width="400" height="400" id="canvas" style="background-color: lightblue"></canvas></code>```

Body:
A common question, but I still need help. I'm trying to get and store the mouse coordinates when someone clicks within the canvas.

my HTML

<canvas id="puppyCanvas" width="500" height="500" style="border:2px solid black" onclick = "storeGuess(event)"></canvas>

and my javascript

//setup canvas
var canvasSetup = document.getElementById("puppyCanvas");
var ctx = canvasSetup.getContext("2d");

guessX = 0;//stores user's click on canvas
 guessY = 0;//stores user's click on canvas

function storeGuess(event){
    var x = event.clientX - ctx.canvas.offsetLeft;
    var y = event.clientY - ctx.canvas.offsetTop;
    /*guessX = x;
    guessY = y;*/

    console.log("x coords:" + x + ", y coords" + y);

I've read loads of forums, w3schools, and videos on this. I'm close to figuring it out, but I'm missing something. I can get the coordinates of the page if I delete the ctx.canvas.offsetLeft and ctx.canvas.offsetTop. But i need to incorporate those somehow to get the coordinates of the canvas, and then store then into the variables guessX and guessY.

Body:
I am using this piece of code.

var myCanvas = document.querySelector('#canvas');

myCanvas.addEventListener('click', function(event) {
    var rect = myCanvas.getBoundingClientRect();
    var x = event.clientX - rect.left;
    var y = event.clientY - rect.top;
    console.log("x: " + x + " y: " + y);
}, false);

<canvas width="400" height="400" id="canvas" style="background-color: lightblue"></canvas>


问:
Python: Create text file, write to it, replace string
I am creating a file, writing to it, then I want to replace a string. I have everything working, except the replace. I have tried re.sub, str.replace, etc. I can't figure it out.

```<code>target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
file.write(target_string)
target_string = re.sub('4', '55', target_string)

Desired Output: foo55bar5555foobar555555foobar, foo55bar
</code>```

Thanks.

答:
You need to change the string before you write to file.

Switch your last two lines.

Body:
I am creating a file, writing to it, then I want to replace a string. I have everything working, except the replace. I have tried re.sub, str.replace, etc. I can't figure it out.

target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
file.write(target_string)
target_string = re.sub('4', '55', target_string)

Desired Output: foo55bar5555foobar555555foobar, foo55bar

Thanks.


问:
How to create subdomain dynamically without going cPanel
I am working on laravel and need to create subdomain using laravel dynamically without going cPanel or server setting.

Say here I have abc.xyz.com and I want create {subdomain}.abc.xyz.com . where subdomain will dynamic.

To access I have Use following code in laravel route.

```<code>Route::group(['domain' => 'abc.xyz'], function()
{
    return 'Main page will be loaded';
});

Route::group(['domain' => '{subdomain}.abc.xyz'], function()
{
    return 'Subdomain page will be loaded';
});
</code>```

Also I have searched, but just found only way by .htaccess .

Is it the only way to do this or is there any other ways also to create subdomain dynamically.

答:
Some time ago I wanted to create a subdomain dynamically in my project. I was coding in Core PHP. I think this could be helpful to you or someone else.
Here is my solution.

I created wildcard subdomain as shown by @Rockers Technology in previous answer

Then Step 2: On at Home Directory of my project I created createSubDomain.php file with following code:

```<code>$subDomain = "mytestdomain";
    $cPanelUser = 'user_name';
    $cPanelPass = 'password';
    $rootDomain = 'main_domain_name';

//  $buildRequest = "/frontend/x3/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain;

//$buildRequest = "/frontend/paper_lantern/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain . "&dir=public_html/code/" . $subDomain;
$buildRequest = "/frontend/paper_lantern/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain . "&dir=public_html/code/";

$openSocket = fsockopen('localhost',2082);
if(!$openSocket) {
    return "Socket error";
    exit();
}

$authString = $cPanelUser . ":" . $cPanelPass;
$authPass = base64_encode($authString);
$buildHeaders  = "GET " . $buildRequest ."\r\n";
$buildHeaders .= "HTTP/1.0\r\n";
$buildHeaders .= "Host:localhost\r\n";
$buildHeaders .= "Authorization: Basic " . $authPass . "\r\n";
$buildHeaders .= "\r\n";

fputs($openSocket, $buildHeaders);
while(!feof($openSocket)) {
fgets($openSocket,128);
}
fclose($openSocket);

$newDomain = "http://" . $subDomain . "." . $rootDomain . "/";
echo $newDomain;
</code>```

After running this code on webserver, you can check in subdomain section, that a new subdomain gets created as shown in following picture:

Body:
I am working on laravel and need to create subdomain using laravel dynamically without going cPanel or server setting.

Say here I have abc.xyz.com and I want create {subdomain}.abc.xyz.com . where subdomain will dynamic.

To access I have Use following code in laravel route.

Route::group(['domain' => 'abc.xyz'], function()
{
    return 'Main page will be loaded';
});

Route::group(['domain' => '{subdomain}.abc.xyz'], function()
{
    return 'Subdomain page will be loaded';
});

Also I have searched, but just found only way by .htaccess .

Is it the only way to do this or is there any other ways also to create subdomain dynamically.

Body:
Some time ago I wanted to create a subdomain dynamically in my project. I was coding in Core PHP. I think this could be helpful to you or someone else.
Here is my solution.

I created wildcard subdomain as shown by @Rockers Technology in previous answer

Then Step 2: On at Home Directory of my project I created createSubDomain.php file with following code:

$subDomain = "mytestdomain";
    $cPanelUser = 'user_name';
    $cPanelPass = 'password';
    $rootDomain = 'main_domain_name';

//  $buildRequest = "/frontend/x3/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain;

//$buildRequest = "/frontend/paper_lantern/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain . "&dir=public_html/code/" . $subDomain;
$buildRequest = "/frontend/paper_lantern/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain . "&dir=public_html/code/";

$openSocket = fsockopen('localhost',2082);
if(!$openSocket) {
    return "Socket error";
    exit();
}

$authString = $cPanelUser . ":" . $cPanelPass;
$authPass = base64_encode($authString);
$buildHeaders  = "GET " . $buildRequest ."\r\n";
$buildHeaders .= "HTTP/1.0\r\n";
$buildHeaders .= "Host:localhost\r\n";
$buildHeaders .= "Authorization: Basic " . $authPass . "\r\n";
$buildHeaders .= "\r\n";

fputs($openSocket, $buildHeaders);
while(!feof($openSocket)) {
fgets($openSocket,128);
}
fclose($openSocket);

$newDomain = "http://" . $subDomain . "." . $rootDomain . "/";
echo $newDomain;

After running this code on webserver, you can check in subdomain section, that a new subdomain gets created as shown in following picture:


问:
How to specify browser language in Puppeteer
I would like to launch a Google Chrome browser with language Spanish es using Puppeteer.

I've tried puppeteer.launch(args:['--lang=es',...],...) but it didn't work.

I've tried passing the environment variable LANGUAGE=es mocha puppeteer-test.js but it didn't work.

I've tried using the userDataDir option and passing a folder with a Preferences file a { "intl": { "accept_languages": "es" } } but the browser Settings - Languages still don't show Spanish and neither does window.navigator.languages neither window.navigator.language

I'm using

Puppeteer 0.11.0

Node 8.4.0

NPM 5.2.0

macOS El Capitan 10.11.6

MacBook Pro Retina, 15-inch, Mid 2015

答:
There are several ways to change locale, you can try all of them to find what works for you,

Use Args when launching

```<code>const browser = await puppeteer.launch({
    headless: false,
    args: ['--lang=bn-BD,bn']
});
</code>```

Send the language as Header

```<code>await page.setExtraHTTPHeaders({
    'Accept-Language': 'bn'
});
</code>```

Forcefully set the language

```<code>// Set the language forcefully on javascript
await page.evaluateOnNewDocument(() => {
    Object.defineProperty(navigator, "language", {
        get: function() {
            return "bn-BD";
        }
    });
    Object.defineProperty(navigator, "languages", {
        get: function() {
            return ["bn-BD", "bn"];
        }
    });
});
</code>```

For the sake of testing, I'll test this in multiple languages, including es, and here is the result.

Google search:

BrowserLeaks:

Body:
There are several ways to change locale, you can try all of them to find what works for you,

Use Args when launching

const browser = await puppeteer.launch({
    headless: false,
    args: ['--lang=bn-BD,bn']
});

Send the language as Header

await page.setExtraHTTPHeaders({
    'Accept-Language': 'bn'
});

Forcefully set the language

// Set the language forcefully on javascript
await page.evaluateOnNewDocument(() => {
    Object.defineProperty(navigator, "language", {
        get: function() {
            return "bn-BD";
        }
    });
    Object.defineProperty(navigator, "languages", {
        get: function() {
            return ["bn-BD", "bn"];
        }
    });
});

For the sake of testing, I'll test this in multiple languages, including es, and here is the result.

Google search:

BrowserLeaks:


问:
Scala create a List with Future in a for loop and check the result of each Future
I need to process list of entry in parallel and validate the results. Can anybody help me in achieving this in Scala

it is something like below,

```<code>FileList = List { "/temp/File1", "/temp/File2","/temp/File3","/temp/File4"........}

for( file <- FileList){
  Future { getRecCount(file) } // Need to create a List with all Futures
}
</code>```

Now i need to check the result of all Futures till it completes

getRecCount - will calculate the record count and writes into an file

答:
Thanks - This is how i implemented

val tobeProcesssed : Seq[String] =  Seq("FileName1", "FileName2", "FileName3,"FileName4)    //  Created a Seq with File Names

```<code>    val latch = new CDL(tobeProcesssed.size)
      val trackFutures: Future[Seq[Try[Boolean]]] = Future.traverse(tobeProcesssed.seq) { fileNm =>
        Future {
          LOG.info("In the Futures Loop for {}", fileNm)
          Try {
                    doProcessing(fileNm)
          }
        }
      }

      trackFutures.map { seq =>
        seq.map {
          case Success(state) => {
            if (state) {
              LOG.info("On Sucess - {} - {}", latch.getCount, state)
              return = 0
              latch.countDown()

            } else {
              LOG.error("Failed - {} - {}", latch.getCount, state)
              while (latch.getCount > 0) {
                return  = 1
                latch.countDown()
              }
            }

          }
          case Failure(exception) => {
            LOG.error("Versioning Failed -{} - {}", latch.countDown(), exception)
            while (latch.getCount > 0) {
              return = = 1
              latch.countDown()
            }
          }
        }
      }
      latch.await()
</code>```

Body:
I need to process list of entry in parallel and validate the results. Can anybody help me in achieving this in Scala

it is something like below,

FileList = List { "/temp/File1", "/temp/File2","/temp/File3","/temp/File4"........}

for( file <- FileList){
  Future { getRecCount(file) } // Need to create a List with all Futures
}

Now i need to check the result of all Futures till it completes

getRecCount - will calculate the record count and writes into an file

Body:
Thanks - This is how i implemented

val tobeProcesssed : Seq[String] =  Seq("FileName1", "FileName2", "FileName3,"FileName4)    //  Created a Seq with File Names

    val latch = new CDL(tobeProcesssed.size)
      val trackFutures: Future[Seq[Try[Boolean]]] = Future.traverse(tobeProcesssed.seq) { fileNm =>
        Future {
          LOG.info("In the Futures Loop for {}", fileNm)
          Try {
                    doProcessing(fileNm)
          }
        }
      }

      trackFutures.map { seq =>
        seq.map {
          case Success(state) => {
            if (state) {
              LOG.info("On Sucess - {} - {}", latch.getCount, state)
              return = 0
              latch.countDown()

            } else {
              LOG.error("Failed - {} - {}", latch.getCount, state)
              while (latch.getCount > 0) {
                return  = 1
                latch.countDown()
              }
            }

          }
          case Failure(exception) => {
            LOG.error("Versioning Failed -{} - {}", latch.countDown(), exception)
            while (latch.getCount > 0) {
              return = = 1
              latch.countDown()
            }
          }
        }
      }
      latch.await()


问:
Load a package and inside classes
I'm creating a package with some classes that I generated with wsimport on the fly and now I'm trying to load it to use, how can I do this? natively? or with some lib like byte-buddy, I tried the bellow code to load each class in a package:

```<code>File [] files = new File("<Path to package in filesystem with classes (*.class)>").listFiles();
    List<URL> classUrls = new ArrayList<>();

    for(File file : files) {
        classUrls.add(new URL("file://" + file.getAbsolutePath()));
    }

    URL[] classz = new URL[classUrls.size()];
    classz = classUrls.toArray(classz);

    URLClassLoader child = new URLClassLoader(classz);
    Class.forName("com.abc.external.resources.genwn239aqyhmfz.SomeClass", true, child);
</code>```

But I still getting (Package: com.abc.external.resources.genwn239aqyhmfz.SomeClass)

```<code>java.lang.ClassNotFoundException: com.abc.external.resources.genwn239aqyhmfz.SomeClass
</code>```

答:
The rules for the class path are not different to the rules you have to obey when launching your application. The class path entries are not class files nor directories containing them, but the roots of your package structure.

So if the class you want to load is com.abc.external.resources.genwn239aqyhmfz.SomeClass, the class path entry has to be the directory containing the com directory, which contains the abc directory, and so on. If you know the expected full qualified name of one of the classes, it’s easy to find the right directory. Just traverse to the file hierarchy up as many times as the qualified name has package components. However, when you don’t know the name beforehand, finding it can be tricky. Here is a sketch:

```<code>// pass the expected name of one class contained in f or null if not known
static void loadClasses(File f, String predictedName)
        throws IOException, ClassNotFoundException {
    File[] classes = f.listFiles((d,n)->n.endsWith(".class"));
    if(classes == null || classes.length == 0) {
        System.err.println("no classes or not a directory");
        return;
    }
    if(predictedName == null) predictedName = predictName(classes[0]);
    for(int p = predictedName.indexOf('.'); p >= 0; p = predictedName.indexOf('.', p+1))
        f = f.getParentFile();
    URLClassLoader classLoader = new URLClassLoader(new URL[] { f.toURI().toURL() });
    String packageName = predictedName.substring(0, predictedName.lastIndexOf('.')+1);
    for(File cf: classes) {
        String name = cf.getName();
        name = name.substring(0, name.length()-6); // strip off ".class"
        Class<?> cl = classLoader.loadClass(packageName+name);
        // what do you wanna do with the classes?
        System.out.println(cl);
    }
}

private static String predictName(File classFile) throws IOException {
    byte[] data = Files.readAllBytes(classFile.toPath());
    return new ClassLoader() {
        String getName() {
            return defineClass(null, data, 0, data.length).getName();
        }
    }.getName();
}
</code>```

The predictName implementation is a very simple one. If the class has dependencies to classes within the same file hierarchy which the JVM immediately tries to resolve, it will fail as we don’t have the necessary information yet. In that case, only a bytecode parsing library allowing to extract the name without loading the class would help. But that exceeds the scope of this question…

Title: Load a package and inside classes

Body:
I'm creating a package with some classes that I generated with wsimport on the fly and now I'm trying to load it to use, how can I do this? natively? or with some lib like byte-buddy, I tried the bellow code to load each class in a package:

File [] files = new File("<Path to package in filesystem with classes (*.class)>").listFiles();
    List<URL> classUrls = new ArrayList<>();

    for(File file : files) {
        classUrls.add(new URL("file://" + file.getAbsolutePath()));
    }

    URL[] classz = new URL[classUrls.size()];
    classz = classUrls.toArray(classz);

    URLClassLoader child = new URLClassLoader(classz);
    Class.forName("com.abc.external.resources.genwn239aqyhmfz.SomeClass", true, child);

But I still getting (Package: com.abc.external.resources.genwn239aqyhmfz.SomeClass)

java.lang.ClassNotFoundException: com.abc.external.resources.genwn239aqyhmfz.SomeClass

Body:
The rules for the class path are not different to the rules you have to obey when launching your application. The class path entries are not class files nor directories containing them, but the roots of your package structure.

So if the class you want to load is com.abc.external.resources.genwn239aqyhmfz.SomeClass, the class path entry has to be the directory containing the com directory, which contains the abc directory, and so on. If you know the expected full qualified name of one of the classes, it’s easy to find the right directory. Just traverse to the file hierarchy up as many times as the qualified name has package components. However, when you don’t know the name beforehand, finding it can be tricky. Here is a sketch:

// pass the expected name of one class contained in f or null if not known
static void loadClasses(File f, String predictedName)
        throws IOException, ClassNotFoundException {
    File[] classes = f.listFiles((d,n)->n.endsWith(".class"));
    if(classes == null || classes.length == 0) {
        System.err.println("no classes or not a directory");
        return;
    }
    if(predictedName == null) predictedName = predictName(classes[0]);
    for(int p = predictedName.indexOf('.'); p >= 0; p = predictedName.indexOf('.', p+1))
        f = f.getParentFile();
    URLClassLoader classLoader = new URLClassLoader(new URL[] { f.toURI().toURL() });
    String packageName = predictedName.substring(0, predictedName.lastIndexOf('.')+1);
    for(File cf: classes) {
        String name = cf.getName();
        name = name.substring(0, name.length()-6); // strip off ".class"
        Class<?> cl = classLoader.loadClass(packageName+name);
        // what do you wanna do with the classes?
        System.out.println(cl);
    }
}

private static String predictName(File classFile) throws IOException {
    byte[] data = Files.readAllBytes(classFile.toPath());
    return new ClassLoader() {
        String getName() {
            return defineClass(null, data, 0, data.length).getName();
        }
    }.getName();
}

The predictName implementation is a very simple one. If the class has dependencies to classes within the same file hierarchy which the JVM immediately tries to resolve, it will fail as we don’t have the necessary information yet. In that case, only a bytecode parsing library allowing to extract the name without loading the class would help. But that exceeds the scope of this question…


问:
How do you do an incremental search across multiple files in VIM?
Vim already does incremental search within the currently open file but can you do
an incremental search across multiple files?</p>

答:
from :help grepadd

```<code>                            *:grepa* *:grepadd*
:grepa[dd][!] [arguments]
            Just like ":grep", but instead of making a new list of
            errors the matches are appended to the current list.
            Example: >
                :call setqflist([])
                :bufdo grepadd! something %
            The first command makes a new error list which is
            empty.  The second command executes "grepadd" for each
            listed buffer.  Note the use of ! to avoid that
            ":grepadd" jumps to the first error, which is not
            allowed with |:bufdo|.
            An example that uses the argument list and avoids
            errors for files without matches: >
                                :silent argdo try
                  \ | grepadd! something %
                  \ | catch /E480:/
                  \ | endtry"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
from :help grepadd

                            *:grepa* *:grepadd*
:grepa[dd][!] [arguments]
            Just like ":grep", but instead of making a new list of
            errors the matches are appended to the current list.
            Example: >
                :call setqflist([])
                :bufdo grepadd! something %
            The first command makes a new error list which is
            empty.  The second command executes "grepadd" for each
            listed buffer.  Note the use of ! to avoid that
            ":grepadd" jumps to the first error, which is not
            allowed with |:bufdo|.
            An example that uses the argument list and avoids
            errors for files without matches: >
                                :silent argdo try
                  \ | grepadd! something %
                  \ | catch /E480:/
                  \ | endtry"


问:
Regex how do you match a word without numbers and with a preset
I am bashing my brain on how to do this, but can't seem to figure it out. I want to match the following:

one_to_three -> MATCH

three_to_four -> MATCH

thr3_to_f5ve -> NOPE!

So basically I want to (match only words)(_to_)(match only words)

Any help would be appreciated! Thanks in advance!

答:
Aight, thanks to the first two answers in the comments, it was fairly simple...

Using \b[a-z]+_to_[a-z]+\b to get what I need. Thanks!


问:
Sed replace ; with | but ignore ; inside quotes
I want to replace ; inside a file with | but ignore semicolons inside a double quote. I want to perform the operation on the same file using sed -I option

input:  1;2;"3;4;5"

expected output: 1|2|"3;4;5

Body:
GNU AWK solution:

Sample input.txt file:

1;2;"3;4;5"
6;"7;8;9";10

The job:

awk -v FPAT='[^;]+|"[^"]+"' '{ for(i=1;i<=NF;i++) printf "%s%s",$i,(i==NF? ORS:OFS) }' OFS='|' input.txt

The output:

1|2|"3;4;5"
6|"7;8;9"|10


问:
Python loop through text and set numpy array index
Given a block of text with matrix rows and columns separated by commas and semicolons, I want to parse the text and set the indices of numpy arrays. Here is the code with the variable 'matrixText' representing the base text.

I first create the matrices and then split the text by semicolons and then by commas. I loop through the split text and set each index. However with the text ...

1,2,3;4,5,6;7,8,9

I get the result

7,7,7;8,8,8;9,9,9

```<code>temp1=matrixText.split(';')
temp2=temp1[0].split(',')
rows=len(temp1)
columns=len(temp2)
rA=np.zeros((rows, columns))
arrayText=matrixText.split(';')
rowText=range(len(arrayText))
for rowIndex, rowItem in enumerate(arrayText):
    rowText[rowIndex]=arrayText[rowIndex].split(',')
    for colIndex, colItem in enumerate(rowText[rowIndex]):
        rA[[rowIndex, colIndex]]=rowText[rowIndex][colIndex]
</code>```

I thought that by setting each index, I would avoid any copy by reference issues.

To provide more info, in the first iteration, the 0,0 index is set to 1 and the output of that is then 1,1,1;0,0,0;0,0,0 which I can't figure out since setting one index in the numpy array sets three.

In the second iteration, the index 0-1 is set to 2 and the result is then 2,2,2;2,2,2;0,0,0

The third iteration sets 0-2 to 3 but the result is 3,3,3;2,2,2;3,3,3

Any suggestions?

答:
You can (ab-) use the matrix constructor plus the A property

```<code>np.matrix('1,2,3;4,5,6;7,8,9').A
</code>```

Output:

```<code>array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
</code>```

Body:
Given a block of text with matrix rows and columns separated by commas and semicolons, I want to parse the text and set the indices of numpy arrays. Here is the code with the variable 'matrixText' representing the base text.

I first create the matrices and then split the text by semicolons and then by commas. I loop through the split text and set each index. However with the text ...

1,2,3;4,5,6;7,8,9

I get the result

7,7,7;8,8,8;9,9,9

temp1=matrixText.split(';')
temp2=temp1[0].split(',')
rows=len(temp1)
columns=len(temp2)
rA=np.zeros((rows, columns))
arrayText=matrixText.split(';')
rowText=range(len(arrayText))
for rowIndex, rowItem in enumerate(arrayText):
    rowText[rowIndex]=arrayText[rowIndex].split(',')
    for colIndex, colItem in enumerate(rowText[rowIndex]):
        rA[[rowIndex, colIndex]]=rowText[rowIndex][colIndex]

I thought that by setting each index, I would avoid any copy by reference issues.

To provide more info, in the first iteration, the 0,0 index is set to 1 and the output of that is then 1,1,1;0,0,0;0,0,0 which I can't figure out since setting one index in the numpy array sets three.

In the second iteration, the index 0-1 is set to 2 and the result is then 2,2,2;2,2,2;0,0,0

The third iteration sets 0-2 to 3 but the result is 3,3,3;2,2,2;3,3,3

Any suggestions?

Body:
You can (ab-) use the matrix constructor plus the A property

np.matrix('1,2,3;4,5,6;7,8,9').A

Output:

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])


答:
You can try this:

```<code>target_string = 'foo4bar44foobar444foobar, foo4bar'
final_string = ''
seen_val = False
for i in target_string:
   if i.isdigit():
      if seen_val:
         final_string += str(int(i)+1)*2
      else:
          final_string += str(int(i)+1)*2
          seen_val = True
   else:
       final_string += i
       seen_val = False
</code>```

Output:

```<code>'foo55bar5555foobar555555foobar, foo55bar'
</code>```

Title: Python: Create text file, write to it, replace string

Body:
You can try this:

target_string = 'foo4bar44foobar444foobar, foo4bar'
final_string = ''
seen_val = False
for i in target_string:
   if i.isdigit():
      if seen_val:
         final_string += str(int(i)+1)*2
      else:
          final_string += str(int(i)+1)*2
          seen_val = True
   else:
       final_string += i
       seen_val = False

Output:

'foo55bar5555foobar555555foobar, foo55bar'


问:
What is the best metric to evaluate how well a CNN is trained? validation error or training loss?
I want to train a CNN, but I want to use all data to train the network thus not performing validation. Is this a good choice? am I risking to overfit my CNN if using only the training loss as the criterium for early stopping the CNN?

In other words, what is the best 'monitor' parameter in KERAS (for example) for early stopping, among the options below?

```<code>early_stopper=EarlyStopping(monitor='train_loss', min_delta=0.0001, patience=20)
early_stopper=EarlyStopping(monitor='train_acc', min_delta=0.0001, patience=20)
early_stopper=EarlyStopping(monitor='val_loss', min_delta=0.0001, patience=20)
early_stopper=EarlyStopping(monitor='val_acc', min_delta=0.0001, patience=20)
</code>```

There is a discussion like this in stackoverflow Keras: Validation error is a good measure for stopping criteria or validation accuracy?, however, they talk about the validation only. Is it better using criteria in validation or training data to early stopping a CNN training?

答:
I've already up-voted Tin Luu's answer, but wanted to refine one critical, practical point: the best criterion is the one that best matches your success criteria.  To wit, you have to define your practical scoring function before your question makes complete sense for us.

What is important to the application for which you're training this model?  If it's nothing more than top-1 prediction accuracy, then validation accuracy (val_acc) is almost certainly your sole criterion.  If you care about confidence levels (e.g. hedging your bets when 48% chance it's a cat, 42% it's a wolf, 10% it's a Ferrari), then proper implementation of an error function will make validation error (val_err) a better choice.

Finally, I stress again that the ultimate metric is actual performance according to your chosen criteria.  Test data are a representative sampling of your actual input.  You can use an early stopping criterion for faster training turnaround, but you're not ready for deployment until your real-world criteria are tested and satisfied.

Body:
I want to train a CNN, but I want to use all data to train the network thus not performing validation. Is this a good choice? am I risking to overfit my CNN if using only the training loss as the criterium for early stopping the CNN?

In other words, what is the best 'monitor' parameter in KERAS (for example) for early stopping, among the options below?

early_stopper=EarlyStopping(monitor='train_loss', min_delta=0.0001, patience=20)
early_stopper=EarlyStopping(monitor='train_acc', min_delta=0.0001, patience=20)
early_stopper=EarlyStopping(monitor='val_loss', min_delta=0.0001, patience=20)
early_stopper=EarlyStopping(monitor='val_acc', min_delta=0.0001, patience=20)

There is a discussion like this in stackoverflow Keras: Validation error is a good measure for stopping criteria or validation accuracy?, however, they talk about the validation only. Is it better using criteria in validation or training data to early stopping a CNN training?


问:
Resend HTTP post before error timeout
I have an Angular 4 project that uses a http post to commands across to our backend. The issue is that sometimes a command can be sent out before the backend is fully up and running. Normally an "ERR_CONNECTION_TIME_OUT" would occur, but our embedded browser for whatever reason holds onto the post for an extremely long time before giving us the error (5 minutes). Since a 5 minute wait is unacceptable, I need to come up with a way to re-send our http post if there isn't a response within 15-30~ seconds

Here is what the current post looks like

```<code>this._http.post(this.sockclientURL, body, { headers: headers })
  .subscribe((res) => {

    let text = res.text();

    if (text.startsWith("ERROR")) {
      console.log("Sockclient Error.");
      if (this.sockclientErrorRetryCount < this.sockclientErrorRetryLimit) {
        console.log("Retrying in 3 seconds.");
        this.sockclientErrorRetryCount++;

        setTimeout(() => {
          this.SendCommand(command, success, fail);
        }, 3000);
      }
      return;
    }
    else {
      this.sockclientErrorRetryCount = 0;
    }

    if (text == "N" || text.startsWith("N ")) {
      this._modalService.alert(this._nackLookup.convert(text));
      if (typeof fail == 'function') {
        fail(text);
      }
    }
    else {

      let deserializedCommand = command.deserialize(text);

      success(deserializedCommand);

      let repeatMillis: number = deserializedCommand.getRepeatMillis();

      if (repeatMillis && repeatMillis > 0) {
        setTimeout(() => {
          this.SendCommand(command, success, fail);
        }, repeatMillis);
      }
    }
  },
  (err) => {
    console.log(err);
    let repeatMillis = 1000;
      setTimeout(() => {
        this.SendCommand(command, success, fail);
      }, repeatMillis);
  });
</code>```

So to re-cap, I have some code in place to re-attempt the command if an error occurs, but our embedded browser holds onto its timeout error for several minutes. I need something to attempt to re-send after 15-30 seconds of no response

答:
Retries are immediately executed without waiting for a delay. A better one consists of waiting for a bit before retrying and abort after a given amount of time. Observables allow to mix retryWhen, delay and timeout operators to achieve this, as described in the following snippet:</p>

```<code>this._http.post(this.sockclientURL, body, { headers: headers })
 .retryWhen(error => error.delay(500))
 .timeout(2000, new Error('delay exceeded'))
 .map(res => res.map());
</code>```

Title: Resend HTTP post before error timeout

Body:
I have an Angular 4 project that uses a http post to commands across to our backend. The issue is that sometimes a command can be sent out before the backend is fully up and running. Normally an "ERR_CONNECTION_TIME_OUT" would occur, but our embedded browser for whatever reason holds onto the post for an extremely long time before giving us the error (5 minutes). Since a 5 minute wait is unacceptable, I need to come up with a way to re-send our http post if there isn't a response within 15-30~ seconds

Here is what the current post looks like

this._http.post(this.sockclientURL, body, { headers: headers })
  .subscribe((res) => {

    let text = res.text();

    if (text.startsWith("ERROR")) {
      console.log("Sockclient Error.");
      if (this.sockclientErrorRetryCount < this.sockclientErrorRetryLimit) {
        console.log("Retrying in 3 seconds.");
        this.sockclientErrorRetryCount++;

        setTimeout(() => {
          this.SendCommand(command, success, fail);
        }, 3000);
      }
      return;
    }
    else {
      this.sockclientErrorRetryCount = 0;
    }

    if (text == "N" || text.startsWith("N ")) {
      this._modalService.alert(this._nackLookup.convert(text));
      if (typeof fail == 'function') {
        fail(text);
      }
    }
    else {

      let deserializedCommand = command.deserialize(text);

      success(deserializedCommand);

      let repeatMillis: number = deserializedCommand.getRepeatMillis();

      if (repeatMillis && repeatMillis > 0) {
        setTimeout(() => {
          this.SendCommand(command, success, fail);
        }, repeatMillis);
      }
    }
  },
  (err) => {
    console.log(err);
    let repeatMillis = 1000;
      setTimeout(() => {
        this.SendCommand(command, success, fail);
      }, repeatMillis);
  });

So to re-cap, I have some code in place to re-attempt the command if an error occurs, but our embedded browser holds onto its timeout error for several minutes. I need something to attempt to re-send after 15-30 seconds of no response

Body:
Retries are immediately executed without waiting for a delay. A better one consists of waiting for a bit before retrying and abort after a given amount of time. Observables allow to mix retryWhen, delay and timeout operators to achieve this, as described in the following snippet:

this._http.post(this.sockclientURL, body, { headers: headers })
 .retryWhen(error => error.delay(500))
 .timeout(2000, new Error('delay exceeded'))
 .map(res => res.map());


问:
Change Display Value in Radio Button Column
I have a radio button in datawindow and I want to change the display value using codes depending on command button I'll click. Is it possible? What function I can use? Thanks in advance. </p>

答:
Here is some code:

```<code>string ls
dw_1.insertrow(0)
dw_1.setredraw(FALSE)
// get the current values
ls = dw_1.describe("blue_1.values")
//ls is 'Red~tR/Blue~tB/Orange~tO'
// change the values
ls = dw_1.modify("blue_1.values = 'Green~tG/Teal~tT/Brown~tB'")
dw_1.setredraw(TRUE)
</code>```

The radiobutton column in this example is "blue_1".

Body:
Here is some code:

string ls
dw_1.insertrow(0)
dw_1.setredraw(FALSE)
// get the current values
ls = dw_1.describe("blue_1.values")
//ls is 'Red~tR/Blue~tB/Orange~tO'
// change the values
ls = dw_1.modify("blue_1.values = 'Green~tG/Teal~tT/Brown~tB'")
dw_1.setredraw(TRUE)

The radiobutton column in this example is "blue_1".


问:
relevance by keyword solr
How can we sort the results of a query according to the position of the keyword?

I start the search only on the field Label

when I have

solr search query titi

titi test tilte

toto titi tata

what parameter should we put in place to have this order back?

titi test tilte

toto titi tata

solr search query titi

I use Drupal for connect and send query to solr.

答:
If your domain is very contained and you know for example the size of the label you expect you can obtain something close to what you want with copy fields and the dismax query parser.
Specifically you could build N "copyfields" in this way :

<field name="label" type="text_general" indexed="true" stored="true"/>
<field name="label_3" type="text_first_3" indexed="true" stored="true"/>
<field name="label_5" type="text_first_5" indexed="true" stored="true"/>
...
<fieldType name="text_first_3" class="solr.TextField" positionIncrementGap="100">
        <analyzer type="index">
            <tokenizer class="solr.WhitespaceTokenizerFactory"/>
            <filter class="solr.LimitTokenPositionFilterFactory"             maxTokenPosition="3" consumeAllTokens="false" />
</analyzer>
        <analyzer type="query">
            <tokenizer class="solr.StandardTokenizerFactory"/>
        </analyzer>
    </fieldType>

<fieldType name="text_first_5" class="solr.TextField" positionIncrementGap="100">
        <analyzer type="index">
            <tokenizer class="solr.WhitespaceTokenizerFactory"/>
            <filter class="solr.LimitTokenPositionFilterFactory"             maxTokenPosition="5" consumeAllTokens="false" />
</analyzer>
        <analyzer type="query">
            <tokenizer class="solr.StandardTokenizerFactory"/>
        </analyzer>
    </fieldType>
...
<copyField source="label" dest="label_3"/>
<copyField source="label" dest="label_5"/>```

This works thanks to the limit token position filter[1].
Then you can specify a different boost with the edismax :

qf="label_3^5 label_5^2 label"

The problem is also discussed here [2].

An alternative approach is mentioned here[3].

[1] https://lucene.apache.org/solr/guide/6_6/filter-descriptions.html#FilterDescriptions-LimitTokenPositionFilter

[2] https://issues.apache.org/jira/browse/SOLR-3925

[3] Solr - How to boost score for early matches?

Title: relevance by keyword solr

Body:
If your domain is very contained and you know for example the size of the label you expect you can obtain something close to what you want with copy fields and the dismax query parser.
Specifically you could build N "copyfields" in this way :

<field name="label" type="text_general" indexed="true" stored="true"/>
<field name="label_3" type="text_first_3" indexed="true" stored="true"/>
<field name="label_5" type="text_first_5" indexed="true" stored="true"/>
...
<fieldType name="text_first_3" class="solr.TextField" positionIncrementGap="100">
        <analyzer type="index">
            <tokenizer class="solr.WhitespaceTokenizerFactory"/>
            <filter class="solr.LimitTokenPositionFilterFactory"             maxTokenPosition="3" consumeAllTokens="false" />
</analyzer>
        <analyzer type="query">
            <tokenizer class="solr.StandardTokenizerFactory"/>
        </analyzer>
    </fieldType>

<fieldType name="text_first_5" class="solr.TextField" positionIncrementGap="100">
        <analyzer type="index">
            <tokenizer class="solr.WhitespaceTokenizerFactory"/>
            <filter class="solr.LimitTokenPositionFilterFactory"             maxTokenPosition="5" consumeAllTokens="false" />
</analyzer>
        <analyzer type="query">
            <tokenizer class="solr.StandardTokenizerFactory"/>
        </analyzer>
    </fieldType>
...
<copyField source="label" dest="label_3"/>
<copyField source="label" dest="label_5"/>

This works thanks to the limit token position filter[1].
Then you can specify a different boost with the edismax :

qf="label_3^5 label_5^2 label"

The problem is also discussed here [2].

An alternative approach is mentioned here[3].

[1] https://lucene.apache.org/solr/guide/6_6/filter-descriptions.html#FilterDescriptions-LimitTokenPositionFilter

[2] https://issues.apache.org/jira/browse/SOLR-3925

[3] Solr - How to boost score for early matches?


答:
The official terminology for what you have got wrong is the sequencing of your code.

You write the target_string to your file before doing the re.sub on it! You need to switch these operations around so you write the modified string to the file:

```<code>target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
target_string = re.sub('4', '55', target_string)
file.write(target_string)
</code>```

Also, when you are working with files, you should ideally use a with statement as if the program throws an error before you call file.close() (which I assume you are doing later), you will lead into problems.

So, your final code should look something like:

```<code>target_string = 'foo4bar44foobar444foobar, foo4bar'
with open(source_file, "w+") as f:
    target_string = re.sub('4', '55', target_string) #could be moved out of with
    file.write(target_string)
</code>```

Body:
I am creating a file, writing to it, then I want to replace a string. I have everything working, except the replace. I have tried re.sub, str.replace, etc. I can't figure it out.

target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
file.write(target_string)
target_string = re.sub('4', '55', target_string)

Desired Output: foo55bar5555foobar555555foobar, foo55bar

Thanks.

Body:
The official terminology for what you have got wrong is the sequencing of your code.

You write the target_string to your file before doing the re.sub on it! You need to switch these operations around so you write the modified string to the file:

target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
target_string = re.sub('4', '55', target_string)
file.write(target_string)

Also, when you are working with files, you should ideally use a with statement as if the program throws an error before you call file.close() (which I assume you are doing later), you will lead into problems.

So, your final code should look something like:

target_string = 'foo4bar44foobar444foobar, foo4bar'
with open(source_file, "w+") as f:
    target_string = re.sub('4', '55', target_string) #could be moved out of with
    file.write(target_string)


问:
What's the difference between OC xor and Java xor?
I hava a question about  Java and OC  xor:

First xor, the second  Base64

In  java, the code :

```<code>     String  numberStr = ("123456");

    char[] array = numberStr.toCharArray();
    for (int i = 0; i < array.length; i++)
    {
        array[i] = (char) (array[i] ^ 1984);
    }
    String xorStr = new String(array);

    byte[] b = null;
    String s = null;
    try {
        b = xorStr.getBytes("utf-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    if (b != null) {
        try {
            s = Base64.encodeToString(b, Base64.DEFAULT);;
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }
</code>```

the result is : 37Hfst+z37Tftd+2

In OC,the code:

```<code>    NSString *numberString = @"123456";
    NSData* bytes = [numberString dataUsingEncoding:NSUTF8StringEncoding];
    int8_t * bytePtr = ( int8_t * )[bytes bytes];
    NSInteger totalData = [bytes length] / sizeof(int8_t);
    NSMutableString *finalString = [NSMutableString new];
    for (int i = 0 ; i < totalData; i ++){
    bytePtr[i] = (int8_t)(bytePtr[i]) ^ (1984);
    [finalString appendString:[NSString stringWithFormat:@"%c",bytePtr[i]]];
    NSLog(@"encrypt data = %d", bytePtr[i]);
    }

    NSData *finalData = [finalString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *baseString = [finalData base64EncodedStringWithOptions:0];
</code>```

the  result  baseString is : w7HDssOzw7TDtcO2

why  the result  is different?  I just know  my  OC  code  is wrong !
Could someone  tell  me  the  correct answer ?

答:
Given that a Java char is a 16-bit value, your Objective-C code is giving a different result because you are trying to use UTF-8 encoding and 8-bit values.

To make the Objective-C code work like the Java code, you need to work with 16-bit characters instead of 8-bit bytes.

```<code>NSString *numberString = @"123456";
NSMutableString *finalString = [NSMutableString new];
for (NSInteger c = 0; c < numberString.length; c++) {
    unichar char = [numberString characterAt:c];
    char = char ^ 1984;
    [finalString appendFormat:@"%C", char]; // Note C, not c
}

NSData *finalData = [finalString dataUsingEncoding:NSUTF8StringEncoding];
NSString *baseString = [finalData base64EncodedStringWithOptions:0];
</code>```

Body:
I hava a question about  Java and OC  xor:

First xor, the second  Base64

In  java, the code :

     String  numberStr = ("123456");

    char[] array = numberStr.toCharArray();
    for (int i = 0; i < array.length; i++)
    {
        array[i] = (char) (array[i] ^ 1984);
    }
    String xorStr = new String(array);

    byte[] b = null;
    String s = null;
    try {
        b = xorStr.getBytes("utf-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    if (b != null) {
        try {
            s = Base64.encodeToString(b, Base64.DEFAULT);;
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

the result is : 37Hfst+z37Tftd+2

In OC,the code:

    NSString *numberString = @"123456";
    NSData* bytes = [numberString dataUsingEncoding:NSUTF8StringEncoding];
    int8_t * bytePtr = ( int8_t * )[bytes bytes];
    NSInteger totalData = [bytes length] / sizeof(int8_t);
    NSMutableString *finalString = [NSMutableString new];
    for (int i = 0 ; i < totalData; i ++){
    bytePtr[i] = (int8_t)(bytePtr[i]) ^ (1984);
    [finalString appendString:[NSString stringWithFormat:@"%c",bytePtr[i]]];
    NSLog(@"encrypt data = %d", bytePtr[i]);
    }

    NSData *finalData = [finalString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *baseString = [finalData base64EncodedStringWithOptions:0];

the  result  baseString is : w7HDssOzw7TDtcO2

why  the result  is different?  I just know  my  OC  code  is wrong !
Could someone  tell  me  the  correct answer ?

Body:
Given that a Java char is a 16-bit value, your Objective-C code is giving a different result because you are trying to use UTF-8 encoding and 8-bit values.

To make the Objective-C code work like the Java code, you need to work with 16-bit characters instead of 8-bit bytes.

NSString *numberString = @"123456";
NSMutableString *finalString = [NSMutableString new];
for (NSInteger c = 0; c < numberString.length; c++) {
    unichar char = [numberString characterAt:c];
    char = char ^ 1984;
    [finalString appendFormat:@"%C", char]; // Note C, not c
}

NSData *finalData = [finalString dataUsingEncoding:NSUTF8StringEncoding];
NSString *baseString = [finalData base64EncodedStringWithOptions:0];


问:
C: Loop jumps from 0 to 1000 and therefore doesn't loop. Why?
im studying for a exam and the task says: (Translated from german to english)
Expand the program to show 1000 different "average values".

So it loops 0-1000 to get 1 "average value" and it should do that 1000 times so i have 1000 different values. The problem is that the first for-loop goes from 0-1000 immediately and prints only one value.

```<code>int i, r, j = 0;
long sum, total = 0;

for (j = 0; j < 1000; j++);  { // jumps here
    srand(time(NULL));

    for (i = 0; i < 1000; i++) {
        r = rand();
        //printf("%d %d\n", i, r);
        sum += r;
    }
    total += sum;
    printf("%d\n", total);
}
printf("Durchschnitt sum = %li\n", sum / 1000);
printf("Durchschnitt total = %li", total / 1000);
</code>```

答:
```<code>for (j = 0; j < 1000; j++) { // jumps here
</code>```

instead of

```<code>for (j = 0; j < 1000; j++);  { // jumps here
</code>```

Body:
im studying for a exam and the task says: (Translated from german to english)
Expand the program to show 1000 different "average values".

So it loops 0-1000 to get 1 "average value" and it should do that 1000 times so i have 1000 different values. The problem is that the first for-loop goes from 0-1000 immediately and prints only one value.

int i, r, j = 0;
long sum, total = 0;

for (j = 0; j < 1000; j++);  { // jumps here
    srand(time(NULL));

    for (i = 0; i < 1000; i++) {
        r = rand();
        //printf("%d %d\n", i, r);
        sum += r;
    }
    total += sum;
    printf("%d\n", total);
}
printf("Durchschnitt sum = %li\n", sum / 1000);
printf("Durchschnitt total = %li", total / 1000);

Body:
for (j = 0; j < 1000; j++) { // jumps here

instead of

for (j = 0; j < 1000; j++);  { // jumps here


问:
Can I use Homebrew on Ubuntu?
I just tried to use Homebrew and Linuxbrew to install packages on my Ubuntu Server but both failed. This is how I tried to install them:

```<code>sudo apt-get install build-essential curl git m4 ruby texinfo libbz2-dev libcurl4-openssl-dev libexpat-dev libncurses-dev zlib1g-dev

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/linuxbrew/go/install)"
</code>```

I got the following warning:

```<code>Warning: /home/tong/.linuxbrew/bin is not in your PATH.
</code>```

I vi my bash.bashrc in home/etc and add this:

```<code>export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"
</code>```

Then I tried brew doctor but got No command 'brew' found. How am I able to use Homebrew on Ubuntu?

答:
Because all previous answers doesn't work for me for ubuntu 14.04
here what I did, if any one get the same problem:

```<code>git clone https://github.com/Linuxbrew/brew.git ~/.linuxbrew
PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$(brew --prefix)/share/man:$MANPATH"
export INFOPATH="$(brew --prefix)/share/info:$INFOPATH"
</code>```

then

```<code>sudo apt-get install gawk
sudo yum install gawk
brew install hello
</code>```

you can follow this link for more information.

Title: Can I use Homebrew on Ubuntu?

Body:
I just tried to use Homebrew and Linuxbrew to install packages on my Ubuntu Server but both failed. This is how I tried to install them:

sudo apt-get install build-essential curl git m4 ruby texinfo libbz2-dev libcurl4-openssl-dev libexpat-dev libncurses-dev zlib1g-dev

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/linuxbrew/go/install)"

I got the following warning:

Warning: /home/tong/.linuxbrew/bin is not in your PATH.

I vi my bash.bashrc in home/etc and add this:

export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"

Then I tried brew doctor but got No command 'brew' found. How am I able to use Homebrew on Ubuntu?

Body:
Because all previous answers doesn't work for me for ubuntu 14.04
here what I did, if any one get the same problem:

git clone https://github.com/Linuxbrew/brew.git ~/.linuxbrew
PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$(brew --prefix)/share/man:$MANPATH"
export INFOPATH="$(brew --prefix)/share/info:$INFOPATH"

then

sudo apt-get install gawk
sudo yum install gawk
brew install hello

you can follow this link for more information.


问:
Loop through Range Areas
In Excel, make a multi-selection, ie: A1:A3 and D1:F4.

In VBA, I can easily loop through Range's Areas using:

```<code>Sub Main()
    Dim i As Long

    For i = 1 To Selection.Areas.Count
        Debug.Print Selection.Areas(i).Address
    Next i
End Sub
</code>```

This is a very important Range property. How can I accomplish this in Excel Javascript API?

答: This feature is not available right now; but it is something we are looking into adding support for in the coming months. No timeline available yet. </p>

Title: Loop through Range Areas

Body:
In Excel, make a multi-selection, ie: A1:A3 and D1:F4.

In VBA, I can easily loop through Range's Areas using:

Sub Main()
    Dim i As Long

    For i = 1 To Selection.Areas.Count
        Debug.Print Selection.Areas(i).Address
    Next i
End Sub

This is a very important Range property. How can I accomplish this in Excel Javascript API?


问:
PHP keeping $variable outside scope of if statement
I've picked up a project from another developer and I'm trying to finish and clean up a bit.  This part of the code renders products from a database after checking for a language cookie:

```<code>                            <?php if (get_cookie('spanish')) : ?>
                                <?php if ($product['details_spanish'] != '') : ?>
                                    <?php $details = explode(':',$product['details_spanish']); ?>
                                    <h3>Especificaciones</h3>
                                <?php else : ?>
                                    <?php if ($product['details'] != '') : ?>
                                        <?php $details = explode(':',$product['details']); ?>
                                        <h3>Especificaciones</h3>
                                    <?php endif ?>
                                <?php endif; ?>

                            <?php else : ?>
                                <?php if ($product['details'] != '') : ?>
                                    <?php $details = explode(':',$product['details']); ?>
                                    <h3>Specifications</h3>
                                <?php endif; ?>

                            <?php endif; ?>
                            <ul>
                            <?php if ($details) : ?>
                                <?php foreach ($details as $detail) : ?>
                                <?php $detail = split(',',$detail); ?>
                                <?php if ($detail[0] != '' && $detail[1] != '') : ?>
                                <li>
                                    <strong><?=ucwords($detail[0])?></strong> : <?=$detail[1]?>
                                </li>
                                <?php endif; ?>
                                <?php $i++; ?>
                                <?php endforeach; ?>
                            <?php endif; ?>
</code>```

Sorry, I know this is hard to read due to inconsistency and bad coding (not my project initially.  What it's doing is checking for a spanish cookie on the users machine.  If it finds it, it pulls the values from the spanish column of the table instead of the regular.   It falls back on the english value if there is no spanish value in the table.  Also, it creates a $details variable that contains one of the values of the database, and splits it where the : is.

The problem I'm having is on some products, it gives me an error saying it can't find the $details variable, I'm assuming it is because the variable doesn't live outside the scope of the first if statement?

I'm a php noob really but even I know this isn't good practice.  is there a better way to clean this up and have my $detail variable available?

答:
Quick workaround is to pre-initialize that variable at the very top:</p>

```<code><?php $details = ''; ?>
</code>```

Body:
I've picked up a project from another developer and I'm trying to finish and clean up a bit.  This part of the code renders products from a database after checking for a language cookie:

                            <?php if (get_cookie('spanish')) : ?>
                                <?php if ($product['details_spanish'] != '') : ?>
                                    <?php $details = explode(':',$product['details_spanish']); ?>

Especificaciones

                                <?php else : ?>
                                    <?php if ($product['details'] != '') : ?>
                                        <?php $details = explode(':',$product['details']); ?>

Especificaciones

                                    <?php endif ?>
                                <?php endif; ?>

                            <?php else : ?>
                                <?php if ($product['details'] != '') : ?>
                                    <?php $details = explode(':',$product['details']); ?>

Specifications

                                <?php endif; ?>

                            <?php endif; ?>

                            <?php if ($details) : ?>
                                <?php foreach ($details as $detail) : ?>
                                <?php $detail = split(',',$detail); ?>
                                <?php if ($detail[0] != '' && $detail[1] != '') : ?>

                                    <?=ucwords($detail[0])?> : <?=$detail[1]?>

                                <?php endif; ?>
                                <?php $i++; ?>
                                <?php endforeach; ?>
                            <?php endif; ?>

Sorry, I know this is hard to read due to inconsistency and bad coding (not my project initially.  What it's doing is checking for a spanish cookie on the users machine.  If it finds it, it pulls the values from the spanish column of the table instead of the regular.   It falls back on the english value if there is no spanish value in the table.  Also, it creates a $details variable that contains one of the values of the database, and splits it where the : is.

The problem I'm having is on some products, it gives me an error saying it can't find the $details variable, I'm assuming it is because the variable doesn't live outside the scope of the first if statement?

I'm a php noob really but even I know this isn't good practice.  is there a better way to clean this up and have my $detail variable available?

Body:
Quick workaround is to pre-initialize that variable at the very top:

<?php $details = ''; ?>


问:
Primefaces DataExporter Set Table Columns Width
I have a Primefaces DataGrid that I export whith Primefaces DataExporter but I can't figure out how to resize the columns.

I added a preporcessor

```<code><p:dataExporter type="pdf" target="tbl" fileName="cars" preProcessor="#{customizedDocumentsView.preProcessPDF}" />
</code>```

And this is the code in my bean

```<code>public void preProcessPDF(Object document) {
        Document pdf = (Document) document;
        pdf.open();
        pdf.setPageSize(PageSize.A4);

        //I need to do something like that
        //PdfPTable table = new PdfPTable(4);
        //float[] columnWidths = new float[] {10f, 20f, 30f, 10f};
        //table.setWidths(columnWidths);
    }
</code>```

Is there any way to do this ?

答:
Recently I inherited project with many already existing exporters with already set options tags so I needed to find solution that will keep all of them intact.

I got an idea from this accepted answer.

My solution sets column widths via options tag of p:dataExporter so there is no need for pre/post processing. I tested it using Primefaces ver 4.x and up.

Step by step procedure:

Create new package
org.primefaces.component.export
inside your project.

From Primefaces git repository fully copy following classes
ExporterOptions ,PDFOptions, Exportedfactory and PDFExporter
into newly created package.

In ExporterOptions add
public float[] getColumnWidths();

In PDFOptions add
float[] columnWidths;
and add getter and setter.

In ExporterFactory modify line
exporter = new PdfExporter(); to  exporter = new CustomPdfExporter();

Rename PDFExporter class to CustomPDFExporter and keep just following export method fully

```<code>public void export(FacesContext context, DataTable table, String filename, boolean pageOnly, boolean selectionOnly, String encodingType,MethodExpression preProcessor, MethodExpression postProcessor, ExporterOptions options) throws IOException
</code>```

Delete code from other export methods but keep declarations.

Inside CustomPDFExporter add 2 lines in ExportPdfTable method

```<code>protected PdfPTable exportPDFTable(FacesContext context, DataTable table, boolean pageOnly, boolean selectionOnly, String encoding) throws DocumentException {
   int columnsCount = getColumnsCount(table);
   PdfPTable pdfTable = new PdfPTable(columnsCount);
   this.cellFont = FontFactory.getFont(FontFactory.TIMES, encoding);
   this.facetFont = FontFactory.getFont(FontFactory.TIMES, encoding, Font.DEFAULTSIZE, Font.BOLD);

    if (this.expOptions != null) {
        applyFacetOptions(this.expOptions);
        applyCellOptions(this.expOptions);
        //line 1
        //sets columns column relative widths to iText PdfTable object
        pdfTable.setWidths(this.expOptions.getColumnWidths());
        //line 2
        //decreases page margins comparing to original 'Primefaces' layout
        pdfTable.setWidthPercentage(100);
    }

    //....
</code>```

}

Now you are ready to go managed bean and add pdf option. For example

```<code>pdfOpt = new PDFOptions(); //add getter and setter too
pdfOpt.setFacetBgColor("#F88017");
...
//if, for example, your PDF table has 4 columns
//1st column will occupy 10% of table's horizontal width,...3rd - 20%, 4th - 60%
float[] columnWidths = new float[]{0.1f, 0.1f, 0.2f, 0.6f};
pdfOpt.setColumnWidths(columnWidths);
...
</code>```

Finally your p:dataExporter component should look like this

```<code><p:dataExporter type="pdf" target="tbl" fileName="cars" options="#{customizedDocumentsView.pdfOpt}"/>
</code>```

This solution using PF showcase produces following result

Suggestion for extending this solution:

Primefaces exporter uses iText ver 2.1.7. with old but still powerful API.
For example, in ExporterOptions in step 1. you can add

```<code>public int[] getColumnWidths();
</code>```

to set absolute column widths
or you can set any other option driven by your project requirements.

Body:
I have a Primefaces DataGrid that I export whith Primefaces DataExporter but I can't figure out how to resize the columns.

I added a preporcessor

And this is the code in my bean

public void preProcessPDF(Object document) {
        Document pdf = (Document) document;
        pdf.open();
        pdf.setPageSize(PageSize.A4);

        //I need to do something like that
        //PdfPTable table = new PdfPTable(4);
        //float[] columnWidths = new float[] {10f, 20f, 30f, 10f};
        //table.setWidths(columnWidths);
    }

Is there any way to do this ?

Body:
Recently I inherited project with many already existing exporters with already set options tags so I needed to find solution that will keep all of them intact.

I got an idea from this accepted answer.

My solution sets column widths via options tag of p:dataExporter so there is no need for pre/post processing. I tested it using Primefaces ver 4.x and up.

Step by step procedure:

Create new package
org.primefaces.component.export
inside your project.

From Primefaces git repository fully copy following classes
ExporterOptions ,PDFOptions, Exportedfactory and PDFExporter
into newly created package.

In ExporterOptions add
public float[] getColumnWidths();

In PDFOptions add
float[] columnWidths;
and add getter and setter.

In ExporterFactory modify line
exporter = new PdfExporter(); to  exporter = new CustomPdfExporter();

Rename PDFExporter class to CustomPDFExporter and keep just following export method fully

public void export(FacesContext context, DataTable table, String filename, boolean pageOnly, boolean selectionOnly, String encodingType,MethodExpression preProcessor, MethodExpression postProcessor, ExporterOptions options) throws IOException

Delete code from other export methods but keep declarations.

Inside CustomPDFExporter add 2 lines in ExportPdfTable method

protected PdfPTable exportPDFTable(FacesContext context, DataTable table, boolean pageOnly, boolean selectionOnly, String encoding) throws DocumentException {
   int columnsCount = getColumnsCount(table);
   PdfPTable pdfTable = new PdfPTable(columnsCount);
   this.cellFont = FontFactory.getFont(FontFactory.TIMES, encoding);
   this.facetFont = FontFactory.getFont(FontFactory.TIMES, encoding, Font.DEFAULTSIZE, Font.BOLD);

    if (this.expOptions != null) {
        applyFacetOptions(this.expOptions);
        applyCellOptions(this.expOptions);
        //line 1
        //sets columns column relative widths to iText PdfTable object
        pdfTable.setWidths(this.expOptions.getColumnWidths());
        //line 2
        //decreases page margins comparing to original 'Primefaces' layout
        pdfTable.setWidthPercentage(100);
    }

    //....

}

Now you are ready to go managed bean and add pdf option. For example

pdfOpt = new PDFOptions(); //add getter and setter too
pdfOpt.setFacetBgColor("#F88017");
...
//if, for example, your PDF table has 4 columns
//1st column will occupy 10% of table's horizontal width,...3rd - 20%, 4th - 60%
float[] columnWidths = new float[]{0.1f, 0.1f, 0.2f, 0.6f};
pdfOpt.setColumnWidths(columnWidths);
...

Finally your p:dataExporter component should look like this

<p:dataExporter type="pdf" target="tbl" fileName="cars" options="#{customizedDocumentsView.pdfOpt}"/>

This solution using PF showcase produces following result

Suggestion for extending this solution:

Primefaces exporter uses iText ver 2.1.7. with old but still powerful API.
For example, in ExporterOptions in step 1. you can add

public int[] getColumnWidths();

to set absolute column widths
or you can set any other option driven by your project requirements.


答:
A little more information would be needed as to the entire scope of the application, however when I get myself in to situations like this I normally look at the following avenues of approach:

Will a try / catch solve my problem.
    In your catch, you could redirect elsewhere. If you don't catch anything
    often times you will get a bit of lag.

Is there a way to avoid the error all together through user constraints.

Lastly, You may want to use setInterval() over setTimeout().

Can you provide more information as to the scope of the operation?

Title: Resend HTTP post before error timeout

Body:
I have an Angular 4 project that uses a http post to commands across to our backend. The issue is that sometimes a command can be sent out before the backend is fully up and running. Normally an "ERR_CONNECTION_TIME_OUT" would occur, but our embedded browser for whatever reason holds onto the post for an extremely long time before giving us the error (5 minutes). Since a 5 minute wait is unacceptable, I need to come up with a way to re-send our http post if there isn't a response within 15-30~ seconds

Here is what the current post looks like

this._http.post(this.sockclientURL, body, { headers: headers })
  .subscribe((res) => {

    let text = res.text();

    if (text.startsWith("ERROR")) {
      console.log("Sockclient Error.");
      if (this.sockclientErrorRetryCount < this.sockclientErrorRetryLimit) {
        console.log("Retrying in 3 seconds.");
        this.sockclientErrorRetryCount++;

        setTimeout(() => {
          this.SendCommand(command, success, fail);
        }, 3000);
      }
      return;
    }
    else {
      this.sockclientErrorRetryCount = 0;
    }

    if (text == "N" || text.startsWith("N ")) {
      this._modalService.alert(this._nackLookup.convert(text));
      if (typeof fail == 'function') {
        fail(text);
      }
    }
    else {

      let deserializedCommand = command.deserialize(text);

      success(deserializedCommand);

      let repeatMillis: number = deserializedCommand.getRepeatMillis();

      if (repeatMillis && repeatMillis > 0) {
        setTimeout(() => {
          this.SendCommand(command, success, fail);
        }, repeatMillis);
      }
    }
  },
  (err) => {
    console.log(err);
    let repeatMillis = 1000;
      setTimeout(() => {
        this.SendCommand(command, success, fail);
      }, repeatMillis);
  });

So to re-cap, I have some code in place to re-attempt the command if an error occurs, but our embedded browser holds onto its timeout error for several minutes. I need something to attempt to re-send after 15-30 seconds of no response


问:
Remove preceding spaces and tabs from a given string in C language
What C function, if any, removes all preceding spaces and tabs from a string?</p>

答:
A simpler function to trim white spaces</p>
```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char * trim(char * buff);

int main()
{
    char buff[] = "    \r\n\t     abcde    \r\t\n     ";
    char* out = trim(buff);
    printf(">>>>%s<<<<\n",out);
}

char * trim(char * buff)
{
    //PRECEDING CHARACTERS
    int x = 0;
    while(1==1)
    {
        if((*buff == ' ') || (*buff == '\t') || (*buff == '\r') || (*buff == '\n'))
            {
                x++;
                ++buff;
            }
        else
            break;
    }
    printf("PRECEDING spaces : %d\n",x);
    //TRAILING CHARACTERS
    int y = strlen(buff)-1;
    while(1==1)
    {
        if(buff[y] == ' ' || (buff[y] == '\t') || (buff[y] == '\r') || (buff[y] == '\n'))
            {
                y--;
            }
        else
            break;
    }
    y = strlen(buff)-y;
    printf("TRAILING spaces : %d\n",y);
    buff[strlen(buff)-y+1]='\0';
    return buff;
}
</code>```

Body:
A simpler function to trim white spaces

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char * trim(char * buff);

int main()
{
    char buff[] = "    \r\n\t     abcde    \r\t\n     ";
    char* out = trim(buff);
    printf(">>>>%s<<<<\n",out);
}

char * trim(char * buff)
{
    //PRECEDING CHARACTERS
    int x = 0;
    while(1==1)
    {
        if((*buff == ' ') || (*buff == '\t') || (*buff == '\r') || (*buff == '\n'))
            {
                x++;
                ++buff;
            }
        else
            break;
    }
    printf("PRECEDING spaces : %d\n",x);
    //TRAILING CHARACTERS
    int y = strlen(buff)-1;
    while(1==1)
    {
        if(buff[y] == ' ' || (buff[y] == '\t') || (buff[y] == '\r') || (buff[y] == '\n'))
            {
                y--;
            }
        else
            break;
    }
    y = strlen(buff)-y;
    printf("TRAILING spaces : %d\n",y);
    buff[strlen(buff)-y+1]='\0';
    return buff;
}


问:
Creating new record in Sequel via Sinatra
I have following model:

```<code>DB.create_table :teams do
  primary_key :id
  column :name, :text, :unique=>true
end

DB.create_table :players do
  primary_key :id
  column :name, :text, :unique=>true
  column :position, :text
  foreign_key :team_id
end

class Team < Sequel::Model
    plugin :json_serializer
    one_to_many :players
end

class Player < Sequel::Model
    plugin :serialization, :json
    many_to_one :teams
end
</code>```

My full code looks like

```<code>require 'rubygems'
require 'sequel'
require 'sinatra'
require 'db' #model file
require 'thread'
require 'json'
require "sinatra/reloader" if development?  # reload

before do
  @teams = Team.all
end

get '/teams/:id' do |id|
  @team = Team[id]
  haml :team_view
end

post '/teams/?' do
    Team.create(:name => 'FC Barcelona')
#here: Read error: #<NoMethodError: undefined method `bytesize' for [:name, "FC Barcelona"]:Array>

end
</code>```

Am I thinking wrong? how to do it correctly?
Can you provide me some working example?
How I can process JSON data which I want to post?

Thank you!

答:
Your first creation doesn't work as written because you have no variable named "name". Perhaps you meant b.name = jdata?

It works for me with a valid name attribute, and the call to create works fine as well:

```<code>require 'sequel'
p Sequel::VERSION #=> "3.15.0"

DB = Sequel.sqlite

DB.create_table :teams do
  primary_key :id
  column :name, :text, :unique=>true
end

DB.create_table :players do
  primary_key :id
  column :name, :text, :unique=>true
  column :position, :text
  foreign_key :team_id
end

class Team < Sequel::Model
  plugin :json_serializer
  one_to_many :players
end

class Player < Sequel::Model
  plugin :serialization, :json
  many_to_one :teams
end

begin
  Team.new do |b|
    b.name = name
    b.save
  end
rescue Exception=>e
  p e
  #=> #<NameError: undefined local variable or method `name' for main:Object>
end

Team.new do |b|
  b.name = "Boo!"
  b.save
end
Team.create(:name => 'FC Barcelona')

p Team.all
# [
#  #<Team @values={:id=>1, :name=>"Boo!"}>,
#  #<Team @values={:id=>2, :name=>"FC Barcelona"}>
# ]
</code>```

You'll need to share more details for us to reproduce your problem before we can help. Also note that your code includes some red herrings, which I've included above just for completeness. The Player table, model, relationships, and JSON serialization all do not affect my test case. The code could just as well be:

```<code>require 'sequel'
DB = Sequel.sqlite
DB.create_table :teams do
  primary_key :id
  column :name, :text, :unique=>true
end
class Team < Sequel::Model; end
Team.create(:name => 'FC Barcelona')
p Team.all
</code>```

Body:
I have following model:

DB.create_table :teams do
  primary_key :id
  column :name, :text, :unique=>true
end

DB.create_table :players do
  primary_key :id
  column :name, :text, :unique=>true
  column :position, :text
  foreign_key :team_id
end

class Team < Sequel::Model
    plugin :json_serializer
    one_to_many :players
end

class Player < Sequel::Model
    plugin :serialization, :json
    many_to_one :teams
end

My full code looks like

require 'rubygems'
require 'sequel'
require 'sinatra'
require 'db' #model file
require 'thread'
require 'json'
require "sinatra/reloader" if development?  # reload

before do
  @teams = Team.all
end

get '/teams/:id' do |id|
  @team = Team[id]
  haml :team_view
end

post '/teams/?' do
    Team.create(:name => 'FC Barcelona')
#here: Read error: #<NoMethodError: undefined method `bytesize' for [:name, "FC Barcelona"]:Array>

end

Am I thinking wrong? how to do it correctly?
Can you provide me some working example?
How I can process JSON data which I want to post?

Thank you!

Body:
Your first creation doesn't work as written because you have no variable named "name". Perhaps you meant b.name = jdata?

It works for me with a valid name attribute, and the call to create works fine as well:

require 'sequel'
p Sequel::VERSION #=> "3.15.0"

DB = Sequel.sqlite

DB.create_table :teams do
  primary_key :id
  column :name, :text, :unique=>true
end

DB.create_table :players do
  primary_key :id
  column :name, :text, :unique=>true
  column :position, :text
  foreign_key :team_id
end

class Team < Sequel::Model
  plugin :json_serializer
  one_to_many :players
end

class Player < Sequel::Model
  plugin :serialization, :json
  many_to_one :teams
end

begin
  Team.new do |b|
    b.name = name
    b.save
  end
rescue Exception=>e
  p e
  #=> #<NameError: undefined local variable or method `name' for main:Object>
end

Team.new do |b|
  b.name = "Boo!"
  b.save
end
Team.create(:name => 'FC Barcelona')

p Team.all
# [
#  #<Team @values={:id=>1, :name=>"Boo!"}>,
#  #<Team @values={:id=>2, :name=>"FC Barcelona"}>
# ]

You'll need to share more details for us to reproduce your problem before we can help. Also note that your code includes some red herrings, which I've included above just for completeness. The Player table, model, relationships, and JSON serialization all do not affect my test case. The code could just as well be:

require 'sequel'
DB = Sequel.sqlite
DB.create_table :teams do
  primary_key :id
  column :name, :text, :unique=>true
end
class Team < Sequel::Model; end
Team.create(:name => 'FC Barcelona')
p Team.all


问:
SAMBA in Centos 7 doesn't starts
I'm new in installing services in centos and I have sume issue that I can't find the solution. I installed SAMBA with the comand

```<code>yum install samba samba-client samba-common
</code>```

being root, but when I do

```<code>systemctl start smb
</code>```

it shows me this errors when I do systemctl status smb:

photo

I'm desperate, please could someone help me? Thanks!

答: I've solved the problem installing Centos 7 with xfce unstead of GNOME and it's work's perfecty. I hope this will help someone other.</p>

Title: SAMBA in Centos 7 doesn't starts

Body:
I'm new in installing services in centos and I have sume issue that I can't find the solution. I installed SAMBA with the comand

yum install samba samba-client samba-common

being root, but when I do

systemctl start smb

it shows me this errors when I do systemctl status smb:

photo

I'm desperate, please could someone help me? Thanks!


问:
Python: Create text file, write to it, replace string
I am creating a file, writing to it, then I want to replace a string. I have everything working, except the replace. I have tried re.sub, str.replace, etc. I can't figure it out.

```<code>target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
file.write(target_string)
target_string = re.sub('4', '55', target_string)

Desired Output: foo55bar5555foobar555555foobar, foo55bar
</code>```

Thanks.

答:
here  (does also a bonus backup of the text file) :P

```<code>import fileinput

# CREATE / WRITE
f = open("test.txt","w+")
f.write("foo4bar44foobar444foobar, foo4bar")
f.close()

# REPLACE
with fileinput.FileInput("test.txt", inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace("4", "55"), end='')
</code>```

if you don't need the backup file to compare just remove  backup='.bak' form the arguments passed inside fileinput.FileInput

Body:
I am creating a file, writing to it, then I want to replace a string. I have everything working, except the replace. I have tried re.sub, str.replace, etc. I can't figure it out.

target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
file.write(target_string)
target_string = re.sub('4', '55', target_string)

Desired Output: foo55bar5555foobar555555foobar, foo55bar

Thanks.

Body:
here  (does also a bonus backup of the text file) :P

import fileinput

# CREATE / WRITE
f = open("test.txt","w+")
f.write("foo4bar44foobar444foobar, foo4bar")
f.close()

# REPLACE
with fileinput.FileInput("test.txt", inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace("4", "55"), end='')

if you don't need the backup file to compare just remove  backup='.bak' form the arguments passed inside fileinput.FileInput


问:
How to organize a framework project which depends on pods?
We are going to create a framework project (let's name it F) to be shared along a couple of iOS app projects.
F depends on several third-party frameworks (distributed by Cocoa pods).

It is decided that F will be distributed as a .framework (not as pod).

The idea is that apps will only include F. Developers of the apps does not even need not to know that F internally uses some other frameworks.

We will create a test project (let's name it T) to test that F behaves well.

The question is how to organize it?

Normally, I would make F subproject of T in Xcode:

```<code>T.xcodeproj
    F.xcodeproj
</code>```

Then I develop F, test it and eventually distribute F.framework to guys working on the apps.

But is this case, F depends on pods. After pod install I get F.xcworkspace. Obviously, I cannot make project dependent on workspace:

```<code>T.xcodeproj???
    F.xcworkspace???
</code>```

Does it mean that I cannot combine the T and F projects (which would make it easier to develop both the framework and test app T simultaneously)

答:
You should be able to put a full project in the same .xcodeproj as your framework you are developing. What I did was created a sample app (Here it's called "TestRunner") that would be used to run some unit tests and show some basic functionality as a target in my frameworks' .xcodeproj.

This way we have the tests for the framework and a working project with it in the same repo. Here is what the structure looks like.

TestRunner is a full app that you can run in the simulator and includes DCExtensions.framework. When we go to build the DCExtension framework, the TestRunner code is not included. The pods we have installed are included.

Your Podfile might look something like this.

```<code># Uncomment the next line to define a global platform for your project
platform :ios, '9.0'

target 'DCExtensions' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for DCExtensions
  pod 'Alamofire'

  target 'DCExtensionsTests' do
    inherit! :search_paths
    # Pods for testing

  end

end

target 'TestRunner' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for TestRunner

end
</code>```

Body:
We are going to create a framework project (let's name it F) to be shared along a couple of iOS app projects.
F depends on several third-party frameworks (distributed by Cocoa pods).

It is decided that F will be distributed as a .framework (not as pod).

The idea is that apps will only include F. Developers of the apps does not even need not to know that F internally uses some other frameworks.

We will create a test project (let's name it T) to test that F behaves well.

The question is how to organize it?

Normally, I would make F subproject of T in Xcode:

T.xcodeproj
    F.xcodeproj

Then I develop F, test it and eventually distribute F.framework to guys working on the apps.

But is this case, F depends on pods. After pod install I get F.xcworkspace. Obviously, I cannot make project dependent on workspace:

T.xcodeproj???
    F.xcworkspace???

Does it mean that I cannot combine the T and F projects (which would make it easier to develop both the framework and test app T simultaneously)

Body:
You should be able to put a full project in the same .xcodeproj as your framework you are developing. What I did was created a sample app (Here it's called "TestRunner") that would be used to run some unit tests and show some basic functionality as a target in my frameworks' .xcodeproj.

This way we have the tests for the framework and a working project with it in the same repo. Here is what the structure looks like.

TestRunner is a full app that you can run in the simulator and includes DCExtensions.framework. When we go to build the DCExtension framework, the TestRunner code is not included. The pods we have installed are included.

Your Podfile might look something like this.

# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'

target 'DCExtensions' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for DCExtensions
  pod 'Alamofire'

  target 'DCExtensionsTests' do
    inherit! :search_paths
    # Pods for testing

  end

end

target 'TestRunner' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for TestRunner

end


问:
JavaScript function wrapped in TypeScript function is not working
I am trying to implement a datepicker whose button upon being clicked displays a calendar. For this purpose, I have wrapped datepicker() (JavaScript function) in pickDate() (user defined TypeScript function) but the button is not clicking/displaying anything. What could be going wrong?

Below are my code snippets

HTML file

          <input type='text' class="form-control" />

```

<p><strong>.ts file</strong></p>

```import {Component} from '@angular/core';
import * as $ from 'jquery';

@Component({
    selector : 'pm-datepicker', /** This is a directive which implies this Component's template can be
    used as any other Component's template.  */
    templateUrl : './datepicker.component.html' /** Path to our HTML file */
})

export class DatePickerComponent {

    pickDate() {
        console.log(5); /** To check if something is logging */
        $('#datetimepicker1').datepicker();
    }
}
```

<p><strong>Errors on console</strong></p>

```ERROR TypeError: __WEBPACK_IMPORTED_MODULE_1_jquery__(...).datepicker is not a function
    at DatePickerComponent.webpackJsonp.../../../../../src/app/datepicker/datepicker.component.ts.DatePickerComponent.pickDate (datepicker.component.ts:18)
    at Object.eval [as handleEvent] (DatePickerComponent.html:21)
    at handleEvent (core.es5.js:11998)
    at callWithDebugContext (core.es5.js:13467)
    at Object.debugHandleEvent [as handleEvent] (core.es5.js:13055)
    at dispatchEvent (core.es5.js:8614)
    at core.es5.js:9228
    at HTMLSpanElement.<anonymous> (platform-browser.es5.js:2648)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.es5.js:3881)
```

<p><strong>Edit 2</strong></p>

<p>I carried out the following steps : </p>

```npm install jquery-ui --save
```

and then I included the script URLs with respect to jQuery and jQuery-ui in index.html but the errors still persist. Is there anything specifically I need to import in my component.ts or app.module.ts?

答:
Issue might be

If there is any other library using $ variable

may be missing some files from jQuery

If nothing works then include datepicker.js also

```

Body:
I am trying to implement a datepicker whose button upon being clicked displays a calendar. For this purpose, I have wrapped datepicker() (JavaScript function) in pickDate() (user defined TypeScript function) but the button is not clicking/displaying anything. What could be going wrong?

Below are my code snippets

HTML file

          <input type='text' class="form-control" />

.ts file

import {Component} from '@angular/core';
import * as $ from 'jquery';

@Component({
    selector : 'pm-datepicker', /** This is a directive which implies this Component's template can be
    used as any other Component's template.  */
    templateUrl : './datepicker.component.html' /** Path to our HTML file */
})

export class DatePickerComponent {

    pickDate() {
        console.log(5); /** To check if something is logging */
        $('#datetimepicker1').datepicker();
    }
}

Errors on console

ERROR TypeError: __WEBPACK_IMPORTED_MODULE_1_jquery__(...).datepicker is not a function
    at DatePickerComponent.webpackJsonp.../../../../../src/app/datepicker/datepicker.component.ts.DatePickerComponent.pickDate (datepicker.component.ts:18)
    at Object.eval [as handleEvent] (DatePickerComponent.html:21)
    at handleEvent (core.es5.js:11998)
    at callWithDebugContext (core.es5.js:13467)
    at Object.debugHandleEvent [as handleEvent] (core.es5.js:13055)
    at dispatchEvent (core.es5.js:8614)
    at core.es5.js:9228
    at HTMLSpanElement.<anonymous> (platform-browser.es5.js:2648)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.es5.js:3881)

Edit 2

I carried out the following steps :

npm install jquery-ui --save

and then I included the script URLs with respect to jQuery and jQuery-ui in index.html but the errors still persist. Is there anything specifically I need to import in my component.ts or app.module.ts?

Body:
Issue might be

If there is any other library using $ variable

may be missing some files from jQuery

If nothing works then include datepicker.js also

<script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.5.4/datepicker.js"></script>


问:
Is it possible to pass the reference to the i-th element of a primitive array?
Right now, somewhere in my code, I am passing a reference to a primitive, for example an Int

```<code>val i = 0
</code>```

to

```<code>fun whatever(i: KMutableProperty0<Int>)
</code>```

as

```<code>whatever(::i)
</code>```

to being able to get/set its value from within the function

Everything worked great so far.

I'd like now to do the same for an i-th element of a primitive array, such as an IntArray

```<code>val arr = intArrayOf(1, 2, 3)

whatever(/* passing the reference to item 2 of arr*/)
</code>```

Is it possible?

答:
It is not possible, since Java doesn't allow pointer operations on arrays. Kotlin doing that (if possible at all at the bytecode level) would break interoperability.

EDIT: It seems you don't care about true array pointers, like in C, so you can create yourself wrappers similar to those KMutableProperty:

```<code>class IntArrayRef(val array: IntArray, val index: Int) {
    fun get(): Int = array.get(index)
    fun set(value: Int) { array[index] = value }
}

fun modify(value: IntArrayRef) {
    value.set(4)
}

fun test() {
    val s = "abc"
    val arr = intArrayOf(1, 2, 3)
    modify(IntArrayRef(arr, 1))
}
</code>```

My guess is you would need to create manually one wrapper for each native array type, since they are exposed at the Kotlin level as non generic types.

Body:
Right now, somewhere in my code, I am passing a reference to a primitive, for example an Int

val i = 0

to

fun whatever(i: KMutableProperty0<Int>)

as

whatever(::i)

to being able to get/set its value from within the function

Everything worked great so far.

I'd like now to do the same for an i-th element of a primitive array, such as an IntArray

val arr = intArrayOf(1, 2, 3)

whatever(/* passing the reference to item 2 of arr*/)

Is it possible?

Body:
It is not possible, since Java doesn't allow pointer operations on arrays. Kotlin doing that (if possible at all at the bytecode level) would break interoperability.

EDIT: It seems you don't care about true array pointers, like in C, so you can create yourself wrappers similar to those KMutableProperty:

class IntArrayRef(val array: IntArray, val index: Int) {
    fun get(): Int = array.get(index)
    fun set(value: Int) { array[index] = value }
}

fun modify(value: IntArrayRef) {
    value.set(4)
}

fun test() {
    val s = "abc"
    val arr = intArrayOf(1, 2, 3)
    modify(IntArrayRef(arr, 1))
}

My guess is you would need to create manually one wrapper for each native array type, since they are exposed at the Kotlin level as non generic types.


问:
Can I call Java from Node.js via JNI and how?
can I call Java from Node.js via JNI? Are there any examples?

答:
I am not aware of all the details of Node.js but i am assuming that your mentioning of JNI is actually the Java Native Interface. One can only use JNI from Java, so imho it does not make sense to access Java from JNI if you are not already in java.

It would appear that this is the wrong approach, and you need to search the Node.js doco for their integration chapter...