问:
Hibernate domain object validation error redundant ,why?
I am using Hibernate on Grails.

When I have field validation error, the exception message contains redundant message.

e.g

Provided id of the wrong type for class ad.Client. Expected: class java.lang.String, got class java.lang.Long; nested exception is org.hibernate.TypeMismatchException: Provided id of the wrong type for class org.ad.Client. Expected: class java.lang.String, got class java.lang.Long

when I have many field erros, I got a lot of unexpected redundant messages, why is this happening?

答: This is due to the way exceptions wrap each other, and how getMessage() works.  Stack traces and exception messages of any kind often have some redundant information.  Better too much than not enough :) It shouldn't really be an issue as this is for you, the developer.  This isn't something you show externally, and not something to spend time on trying to improve.


来源: stackexchange

问:
remove string using strtr
say it if i want to remove a word like this: ',40,15,550);context2.fillText('MY_TEXT_HERE',40,20,550);context2.fillText('

so, i want to remove ',40,15,550);context2.fillText(' and ',40,20,550);context2.fillText('

if using standart strtr is we need to create 2 condition like

```<code>$lyrics = ($_POST['utamapkanji']);
$replacements = [
            "',40,15,550);context2.fillText('" => " ",
            "',40,20,550);context2.fillText('" => " ",
            ];
            $result = strtr($lyrics , $replacements);
            ?>
</code>```

result will be MY_TEXT_HERE.

what i want to do is, remove a word that begin ',40 and ended with fillText(' so, by doing this i only need to make 1 condition to remove it.

答:
Try this replacement:</p>

```<code>$result = preg_replace("(\',40[^\']*\')", '', $lyrics);
</code>```

ContentLicense: CC BY-SA 3.0

Title: remove string using strtr

Body:
say it if i want to remove a word like this: ',40,15,550);context2.fillText('MY_TEXT_HERE',40,20,550);context2.fillText('

so, i want to remove ',40,15,550);context2.fillText(' and ',40,20,550);context2.fillText('

if using standart strtr is we need to create 2 condition like

$lyrics = ($_POST['utamapkanji']);
$replacements = [
            "',40,15,550);context2.fillText('" => " ",
            "',40,20,550);context2.fillText('" => " ",
            ];
            $result = strtr($lyrics , $replacements);
            ?>

result will be MY_TEXT_HERE.

what i want to do is, remove a word that begin ',40 and ended with fillText(' so, by doing this i only need to make 1 condition to remove it.

Body:
Try this replacement:

$result = preg_replace("(\',40[^\']*\')", '', $lyrics);


问:
How powerful is OpenGL?
I want to create an application which will capture one by camera and will manipulate the live images taken by it in milliseconds of the time.

The goal is that the application should change my clothes with some other clothes which I will supply.

I have few questions:

Does OpenGL have such power of modifying live images in a way it will change my clothes in the computer image? I will be moving my hands and the like, can it be that accurate so it'll just look like I am in changed clothes and not the original I am wearing?

答:
OpenGL can add the clothing very quickly indeed. This will not even begin to strain its capability in compositing images.

However, you may have a misunderstanding about what exactly it can do for you. It can blend images, but you will have to tell it exactly where to draw your clothes, how to deform them, etc., and you will have to figure these things out by yourself. OpenGL will not help you find out where the person's hand is.

ContentLicense: CC BY-SA 2.5

Title: How powerful is OpenGL?


问:
Opposite of INT into STRING
What is the Opposite of this code in to string? </p>

```<code>int number = Integer.parseInt(input.getText().toString());
</code>```

答:
The opposite of String to an int would be an int to a String.

```<code>String strNumber = String.valueOf(number); //< fast and efficient.
</code>```

or

```<code>String strNumber = "" + number; //< lazy and slow.
</code>```

Title: Opposite of INT into STRING

Body:
What is the Opposite of this code in to string?

int number = Integer.parseInt(input.getText().toString());

Body:
The opposite of String to an int would be an int to a String.

String strNumber = String.valueOf(number); //< fast and efficient.

or

String strNumber = "" + number; //< lazy and slow.


问:
Bootstrap form validation not working without console error
This is Simple form.

This is JS code:

$(document).ready(function() {
  $('#ledgerHolderjHolderFormEdit').bootstrapValidator({
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      JH_INIT: {
        validators: {
          notEmpty: {
            message: "'First Name' is required."
          },
          regexp: {
            regexp: /^07[a-zA-Z0-9.,:;!-@#\$%\^\&*\)\(+=_-`~><|].+$/,
            message: "'Mobile Number' must only start with '07'."
          },
          stringLength: {
            min: 5,
            max: 30,
            message: "'First Name' must be more than 2 and less than 255 characters long."
          }
        }
      }
    }
  });
});
```

There are no errors show in console, and could not find errors. Can anyone help me?

答:
Solution Found

There are no effect in form and js. Issue was, I wrote html form in 'edit function'(append html form using jQuery). And after validation function wrote in another function. That is the reason.

After many efforts, I wrote validation inside that 'edit function'. The issue was solved.

Body:
This is Simple form.

This is JS code:

$(document).ready(function() {
  $('#ledgerHolderjHolderFormEdit').bootstrapValidator({
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      JH_INIT: {
        validators: {
          notEmpty: {
            message: "'First Name' is required."
          },
          regexp: {
            regexp: /^07[a-zA-Z0-9.,:;!-@#\$%\^\&*\)\(+=_-`~><|].+$/,
            message: "'Mobile Number' must only start with '07'."
          },
          stringLength: {
            min: 5,
            max: 30,
            message: "'First Name' must be more than 2 and less than 255 characters long."
          }
        }
      }
    }
  });
});

There are no errors show in console, and could not find errors. Can anyone help me?


问:
Display alias of a subdomain as main domain name
first of all thanks for being there because I don't know what I could do without Stack Overflow through all these years!

Here's the thing. I developed a Wordpress website in a subdomain comeovercome.livewithauthenticity.com

and I bought a domain alias to access the url easily

comeovercome.com

but when I use the share feature and when I setup the Yoast SEO plugin, I can't use this domain name as the main one, so in the shared post people get automatically the long real url instead of the easy one.

How can I keep the website in this subdomain but always point to it with the nice URL?

I hope my question is clear. Thanks in advance!

答:
Before change anything please backup backup backup
read the #tag comments and then change according to your domain name

.htaccess main domain to subdirectory redirect

```<code># Do not change this line.
RewriteEngine on
# Change example.com to be your main domain.
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteCond %{REQUEST_URI} !^/subdirectory/
# Don't change the following two lines.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteRule ^(.*)$ /subdirectory/$1
# Change example.com to be your main domain again.
# Change 'subdirectory' to be the directory you will use for your main domain
# followed by / then the main file for your site, index.php, index.html, etc.
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ subdirectory/index.html [L]
</code>```

Thanks

Body:
Before change anything please backup backup backup
read the #tag comments and then change according to your domain name

.htaccess main domain to subdirectory redirect

# Do not change this line.
RewriteEngine on
# Change example.com to be your main domain.
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteCond %{REQUEST_URI} !^/subdirectory/
# Don't change the following two lines.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteRule ^(.*)$ /subdirectory/$1
# Change example.com to be your main domain again.
# Change 'subdirectory' to be the directory you will use for your main domain
# followed by / then the main file for your site, index.php, index.html, etc.
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ subdirectory/index.html [L]

Thanks


问:
Why does select result fields double data scanned in BigQuery
I have a table with 2 integer fields x,y and few millions of rows.

The fields are created with the following code:

```<code>Field.newBuilder("x", LegacySQLTypeName.INTEGER).setMode(Field.Mode.NULLABLE).build();
</code>```

If I run the following from the web:

```<code>SELECT x,y FROM [myproject:Test.Test]  where  x=1 LIMIT 50
Query Editor: "Valid: This query will process 64.9 MB when run."
</code>```

compared to:

```<code>SELECT x FROM [myproject:Test.Test]  where  x=1 LIMIT 50
Query Editor: " Valid: This query will process 32.4 MB when run."
</code>```

It scans more than double of the original data scanned.

I would expect it will first find the relevant rows based on where clause and then bring the extra field without scanning the entire second field.

Any inputs on why it doubles the data scanned and how to avoid it will be appreciated.

In my application I have hundred of possible fields which I need to fetch for a very small number of rows (50) which answer the query.

Does this means I will need to processed all fields data?

* I'm aware how columnar database works, but wasn't aware for the huge price when you want to brings lots of fields based on a very specific where clause.

The following link provide very clear answer:
best-practices-performance-input

答:
BigQuery does not have a concept of index or something like that. When you query a field column, BigQuery will scan through all the values of that column and then make the operations you want (for a deeper deep understanding they have some pretty cool posts about the inner workings of BQ).

That means that when you select x and y where x = 1, BQ will read through all values of x and y and then find where x = 1.

This ends up being an amazing feature of BQ, you just load your data there and it just works. It does force you to be aware on how much data you retrieve from each query. Queries of the type select * from table should be used only if you really need all columns.

Body:
I have a table with 2 integer fields x,y and few millions of rows.

The fields are created with the following code:

Field.newBuilder("x", LegacySQLTypeName.INTEGER).setMode(Field.Mode.NULLABLE).build();

If I run the following from the web:

SELECT x,y FROM [myproject:Test.Test]  where  x=1 LIMIT 50
Query Editor: "Valid: This query will process 64.9 MB when run."

compared to:

SELECT x FROM [myproject:Test.Test]  where  x=1 LIMIT 50
Query Editor: " Valid: This query will process 32.4 MB when run."

It scans more than double of the original data scanned.

I would expect it will first find the relevant rows based on where clause and then bring the extra field without scanning the entire second field.

Any inputs on why it doubles the data scanned and how to avoid it will be appreciated.

In my application I have hundred of possible fields which I need to fetch for a very small number of rows (50) which answer the query.

Does this means I will need to processed all fields data?

* I'm aware how columnar database works, but wasn't aware for the huge price when you want to brings lots of fields based on a very specific where clause.

The following link provide very clear answer:
best-practices-performance-input


答:
you can do it like this

```<code> int a=5;
 String s = ""+a;
</code>```

or

```<code>int a =5;
String s=Integer.toString(a);
</code>```

Title: Opposite of INT into STRING

Body:
you can do it like this

 int a=5;
 String s = ""+a;

or

int a =5;
String s=Integer.toString(a);


问:
Synchronising threads for multiple readers / single writer in Clojure
I have some non-thread-safe code (a writer to shared data) that can only be called from multiple threads in a serialised manner, but I don't want to block any other thread-safe work (multiple readers) when this code is not being called.

This is essentially a multiple reader / single writer type locking situation where writers need to exclude both readers and other writers.

i.e. I have two functions:

```<code>(defn reader-function [] ....) // only reads from shared data

(defn writer-function [] ....) // writes to shared data
</code>```

And a number of threads that are running (possibly in a loop) the following:

```<code>(do
  (reader-function)
  ...
  (writer-function))
</code>```

If any single thread is executing the writer function, all the other threads must block. i.e. at any one time either:

one thread is executing the
writer and all
others are blocked

multiple threads are
executing the reader function, possibly some threads are
blocked waiting to execute
the writer once all readers are completed

What's the best way to achieve this kind of synchronisation in Clojure?

答: Take a look at java.util.concurrent.locks.ReentrantReadWriteLock. This class allow you to have multiple readers that do not contend with each other on one writer at a time.</p>

Body:
I have some non-thread-safe code (a writer to shared data) that can only be called from multiple threads in a serialised manner, but I don't want to block any other thread-safe work (multiple readers) when this code is not being called.

This is essentially a multiple reader / single writer type locking situation where writers need to exclude both readers and other writers.

i.e. I have two functions:

(defn reader-function [] ....) // only reads from shared data

(defn writer-function [] ....) // writes to shared data

And a number of threads that are running (possibly in a loop) the following:

(do
  (reader-function)
  ...
  (writer-function))

If any single thread is executing the writer function, all the other threads must block. i.e. at any one time either:

one thread is executing the
writer and all
others are blocked

multiple threads are
executing the reader function, possibly some threads are
blocked waiting to execute
the writer once all readers are completed

What's the best way to achieve this kind of synchronisation in Clojure?


问:
Design repositories following the DDD concepts
I'm facing a DDD design issue. I'm confused on how to scope/use repositories with aggregates.

I currently have two aggregates TecTacClient and Entitlement.

```<code>public class TecTacClient
{
    (...)
    public ICollection<Entitlement> Entitlements { get; }
    public bool HasActiveEntitlements => Entitlements.Any(x => x.EndDate >= DateTime.Now);

    public TecTacClient((...),IEnumerable<Entitlement> entitlements)
    {
        (...)
        Entitlements = new List<Entitlement>(entitlements ?? Enumerable.Empty<Entitlement>());
    }
}
</code>```

I consider Entitlement as another aggregate. It also holds a collection of entitlement records. Entitlements records are created/updated independently of entitlements. For instance, when I create a booking, I would also create an entitlement record. This operation would not impact the entitlement.

```<code>public abstract class Entitlement : Entity
{
    (...)

    public ICollection<EntitlementRecord> Records { get; }

    protected Entitlement((...), IEnumerable<EntitlementRecord> records)
    {
        (...)
        Records = new List<EntitlementRecord>(records ?? Enumerable.Empty<EntitlementRecord>());
    }

    public abstract bool IsEligible(Resource resource);
    public DateTimeRange GetCoveringPeriod(DateTime date)  { ... }
    public double GetAvailableQuantity(DateTime date)  { ... }
    public void Consume(DateTime date, double quantity)  { ... }
    public void Match(DateTime date, double quantity)  { ... }
    public void Cancel(int bookingId) { ... }
}
</code>```

I understand that aggregates must be retrieved/persisted using repositories.

Does this mean that I need to create two repositories (for tectacclient and entitlement) and use the entitlement repo whithin the client repo to retrieved entitlements?

Shall I create another repo for EntitlementRecords? Otherwise I end-up having an entitlement repo that looks like this

```<code>IEntitlementRepo
{
  void Create(...);
  void Update(...);
  void Delete(...);

  void AddRecord(...);
  void DeleteRecord(...);
}
</code>```

In the end, in the DDD world do I need to introduce dependencies between repositories to retrieve/persist my aggregates?

答:
One repository per aggregate is simple and good solution, so it's better to have one repo for Entitlements and another for EntitlementRecords.

By the way, your TecTacClient aggregate does't look well-designed. Normally it should not contain Entitlement aggregates. Or Entitlement should not be considered as separate aggregate, it should be a part of TecTacClient aggregate. The same is for EntitlementRecord: it should be considered as part of Entitlement aggregate or Entitlement should not contain it.
Read more about "Design Small Aggregates" rule.

Body:
I'm facing a DDD design issue. I'm confused on how to scope/use repositories with aggregates.

I currently have two aggregates TecTacClient and Entitlement.

public class TecTacClient
{
    (...)
    public ICollection<Entitlement> Entitlements { get; }
    public bool HasActiveEntitlements => Entitlements.Any(x => x.EndDate >= DateTime.Now);

    public TecTacClient((...),IEnumerable<Entitlement> entitlements)
    {
        (...)
        Entitlements = new List<Entitlement>(entitlements ?? Enumerable.Empty<Entitlement>());
    }
}

I consider Entitlement as another aggregate. It also holds a collection of entitlement records. Entitlements records are created/updated independently of entitlements. For instance, when I create a booking, I would also create an entitlement record. This operation would not impact the entitlement.

public abstract class Entitlement : Entity
{
    (...)

    public ICollection<EntitlementRecord> Records { get; }

    protected Entitlement((...), IEnumerable<EntitlementRecord> records)
    {
        (...)
        Records = new List<EntitlementRecord>(records ?? Enumerable.Empty<EntitlementRecord>());
    }

    public abstract bool IsEligible(Resource resource);
    public DateTimeRange GetCoveringPeriod(DateTime date)  { ... }
    public double GetAvailableQuantity(DateTime date)  { ... }
    public void Consume(DateTime date, double quantity)  { ... }
    public void Match(DateTime date, double quantity)  { ... }
    public void Cancel(int bookingId) { ... }
}

I understand that aggregates must be retrieved/persisted using repositories.

Does this mean that I need to create two repositories (for tectacclient and entitlement) and use the entitlement repo whithin the client repo to retrieved entitlements?

Shall I create another repo for EntitlementRecords? Otherwise I end-up having an entitlement repo that looks like this

IEntitlementRepo
{
  void Create(...);
  void Update(...);
  void Delete(...);

  void AddRecord(...);
  void DeleteRecord(...);
}

In the end, in the DDD world do I need to introduce dependencies between repositories to retrieve/persist my aggregates?


问:
Dynamically populate variable number of sprites on grid layout group
As the title suggests, I'm trying to populate a UI panel with a GridLayoutGroup component at runtime with sprites from the resources folder. The problem is that the sprites do not auto-align to the grid cells, instead getting drawn on the center of the panel.

I've tried the approach mentioned here but it does not work for me. Here is the script I've attached to the gui with the GridLayoutGroup:

public class SpriteList : MonoBehaviour
{
    public GameObject gridPanel;
    public const string sortingLayer = "Foreground";

    // Use this for initialization
    void Start()
    {
        Sprite[] spriteArray = Resources.LoadAll<Sprite>("Sprites");
        RectTransform gridRT = gridPanel.GetComponent<RectTransform>();

        for (int i = 0; i < spriteArray.Length; i++)
        {
            GameObject cellObject = new GameObject();
            cellObject.AddComponent<SpriteRenderer>();
            cellObject.GetComponent<SpriteRenderer>().sprite = spriteArray[i];
            cellObject.GetComponent<SpriteRenderer>().sortingLayerName = sortingLayer;

            GameObject sprite = (GameObject) Instantiate(cellObject);
            sprite.transform.SetParent(gridPanel.transform, false);
            LayoutRebuilder.ForceRebuildLayoutImmediate(
                    gridPanel.GetComponent<RectTransform>());
            sprite.transform.localScale = new Vector3(30, 30, 1);
    }
}
```

<p>Changing the settings of the <code>GridLayoutGroup</code> do not modify the behaviour I'm seeing at all.</p>

<p>Since everything I see online seems to indicate that the key is the line </p>

<pre class="lang-c# prettyprint-override"><code>sprite.transform.SetParent(gridPanel.transform, false);
</code>```

which I use, what am I missing?

Much gratitude!

答:
I was able to solve this by creating a rect transform prefab with a SpriteRenderer attached, and then instantiating copies of the prefab and assigning the desired sprite at runtime. I'm not sure why my old approach did not work (I think I am missing something very fundamental) but here is the code I'm using now:

```<code>public GameObject gridPanel;
public const string sortingLayer = "Foreground";
public GameObject prefab;

// Use this for initialization
void Start()
{
    Sprite[] spriteArray = Resources.LoadAll<Sprite>("Sprites");
    GameObject newObj;

    for (int i = 0; i < spriteArray.Length; i++)
    {
        newObj = (GameObject)Instantiate(prefab, transform);
        newObj.GetComponent<SpriteRenderer>().sprite = spriteArray[i];
        newObj.GetComponent<SpriteRenderer>().sortingLayerName = sortingLayer;
        LayoutRebuilder.ForceRebuildLayoutImmediate(gridPanel.transform as RectTransform);
    }
}
</code>```

I should mention that this approach has introduced/uncovered a new issue which is that the sizing and spacing of the sprites is way off. I've been trying to fix this for a while now with no success; I'll continue to try and post my solution here when I determine it, or else ask a separate question and post a link to that here.

Body:
As the title suggests, I'm trying to populate a UI panel with a GridLayoutGroup component at runtime with sprites from the resources folder. The problem is that the sprites do not auto-align to the grid cells, instead getting drawn on the center of the panel.

I've tried the approach mentioned here but it does not work for me. Here is the script I've attached to the gui with the GridLayoutGroup:

public class SpriteList : MonoBehaviour
{
    public GameObject gridPanel;
    public const string sortingLayer = "Foreground";

    // Use this for initialization
    void Start()
    {
        Sprite[] spriteArray = Resources.LoadAll<Sprite>("Sprites");
        RectTransform gridRT = gridPanel.GetComponent<RectTransform>();

        for (int i = 0; i < spriteArray.Length; i++)
        {
            GameObject cellObject = new GameObject();
            cellObject.AddComponent<SpriteRenderer>();
            cellObject.GetComponent<SpriteRenderer>().sprite = spriteArray[i];
            cellObject.GetComponent<SpriteRenderer>().sortingLayerName = sortingLayer;

            GameObject sprite = (GameObject) Instantiate(cellObject);
            sprite.transform.SetParent(gridPanel.transform, false);
            LayoutRebuilder.ForceRebuildLayoutImmediate(
                    gridPanel.GetComponent<RectTransform>());
            sprite.transform.localScale = new Vector3(30, 30, 1);
    }
}

Changing the settings of the GridLayoutGroup do not modify the behaviour I'm seeing at all.

Since everything I see online seems to indicate that the key is the line

sprite.transform.SetParent(gridPanel.transform, false);

which I use, what am I missing?

Much gratitude!

Body:
I was able to solve this by creating a rect transform prefab with a SpriteRenderer attached, and then instantiating copies of the prefab and assigning the desired sprite at runtime. I'm not sure why my old approach did not work (I think I am missing something very fundamental) but here is the code I'm using now:

public GameObject gridPanel;
public const string sortingLayer = "Foreground";
public GameObject prefab;

// Use this for initialization
void Start()
{
    Sprite[] spriteArray = Resources.LoadAll<Sprite>("Sprites");
    GameObject newObj;

    for (int i = 0; i < spriteArray.Length; i++)
    {
        newObj = (GameObject)Instantiate(prefab, transform);
        newObj.GetComponent<SpriteRenderer>().sprite = spriteArray[i];
        newObj.GetComponent<SpriteRenderer>().sortingLayerName = sortingLayer;
        LayoutRebuilder.ForceRebuildLayoutImmediate(gridPanel.transform as RectTransform);
    }
}

I should mention that this approach has introduced/uncovered a new issue which is that the sizing and spacing of the sprites is way off. I've been trying to fix this for a while now with no success; I'll continue to try and post my solution here when I determine it, or else ask a separate question and post a link to that here.


问:
Checking remainder in Javascript
I am super new at Javascript. I'm trying to write a script that logs numbers in order, and then at the end tells me if the final number is even or odd.

What I have is:

```<code>var i = 0;

  do {
    i++;
    console.log(i)
    }

 while (i <= 9);

 if(i % 2 = 1) {
   console.log("odd")
   }

 else {
   console.log("even")
    }
</code>```

Before I added the if/else, it worked. Now I keep getting the error: invalid left-hand side in assignment

What am I doing wrong? And to really display my ignorance, what is the left-hand side in the assignment?

Thanks!

答: Instead of = it should be == in the if condition.

Title: Checking remainder in Javascript

Body:
I am super new at Javascript. I'm trying to write a script that logs numbers in order, and then at the end tells me if the final number is even or odd.

What I have is:

var i = 0;

  do {
    i++;
    console.log(i)
    }

 while (i <= 9);

 if(i % 2 = 1) {
   console.log("odd")
   }

 else {
   console.log("even")
    }

Before I added the if/else, it worked. Now I keep getting the error: invalid left-hand side in assignment

What am I doing wrong? And to really display my ignorance, what is the left-hand side in the assignment?

Thanks!


答:
```<code>if(i % 2 == 1) {
   console.log("odd")
}else {
   console.log("even")
}
</code>```

Because == is for equality comparison while = is for assigning of value.

Title: Checking remainder in Javascript

Body:
if(i % 2 == 1) {
   console.log("odd")
}else {
   console.log("even")
}

Because == is for equality comparison while = is for assigning of value.


问:
Python - Remove quotes and double minus using replace
Given a string such as

```<code>--"I like salami. "-I want to walk to the shops"
</code>```

How can I return the string such as

```<code>I like salami. I want to walk to the shops.
</code>```

I can alter each individually but when I use '-"' it fails.

Quotes

```<code>b = '"'

for char in b:
    solution = MyString.replace(char,"")

#output --I like salami. -I want to walk to the shops
</code>```

Minus

```<code>b = '-'

for char in b:
    solution = MyString.replace(char,"")

#output "I like salami. "I want to walk to the shops"
</code>```

Together

```<code>MyString = '--"I like salami. "-I want to walk to the shops"'

b = '"-'

for char in b:
    print(MyString.replace(char,""))

#output "I like salami. "I want to walk to the shops"
</code>```

答:
```<code>In [1]: MyString = '--"I like salami. "-I want to walk to the shops"'
In [2]: MyString.replace('-', '').replace('"', '')
Out[2]: 'I like salami. I want to walk to the shops'
</code>```

Body:
Given a string such as

--"I like salami. "-I want to walk to the shops"

How can I return the string such as

I like salami. I want to walk to the shops.

I can alter each individually but when I use '-"' it fails.

Quotes

b = '"'

for char in b:
    solution = MyString.replace(char,"")

#output --I like salami. -I want to walk to the shops

Minus

b = '-'

for char in b:
    solution = MyString.replace(char,"")

#output "I like salami. "I want to walk to the shops"

Together

MyString = '--"I like salami. "-I want to walk to the shops"'

b = '"-'

for char in b:
    print(MyString.replace(char,""))

#output "I like salami. "I want to walk to the shops"


答:
you need to   change if condition from  if(i % 2 = 1)

to

```<code>if(i % 2 ==1)
</code>```

Title: Checking remainder in Javascript

Body:
you need to   change if condition from  if(i % 2 = 1)

to

if(i % 2 ==1)


问:
Recursive unitless element type
I am trying to come up with a function that gives me the recursive unitless element type. So for example, to shorten it let's call it ruet, I would like to have:

```<code>A = zeros(5,5)
reut(A) == Float64
using Unitful
A = zeros(5,5)*1u"kg"
reut(A) == Float64
AA = [zeros(5,5) for i in 1:5]
reut(AA) == Array{Float64,2}
AofA = [copy(A) for i in 1:5]
reut(AofA) == Array{Float64,2}
using StaticArrays
AofSA = [@SVector [2.0,3.0] for i in 1:5]
reut(AofSA) == SVector{2,Float64}
AofuSA = [@SVector [2.0u"kg",3.0u"kg"] for i in 1:5]
reut(AofuSA) == SVector{2,Float64}
</code>```

So basically strip away the units but still return the correct element type, which could be an array. It's the array part that's hard. I can recurse:

```<code>recursive_eltype(a) = recursive_eltype(eltype(a))
recursive_eltype{T<:Number}(a::Type{T}) = eltype(a)
</code>```

and then get the unitless element type:

```<code>uEltype = recursive_eltype(u)
uEltypeNoUnits = typeof(one(uEltype))
</code>```

but then this is always the number type, and I can't seem to find a good way to get back the array types when it's an array of arrays, i.e. this method is returning Float64 in all of the examples above. I am wondering if dispatching on static arrays and using similar_type is required here.

Note that I would like the solution to, if possible, not have a requirement on Unitful.jl. Getting the unitless type for the number can be done via one(u), so I think this should be possible.

(Somewhat related Julia issue: https://github.com/JuliaLang/julia/issues/22216)

答:
I came up with:

```<code>Base.@pure recursive_unitless_eltype(a) = recursive_unitless_eltype(eltype(a))
Base.@pure recursive_unitless_eltype{T<:StaticArray}(a::Type{T}) = similar_type(a,recursive_unitless_eltype(eltype(a)))
Base.@pure recursive_unitless_eltype{T<:Array}(a::Type{T}) = Array{recursive_unitless_eltype(eltype(a)),ndims(a)}
Base.@pure recursive_unitless_eltype{T<:Number}(a::Type{T}) = typeof(one(eltype(a)))
</code>```

This still isn't fully generic, but works on quite a broad range of things.

Title: Recursive unitless element type

Body:
I am trying to come up with a function that gives me the recursive unitless element type. So for example, to shorten it let's call it ruet, I would like to have:

A = zeros(5,5)
reut(A) == Float64
using Unitful
A = zeros(5,5)*1u"kg"
reut(A) == Float64
AA = [zeros(5,5) for i in 1:5]
reut(AA) == Array{Float64,2}
AofA = [copy(A) for i in 1:5]
reut(AofA) == Array{Float64,2}
using StaticArrays
AofSA = [@SVector [2.0,3.0] for i in 1:5]
reut(AofSA) == SVector{2,Float64}
AofuSA = [@SVector [2.0u"kg",3.0u"kg"] for i in 1:5]
reut(AofuSA) == SVector{2,Float64}

So basically strip away the units but still return the correct element type, which could be an array. It's the array part that's hard. I can recurse:

recursive_eltype(a) = recursive_eltype(eltype(a))
recursive_eltype{T<:Number}(a::Type{T}) = eltype(a)

and then get the unitless element type:

uEltype = recursive_eltype(u)
uEltypeNoUnits = typeof(one(uEltype))

but then this is always the number type, and I can't seem to find a good way to get back the array types when it's an array of arrays, i.e. this method is returning Float64 in all of the examples above. I am wondering if dispatching on static arrays and using similar_type is required here.

Note that I would like the solution to, if possible, not have a requirement on Unitful.jl. Getting the unitless type for the number can be done via one(u), so I think this should be possible.

(Somewhat related Julia issue: https://github.com/JuliaLang/julia/issues/22216)

Body:
I came up with:

Base.@pure recursive_unitless_eltype(a) = recursive_unitless_eltype(eltype(a))
Base.@pure recursive_unitless_eltype{T<:StaticArray}(a::Type{T}) = similar_type(a,recursive_unitless_eltype(eltype(a)))
Base.@pure recursive_unitless_eltype{T<:Array}(a::Type{T}) = Array{recursive_unitless_eltype(eltype(a)),ndims(a)}
Base.@pure recursive_unitless_eltype{T<:Number}(a::Type{T}) = typeof(one(eltype(a)))

This still isn't fully generic, but works on quite a broad range of things.


问:
Placing a call with a text field and a button in iOS
Is it possible to make an app that will work like this:

The app will have a text field and a button.

In the textfield the user types in the phone number.

When the user is done typing in the phone number the user hits the button which will open the Phone app and call that number.

答:
Yes, this is possible. You'd set up the text field and button as per usual and have the action associated with the button extract the text from the UITextField using the "text" property. You can then use the "tel://" URL handler to make a call, although this will bring up a dialog asking the user to confirm:</p>

```<code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://xxxx"]];
</code>```

Body:
Yes, this is possible. You'd set up the text field and button as per usual and have the action associated with the button extract the text from the UITextField using the "text" property. You can then use the "tel://" URL handler to make a call, although this will bring up a dialog asking the user to confirm:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://xxxx"]];


问:
Can't up my Eureka Spring REST service in a Docker container
My project consists of a REST service, which is registered in Eureka, also I use Zuul proxy to manage requests as seen in this image. It runs perfectly on my computer in a local way but when I create a docker container for my service, it doesn't start. The steps I followed:

I created a Docker container for each service: Eureka server, Zuul API Gateway, the REST service and my Mysql database.

I get the data of my service from a stored procedure in the database, this conection was tested and it works.

I start all instances with docker-compose, Eureka and database instances remains up but the REST service instance stops abruptly. Zuul not is implemented yet.

The error:

```<code>matriculas-ms_1  | org.springframework.context.ApplicationContextException: Failed to start bean 'org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.eurekaClient' defined in class path resource [org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.discovery.EurekaClient]: Factory method 'eurekaClient' threw exception; nested exception is java.lang.RuntimeException: Failed to initialize DiscoveryClient!
</code>```

Here is the docker-compose.yml

```<code>version: '3.3'
services:
 srclbd:
  build: ./srclbd
  ports:
   - "3307:3306"
  expose:
   - "3306"
  volumes:
   - ./srclbd/data:/var/lib/mysql
 eureka:
  build: ./Eureka
  ports:
   - "8761:8761"
  expose:
   - "8761"
  matriculas-ms:
   build: ./matriculas-ms
   ports:
    - "3333:3333"
   expose:
    - "3333"
   depends_on:
    - srclbd
    - eureka
   links:
    - srclbd
    - eureka
   environment:
    - DATABASE_HOST=srclbd
    - EUREKA_HOST=eureka
</code>```

Eureka's Dockerfile:

```<code>FROM java:8
ADD /target/eureka-0.0.1-SNAPSHOT.jar eureka-0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java","-jar","eureka-0.0.1-SNAPSHOT.jar"]
</code>```

REST service Dockerfile:

```<code>FROM java:8
ADD /target/matriculas-service-0.0.1-SNAPSHOT.jar matriculas-service-     0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java","-jar","matriculas-service-0.0.1-SNAPSHOT.jar","-Xdebug -Xrunjdwp:server=y,transport=dt_socket,suspend=n"]
</code>```

Here is my project on github

Which is my error?

答:
Finally I solved my error setting up a separated configuration profile to Docker container like this:

```<code>spring:
 profiles: container
 application:
  name: matriculas-ms
jpa:
 hibernate:
  ddl-auto: none
datasource:
 url: jdbc:mysql://srclbd:3306/srcl?useSSL=false&noAccessToProcedureBodies=true
 username: root
 password: root
 initialize: true
eureka:
 client:
  serviceUrl:
   defaultZone: http://eureka:8761/eureka/
server:
 port: 1111
</code>```

Then, I established this profile in the Dockerfile created to my REST service. So, every time it executes the JAR file, it will with the created profile's configuration.

```<code>FROM java:8
ADD /target/svcMatriculas.jar svcMatriculas.jar
ENTRYPOINT ["java","-Dspring.profiles.active=container","-jar","svcMatriculas.jar"]
</code>```

Thanks!

Body:
My project consists of a REST service, which is registered in Eureka, also I use Zuul proxy to manage requests as seen in this image. It runs perfectly on my computer in a local way but when I create a docker container for my service, it doesn't start. The steps I followed:

I created a Docker container for each service: Eureka server, Zuul API Gateway, the REST service and my Mysql database.

I get the data of my service from a stored procedure in the database, this conection was tested and it works.

I start all instances with docker-compose, Eureka and database instances remains up but the REST service instance stops abruptly. Zuul not is implemented yet.

The error:

matriculas-ms_1  | org.springframework.context.ApplicationContextException: Failed to start bean 'org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.eurekaClient' defined in class path resource [org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.discovery.EurekaClient]: Factory method 'eurekaClient' threw exception; nested exception is java.lang.RuntimeException: Failed to initialize DiscoveryClient!

Here is the docker-compose.yml

version: '3.3'
services:
 srclbd:
  build: ./srclbd
  ports:
   - "3307:3306"
  expose:
   - "3306"
  volumes:
   - ./srclbd/data:/var/lib/mysql
 eureka:
  build: ./Eureka
  ports:
   - "8761:8761"
  expose:
   - "8761"
  matriculas-ms:
   build: ./matriculas-ms
   ports:
    - "3333:3333"
   expose:
    - "3333"
   depends_on:
    - srclbd
    - eureka
   links:
    - srclbd
    - eureka
   environment:
    - DATABASE_HOST=srclbd
    - EUREKA_HOST=eureka

Eureka's Dockerfile:

FROM java:8
ADD /target/eureka-0.0.1-SNAPSHOT.jar eureka-0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java","-jar","eureka-0.0.1-SNAPSHOT.jar"]

REST service Dockerfile:

FROM java:8
ADD /target/matriculas-service-0.0.1-SNAPSHOT.jar matriculas-service-     0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java","-jar","matriculas-service-0.0.1-SNAPSHOT.jar","-Xdebug -Xrunjdwp:server=y,transport=dt_socket,suspend=n"]

Here is my project on github

Which is my error?

Body:
Finally I solved my error setting up a separated configuration profile to Docker container like this:

spring:
 profiles: container
 application:
  name: matriculas-ms
jpa:
 hibernate:
  ddl-auto: none
datasource:
 url: jdbc:mysql://srclbd:3306/srcl?useSSL=false&noAccessToProcedureBodies=true
 username: root
 password: root
 initialize: true
eureka:
 client:
  serviceUrl:
   defaultZone: http://eureka:8761/eureka/
server:
 port: 1111

Then, I established this profile in the Dockerfile created to my REST service. So, every time it executes the JAR file, it will with the created profile's configuration.

FROM java:8
ADD /target/svcMatriculas.jar svcMatriculas.jar
ENTRYPOINT ["java","-Dspring.profiles.active=container","-jar","svcMatriculas.jar"]

Thanks!


问:
AWS S3 Bucket Policy - Allow GetObject only within a prefix
I'm trying to put a policy on my bucket to allow public 'GetObject' access on my objects, but only those within a certain prefix.  Like this:

```<code>    {
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::mybucket/publicstuff/*"
    }
</code>```

The problem is, AWS warns me that this makes the entire bucket public.  And sure enough, it does; if I try to GET an object from /mybucket/anywhereelse/, S3 serves it up freely.  So everything after 'mybucket' is ignored.

Is there any way to build a bucket policy applicable to a specific prefix within the bucket?  I tried a policy condition, but found the s3:prefix cannot be used when using the s3:GetObject action.

答:
That is totally fine, although you see an indication, showing that your bucket is publicly accessible. You should notice that this indicator shows that the public access to (some contents of) this bucket is provided.

So to check that there is no problem you can just test a file outside the publicly accessible folder and compare that with a file which should be publicly accessible due to your policy.

You can see in the following picture that I have made a sub-folder of my bucket (toignore), accessible to the public:

This is the tree-view of the bucket:

├── directory

│   ├── toignore

│   │   └── i.txt

└── ni.txt

Based on my policy, i.txt is publicly accessible but ni.txt is not, and the indicator shows the public access.

Body:
I'm trying to put a policy on my bucket to allow public 'GetObject' access on my objects, but only those within a certain prefix.  Like this:

    {
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::mybucket/publicstuff/*"
    }

The problem is, AWS warns me that this makes the entire bucket public.  And sure enough, it does; if I try to GET an object from /mybucket/anywhereelse/, S3 serves it up freely.  So everything after 'mybucket' is ignored.

Is there any way to build a bucket policy applicable to a specific prefix within the bucket?  I tried a policy condition, but found the s3:prefix cannot be used when using the s3:GetObject action.


问:
Best way to import a large dataset into Oracle sql database?
I'm new to oracle Database and I'm making a very simple bilingual dictionary ( 2 tables - English and French).

A dictionary often contains thousands of words. My question is that instead of writing thousand of [INSERT INTO ... VALUES] commands, is there any better way to somehow automate the process, like making a import form? Since the book my school provides only mentions about the INSERT command.

答: Oracle's Sql Loader product is great for quickly loading large amounts of data.</p>


答:
When it says invalid left-hand side, it means that you are trying to assign a value to something on the left side. You have used -

```<code>if(i % 2 = 1)
</code>```

However, = is an assignment operator, which basically assigns a value to a variable on the left. What you need is == which is a comparison operator since you are trying to compare two values.

This should be your code -

```<code>if(i % 2 == 1)
</code>```

Title: Checking remainder in Javascript

Body:
When it says invalid left-hand side, it means that you are trying to assign a value to something on the left side. You have used -

if(i % 2 = 1)

However, = is an assignment operator, which basically assigns a value to a variable on the left. What you need is == which is a comparison operator since you are trying to compare two values.

This should be your code -

if(i % 2 == 1)


答:
Firstly, you will want to use the double equal (==) or the triple equal (===), when checking your remainder, since the single equal (=) is used to assign values to variables.

Difference between == and ===:

=== is more strict than == since === checks the value AND type whereas the == only checks the values.

Example:

```<code>if(1 == '1') // true
if(1 === '1') //false : their types are different.
</code>```

Secondly, you will likely want to wrap your if statement inside of your do-while loop to get an output of even or odd after logging each number.

Here is the final result:

```<code>var i = 0;

do {
  i++;
  console.log(i);
  if(i % 2 === 1) {
    console.log("odd");
  } else {
    console.log("even");
  }
} while (i <= 9);
</code>```

Title: Checking remainder in Javascript

Body:
Firstly, you will want to use the double equal (==) or the triple equal (===), when checking your remainder, since the single equal (=) is used to assign values to variables.

Difference between == and ===:

=== is more strict than == since === checks the value AND type whereas the == only checks the values.

Example:

if(1 == '1') // true
if(1 === '1') //false : their types are different.

Secondly, you will likely want to wrap your if statement inside of your do-while loop to get an output of even or odd after logging each number.

Here is the final result:

var i = 0;

do {
  i++;
  console.log(i);
  if(i % 2 === 1) {
    console.log("odd");
  } else {
    console.log("even");
  }
} while (i <= 9);


问:
Types of Select Statement
This has been bothering me for quite some time but I do come across two ways of using select statement in SQL.

The first way is the obvious :

```<code>Select column_Name
from table_Name
</code>```

And then there is a second one:

```<code> Select column_Name a
 from table_Name
</code>```

What is the difference in using the second one?

答:
Using an column alias comes handy when you want to change the table column name for display purpose, for an example think that you want to generate the excel sheet from your program that returns data set from sql server. You can concentrate only the excel generation part in your application [treat this is an common routine to generate multiple excels] and you can change your column names what ever you want using the mentioned method. Alias can be seen in below syntaxas </p>

```<code>  SELECT yourcolumnname abc
  SELECT yourcolumnname  [abc def]
  SELECT yourcolumnname AS abc
  SELECT yourcolumnname AS 'abc def'
  SELECT yourcolumnname AS [abc def]
</code>```

Title: Types of Select Statement

Body:
This has been bothering me for quite some time but I do come across two ways of using select statement in SQL.

The first way is the obvious :

Select column_Name
from table_Name

And then there is a second one:

 Select column_Name a
 from table_Name

What is the difference in using the second one?

Body:
Using an column alias comes handy when you want to change the table column name for display purpose, for an example think that you want to generate the excel sheet from your program that returns data set from sql server. You can concentrate only the excel generation part in your application [treat this is an common routine to generate multiple excels] and you can change your column names what ever you want using the mentioned method. Alias can be seen in below syntaxas

  SELECT yourcolumnname abc
  SELECT yourcolumnname  [abc def]
  SELECT yourcolumnname AS abc
  SELECT yourcolumnname AS 'abc def'
  SELECT yourcolumnname AS [abc def]


问:
Why doesn't **find** find anything?
I'm looking for shell scripts files installed on my system, but find doesn't work:

```<code>$ find /usr -name *.sh
</code>```

But I know there are a ton of scripts out there.  For instance:

```<code>$ ls /usr/local/lib/*.sh
/usr/local/lib/tclConfig.sh
/usr/local/lib/tkConfig.sh
</code>```

Why doesn't find work?

答:
For finding files on your disks, lean to use "locate" instead that is instantaneous
(looks into a daily built index)
you example would be:</p>

```<code>locate '/usr*.sh'
</code>```

OwnerDisplayName: Jon Ericson

Title: Why doesn't **find** find anything?

Body:
I'm looking for shell scripts files installed on my system, but find doesn't work:

$ find /usr -name *.sh

But I know there are a ton of scripts out there.  For instance:

$ ls /usr/local/lib/*.sh
/usr/local/lib/tclConfig.sh
/usr/local/lib/tkConfig.sh

Why doesn't find work?

LastEditorDisplayName: Mark Harrison

Body:
For finding files on your disks, lean to use "locate" instead that is instantaneous
(looks into a daily built index)
you example would be:

locate '/usr*.sh'


问:
Decode JSON value which can be either string or number
When I make an HTTP call to a REST API I may get the JSON value count back as a Number or String. I'ld like to marshal it to be an integer in either case. How can I deal with this in Go?.

答:
```<code>// Format of your expected request
type request struct {
    ACTIVE    string `json:"active"`
    CATEGORY  string `json:"category"`
}

// struct to read JSON input
var myReq request

// Decode the received JSON request to struct
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&myReq)
  if err != nil {
  log.Println( err)
// Handler for invalid JSON received or if you want to decode the request using another struct with int.
  return
}
defer r.Body.Close()

// Convert string to int
numActive, err = strconv.Atoi(myReq.ACTIVE)
if err != nil {
  log.Println(err)
// Handler for invalid int received
  return
}

// Convert string to int
numCategory, err = strconv.Atoi(myReq.CATEGORY)
if err != nil {
  log.Println(err)
// Handler for invalid int received
  return
}
</code>```


问:
gunicorn setup for django channels
My django app works fine on local machine as well as on Heroku, however I'm having troubles to deploy it do Digital Ocean Ubuntu 16.04 droplet. Followed this tutorial, app has started but websockets didn't work.
By running in terminal virtual environment: daphne -b 0.0.0.0 -p 8000 slist.asgi:channel_layer
and in second terminal window:

```<code>./manage.py runworker
</code>```

The app works but only on port 8000. I can't access it on mydomain.com but only on mydomain.com:8000.
When I close terminal windows the site cannot be accessed.
What and how needs to be set for the site to run without my terminal windows and without the ':8000'?

My gunicorn.service file:

```<code>[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=kuba1
Group=www-data
WorkingDirectory=/home/kuba1/slistproject
ExecStart=/home/kuba1/slistproject/slistvenv/bin/gunicorn --workers 3 --bind unix:/home/kuba1/slistproject/slistvenv/src/slist.sock slist.wsgi:application

[Install]
WantedBy=multi-user.target
</code>```

my Nginx settings:

```<code>server {
    listen 80;
    server_name server_name fortests.ovh;
    client_max_body_size 20M;

    location /static/ {
        root /home/kuba1/slistproject/slistvenv/src;
    }

    location / {

        proxy_pass http://unix:/home/kuba1/slistproject/slistvenv/src/slist.sock;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";

            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;

        }

}
</code>```

答:
It should be:

```<code>proxy_set_header Connection "Upgrade";
</code>```

Working config for me:

```<code>upstream websocket {
    server  unix:/path/to/daphne.sock fail_timeout=20;
}

location /url/socket/ {
    try_files $uri @proxy_to_channel_app;
}

location @proxy_to_channel_app {

    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    # enable this if and only if you use HTTPS
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header Host $http_host;

    # web socket setup
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'Upgrade';

    # we don't want nginx trying to do something clever with
    # redirects, we set the Host: header above already.
    proxy_redirect off;
    proxy_pass http://websocket;
}
</code>```

Daphne command:

```<code>daphne -u run/daphne.sock project.asgi:channel_layer
</code>```

Title: gunicorn setup for django channels

Body:
My django app works fine on local machine as well as on Heroku, however I'm having troubles to deploy it do Digital Ocean Ubuntu 16.04 droplet. Followed this tutorial, app has started but websockets didn't work.
By running in terminal virtual environment: daphne -b 0.0.0.0 -p 8000 slist.asgi:channel_layer
and in second terminal window:

./manage.py runworker

The app works but only on port 8000. I can't access it on mydomain.com but only on mydomain.com:8000.
When I close terminal windows the site cannot be accessed.
What and how needs to be set for the site to run without my terminal windows and without the ':8000'?

My gunicorn.service file:

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=kuba1
Group=www-data
WorkingDirectory=/home/kuba1/slistproject
ExecStart=/home/kuba1/slistproject/slistvenv/bin/gunicorn --workers 3 --bind unix:/home/kuba1/slistproject/slistvenv/src/slist.sock slist.wsgi:application

[Install]
WantedBy=multi-user.target

my Nginx settings:

server {
    listen 80;
    server_name server_name fortests.ovh;
    client_max_body_size 20M;

    location /static/ {
        root /home/kuba1/slistproject/slistvenv/src;
    }

    location / {

        proxy_pass http://unix:/home/kuba1/slistproject/slistvenv/src/slist.sock;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";

            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;

        }

}

Body:
It should be:

proxy_set_header Connection "Upgrade";

Working config for me:

upstream websocket {
    server  unix:/path/to/daphne.sock fail_timeout=20;
}

location /url/socket/ {
    try_files $uri @proxy_to_channel_app;
}

location @proxy_to_channel_app {

    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    # enable this if and only if you use HTTPS
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header Host $http_host;

    # web socket setup
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'Upgrade';

    # we don't want nginx trying to do something clever with
    # redirects, we set the Host: header above already.
    proxy_redirect off;
    proxy_pass http://websocket;
}

Daphne command:

daphne -u run/daphne.sock project.asgi:channel_layer


问:
Run different data sets for each test in a sequence for each iteration using Test NG

Expected behaviour

The point here that i'm expecting is to iterate the data set for each of the test in sequence for each iteration, in such a way all the tests should run in with first set of data, follows by second until the end

```<code>public class SampleFactory {
DataGenerators dataGen;

@Factory(dataProvider="dp")
public Object[] createInstances(String country, String email, String firstName, String securityQuestion, String title, String ccyFrom, String ccyTo) {
    return new Object[] {new PersonalRegoTest(country, email, firstName, securityQuestion, title, ccyFrom, ccyTo)};
}

@DataProvider(name="dp")
public static Object[][] dataProvider() {
   // dataGen = new DataGenerators();

    Object[][] dataArray = {
            {"country1", "test@testmail.com","abc", "Model", "Mr", "AUD", "USD"},
            {"country2", "test1@testmail.com","abcd", "Model", "Mr", "USD", "NZD"}
    };
    return dataArray;
}
}
</code>```

And my PersonalRegoTest is as follows

```<code>public class PersonalRegoTest extends Appium {
PersonalRego personalRego;
DataGenerators dataGen;
String country="";
String email="";
String firstName="";
String securityQuestion="";
String title="";
String ccyFrom="";
String ccyTo="";`

PersonalRegoTest(String country, String email, String firstName, String
securityQuestion, String title, String ccyFrom, String ccyTo) {
    super();
    this.country = country;
    this.email = email;
    this.firstName = firstName;
    this.securityQuestion = securityQuestion;
    this.title = title;
    this.ccyFrom = ccyFrom;
    this.ccyTo = ccyTo;
}
@BeforeClass(alwaysRun = true)
public void initialize() throws IOException {
    personalRego = new PersonalRego(driver, System.getProperty("platform"));
    dataGen = new DataGenerators();
}
@Test(priority = 1, alwaysRun=true, description="select of Personal Rego form", groups="personalRego")
public void verifyPersonalRegoPageWindow() {
    personalRego.isPersonalRegoWindowDisplayed();
}
@Test(priority = 2, alwaysRun=true, description = "fill step 1 of Personal Rego form", groups="personalRego")
public void validateAndCompletePersonalRegoForm_FirstPage() {
    ...
}
@Test(priority = 3, alwaysRun=true, description = "fill step 2 of Personal Rego form", groups="personalRego", dependsOnMethods = "validateAndCompletePersonalRegoForm_FirstPage")
public void validateAndCompletePersonalRegoForm_SecondPage() {
    ...
}
@Test(priority = 4, alwaysRun=true, description = "fill step 3 of Personal Rego form", groups="personalRego", dependsOnMethods = {"validateAndCompletePersonalRegoForm_FirstPage", "validateAndCompletePersonalRegoForm_SecondPage"})
public void validateAndSubmitPersonalRegoForm_ThirdPage() {
   ...
}
@Test(priority = 5, alwaysRun=true, description = "Last step of Personal Rego form to reset app", groups="personalRego", dependsOnMethods = {"validateAndSubmitPersonalRegoForm_ThirdPage"})
public void resetApplication(String reset) {
    System.out.println("reset application ");
    ..
}
</code>```

PFA the similar result as like before. Please advise me if i'm doing something wrong now

Current problem:
My tests runs as follows

```<code>verifyPersonalRegoPageWindow
verifyPersonalRegoPageWindow(1)
validateAndCompletePersonalRegoForm_FirstPage
validateAndCompletePersonalRegoForm_FirstPage(1)
validateAndCompletePersonalRegoForm_SecondPage
validateAndCompletePersonalRegoForm_SecondPage(1)
..
</code>```

Expected result

```<code>Iteration - 1
verifyPersonalRegoPageWindow
validateAndCompletePersonalRegoForm_FirstPage
validateAndCompletePersonalRegoForm_SecondPage
..

Iteration - 2
verifyPersonalRegoPageWindow
validateAndCompletePersonalRegoForm_FirstPage
validateAndCompletePersonalRegoForm_SecondPage
..
</code>```

Can someone please advise as I got struck here?

答: It was an E2E Tests for countries selected. All that is required is to remove the priority from each tests and just have dependOnMethods which will resolve this issue.

Body:
Expected behaviour

The point here that i'm expecting is to iterate the data set for each of the test in sequence for each iteration, in such a way all the tests should run in with first set of data, follows by second until the end

public class SampleFactory {
DataGenerators dataGen;

@Factory(dataProvider="dp")
public Object[] createInstances(String country, String email, String firstName, String securityQuestion, String title, String ccyFrom, String ccyTo) {
    return new Object[] {new PersonalRegoTest(country, email, firstName, securityQuestion, title, ccyFrom, ccyTo)};
}

@DataProvider(name="dp")
public static Object[][] dataProvider() {
   // dataGen = new DataGenerators();

    Object[][] dataArray = {
            {"country1", "test@testmail.com","abc", "Model", "Mr", "AUD", "USD"},
            {"country2", "test1@testmail.com","abcd", "Model", "Mr", "USD", "NZD"}
    };
    return dataArray;
}
}

And my PersonalRegoTest is as follows

public class PersonalRegoTest extends Appium {
PersonalRego personalRego;
DataGenerators dataGen;
String country="";
String email="";
String firstName="";
String securityQuestion="";
String title="";
String ccyFrom="";
String ccyTo="";`

PersonalRegoTest(String country, String email, String firstName, String
securityQuestion, String title, String ccyFrom, String ccyTo) {
    super();
    this.country = country;
    this.email = email;
    this.firstName = firstName;
    this.securityQuestion = securityQuestion;
    this.title = title;
    this.ccyFrom = ccyFrom;
    this.ccyTo = ccyTo;
}
@BeforeClass(alwaysRun = true)
public void initialize() throws IOException {
    personalRego = new PersonalRego(driver, System.getProperty("platform"));
    dataGen = new DataGenerators();
}
@Test(priority = 1, alwaysRun=true, description="select of Personal Rego form", groups="personalRego")
public void verifyPersonalRegoPageWindow() {
    personalRego.isPersonalRegoWindowDisplayed();
}
@Test(priority = 2, alwaysRun=true, description = "fill step 1 of Personal Rego form", groups="personalRego")
public void validateAndCompletePersonalRegoForm_FirstPage() {
    ...
}
@Test(priority = 3, alwaysRun=true, description = "fill step 2 of Personal Rego form", groups="personalRego", dependsOnMethods = "validateAndCompletePersonalRegoForm_FirstPage")
public void validateAndCompletePersonalRegoForm_SecondPage() {
    ...
}
@Test(priority = 4, alwaysRun=true, description = "fill step 3 of Personal Rego form", groups="personalRego", dependsOnMethods = {"validateAndCompletePersonalRegoForm_FirstPage", "validateAndCompletePersonalRegoForm_SecondPage"})
public void validateAndSubmitPersonalRegoForm_ThirdPage() {
   ...
}
@Test(priority = 5, alwaysRun=true, description = "Last step of Personal Rego form to reset app", groups="personalRego", dependsOnMethods = {"validateAndSubmitPersonalRegoForm_ThirdPage"})
public void resetApplication(String reset) {
    System.out.println("reset application ");
    ..
}

PFA the similar result as like before. Please advise me if i'm doing something wrong now

Current problem:
My tests runs as follows

verifyPersonalRegoPageWindow
verifyPersonalRegoPageWindow(1)
validateAndCompletePersonalRegoForm_FirstPage
validateAndCompletePersonalRegoForm_FirstPage(1)
validateAndCompletePersonalRegoForm_SecondPage
validateAndCompletePersonalRegoForm_SecondPage(1)
..

Expected result

Iteration - 1
verifyPersonalRegoPageWindow
validateAndCompletePersonalRegoForm_FirstPage
validateAndCompletePersonalRegoForm_SecondPage
..

Iteration - 2
verifyPersonalRegoPageWindow
validateAndCompletePersonalRegoForm_FirstPage
validateAndCompletePersonalRegoForm_SecondPage
..

Can someone please advise as I got struck here?


问:
Dropdown Can't be sorted
I'm having trouble sorting a dropdown.

So far my datatable can sort the ID, Name, Position, and Application Date as shown in the picture.
But my datatable can't sort the category. How can I sort the category? Your help would be appreciated.

Here is the code that I use to show the data in the datatable.

Here is a picture of my user interface
Sorry for using a link, I'm newbie and not allowed to use pictures yet.

```<code><table class="table isSearch table-bordered table-striped"  id="table" cellspacing="0">
    <thead>
        <tr class="table-heads ">
            <th>ID</th>
            <th>Name</th> <!-- Table Header -->
            <th>Position</th>
            <th>Application Date</th>
            <th>Category</th>
            <th>Arrange Interview</th>
                <th>Online Interview</th></tr>

        </thead>

        <tbody>
              <?php
                include"../database.php";
              $query="SELECT user.name, job_application.created_at,
              job.job_name, job_application_id, status_id, email, skypeid
              FROM user, job_application, job
              WHERE user.user_id = job_application.user_id
              AND job.job_id = job_application.job_id
              ORDER BY STATUS_ID ASC";
              $result=mysqli_query ($connect,$query);

              while($data = mysqli_fetch_array($result))
                  {
                  echo
                "<tr><form action='update_status.php?id=".$data['job_application_id']."' method='post'>";
                echo"<td>".$data['job_application_id']."</td>";
                echo"<td>".$data['name']."</td>";
                echo"<td>".$data['job_name']."</td>";
                echo"<td>".$data['created_at']."</td>";
                echo"<td>
                <select name='status'>
                    <option name='status' value='1'";?><?php if ($data['status_id']=='1') {echo " selected";}echo "> Waiting </option>
                    <option name='status' value='2'";?><?php if ($data['status_id']=='2') {echo " selected";}echo "> Rejected </option>
                    <option name='status' value='3'";?><?php if ($data['status_id']=='3') {echo " selected";}echo "> Interviewed </option>
                    <option name='status' value='4'";?><?php if ($data['status_id']=='4') {echo " selected";}echo "> Hired </option>
                </select>
                    <br>
                    <input type='submit' name='submit' value='Save'>
                    </form>
                </td>";
                echo"<td>
               <center><a href='email.php?email=".$data['email']."&id=".$data['job_application_id']." 'target='_blank' style='border-radius:30px' class='btn btn-secondary btn-sm'>E-Mail</a><center>
                </td>";
                echo"<td><center><a href='skype:".$data['skypeid']."?call' style='border-radius:30px' class='btn btn-primary btn-sm'><img src='assets/images/skype.png' width='25 height='13'>Call</a><center></td>";
                echo"</tr>";
                  }
                  ?>
            </tbody>
          </table>
</code>```

答:
What you need to do is to create a local array in the javascript

```<code>          var categories = [];
</code>```

and push the data from the database to this variable

```<code>          categories.push({}) // you can push the object or the string
</code>```

and then define the sort function with your custom logic https://www.w3schools.com/jsref/jsref_sort.asp .

```<code>           function sortTheCategory();
</code>```

Now call this function based on the event happening with the header column.

Title: Dropdown Can't be sorted

Body:
I'm having trouble sorting a dropdown.

So far my datatable can sort the ID, Name, Position, and Application Date as shown in the picture.
But my datatable can't sort the category. How can I sort the category? Your help would be appreciated.

Here is the code that I use to show the data in the datatable.

Here is a picture of my user interface
Sorry for using a link, I'm newbie and not allowed to use pictures yet.

            ID
            Name
            Position
            Application Date
            Category
            Arrange Interview
                Online Interview

              <?php
                include"../database.php";
              $query="SELECT user.name, job_application.created_at,
              job.job_name, job_application_id, status_id, email, skypeid
              FROM user, job_application, job
              WHERE user.user_id = job_application.user_id
              AND job.job_id = job_application.job_id
              ORDER BY STATUS_ID ASC";
              $result=mysqli_query ($connect,$query);

              while($data = mysqli_fetch_array($result))
                  {
                  echo
                "
<form action='update_status.php?id=".$data['job_application_id']."' method='post'>";
                echo"".$data['job_application_id']."	";
                echo"".$data['name']."	";
                echo"".$data['job_name']."	";
                echo"".$data['created_at']."	";
                echo"
                <select name='status'>
                    <option name='status' value='1'";?><?php if ($data['status_id']=='1') {echo " selected";}echo "> Waiting </option>
                    <option name='status' value='2'";?><?php if ($data['status_id']=='2') {echo " selected";}echo "> Rejected </option>
                    <option name='status' value='3'";?><?php if ($data['status_id']=='3') {echo " selected";}echo "> Interviewed </option>
                    <option name='status' value='4'";?><?php if ($data['status_id']=='4') {echo " selected";}echo "> Hired </option>
                </select>

                    <input type='submit' name='submit' value='Save'>
                    </form>
                	";
                echo"
               E-Mail
                	";
                echo"Call	";
                echo"
";
                  }
                  ?>

Body:
What you need to do is to create a local array in the javascript

          var categories = [];

and push the data from the database to this variable

          categories.push({}) // you can push the object or the string

and then define the sort function with your custom logic https://www.w3schools.com/jsref/jsref_sort.asp .

           function sortTheCategory();

Now call this function based on the event happening with the header column.


问:
Merge two columns in Select into one column based on a condition
I have a SELECT with two columns I'd like to merge based on the condition that if the left one is null it should choose the right column but when the left column is not null it should always choose the left.

scenario

What I have on the left is what I currently Have and I'd like to get the table on the right

AlphabetTable

```<code>+-------+------+    +---------+
| A     | B    |    | Desired |
+-------+------+    |---------+
| null  | 1    |    | 1       |
| null  | 1    |    | 1       |
|  2    | null |    | 2       |
|  2    | 3    |    | 2       |
|  2    | 5    |    |  2      |
|  null | null |    | null    |
+-------+------+    +---------+
</code>```

SQL for left table above

```<code>SELECT
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as A
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as B
From IDTable
</code>```

Heres what I have so far

```<code>SELECT
        CASE WHEN
            CAST((select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT) IS NULL
            THEN
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
            ELSE
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
 FROM AlphabetTable AT
</code>```

答:
You can achieve this with ISNULL Condition as shown below</p>

```<code>    SELECT
        CAST((select sum(Total) from LettersTable LT
                                    WHERE LT.ID = ID
                                    AND LT.Count > 5)
                                    AS INT) as A,
        CAST((select sum(Total) from LettersTable LT
                                    WHERE LT.ID = ID
                                    AND LT.Count > 5)
                                    AS INT) as B
    INTO #tmpIDTable
    From IDTable

    SELECT ISNULL(A,B) FROM #tmpIDTable
</code>```

Body:
I have a SELECT with two columns I'd like to merge based on the condition that if the left one is null it should choose the right column but when the left column is not null it should always choose the left.

scenario

What I have on the left is what I currently Have and I'd like to get the table on the right

AlphabetTable

+-------+------+    +---------+
| A     | B    |    | Desired |
+-------+------+    |---------+
| null  | 1    |    | 1       |
| null  | 1    |    | 1       |
|  2    | null |    | 2       |
|  2    | 3    |    | 2       |
|  2    | 5    |    |  2      |
|  null | null |    | null    |
+-------+------+    +---------+

SQL for left table above

SELECT
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as A
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as B
From IDTable

Heres what I have so far

SELECT
        CASE WHEN
            CAST((select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT) IS NULL
            THEN
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
            ELSE
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
 FROM AlphabetTable AT

Body:
You can achieve this with ISNULL Condition as shown below

    SELECT
        CAST((select sum(Total) from LettersTable LT
                                    WHERE LT.ID = ID
                                    AND LT.Count > 5)
                                    AS INT) as A,
        CAST((select sum(Total) from LettersTable LT
                                    WHERE LT.ID = ID
                                    AND LT.Count > 5)
                                    AS INT) as B
    INTO #tmpIDTable
    From IDTable

    SELECT ISNULL(A,B) FROM #tmpIDTable


问:
Accessing the result of a returned promise
I'm trying to understand promises better and have implemented code that basically looks like this:

console.log(getRemoteData())

function getRemoteData (){
  return fetch('http://w.x.y.z')
  .then(response => {
    return response.json();
  });
}```

Assuming that getRemoteData() returns a promise, how do I access the value of that response? I've tried to resolve the promise before logging to the console and I can't get it to do anything but log the promise obj. I think I'm missing a fundamental component of how promises work.

I've tried searching SO and all the answers I find point to a //do something with the returned data comment in the .then() method but I'd like to learn what I should do from there. The returned value is an array[].

答:
fetch(...) returns a promise, and response.json() returns another promise.

The returned value is not an array but a promise of an array. It should be:

```<code>getRemoteData().then(result => {
  console.log(result);
});
</code>```

The structure can be flattened similarly to synchronous code in async functions (ES2017). They are syntactic sugar for promises, this snippet is equal to the previous one:

```<code>(async () => {
    const result = await getRemoteData();
    console.log(result);
})();
</code>```

Body:
I'm trying to understand promises better and have implemented code that basically looks like this:

console.log(getRemoteData())

function getRemoteData (){
  return fetch('http://w.x.y.z')
  .then(response => {
    return response.json();
  });
}

Assuming that getRemoteData() returns a promise, how do I access the value of that response? I've tried to resolve the promise before logging to the console and I can't get it to do anything but log the promise obj. I think I'm missing a fundamental component of how promises work.

I've tried searching SO and all the answers I find point to a //do something with the returned data comment in the .then() method but I'd like to learn what I should do from there. The returned value is an array[].

Body:
fetch(...) returns a promise, and response.json() returns another promise.

The returned value is not an array but a promise of an array. It should be:

getRemoteData().then(result => {
  console.log(result);
});

The structure can be flattened similarly to synchronous code in async functions (ES2017). They are syntactic sugar for promises, this snippet is equal to the previous one:

(async () => {
    const result = await getRemoteData();
    console.log(result);
})();


问:
How should I input data from a Settings menu into the MainActivity.java file to adjust the size of the text in the Textview window?
all! I'm currently working on an assessment that's due in by tomorrow wherein I need to create a working application in Android Studio which features, amongst other things, a menu-adjustable option for the size of the text. The app itself is a 'quote-of-the-day' style application. Below is the code I've written up for the actual menu option.

```<code><EditTextPreference
        android:defaultValue="14"
        android:key="edit_text_preference_1"
        android:selectAllOnFocus="true"
        android:singleLine="true"
        android:title="Text Size"
        android:inputType="number"/>
</code>```

While this works, and I am able to input a number into the settings area, I have no idea of how to link the value inputted through to adjust the size of my Text in the Textview window.

I apologize that this doesn't exactly follow the normal criteria, but I honestly have no results to show per se on this point. Any help would be appreciated.

答:
You can use SharedPreference for saving some value that will be used in another activity.

Here example based from documentation

To save:

```<code>SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.yourKeyStringName), yourValue);
editor.commit();
</code>```

To read:

```<code>SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValueIfKeyDoesntExist = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.yourKeyStringName), defaultValueIfKeyDoesntExist);
</code>```

https://developer.android.com/training/data-storage/shared-preferences.html

Body:
all! I'm currently working on an assessment that's due in by tomorrow wherein I need to create a working application in Android Studio which features, amongst other things, a menu-adjustable option for the size of the text. The app itself is a 'quote-of-the-day' style application. Below is the code I've written up for the actual menu option.

<EditTextPreference
        android:defaultValue="14"
        android:key="edit_text_preference_1"
        android:selectAllOnFocus="true"
        android:singleLine="true"
        android:title="Text Size"
        android:inputType="number"/>

While this works, and I am able to input a number into the settings area, I have no idea of how to link the value inputted through to adjust the size of my Text in the Textview window.

I apologize that this doesn't exactly follow the normal criteria, but I honestly have no results to show per se on this point. Any help would be appreciated.

Body:
You can use SharedPreference for saving some value that will be used in another activity.

Here example based from documentation

To save:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.yourKeyStringName), yourValue);
editor.commit();

To read:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValueIfKeyDoesntExist = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.yourKeyStringName), defaultValueIfKeyDoesntExist);

https://developer.android.com/training/data-storage/shared-preferences.html


问:
Exchange server 2013 Search-Mailbox for criteria BODY in remote powershell
I am trying to search emails that contains some string in their body. I have two email which contains the work booze.

The command I am using to search is

```<code>Get-Mailbox | Search-Mailbox -SearchQuery "Body:'booze'" -WarningAction:SilentlyContinue -EstimateResultOnly -SearchDumpster:$false
</code>```

but this command is returning 0. What is wrong with this command?

I run a similar command for subject which works

```<code>Get-Mailbox | Search-Mailbox -SearchQuery "Subject:'test'" -WarningAction:SilentlyContinue -EstimateResultOnly -SearchDumpster:$false
</code>```

答:
You don't need to add the Body: section. Try this (untested):

```<code>Get-Mailbox | Search-Mailbox -SearchQuery 'booze' -WarningAction:SilentlyContinue -EstimateResultOnly -SearchDumpster:$false
</code>```

https://technet.microsoft.com/en-us/library/dd298173(v=exchg.160).aspx

Body:
I am trying to search emails that contains some string in their body. I have two email which contains the work booze.

The command I am using to search is

Get-Mailbox | Search-Mailbox -SearchQuery "Body:'booze'" -WarningAction:SilentlyContinue -EstimateResultOnly -SearchDumpster:$false

but this command is returning 0. What is wrong with this command?

I run a similar command for subject which works

Get-Mailbox | Search-Mailbox -SearchQuery "Subject:'test'" -WarningAction:SilentlyContinue -EstimateResultOnly -SearchDumpster:$false

Body:
You don't need to add the Body: section. Try this (untested):

Get-Mailbox | Search-Mailbox -SearchQuery 'booze' -WarningAction:SilentlyContinue -EstimateResultOnly -SearchDumpster:$false

https://technet.microsoft.com/en-us/library/dd298173(v=exchg.160).aspx


问:
Synchronising threads for multiple readers / single writer in Clojure
I have some non-thread-safe code (a writer to shared data) that can only be called from multiple threads in a serialised manner, but I don't want to block any other thread-safe work (multiple readers) when this code is not being called.

This is essentially a multiple reader / single writer type locking situation where writers need to exclude both readers and other writers.

i.e. I have two functions:

```<code>(defn reader-function [] ....) // only reads from shared data

(defn writer-function [] ....) // writes to shared data
</code>```

And a number of threads that are running (possibly in a loop) the following:

```<code>(do
  (reader-function)
  ...
  (writer-function))
</code>```

If any single thread is executing the writer function, all the other threads must block. i.e. at any one time either:

one thread is executing the
writer and all
others are blocked

multiple threads are
executing the reader function, possibly some threads are
blocked waiting to execute
the writer once all readers are completed

What's the best way to achieve this kind of synchronisation in Clojure?

答:
Put your data in a ref.  The data should be a Clojure data structure (not a Java class).  Use dosync to create a transaction around the read and write.

Example.  Because you split your writer into a separate function, that function must modify a ref with something like an alter.  Doing so requires a transaction (dosync).  You could rely on writer being called only in a dosync but you can also put a dosync inside the write and rely on nested transactions doing what you want - this makes writer safe to call either in or out of a transaction.

```<code>(defn reader [shared]
  (println "I see" @shared))

(defn writer [shared item]
  (dosync
    (println "Writing to shared")
    (alter shared conj item)))

;; combine the read and the write in a transaction
(defn combine [shared item]
  (dosync
    (reader shared)
    (writer shared item)))

;; run a loop that adds n thread-specific items to the ref
(defn test-loop [shared n]
  (doseq [i (range n)]
    (combine shared (str (System/identityHashCode (Thread/currentThread)) "-" i))
    (Thread/sleep 50)))

;; run t threads adding n items in parallel
(defn test-threaded [t n]
  (let [shared (ref [])]
    (doseq [_ (range t)]
      (future (test-loop shared n)))))
</code>```

Run the test with something like (test-threaded 3 10).

More info here: http://clojure.org/refs

You didn't ask about this case, but it's important to note that anyone can read the shared ref by derefing it at any time.  This does not block concurrent writers.

Body:
I have some non-thread-safe code (a writer to shared data) that can only be called from multiple threads in a serialised manner, but I don't want to block any other thread-safe work (multiple readers) when this code is not being called.

This is essentially a multiple reader / single writer type locking situation where writers need to exclude both readers and other writers.

i.e. I have two functions:

(defn reader-function [] ....) // only reads from shared data

(defn writer-function [] ....) // writes to shared data

And a number of threads that are running (possibly in a loop) the following:

(do
  (reader-function)
  ...
  (writer-function))

If any single thread is executing the writer function, all the other threads must block. i.e. at any one time either:

one thread is executing the
writer and all
others are blocked

multiple threads are
executing the reader function, possibly some threads are
blocked waiting to execute
the writer once all readers are completed

What's the best way to achieve this kind of synchronisation in Clojure?

Body:
Put your data in a ref.  The data should be a Clojure data structure (not a Java class).  Use dosync to create a transaction around the read and write.

Example.  Because you split your writer into a separate function, that function must modify a ref with something like an alter.  Doing so requires a transaction (dosync).  You could rely on writer being called only in a dosync but you can also put a dosync inside the write and rely on nested transactions doing what you want - this makes writer safe to call either in or out of a transaction.

(defn reader [shared]
  (println "I see" @shared))

(defn writer [shared item]
  (dosync
    (println "Writing to shared")
    (alter shared conj item)))

;; combine the read and the write in a transaction
(defn combine [shared item]
  (dosync
    (reader shared)
    (writer shared item)))

;; run a loop that adds n thread-specific items to the ref
(defn test-loop [shared n]
  (doseq [i (range n)]
    (combine shared (str (System/identityHashCode (Thread/currentThread)) "-" i))
    (Thread/sleep 50)))

;; run t threads adding n items in parallel
(defn test-threaded [t n]
  (let [shared (ref [])]
    (doseq [_ (range t)]
      (future (test-loop shared n)))))

Run the test with something like (test-threaded 3 10).

More info here: http://clojure.org/refs

You didn't ask about this case, but it's important to note that anyone can read the shared ref by derefing it at any time.  This does not block concurrent writers.


问:
laravel generate PDF from blade
I am trying to download my page in pdf format and I have been following this tutorial step by step to do it. I tried using a sample data to do it and it work but when I try to use my own data it keep giving me undefined $data3, $object, ..

But I have already defined them already in my controller already:

testController

```<code>     public function getTestdata($id){
           $user = PersonalInfo::find($id);
          $object = PersonalInfo::where('id',$id)->get();
        $object1 = AdditionalInformation::where('user_id',$id)->get();
         $data3=UserImage::where('user_id',$id)->get();
     return view('test',compact('id','object','object1','user','data3'));
 }
</code>```

test.blade.php

```<code><a href="{{  url('/pdf')  }}">Download PDF</a>
...
<th>
      @foreach($data3 as $currentUser)
      <img src="{{ url('images/' . $currentUser->name ) }}">
      @endforeach
 </th>
...
  @php
    $userFamily = $user->userFamily;
  @endphp
    <tr>
    <td><b>FAMILY Members</b></td>
      <td>
    @foreach($userFamily as $val)

    @if($val["meta_key"] == "relationshiplist")
    {{  $val["meta_value"]  }}  |
    @endif
        @endforeach
    </td>
</code>```

DownloadPDFController:

```<code>public function fun_pdf(){
    $pdf = PDF::loadView('test'); //load view page
    return $pdf->download('test.pdf'); // download pdf file
}
</code>```

Route:

```<code>Route::get('/pdf', 'pdfDownloadController@fun_pdf');
Route::get('/user/showtest/{id}/test1', 'testController@getTestData')->name('template');
</code>```

I also tried following this website to do but it does't seem to work as well, instead it gave me undefined $id. http://itsolutionstuff.com/post/laravel-5-generate-pdf-from-html-view-file-and-download-using-dompdfexample.html

If possible could you guys guide me on how to generate the PDF file

答:
For this first, you should install Dompdf plugin https://github.com/barryvdh/laravel-dompdf

and everything else in its documentation

I think you should update the controller like this and pass id parameter, change the route also

```<code>    public function fun_pdf($id){
        $user = PersonalInfo::find($id);
        $object = PersonalInfo::where('id',$id)->get();
        $object1 = AdditionalInformation::where('user_id',$id)->get();
        $data3=UserImage::where('user_id',$id)->get();
        $data =[
            'id' => $id,
            'object' => $object,
            'object1' => $object1,
            'user' => $user,
            'data3' => $data3,
        ];

        $pdf = PDF::loadView('test',$data); //load view page
        return $pdf->download('test.pdf'); // download pdf file
    }
</code>```

Title: laravel generate PDF from blade

Body:
I am trying to download my page in pdf format and I have been following this tutorial step by step to do it. I tried using a sample data to do it and it work but when I try to use my own data it keep giving me undefined $data3, $object, ..

But I have already defined them already in my controller already:

testController

     public function getTestdata($id){
           $user = PersonalInfo::find($id);
          $object = PersonalInfo::where('id',$id)->get();
        $object1 = AdditionalInformation::where('user_id',$id)->get();
         $data3=UserImage::where('user_id',$id)->get();
     return view('test',compact('id','object','object1','user','data3'));
 }

test.blade.php

Download PDF
...

      @foreach($data3 as $currentUser)
      name ) }}">
      @endforeach

...
  @php
    $userFamily = $user->userFamily;
  @endphp

    FAMILY Members

    @foreach($userFamily as $val)

    @if($val["meta_key"] == "relationshiplist")
    {{  $val["meta_value"]  }}  |
    @endif
        @endforeach

DownloadPDFController:

public function fun_pdf(){
    $pdf = PDF::loadView('test'); //load view page
    return $pdf->download('test.pdf'); // download pdf file
}

Route:

Route::get('/pdf', 'pdfDownloadController@fun_pdf');
Route::get('/user/showtest/{id}/test1', 'testController@getTestData')->name('template');

I also tried following this website to do but it does't seem to work as well, instead it gave me undefined $id. http://itsolutionstuff.com/post/laravel-5-generate-pdf-from-html-view-file-and-download-using-dompdfexample.html

If possible could you guys guide me on how to generate the PDF file

Body:
For this first, you should install Dompdf plugin https://github.com/barryvdh/laravel-dompdf

and everything else in its documentation

I think you should update the controller like this and pass id parameter, change the route also

    public function fun_pdf($id){
        $user = PersonalInfo::find($id);
        $object = PersonalInfo::where('id',$id)->get();
        $object1 = AdditionalInformation::where('user_id',$id)->get();
        $data3=UserImage::where('user_id',$id)->get();
        $data =[
            'id' => $id,
            'object' => $object,
            'object1' => $object1,
            'user' => $user,
            'data3' => $data3,
        ];

        $pdf = PDF::loadView('test',$data); //load view page
        return $pdf->download('test.pdf'); // download pdf file
    }


问:
as3 tabbing to next form field starts on 2nd line
I have a simple form I created in flash and I set it up so you can tab from one field to the next.  The problem is when I tab to one of the fields, a multiline textbox, it starts on the second line of that field. If I click on the textfield it goes to the 1st line.

ANy idea how I can remedy this?

The code is pretty simple:

_styleLibForm.tabChildren = true;

```<code>_styleLibForm.first_name.tabIndex = 1;

                _styleLibForm.first_name.tabEnabled = true;
                _styleLibForm.first_name.focusRect = true;

                _styleLibForm.city.tabIndex = 2;
                _styleLibForm.city.tabEnabled = true;
                _styleLibForm.city.focusRect = true;

                _styleLibForm.description.tabIndex = 3;
                _styleLibForm.description.tabEnabled = true;
                _styleLibForm.description.focusRect = true;

                _styleLibForm.email.tabIndex = 4;
                _styleLibForm.email.tabEnabled = true;
                _styleLibForm.email.focusRect = true;
</code>```

答:
this might help
 and did you try making your lowest tabIndex = 2?

Body:
I have a simple form I created in flash and I set it up so you can tab from one field to the next.  The problem is when I tab to one of the fields, a multiline textbox, it starts on the second line of that field. If I click on the textfield it goes to the 1st line.

ANy idea how I can remedy this?

The code is pretty simple:

_styleLibForm.tabChildren = true;

_styleLibForm.first_name.tabIndex = 1;

                _styleLibForm.first_name.tabEnabled = true;
                _styleLibForm.first_name.focusRect = true;

                _styleLibForm.city.tabIndex = 2;
                _styleLibForm.city.tabEnabled = true;
                _styleLibForm.city.focusRect = true;

                _styleLibForm.description.tabIndex = 3;
                _styleLibForm.description.tabEnabled = true;
                _styleLibForm.description.focusRect = true;

                _styleLibForm.email.tabIndex = 4;
                _styleLibForm.email.tabEnabled = true;
                _styleLibForm.email.focusRect = true;