问:
mapping between routes and direction using javascript or python graph or tree?
I need to create the relationship between routes and direction. I am not sure which data structure is appropriate for me and how should I proceed. Currently I have two lists/arrays. One array contains routes and another contains direction. For example, routes = [11,12,13,14,15,16,17,18,19,20] directions = ["north","south","west","east","inbound","outbound"]. Some of these routes(as in bus service) goes only in 2 directions, 1 direction,etc . For example say 11,12,19 goes north and south. 18,20 goes to to inbound and outbound. 17 goes only inbound. 14,15 goes to all the directions.

So what would be better approach to implement this in JavaScript or python. I can see this as a graph DS problem. Can anyone help me or know better approach

答:
You could structure your data like a dict in Python (which is essentially a hashmap). The idea is that you have key : value pairs that are easily accessible.

Depending on how you need to access the data, you could structure it like this:

```<code>{
     11 : ['north', 'south'],
     17 : ['inbound'],
     ...
}
</code>```

Where the key are the routes and the values are the list of directions.

OR

You could structure like this:

```<code>{
    'north' : [11, 12, 14, 15, 19],
    'inbound' : [17, 18, ...],
    ...
}
</code>```

Where the keys are the directions and the values are the list of routes that go in that direction.

Getting values in a dict is O(1) and looking up values in a list is O(n). To get even better speeds, you could instead use a set for the values, which has a lookup speed of O(1) as well.

Body:
You could structure your data like a dict in Python (which is essentially a hashmap). The idea is that you have key : value pairs that are easily accessible.

Depending on how you need to access the data, you could structure it like this:

{
     11 : ['north', 'south'],
     17 : ['inbound'],
     ...
}

Where the key are the routes and the values are the list of directions.

OR

You could structure like this:

{
    'north' : [11, 12, 14, 15, 19],
    'inbound' : [17, 18, ...],
    ...
}

Where the keys are the directions and the values are the list of routes that go in that direction.

Getting values in a dict is O(1) and looking up values in a list is O(n). To get even better speeds, you could instead use a set for the values, which has a lookup speed of O(1) as well.


来源: stackexchange

问:
How to import the same txt file (That updated daily) to Excel
I have a txt file that automatically do updates in a daily bases, I have to open that txt file in Excel (Delimited) and review the data.
What is the way to make Excel automatically import that specific txt file?
Or in another words: I need to Double click on a saved Excel file and it will automatically import that specific txt file (instead of doing File->open->Browse...)
Thanks!</p>

答:
This should work
http://www.jkp-ads.com/Articles/importtext.asp?AllComments=True

In case you are getting your data from sql or any other data source , you can update the data connections in EXCEL

Just Open the excel file and hit refresh

ContentLicense: CC BY-SA 3.0


问:
Animate height when max-height is changed to none
On my website I want to animate when a menu opens. I do that by changing the max-height of the
 that is the menu (and also changing display).

max-height is changed from 4em to none.
It used to be that it was changed to 500px instead of none and then the animation did work, however it doesn't work with none.

What am I doing wrong?

Here is my website

答: None is not valid for max-height. I would change it to 0.</p>


问:
What is the equivalent to ng-if in react.js?
I'm coming to react from using angular and I'm trying to figure out a good react alternative to angular's ng-if directive where I render or dont render an element based on a condition. Take this code for example. I'm using typescript (tsx) btw but that shouldn't matter much.

```<code>"use strict";

import * as React from 'react';

interface MyProps {showMe: Boolean}
interface MyState {}

class Button extends React.Component <MyProps, MyState>{
  constructor(props){
    super(props);
    this.state = {};
  }

  render(){
    let button;
    if (this.props.showMe === true){
       button = (
        <button type="submit" className="btn nav-btn-red">SIGN UP</button>
      )
    } else {
      button = null;
    }
    return button;

}
}
export default Button;
</code>```

This solution works, but is there another way that's generally used to achieve this effect? I'm just sort of guessing

答:
false, null, undefined, and true are valid children. They simply don’t
  render. These JSX expressions will all render to the same thing:

So you can try this

```<code>const conditional=({condition,someArray})=>{
     return(
        <div>
          {condition && <Header /> // condition being boolean}
          {someArray.length>0 && <Content />}
        </div>
      )
}
</code>```

this can be useful to conditionally render React elements. This JSX only renders a  if condition is true
and will render  only if someArray.length>0

Body:
I'm coming to react from using angular and I'm trying to figure out a good react alternative to angular's ng-if directive where I render or dont render an element based on a condition. Take this code for example. I'm using typescript (tsx) btw but that shouldn't matter much.

"use strict";

import * as React from 'react';

interface MyProps {showMe: Boolean}
interface MyState {}

class Button extends React.Component <MyProps, MyState>{
  constructor(props){
    super(props);
    this.state = {};
  }

  render(){
    let button;
    if (this.props.showMe === true){
       button = (
        <button type="submit" className="btn nav-btn-red">SIGN UP</button>
      )
    } else {
      button = null;
    }
    return button;

}
}
export default Button;

This solution works, but is there another way that's generally used to achieve this effect? I'm just sort of guessing

Body:
false, null, undefined, and true are valid children. They simply don’t
  render. These JSX expressions will all render to the same thing:

So you can try this

const conditional=({condition,someArray})=>{
     return(
        <div>
          {condition && <Header /> // condition being boolean}
          {someArray.length>0 && <Content />}
        </div>
      )
}

this can be useful to conditionally render React elements. This JSX only renders a  if condition is true
and will render  only if someArray.length>0


问:
MS format tag for Opus codec
Is there a defined format tag for Opus that should be used with the WAVEFORMATEX structure? See WAVEFORMATEX structure, wFormatTag.

答:
Windows SDK defines WAVE_FORMAT_OPUS (0x704F == 'Op') and MFAudioFormat_Opus which is a Media Foundation equivalent for supposed MEDIASUBTYPE_OPUS, and is a standard FourCC based mapping from WAVE_FORMAT_OPUS.

That is, those are suggested for use identifiers.

However though, Microsoft's own implementation of Opus decoder is not available to public and reserved for use in Microsoft's products (presumably Edge browser), so there is no adopted practice and even documentation more on these identifiers, and everyone on his own how to use them (or use something else instead).

Title: MS format tag for Opus codec


问:
How do I connect GitHub to Shopify?
I've used Beanstalk and Tower in the past for version control, however, is there a way to connect Shopify to GitHub?

Ideally, I'd like to have a copy of my Shopify theme on my desktop to work on, then when I'm ready to push the changes, I'll use the GitHub Desktop app to push to Shopify.

How do I go about connecting Shopify and GitHub together?

Cheers

答:
In order to preview your local changes on a Shopify theme you need to push them to the Shopify server and test them on a development store or as an unpublished theme on a live store.

Accordingly, I would recommend using a command line tool like Shopify's slate (https://github.com/Shopify/slate). This will allow you to watch for changes in your local files and push them to your Shopify store. I wrote a post here on setting up a new theme for local dev with slate http://www.codeshopify.com/blog_posts/local-shopify-development-with-slate

In terms of git / github integration you can use this for version control the same way you would any other site.

When it comes time to put your Shopify site live you can simply publish the theme and make sure you have removed the storefront password.

Title: How do I connect GitHub to Shopify?


问:
Initialize the size of vector else appending wont work, why?
```<code>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main()
{
int n;
vector < string > arr(100); // initialise the size of vector always else
appending wont work,why?
string y;
int x;
cin>>n;
for(int i=0;i<n;i++)
{
    cin>>x>>y;
    fflush(stdin);
    if(i<n/2)
    {
       arr[x].append("- "); //appending the first 10 positions with "- "
    }
    else
    {
        arr[x].append(y);
        arr[x].append(" "); //appending the last 10 positions with given
strings
    }
}
for(int i=0;i<100;i++)
{
    cout<<arr[i];
}
return 0;
}
</code>```

appending isnt working either by using + or append it gives warning please explain why sir?
it gives warning that a pointer to function used in arithmetic operation...

答:
initialise the size of vector always else appending wont work,why?

Because this code:

```<code>arr[x].append("- ");
</code>```

means "call method append() on x-th element of vector arr". When you create arr empty x-th element (no matter what value x has) does not exists and your code has UB.

Body:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main()
{
int n;
vector < string > arr(100); // initialise the size of vector always else
appending wont work,why?
string y;
int x;
cin>>n;
for(int i=0;i<n;i++)
{
    cin>>x>>y;
    fflush(stdin);
    if(i<n/2)
    {
       arr[x].append("- "); //appending the first 10 positions with "- "
    }
    else
    {
        arr[x].append(y);
        arr[x].append(" "); //appending the last 10 positions with given
strings
    }
}
for(int i=0;i<100;i++)
{
    cout<<arr[i];
}
return 0;
}

appending isnt working either by using + or append it gives warning please explain why sir?
it gives warning that a pointer to function used in arithmetic operation...

Body:
initialise the size of vector always else appending wont work,why?

Because this code:

arr[x].append("- ");

means "call method append() on x-th element of vector arr". When you create arr empty x-th element (no matter what value x has) does not exists and your code has UB.


问:
drupal l() function external link does not work
I need a help with l() function. I want to create anchor to url which user sets in a administration form. It has to be an external link. I have set up the external option true, but the anchor still behaves like internal and the result is mydrupalpage.com/www.facebook.com instead of www.facebook.com

Could anyone help me with this?
I am beginner in drupal so maybe I did something wrong in code:

```<code> $output .= l(t('Facebook'),$variables['facebook_link'], array('attributes'=>array('external' => TRUE)));
</code>```

答:
I had the same issue. Drupal output my-domain-name/www.facebook.com all the time.

You just need to append 'http://' or some other protocol to your links. Otherwise Drupal will consider this an internal link. Fixed it for me. Now it reads 'www.facebook.com'.

Body:
I need a help with l() function. I want to create anchor to url which user sets in a administration form. It has to be an external link. I have set up the external option true, but the anchor still behaves like internal and the result is mydrupalpage.com/www.facebook.com instead of www.facebook.com

Could anyone help me with this?
I am beginner in drupal so maybe I did something wrong in code:

 $output .= l(t('Facebook'),$variables['facebook_link'], array('attributes'=>array('external' => TRUE)));


问:
How to keep animated gif running while doing intense calculations
I have a page which does some intense and long lasting calculations in Javascript. I would like to have a loading animation to tell the user progress is being made. I have an animated gif now, but the whole browser window freezes (and the gif does not play) while the Javascript is running. Then when it's done, it unfreezes. The calculations must be client-side so they cannot be done on a server.

Is there a way to keep Javascript from freezing the page and stopping animations from playing while it's doing calculations?

答:
I answered this with a functioning example (with simple progress indicator) here.

It uses "yield" and is extremely simple to use (and modify existing JS loops) when you simply want to allow other processes a timeslice, and it is simpler to set up than web workers (which I have used as well), especially if you already have a loop interacting with global variables.


问:
Schema Extension in Microsoft Graph Limited to Tenant Only?
Per https://developer.microsoft.com/en-us/graph/docs/concepts/extensibility_overview#permissions (section "Schema extensions lifetime", State "Available"): "The schema extension is available for use by all apps in any tenant. "

What is the reasoning to not allow limiting schema extensions to a single tenant only? (or did I miss the HowTo on this one)

答:
There is a way to limit this by not moving the schema to "Available" and leaving it in "InDevelopment".  The lifecycle is documented here under Schema Extensions Lifecycle.  However we are investigating some tighter controls around visibility (my tenant only, any tenant) and authorization for schema extensions and which apps can get/set schema extension properties.

Be interested to hear more about your scenarios and the kinds of controls you are thinking of.

Hope this helps,


问:
Swift 4 String index offset by too slow while processing a large string
I'm processing a csv file with last column not being always same format.
Each row has this structure:

```<code>"Root/Word1","some string","some string","some œ0'fqw[å”ƒ#”≠§
\nfw@\tfa0j
"
"Root/Word2","some string","some string","some string"
...
</code>```

So 6 columns and the last can contain \n. Which makes it hard to split by components.
Another restriction is that all the strings can be any possible special character. Which makes it hard to use regex.

I decided to solve the problem brute force first. (Yes I have seen that index offset by is O(n). But can't come up with an alternative.)

```<code>static func importData(_ db: DB) {
    let csvString = readDataFromCSV(fileName: "data", fileType: "csv")!

    let totalCharCount = csvString.count
    print("total: \(totalCharCount)")
    for i in 0..<totalCharCount {
        print(i)
        if i+5 >= totalCharCount {
            continue
        }
        let index = csvString.index(csvString.startIndex, offsetBy: i)
        let endIndex = csvString.index(csvString.startIndex, offsetBy:i+5)

        let part = csvString[index ..< endIndex]
        if part == "Root/" {
            let accum = lookInside(i: i, totalCharCount: totalCharCount, csvString: csvString)

            var rows = accum.components(separatedBy: "\",\"")

            if var lastt = rows.last {
                lastt.removeLast()
                lastt.removeLast()
                rows[rows.count-1] = lastt
            }
        }
    }
}

static func lookInside(i:Int, totalCharCount: Int, csvString: String) -> String {
    var accum = ""
    var found = false
    var j = i+5
    while !found {

        if j+5 >= totalCharCount {
            found = true
        }
        let index2 = csvString.index(csvString.startIndex, offsetBy: j)
        let endIndex2 = csvString.index(csvString.startIndex, offsetBy:j+5)

        if csvString[index2 ..< endIndex2] == "Root/" {
            found = true
            accum.removeLast()
        } else {
            accum += String(csvString[index2])
        }
        j += 1
    }

    return accum
}
</code>```

Basically I'm traversing the whole string looking for a pattern "Root/".
When found, I advance from this moment to the next occurrence of the pattern.

Problem is that the csv results in a string 200k chars long and when I run this on simulator it lasts too much time (~30min).

So now I'm asking some help here because according to Instruments all the time is consumed in String.index(offset by) method which is called too many times.

答:
First, I would highly recommend using a csv parser if you're needing to read in the entire dataset, e.g. https://github.com/naoty/SwiftCSV

Second, if you're looking for a specific entry in the entire file, you probably want to use the range function: Answer using String.range

Body:
I'm processing a csv file with last column not being always same format.
Each row has this structure:

"Root/Word1","some string","some string","some œ0'fqw[å”ƒ#”≠§
\nfw@\tfa0j
"
"Root/Word2","some string","some string","some string"
...

So 6 columns and the last can contain \n. Which makes it hard to split by components.
Another restriction is that all the strings can be any possible special character. Which makes it hard to use regex.

I decided to solve the problem brute force first. (Yes I have seen that index offset by is O(n). But can't come up with an alternative.)

static func importData(_ db: DB) {
    let csvString = readDataFromCSV(fileName: "data", fileType: "csv")!

    let totalCharCount = csvString.count
    print("total: \(totalCharCount)")
    for i in 0..<totalCharCount {
        print(i)
        if i+5 >= totalCharCount {
            continue
        }
        let index = csvString.index(csvString.startIndex, offsetBy: i)
        let endIndex = csvString.index(csvString.startIndex, offsetBy:i+5)

        let part = csvString[index ..< endIndex]
        if part == "Root/" {
            let accum = lookInside(i: i, totalCharCount: totalCharCount, csvString: csvString)

            var rows = accum.components(separatedBy: "\",\"")

            if var lastt = rows.last {
                lastt.removeLast()
                lastt.removeLast()
                rows[rows.count-1] = lastt
            }
        }
    }
}

static func lookInside(i:Int, totalCharCount: Int, csvString: String) -> String {
    var accum = ""
    var found = false
    var j = i+5
    while !found {

        if j+5 >= totalCharCount {
            found = true
        }
        let index2 = csvString.index(csvString.startIndex, offsetBy: j)
        let endIndex2 = csvString.index(csvString.startIndex, offsetBy:j+5)

        if csvString[index2 ..< endIndex2] == "Root/" {
            found = true
            accum.removeLast()
        } else {
            accum += String(csvString[index2])
        }
        j += 1
    }

    return accum
}

Basically I'm traversing the whole string looking for a pattern "Root/".
When found, I advance from this moment to the next occurrence of the pattern.

Problem is that the csv results in a string 200k chars long and when I run this on simulator it lasts too much time (~30min).

So now I'm asking some help here because according to Instruments all the time is consumed in String.index(offset by) method which is called too many times.


问:
Git checkout branch doesn't change working directory
I am not exactly sure how to phrase this question, as I am new to git.  One of my coworkers was working on a feature in a branch called "rotation."  I wanted to make use of the code he wrote, so I ran git checkout rotation.  The main difference between master and rotation branches is that the rotation branch has an extra subdirectory titled rotation/.  However, after running git checkout, this subdirectory did not show up in my working directory.  How do I get this subdirectory to show up?  I did some googling and found that git doesn't make changes to your working directory when you git checkout a branch if those changes would conflict with tracked changes in your working directory.  However, this is not the case here, at least for the rotation/ subdirectory, as it does not even exist in master.  So why doesn't this subdirectory show up?  How do I get it to?

答:
Have you tried git pull origin rotation?
The form should be git pull <remote> <branchname>.


问:
MySQL Access denied from command connection
So I'm connecting to an AWS EC2 Ubuntu 16.04 instance. As part of my production script I do:

mysql -u root -pmy-secret -e "source resetDb.sql;" >> lastRun.log

This resetDb.sql has the queries to create and populate the database info. Then keep on going with the app.

The thing is that mysql is rejecting my access this way by throwing

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

But if I connect with mysql -u root -p and manually enter the password, it lets me into the console, so this let's me see the password is right.

I get this output on the server

$ mysql --version
mysql  Ver 14.14 Distrib 5.7.20, for Linux (x86_64) using  EditLine wrapper
$ uname -a
Linux ip-xx.xx.xx.xx 4.4.0-1038-aws #47-Ubuntu SMP Thu Sep 28 20:05:35 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

I've seen in another questions about flushing privileges and resetting the root password, but my password is correct so it did no good to me.

Anyone has a clue? The idea is to run the script to automatically setup the whole server. Thanks in advance.

答:
Have tried to use some quotes around the password?
Try this:

```<code>mysql -u root -p"your_passord" -e "SHOW DATABASES"
</code>```

you can even put equals in it:

```<code>mysql --user="root" --password="your_passord" -e "SHOW DATABASES"
</code>```

And if you want something permanent it seems you can try this(never test it):

Body:
Have tried to use some quotes around the password?
Try this:

mysql -u root -p"your_passord" -e "SHOW DATABASES"

you can even put equals in it:

mysql --user="root" --password="your_passord" -e "SHOW DATABASES"

And if you want something permanent it seems you can try this(never test it):


问:
hibernate updating entity attributes to null which are not in form submit
I am building a MVC application using thymeleaf and Spring and Hibernate. My question here is more about hibernate than spring.

This is what i have so far.

A UI

```<code><form role="form" th:action="@{/user/{userId}/official(userId=${userId})}" th:object="${user}" method="post">

            <!--  first form group  -->
            <div class="form-group">

                <label class="control-label col-xs-2">First Name</label>
                <div class="col-xs-2">
                    <input type="text" class="form-control" th:field="*{firstName}" placeholder="First Name" />
                </div>

                <label class="control-label col-xs-2">Last Name</label>
                <div class="col-xs-3">
                    <input type="text" class="form-control" th:field="*{lastName}" placeholder="Last Name" />

            <!--  first form group end  -->
            </div>
            <br/><br/>

            <!--  third form group  -->
                <div class="form-group">
                    <label class="control-label col-xs-2">Email Address</label>
                    <div class="col-xs-2">
                        <input type="text" class="form-control" th:field="*{emailAddress}" placeholder="Email Address" />
                    </div>

            </div>

            <div class="form-group">
                                    <div class="col-xs-2">
                                        <input type="submit" value="Update" class="btn btn-primary" />
    </form>
</code>```

Controller :

```<code>@Controller
public class UserController {

    @Autowired
    private IUserService userServiceImpl;

    @RequestMapping(value = "/user/{userId}/official", method = RequestMethod.GET)
    public String getUserOfficialInfo(@PathVariable("userId") Integer userId, Model model) throws ServiceBusinessException {

                    UserBO userBO = userServiceImpl.findUserByUserId(userId);
                    model.addAttribute("user", userBO);
                    model.addAttribute("userId", userId);
                    model.addAttribute("genders", EnumSet.allOf(Gender.class));
                    return "official";
    }

    @RequestMapping(value = "/user/{userId}/official", method = RequestMethod.POST)
    public String updateUserOfficialInfo(@PathVariable("userId") String userId, @ModelAttribute("user") UserBO user,BindingResult result, Model model) throws ServiceBusinessException {

                    userServiceImpl.updateUser(user);
                    UserBO userBO = userServiceImpl.findUserByUserId(Integer.parseInt(userId));
                    model.addAttribute("user", userBO);
                    model.addAttribute("userId", userId);
                    model.addAttribute("genders", EnumSet.allOf(Gender.class));
                    return "official";
    }
}
</code>```

DAO :

```<code>@Override
    public void updateUser(UserEntity user) throws DaoException {
        entityManager.merge(user);
    }
</code>```

The GET method in the controller, gets the user object to the view. But on the VIew i am just displaying few of those attributes of a user object in the form.

On the form Submit, the POST method in the controller gets called, which calls the service layer and then the merge method in the DAO gets executed.

Now what I have observed is that this merge method on the entity manager is updating the attributes which are not there in the form to null.

I think this is the expected behaviour since the object is detached when its called from the POST method. So the right thing to do here is to first fetch the entity object from the database and then to that object set the fields which are changed in the form and then call the merge method.

Can some one let me know if the above what I said is correct ?

If yes, then my next question would be that isnt this quite tedious and kind of bit more effort. I mean there are going to be cases where in I would not want to display the entire object in the form. Also not in hidden fields. I am quite surprise that there is no way to handle this and I have to follow the approach I just described above each time.

Is there a better way to do this ? Wouldn't i just use JDBC template instead ? I know I would be writing boiler plate code there but I am kind of writing getters and setters here as well for each round trip to the UI.

答:
you can put the following code in a util class and invoke it when you want to fill your object based on another reference object:

```<code>public static <T> void  fillNotNullFields(T reference, T source) {
        try {
            Arrays.asList(Introspector.getBeanInfo(reference.getClass(), Object.class)
                    .getPropertyDescriptors())
                    .stream()
                    .filter(pd -> Objects.nonNull(pd.getReadMethod()))
                    .forEach(pd -> {
                        try {
                            Object value = pd.getReadMethod().invoke(source);
                            if (value != null)
                                pd.getWriteMethod().invoke(reference, value);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
    }
</code>```

So, you can do this on the service:

```<code>public UserBO updateUser(String userId, UserBO user ) {
                    UserBO reference = findOne(Integer.parseInt(userId));
                    fillNotNullFields(reference, user);
                    return updateUser(reference);
    }
</code>```

I found the suport for this answer here. Hope it helps.

Body:
I am building a MVC application using thymeleaf and Spring and Hibernate. My question here is more about hibernate than spring.

This is what i have so far.

A UI

<form role="form" th:action="@{/user/{userId}/official(userId=${userId})}" th:object="${user}" method="post">

                First Name

                    <input type="text" class="form-control" th:field="*{firstName}" placeholder="First Name" />

                Last Name

                    <input type="text" class="form-control" th:field="*{lastName}" placeholder="Last Name" />

                    Email Address

                        <input type="text" class="form-control" th:field="*{emailAddress}" placeholder="Email Address" />

                                        <input type="submit" value="Update" class="btn btn-primary" />
    </form>

Controller :

@Controller
public class UserController {

    @Autowired
    private IUserService userServiceImpl;

    @RequestMapping(value = "/user/{userId}/official", method = RequestMethod.GET)
    public String getUserOfficialInfo(@PathVariable("userId") Integer userId, Model model) throws ServiceBusinessException {

                    UserBO userBO = userServiceImpl.findUserByUserId(userId);
                    model.addAttribute("user", userBO);
                    model.addAttribute("userId", userId);
                    model.addAttribute("genders", EnumSet.allOf(Gender.class));
                    return "official";
    }

    @RequestMapping(value = "/user/{userId}/official", method = RequestMethod.POST)
    public String updateUserOfficialInfo(@PathVariable("userId") String userId, @ModelAttribute("user") UserBO user,BindingResult result, Model model) throws ServiceBusinessException {

                    userServiceImpl.updateUser(user);
                    UserBO userBO = userServiceImpl.findUserByUserId(Integer.parseInt(userId));
                    model.addAttribute("user", userBO);
                    model.addAttribute("userId", userId);
                    model.addAttribute("genders", EnumSet.allOf(Gender.class));
                    return "official";
    }
}

DAO :

@Override
    public void updateUser(UserEntity user) throws DaoException {
        entityManager.merge(user);
    }

The GET method in the controller, gets the user object to the view. But on the VIew i am just displaying few of those attributes of a user object in the form.

On the form Submit, the POST method in the controller gets called, which calls the service layer and then the merge method in the DAO gets executed.

Now what I have observed is that this merge method on the entity manager is updating the attributes which are not there in the form to null.

I think this is the expected behaviour since the object is detached when its called from the POST method. So the right thing to do here is to first fetch the entity object from the database and then to that object set the fields which are changed in the form and then call the merge method.

Can some one let me know if the above what I said is correct ?

If yes, then my next question would be that isnt this quite tedious and kind of bit more effort. I mean there are going to be cases where in I would not want to display the entire object in the form. Also not in hidden fields. I am quite surprise that there is no way to handle this and I have to follow the approach I just described above each time.

Is there a better way to do this ? Wouldn't i just use JDBC template instead ? I know I would be writing boiler plate code there but I am kind of writing getters and setters here as well for each round trip to the UI.

Body:
you can put the following code in a util class and invoke it when you want to fill your object based on another reference object:

public static <T> void  fillNotNullFields(T reference, T source) {
        try {
            Arrays.asList(Introspector.getBeanInfo(reference.getClass(), Object.class)
                    .getPropertyDescriptors())
                    .stream()
                    .filter(pd -> Objects.nonNull(pd.getReadMethod()))
                    .forEach(pd -> {
                        try {
                            Object value = pd.getReadMethod().invoke(source);
                            if (value != null)
                                pd.getWriteMethod().invoke(reference, value);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
    }

So, you can do this on the service:

public UserBO updateUser(String userId, UserBO user ) {
                    UserBO reference = findOne(Integer.parseInt(userId));
                    fillNotNullFields(reference, user);
                    return updateUser(reference);
    }

I found the suport for this answer here. Hope it helps.


问:
Unable to write in directory Laravel
In my server, I get this error message

```<code>Unable to write in the "/home/company/blog/public/img" directory
</code>```

When I try to upload an image like this in my controller

```<code>$file = $request->file('img');
        $name = time() . '-' . $file->getClientOriginalName();
        $file->move(public_path() .'/img/', $name);
        $company = company::where('username', $username)->first();
        $company->images()->create(['path' => "/{$name}"]);
</code>```

I know it's about granting permissions I tried

```<code>chmod 755 /home/company/blog/public/img
</code>```

But it still doesn't work.

How can I resolve this?

答:
This is a common case when your server uses different user than you use in console. You can have www-data for web server and user for console.

755 means full rights for owner and read+execute for the user's group and others (read this). So, when you chmod 755 as user, you grant full access for user and no write permission to www-data.

You have to change owner of the directory to your server's user. If your server's user is www-data, use

sudo chown -R www-data:www-data /home/company/blog/public/img

Title: Unable to write in directory Laravel

Body:
In my server, I get this error message

Unable to write in the "/home/company/blog/public/img" directory

When I try to upload an image like this in my controller

$file = $request->file('img');
        $name = time() . '-' . $file->getClientOriginalName();
        $file->move(public_path() .'/img/', $name);
        $company = company::where('username', $username)->first();
        $company->images()->create(['path' => "/{$name}"]);

I know it's about granting permissions I tried

chmod 755 /home/company/blog/public/img

But it still doesn't work.

How can I resolve this?


问:
How to perform two results with a single $('#id').on('change', function);
I have let's say sets of div:

```<code><body>
<div id="div1" style="display: block">
    <p> paragraph here </p>``
    <img>
    <table></table>
</div>

<div id="div2" style="display: none">
    <p> paragraph here </p>
    <img>
    <table></table>
</div>
</code>```

I surrounded each contents with div.

Now I have two radio buttons:

```<code><label for="button1"> Button1 </label>
<input id="button1" name="button" type="radio" value="block">
<label for="button2"> Button2</label>
<input id="button2" name="button" type="radio" value="block">
</code>```

Now what I want to do is to hide the current div and display the second div in place of the first div using .css().
The method I have now is:

```<code>$('#button1').on('change', function1);
function function1() {
    let change1 = $('#button1').val();
        $('#div1').css('display', change1);
</code>```

but here, when I tried the second button:

```<code>$('#button2').on('change',function2);
function function2() {
    let change2 = $('#button2').val();
        $('#div2').css('display', change2);
        $('#div1').css('display', 'none');
</code>```

but it doesn't work, it can only execute one or the other but not both of them. Anyone knows the problem?
Thank you.

答:
Adding some common classes and using the values of the radios would help simplify this

$('.button').on('change', function(e) {
  var val = this.value;
  $('.content').hide().filter('#div' + val).show();

})
// trigger event on checked radio on page load
.filter(':checked').change();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content{display:none}</code>```

 paragraph here 1

 paragraph here 2

 Button1
<input id="button1" class="button" name="button" type="radio" value="1" checked>
 Button2
<input id="button2"  class="button" name="button" type="radio" value="2">```

Body:
I have let's say sets of div:

 paragraph here
``

 paragraph here

I surrounded each contents with div.

Now I have two radio buttons:

 Button1
<input id="button1" name="button" type="radio" value="block">
 Button2
<input id="button2" name="button" type="radio" value="block">

Now what I want to do is to hide the current div and display the second div in place of the first div using .css().
The method I have now is:

$('#button1').on('change', function1);
function function1() {
    let change1 = $('#button1').val();
        $('#div1').css('display', change1);

but here, when I tried the second button:

$('#button2').on('change',function2);
function function2() {
    let change2 = $('#button2').val();
        $('#div2').css('display', change2);
        $('#div1').css('display', 'none');

but it doesn't work, it can only execute one or the other but not both of them. Anyone knows the problem?
Thank you.

Body:
Adding some common classes and using the values of the radios would help simplify this

$('.button').on('change', function(e) {
  var val = this.value;
  $('.content').hide().filter('#div' + val).show();

})
// trigger event on checked radio on page load
.filter(':checked').change();

.content{display:none}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" class="content">
  <p> paragraph here 1</p>
  <img>
  <table></table>
</div>

<div id="div2"  class="content">
  <p> paragraph here 2</p>
  <img>
  <table></table>
</div>

<label for="button1"> Button1 </label>
<input id="button1" class="button" name="button" type="radio" value="1" checked>
<label for="button2"> Button2</label>
<input id="button2"  class="button" name="button" type="radio" value="2">


问:
Consequences of ARCHIVELOG
The guys responsible for the backup of our servers get our database (a large one) offline for over 6h for the whole backup scene.

I spoke to them asking if we could break that down to smaller and more frequent backup tasks, i.e. backing up each schema at time, or even sets of tables in different times.

Their answer was it was sort of possible if we decided to turn the ARCHIVELOG, which, would have performance consequences.

I'm quite unfamiliar with that just as much as with ways of doing backup.

Which other options would you guys recommend for backing up my schemas in a more efficient, or at least, not so down-time intensive way?

thanks!

f.

答:
if your database has its ARCHIVELOG disabled, you will lose data in case of a hardware failure (potentially all data entered since the last backup). If this is acceptable, then you can disable ARCHIVELOG.

On production instances it is common to have the requirement to NOT lose data (this would be the primary goal of a DBA). In that case the argument about performance is moot, you will turn ARCHIVELOG on because it is a requirement. Then you can have hot backups, they are not more complex than cold backups if you use RMAN, they also won't flush the database cache (improving performance). You can use RMAN to make incremental backups (instead of FULL cold backup) that will only log changes since the last backup.

Furthermore, with enough IO (add more disks), you can setup the database so that the writing of the archive logs doesn't impact performance noticeably.

ContentLicense: CC BY-SA 2.5

Title: Consequences of ARCHIVELOG


答:
Simply checking out the branch isn't enough to get remote changes to your machine. You must use git pull or git fetch.

Here is a
useful diagram you can use as a reference.

Title: Git checkout branch doesn't change working directory

Body: I am not exactly sure how to phrase this question, as I am new to git.  One of my coworkers was working on a feature in a branch called "rotation."  I wanted to make use of the code he wrote, so I ran git checkout rotation.  The main difference between master and rotation branches is that the rotation branch has an extra subdirectory titled rotation/.  However, after running git checkout, this subdirectory did not show up in my working directory.  How do I get this subdirectory to show up?  I did some googling and found that git doesn't make changes to your working directory when you git checkout a branch if those changes would conflict with tracked changes in your working directory.  However, this is not the case here, at least for the rotation/ subdirectory, as it does not even exist in master.  So why doesn't this subdirectory show up?  How do I get it to?


问:
Firebase login with AngularDart in Chrome browser
I am testing a web app of firebase login with angular Dart in Chrome browser at localhost, but while clicking on the sign-in the popup for login gets disappeared within 1 sec and doesn't result with successful login. While testing it on Chromium it's working.
Can anyone tell what should I do to fix this?

firebase_service.dart

```<code>import 'dart:async';
import 'package:angular/angular.dart';
import 'package:firebase/firebase.dart' as fb;

@Injectable()
class FirebaseService {
  fb.User user;
  fb.Auth _fbAuth;
  fb.GoogleAuthProvider _fbGoogleAuthProvider;

  FirebaseService() {
    fb.initializeApp(
      apiKey: "AIzaSyBOShlCgUeqTL99n32bjWdNlkH1RPk9Xx4",
      authDomain: "my-app.firebaseapp.com",
      databaseURL: "https://my-app.firebaseio.com",
      storageBucket: "my-app.appspot.com",
    );

    _fbGoogleAuthProvider = new fb.GoogleAuthProvider();
    _fbAuth = fb.auth();
    _fbAuth.onAuthStateChanged.listen(_authChanged);
  }

  void _authChanged(fb.User event) {
    user = event;
  }

  Future signIn() async {
    try {
      await _fbAuth.signInWithPopup(_fbGoogleAuthProvider);
     }
    catch (error) {
      print("$runtimeType::login() -- $error");
    }
  }

  void signOut() {
    _fbAuth.signOut();
  }
}
</code>```

app_component.html

```<code>    <header class="material-header shadow">
    <div class="material-header-row">
        <material-button icon
                         class="material-drawer-button" (trigger)="drawer.toggle()">
            <material-icon icon="menu"></material-icon>
        </material-button>
        <span class="material-header-title">{{appTitle}}</span>
        <div class="material-spacer"></div>
        <nav class="material-navigation">
            <material-button class="material-drawer-button" icon
                             materialTooltip="Notifications"
                             (trigger)="">
                <material-icon icon="notifications"></material-icon>
            </material-button>
            <div id="popup-sign-out" class="popup-user" *ngIf="fbService.user != null">
                <material-button class="material-drawer-button" icon
                                 popupSource
                                 #source="popupSource"
                                 materialTooltip="More options"
                                 (trigger)="basicPopupVisible = !basicPopupVisible">
                    <material-icon icon="more_vert"></material-icon>
                </material-button>
                <material-popup defaultPopupSizeProvider
                                enforceSpaceConstraints
                                [source]="source"
                                [(visible)]="basicPopupVisible">
                    <div header class="custom-header">
                        <img id="popup-user-image" [src]="fbService.user?.photoURL">
                        <div class="user-detail">
                            <div id="user-name">{{fbService.user?.displayName}}</div>
                            <div id="email">{{fbService.user?.email}}</div>
                        </div>
                    </div>

                    <div group class="custom-popup-body">
                        <material-list class="popup-list" size="3">
                                       <div group>
                                <material-list-item class="sign-out-button"
                                                    *ngIf="fbService.user != null"
                                                    (trigger)="fbService.signOut()">
                                    <material-icon icon="exit_to_app" [style.color]="iconColor"
                                                   class="material-list-item-primary" aria-hidden="true">
                                    </material-icon>
                                    Sign out
                                </material-list-item>
                            </div>

                        </material-list>
                    </div>
                </material-popup>
            </div>
        </nav>
        <nav class="material-navigation">
                <div id="sign-in" class="user" *ngIf="fbService.user == null">
                    <material-button raised class="sign-in-button" (trigger)="fbService.signIn()">
                        <img class="google-icon" src="g-logo.png"/>
                        Sign In
                    </material-button>
                </div>

                <div id="sign-out" class="user" *ngIf="fbService.user != null">
                    <img id="header-user-image" [src]="fbService.user?.photoURL">
                </div>
        </nav>
    </div>
</header>
</code>```

app_component.dart

```<code>import 'package:angular/angular.dart';
import 'package:angular_components/angular_components.dart';
import 'package:yns_app/services/firebase_service.dart';

@Component(
  selector: 'my-app',
      styleUrls: const [
    'app_component.css',
'package:angular_components/src/components/app_layout/layout.scss.css',
  ],
  templateUrl: 'app_component.html',
  directives: const [
    materialDirectives,
    DeferredContentDirective,
    MaterialButtonComponent,
    MaterialIconComponent,
    MaterialPersistentDrawerDirective,
    MaterialToggleComponent,
    MaterialListComponent,
    MaterialListItemComponent,
    ClickableTooltipTargetDirective,
    DarkThemeDirective,
    MaterialIconTooltipComponent,
    MaterialInkTooltipComponent,
    MaterialPaperTooltipComponent,
    MaterialPopupComponent,
    MaterialTooltipDirective,
    MaterialTooltipTargetDirective,
    MaterialTooltipSourceDirective,
    NgIf,
    Search,
    NameGenerator,
 ],
  providers: const [
    materialProviders,
    popupBindings,
    DefaultPopupSizeProvider,
  ],
)
class AppComponent {
  final FirebaseService fbService;
  bool basicPopupVisible = false;
  bool end = false;

  String get tooltipMsg => 'All the best messages appear in tooltips.';

  String get longString => 'Learn more about web development with AngularDart '
  'here. You will find tutorials to get you started.';

  AppComponent(FirebaseService this.fbService);
}

@Injectable()
PopupSizeProvider createPopupSizeProvider() {
  return const PercentagePopupSizeProvider();
}

@Directive(selector: '[defaultPopupSizeProvider]', providers: const [
  const Provider(PopupSizeProvider, useFactory: createPopupSizeProvider)
])
class DefaultPopupSizeProvider {}
</code>```

答: connect the domain or the sub-domain to the hosted project, under the Hosting section.</p>

Body:
I am testing a web app of firebase login with angular Dart in Chrome browser at localhost, but while clicking on the sign-in the popup for login gets disappeared within 1 sec and doesn't result with successful login. While testing it on Chromium it's working.
Can anyone tell what should I do to fix this?

firebase_service.dart

import 'dart:async';
import 'package:angular/angular.dart';
import 'package:firebase/firebase.dart' as fb;

@Injectable()
class FirebaseService {
  fb.User user;
  fb.Auth _fbAuth;
  fb.GoogleAuthProvider _fbGoogleAuthProvider;

  FirebaseService() {
    fb.initializeApp(
      apiKey: "AIzaSyBOShlCgUeqTL99n32bjWdNlkH1RPk9Xx4",
      authDomain: "my-app.firebaseapp.com",
      databaseURL: "https://my-app.firebaseio.com",
      storageBucket: "my-app.appspot.com",
    );

    _fbGoogleAuthProvider = new fb.GoogleAuthProvider();
    _fbAuth = fb.auth();
    _fbAuth.onAuthStateChanged.listen(_authChanged);
  }

  void _authChanged(fb.User event) {
    user = event;
  }

  Future signIn() async {
    try {
      await _fbAuth.signInWithPopup(_fbGoogleAuthProvider);
     }
    catch (error) {
      print("$runtimeType::login() -- $error");
    }
  }

  void signOut() {
    _fbAuth.signOut();
  }
}

app_component.html

        <material-button icon
                         class="material-drawer-button" (trigger)="drawer.toggle()">
            <material-icon icon="menu"></material-icon>
        </material-button>
        {{appTitle}}

            <material-button class="material-drawer-button" icon
                             materialTooltip="Notifications"
                             (trigger)="">
                <material-icon icon="notifications"></material-icon>
            </material-button>

                <material-button class="material-drawer-button" icon
                                 popupSource
                                 #source="popupSource"
                                 materialTooltip="More options"
                                 (trigger)="basicPopupVisible = !basicPopupVisible">
                    <material-icon icon="more_vert"></material-icon>
                </material-button>
                <material-popup defaultPopupSizeProvider
                                enforceSpaceConstraints
                                [source]="source"
                                [(visible)]="basicPopupVisible">

{{fbService.user?.displayName}}

{{fbService.user?.email}}

                        <material-list class="popup-list" size="3">

                                <material-list-item class="sign-out-button"
                                                    *ngIf="fbService.user != null"
                                                    (trigger)="fbService.signOut()">
                                    <material-icon icon="exit_to_app" [style.color]="iconColor"
                                                   class="material-list-item-primary" aria-hidden="true">
                                    </material-icon>
                                    Sign out
                                </material-list-item>

                        </material-list>

                </material-popup>

                    <material-button raised class="sign-in-button" (trigger)="fbService.signIn()">

                        Sign In
                    </material-button>

app_component.dart

import 'package:angular/angular.dart';
import 'package:angular_components/angular_components.dart';
import 'package:yns_app/services/firebase_service.dart';

@Component(
  selector: 'my-app',
      styleUrls: const [
    'app_component.css',
'package:angular_components/src/components/app_layout/layout.scss.css',
  ],
  templateUrl: 'app_component.html',
  directives: const [
    materialDirectives,
    DeferredContentDirective,
    MaterialButtonComponent,
    MaterialIconComponent,
    MaterialPersistentDrawerDirective,
    MaterialToggleComponent,
    MaterialListComponent,
    MaterialListItemComponent,
    ClickableTooltipTargetDirective,
    DarkThemeDirective,
    MaterialIconTooltipComponent,
    MaterialInkTooltipComponent,
    MaterialPaperTooltipComponent,
    MaterialPopupComponent,
    MaterialTooltipDirective,
    MaterialTooltipTargetDirective,
    MaterialTooltipSourceDirective,
    NgIf,
    Search,
    NameGenerator,
 ],
  providers: const [
    materialProviders,
    popupBindings,
    DefaultPopupSizeProvider,
  ],
)
class AppComponent {
  final FirebaseService fbService;
  bool basicPopupVisible = false;
  bool end = false;

  String get tooltipMsg => 'All the best messages appear in tooltips.';

  String get longString => 'Learn more about web development with AngularDart '
  'here. You will find tutorials to get you started.';

  AppComponent(FirebaseService this.fbService);
}

@Injectable()
PopupSizeProvider createPopupSizeProvider() {
  return const PercentagePopupSizeProvider();
}

@Directive(selector: '[defaultPopupSizeProvider]', providers: const [
  const Provider(PopupSizeProvider, useFactory: createPopupSizeProvider)
])
class DefaultPopupSizeProvider {}


问:
Java JDBC type conversion (Firebird / Jaybird): check value/type compatibility before using getter or updater ResultSet method?
If I understand (and test a sample JDBC code; using Jaybird for Firebird) well, even using a proper (= respecting the type mapping) updater method (e.g. ResultSet.updateString), or maybe PreparedStatement parameter, can bring a "conversion exception".

Is it possible (and is it a good practice) to test before actually working with the result set (e.g. running an updater method) whether the actual Java Type/value can be safely converted to the target SQL data type?

Is the "problem" just one-way? I.e. when converting back from SQL to Java (using getter method), is it guaranteed that the correct getter method will never fail (due to conversion problems)?

My examples (Using Jaybird 3.0.2, JDK1.8):

I need to update field: NUMERIC(9,2). The corresponding updater is:
ResultSet.updateBigDecimal(int columnIndex, BigDecimal x). If I use x = new BigDecimal("123456789.1234") (bigger precision and scale), I (logically) get an exception:
Exception in thread "main" org.firebirdsql.jdbc.field.TypeConversionException: Error converting to big decimal.

I need to update field: VARCHAR(5). The corresponding updater is: ResultSet.updateString(int columnIndex, String x).
If I use x = "123456" (longer string 6 > 5), I (logically) get an exception: Exception in thread "main" java.sql.DataTruncation: Data truncation.

Is there some general elegant way (not depending on specific type) how to check, whether an actual Java value/object can be "saved" to certain SQL field, other than just trying to run the query and catching the exceptions?

I would like to check the values already in my data editing dialog (before actually running the update query). Simple test "VALUE OK / NOT OK" would be fine (knowing just the target SQL type).

It seems quite difficult for me to find all rules I would have to check "type by type" (i.e. for VARCHAR check string length, for NUMERIC check precision and scale etc. - but what else? or would that be sufficient? for integer and float types no need to check anything?).

I tried to go through the Jaybird source codes but the "conversion process" is very complicated (and type-specific), I could not find the answer myself.

答:
JDBC does not provide anything to 'check' values before you actually set them, so Jaybird doesn't either: setting the value is the check. Exact behaviour is driver dependent, Jaybird attempts to validate on setting values, but other drivers might choose to defer this to the database itself (so the error would only occur on execute).

Normally, you would design your database and pick column types based on your business needs, which should naturally have lead to validation before you even try to put it in the database.

If you haven't done that until now, start adding validation to your input forms, by restricting lengths, using things like Hibernate Validator, or the validation of your UI framework.

If you are working with highly dynamic requirements (eg user provided queries, etc), then you should use the features that JDBC does provide to create your own validation: The ParameterMetaData of a prepared statement and the ResultSetMetaData of a result set (also accessible from a prepared statement), specifically the getPrecision (and getScale) of these objects, or maybe even things like DatabaseMetadata.getColumns.

For a character type, getPrecision will indicate the max number of characters, for a numeric or decimal type you can use the max numbers of digits before the decimal point as precision - scale.

However in Jaybird this is not a 100% exact, for example getPrecision may return 9 for a numeric(8,2) if Jaybird can't identify the underlying column, and Jaybird (and Firebird) will actually allow up to precision 10 with some limitations (that is, unscaled max value of Integer.MAX_VALUE, ie 21474836.47 for this type).

As to your second question if using getters could cause a conversion exception: normal cases will not, but for example calling getInt() on a BIGINT with a value larger than Integer.MAX_VALUE or Integer.MIN_VALUE will.

ContentLicense: CC BY-SA 4.0


问:
PostgreSQL - Avoid listing the same IN() values twice
I have a query on a customer referrals table in which each row contains the customer id of a referring customer, and a referred customer. So if Bob with custID 100 refers John with custID 200 to our product, we enter a row in the referrals table where referring_user_id is 100 and referred_user_id is 200.

Given a list of user_ids, I want to search both the referring_user_id column and the referred_user_id column for any matches. The only way I figured out how to do this is to do an OR on both columns, and copy the list of user_ids twice like so:

```<code>SELECT
    ---columns---
FROM tbl_referrals REF
LEFT JOIN tbl_profile PRF1 ON REF.referring_user_id = PRF1.user_id
LEFT JOIN tbl_profile PRF2 ON REF.referred_user_id = PRF2.user_id
WHERE
    PRF1.user_id IN (
        'id100',
        'id200',
        'id300',
        'id400'
    )
    OR PRF2.user_id IN (
        'id100',
        'id200',
        'id300',
        'id400'
    )
ORDER BY REF.referred_user_id
limit 100;
</code>```

Is there a way to write this query without writing the whole list of ids twice? This is post-gres btw, but I think it applies to all SQL.

答:
Your LEFT join is becoming an INNER join because you are filtering the right tables in your where clause.

Because both of your join predicates are referencing the same filtered column, user_id, you could simplify your query to this:

```<code>SELECT
---columns---
FROM tbl_referrals REF
JOIN tbl_profile PRF1 ON REF.referring_user_id = PRF1.user_id
                      OR REF.referred_user_id = PRF1.user_id
WHERE PRF1.user_id IN ('id100','id200','id300','id400')
ORDER BY REF.referred_user_id
LIMIT 100;
</code>```

Edit for comment:

You could use conditional aggregation to get both names for the select:

```<code>SELECT
     MAX(CASE WHEN REF.referring_user_id = PRF1.user_id THEN PRF1.Name END) ReferringName,
     MAX(CASE WHEN REF.referred_user_id = PRF1.user_id THEN PRF1.Name END) ReferredName,
     ---other columns---
FROM tbl_referrals REF
JOIN tbl_profile PRF1 ON REF.referring_user_id = PRF1.user_id
                      OR REF.referred_user_id = PRF1.user_id
WHERE PRF1.user_id IN ('id100','id200','id300','id400')
GROUP BY ---other columns---
ORDER BY REF.referred_user_id
LIMIT 100;
</code>```

Body:
I have a query on a customer referrals table in which each row contains the customer id of a referring customer, and a referred customer. So if Bob with custID 100 refers John with custID 200 to our product, we enter a row in the referrals table where referring_user_id is 100 and referred_user_id is 200.

Given a list of user_ids, I want to search both the referring_user_id column and the referred_user_id column for any matches. The only way I figured out how to do this is to do an OR on both columns, and copy the list of user_ids twice like so:

SELECT
    ---columns---
FROM tbl_referrals REF
LEFT JOIN tbl_profile PRF1 ON REF.referring_user_id = PRF1.user_id
LEFT JOIN tbl_profile PRF2 ON REF.referred_user_id = PRF2.user_id
WHERE
    PRF1.user_id IN (
        'id100',
        'id200',
        'id300',
        'id400'
    )
    OR PRF2.user_id IN (
        'id100',
        'id200',
        'id300',
        'id400'
    )
ORDER BY REF.referred_user_id
limit 100;

Is there a way to write this query without writing the whole list of ids twice? This is post-gres btw, but I think it applies to all SQL.

Body:
Your LEFT join is becoming an INNER join because you are filtering the right tables in your where clause.

Because both of your join predicates are referencing the same filtered column, user_id, you could simplify your query to this:

SELECT
---columns---
FROM tbl_referrals REF
JOIN tbl_profile PRF1 ON REF.referring_user_id = PRF1.user_id
                      OR REF.referred_user_id = PRF1.user_id
WHERE PRF1.user_id IN ('id100','id200','id300','id400')
ORDER BY REF.referred_user_id
LIMIT 100;

Edit for comment:

You could use conditional aggregation to get both names for the select:

SELECT
     MAX(CASE WHEN REF.referring_user_id = PRF1.user_id THEN PRF1.Name END) ReferringName,
     MAX(CASE WHEN REF.referred_user_id = PRF1.user_id THEN PRF1.Name END) ReferredName,
     ---other columns---
FROM tbl_referrals REF
JOIN tbl_profile PRF1 ON REF.referring_user_id = PRF1.user_id
                      OR REF.referred_user_id = PRF1.user_id
WHERE PRF1.user_id IN ('id100','id200','id300','id400')
GROUP BY ---other columns---
ORDER BY REF.referred_user_id
LIMIT 100;


问:
Load Multiple Fixtures at Once
Is there anyway to load one fixture and have it load multiple fixtures?

I'd ideally like to type:

```<code>python manage.py loaddata all_fixtures
</code>```

And have that load all of the data instead of having to type everything.  Is this possible?

答:
After doing a bit of searching, I ended up writing this script. It searches through all directories named "fixtures" for .json files and runs a "python manage.py loaddata {fixture_name}.json". Sometimes ordering matters for foreign key constraints, so it leaves a fixture in the queue if the constraint cannot be resolved.

(Note: It requires the pip package simple_terminal that I wrote. And I set it up to be run by 'python manage.py runscript ', which requires django-extensions.)

```<code># load_fixture.py
#
# A script that searches for all .json files in fixtures directories
# and loads them into the working database. This is meant to be run after
# dropping and recreating a database then running migrations.
#
# Usage: python manage.py runscript load_fixtures

from simple_terminal import Terminal

from django.core.management import call_command
from django.db.utils import IntegrityError

def load_fixture(fixture_location):
    # runs command: python manage.py loaddata <fixture_location>
    call_command('loaddata', fixture_location)

def run():
    with Terminal() as t:
        # get all .json files in a fixtures directory
        fixture_locations = t.command(
            'find . -name *.json | grep fixtures | grep -v env')

    while fixture_locations:
        # check that every iteration imports are occuring
        errors = []
        length_before = len(fixture_locations)

        for fl in fixture_locations:
            try:
                # try to load fixture and if loaded remove it from the array
                load_fixture(fl)
                print("LOADED: {}".format(fl))
                fixture_locations.remove(fl)
            except IntegrityError as e:
                errors.append(str(e))

        # if import did not occur this iteration raise exception due to
        # missing foreign key reference
        length_after = len(fixture_locations)
        if length_before == length_after:
            raise IntegrityError(' '.join(errors))
</code>```

Title: Load Multiple Fixtures at Once

Body:
Is there anyway to load one fixture and have it load multiple fixtures?

I'd ideally like to type:

python manage.py loaddata all_fixtures

And have that load all of the data instead of having to type everything.  Is this possible?

Body:
After doing a bit of searching, I ended up writing this script. It searches through all directories named "fixtures" for .json files and runs a "python manage.py loaddata {fixture_name}.json". Sometimes ordering matters for foreign key constraints, so it leaves a fixture in the queue if the constraint cannot be resolved.

(Note: It requires the pip package simple_terminal that I wrote. And I set it up to be run by 'python manage.py runscript ', which requires django-extensions.)

# load_fixture.py
#
# A script that searches for all .json files in fixtures directories
# and loads them into the working database. This is meant to be run after
# dropping and recreating a database then running migrations.
#
# Usage: python manage.py runscript load_fixtures

from simple_terminal import Terminal

from django.core.management import call_command
from django.db.utils import IntegrityError

def load_fixture(fixture_location):
    # runs command: python manage.py loaddata <fixture_location>
    call_command('loaddata', fixture_location)

def run():
    with Terminal() as t:
        # get all .json files in a fixtures directory
        fixture_locations = t.command(
            'find . -name *.json | grep fixtures | grep -v env')

    while fixture_locations:
        # check that every iteration imports are occuring
        errors = []
        length_before = len(fixture_locations)

        for fl in fixture_locations:
            try:
                # try to load fixture and if loaded remove it from the array
                load_fixture(fl)
                print("LOADED: {}".format(fl))
                fixture_locations.remove(fl)
            except IntegrityError as e:
                errors.append(str(e))

        # if import did not occur this iteration raise exception due to
        # missing foreign key reference
        length_after = len(fixture_locations)
        if length_before == length_after:
            raise IntegrityError(' '.join(errors))


问:
Capturing the Paste option from the context menu in AS3 Air Application
Here is what I am trying to do:

User right clicks on a textfield, the system menu that shows the options of "cut,copy,paste,delete,Select All" appears (with only "Paste" and "Select all" active)

User clicks on "paste"

The pasted text is added to the textfield.

My issue is being able to run code right after the user selects the "paste" option from the contextmenu. I tried listening to the textfield change, eventchange, to no avail. This is the code I am using. When the above happens, the following code does not fire. "d" is the textfield object

```<code>    d.addEventListener(Event.CHANGE, paste);

    private function paste(e: Event): void {
        trace("paste event fired");
        if(Clipboard.generalClipboard.hasFormat(ClipboardFormats.TEXT_FORMAT)) {
        trace("pasted data is ", String(Clipboard.generalClipboard.getData(ClipboardFormats.TEXT_FORMAT)));
        }
    }
</code>```

UPDATE:

I tried the suggestions below, but still no luck. Here is the code I have. "d" is already added to stage

```<code>    private function start():void {
           d.addEventListener(TextEvent.PASTE, paste);
    }
    private function paste(event:TextEvent):void{
           trace("something got pasted");
    }
</code>```

What's bugging me is that event is not firing for whatever reason

答:
A TextField is an InteractiveObject, which has a paste event. You can listen for it with the flash.events.Event.PASTE constant.

EDIT: Apologies, the paste event documentation says it doesn't work with TextField. It recommends using the Flash Text Engine, though that is difficult and I don't know how to do text input with it.

You could try:

The textInput event.

The paste, change, and textInput events with a TextInput component instead of a TextField.

The paste, change, and textInput events with a TextArea component instead of a TextField.

Body:
Here is what I am trying to do:

User right clicks on a textfield, the system menu that shows the options of "cut,copy,paste,delete,Select All" appears (with only "Paste" and "Select all" active)

User clicks on "paste"

The pasted text is added to the textfield.

My issue is being able to run code right after the user selects the "paste" option from the contextmenu. I tried listening to the textfield change, eventchange, to no avail. This is the code I am using. When the above happens, the following code does not fire. "d" is the textfield object

    d.addEventListener(Event.CHANGE, paste);

    private function paste(e: Event): void {
        trace("paste event fired");
        if(Clipboard.generalClipboard.hasFormat(ClipboardFormats.TEXT_FORMAT)) {
        trace("pasted data is ", String(Clipboard.generalClipboard.getData(ClipboardFormats.TEXT_FORMAT)));
        }
    }

UPDATE:

I tried the suggestions below, but still no luck. Here is the code I have. "d" is already added to stage

    private function start():void {
           d.addEventListener(TextEvent.PASTE, paste);
    }
    private function paste(event:TextEvent):void{
           trace("something got pasted");
    }

What's bugging me is that event is not firing for whatever reason


问:
Status bar color isn't changing on iPhone X to the left and right of notch
Hello I updated to new Xcode 9 and started using safeAreaLayout guide to support iphone X. From xib, I just used safeAreaLayout guide and adjusted by top and bottom constraints to safeArea.

Here is what I got

iphone X (iOS 11)

iphone 6 (iOS 11)

As you can see my custom navigation bar is down 20pxls

iphone 6 (iOS 9 and 10)

Here you can see how the navigation bar starts from 0 and status bar is merged.

Actually,

1) I want the green color to filled by notch.
2) Status Bar should not show in white color but green color as in 3 image.

I have searched many solutions. But none is working. So I need help.

Regards
Ranjit

答:
Your custom bar's view is being laid out like:

[nav.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor];

Anything that is constrained to the view.safeAreaLayoutGuide.topAnchor will be below the statusBar + navigationBar because that is the safe area.. If it is constrained to safeAreaLayoutGuide.bottomAnchor, then it will be above all tabBars or bottom bars so that iPhone X users can swipe up without touching your view..

However, anything constrained to view.topAnchor will be constrained to the top of the view (IE: The screen)..

So constrain your custom view to the top of your controller's view. Then in viewDidLayoutSubviews, add safeAreaInsets.top to the height. This will allow your view to be touching the top of the screen, but tall/large enough to extend below the navBar. Your will need to adjust the contents of your view to layout further down by the same inset top.

```<code>//
//  ViewController.swift
//  SONav
//
//  Created by Brandon Anthony on 2017-11-17.
//  Copyright © 2017 SO. All rights reserved.
//

import UIKit

class CustomNav : UINavigationBar {

    var desiredHeight: CGFloat = 88.0

    override init(frame: CGRect) {
        super.init(frame: frame)

        desiredHeight = frame.size.height
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func sizeThatFits(_ size: CGSize) -> CGSize {
        var size = super.sizeThatFits(size)
        size.height = desiredHeight
        return size
    }

    override var frame: CGRect {
        get {
            return super.frame
        }

        set {
            var frm = newValue
            frm.size.height = desiredHeight
            super.frame = frm
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        for subview in self.subviews {
            if NSStringFromClass(type(of: subview)).contains("Background") {
                subview.frame.size.height = 0
            }
            else if NSStringFromClass(type(of: subview)).contains("ContentView") {
                subview.frame.origin.y = 0
            }
        }
    }
}

class CustomNavigationController : UINavigationController {
    override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
        super.willTransition(to: newCollection, with: coordinator)
        self.setNeedsStatusBarAppearanceUpdate()
    }
}

class ViewController: UIViewController {
    var customNav: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        //Navigation Bar Setup
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        self.navigationController?.navigationBar.isTranslucent = true
        self.navigationController?.view.backgroundColor = UIColor.clear
        self.navigationController?.navigationBar.backgroundColor = UIColor.clear
        self.navigationController?.navigationBar.shadowImage = nil

        self.view.backgroundColor = UIColor.white
        self.customNav = CustomNav(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 100))
        self.customNav.backgroundColor = UIColor.blue
        self.view.addSubview(self.customNav!)

        NSLayoutConstraint.activate([
            self.customNav.leftAnchor.constraint(equalTo: self.view.leftAnchor),
            self.customNav.rightAnchor.constraint(equalTo: self.view.rightAnchor),
            self.customNav.topAnchor.constraint(equalTo: self.view.topAnchor),
            self.customNav.heightAnchor.constraint(equalToConstant: 100.0)
        ])

        self.customNav.translatesAutoresizingMaskIntoConstraints = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

Body:
Your custom bar's view is being laid out like:

[nav.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor];

Anything that is constrained to the view.safeAreaLayoutGuide.topAnchor will be below the statusBar + navigationBar because that is the safe area.. If it is constrained to safeAreaLayoutGuide.bottomAnchor, then it will be above all tabBars or bottom bars so that iPhone X users can swipe up without touching your view..

However, anything constrained to view.topAnchor will be constrained to the top of the view (IE: The screen)..

So constrain your custom view to the top of your controller's view. Then in viewDidLayoutSubviews, add safeAreaInsets.top to the height. This will allow your view to be touching the top of the screen, but tall/large enough to extend below the navBar. Your will need to adjust the contents of your view to layout further down by the same inset top.

//
//  ViewController.swift
//  SONav
//
//  Created by Brandon Anthony on 2017-11-17.
//  Copyright © 2017 SO. All rights reserved.
//

import UIKit

class CustomNav : UINavigationBar {

    var desiredHeight: CGFloat = 88.0

    override init(frame: CGRect) {
        super.init(frame: frame)

        desiredHeight = frame.size.height
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func sizeThatFits(_ size: CGSize) -> CGSize {
        var size = super.sizeThatFits(size)
        size.height = desiredHeight
        return size
    }

    override var frame: CGRect {
        get {
            return super.frame
        }

        set {
            var frm = newValue
            frm.size.height = desiredHeight
            super.frame = frm
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        for subview in self.subviews {
            if NSStringFromClass(type(of: subview)).contains("Background") {
                subview.frame.size.height = 0
            }
            else if NSStringFromClass(type(of: subview)).contains("ContentView") {
                subview.frame.origin.y = 0
            }
        }
    }
}

class CustomNavigationController : UINavigationController {
    override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
        super.willTransition(to: newCollection, with: coordinator)
        self.setNeedsStatusBarAppearanceUpdate()
    }
}

class ViewController: UIViewController {
    var customNav: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        //Navigation Bar Setup
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        self.navigationController?.navigationBar.isTranslucent = true
        self.navigationController?.view.backgroundColor = UIColor.clear
        self.navigationController?.navigationBar.backgroundColor = UIColor.clear
        self.navigationController?.navigationBar.shadowImage = nil

        self.view.backgroundColor = UIColor.white
        self.customNav = CustomNav(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 100))
        self.customNav.backgroundColor = UIColor.blue
        self.view.addSubview(self.customNav!)

        NSLayoutConstraint.activate([
            self.customNav.leftAnchor.constraint(equalTo: self.view.leftAnchor),
            self.customNav.rightAnchor.constraint(equalTo: self.view.rightAnchor),
            self.customNav.topAnchor.constraint(equalTo: self.view.topAnchor),
            self.customNav.heightAnchor.constraint(equalToConstant: 100.0)
        ])

        self.customNav.translatesAutoresizingMaskIntoConstraints = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


答:
You could make a mini table with the desired IDs and inner join it to the existing tables.  This way you only specify the IDs once.  It would look like:</p>

```<code>SELECT
---columns---
FROM tbl_referrals REF
LEFT JOIN tbl_profile PRF1 ON REF.referring_user_id = PRF1.user_id
LEFT JOIN tbl_profile PRF2 ON REF.referred_user_id = PRF2.user_id
INNER JOIN
(
    SELECT 'id100' AS id UNION ALL
    SELECT 'id200' AS id UNION ALL
    SELECT 'id300' AS id UNION ALL
    SELECT 'id400' AS id
) IDS
on IDS.id = PRF1.user_id OR IDS.id = PRF2.user_id
ORDER BY REF.referred_user_id
limit 100;
</code>```

Title: PostgreSQL - Avoid listing the same IN() values twice

Body:
You could make a mini table with the desired IDs and inner join it to the existing tables.  This way you only specify the IDs once.  It would look like:

SELECT
---columns---
FROM tbl_referrals REF
LEFT JOIN tbl_profile PRF1 ON REF.referring_user_id = PRF1.user_id
LEFT JOIN tbl_profile PRF2 ON REF.referred_user_id = PRF2.user_id
INNER JOIN
(
    SELECT 'id100' AS id UNION ALL
    SELECT 'id200' AS id UNION ALL
    SELECT 'id300' AS id UNION ALL
    SELECT 'id400' AS id
) IDS
on IDS.id = PRF1.user_id OR IDS.id = PRF2.user_id
ORDER BY REF.referred_user_id
limit 100;


问:
Publish a bom from a multi-module-project
We are a large company with about 2000 separate Java projects. For historic reasons, we do not have multi-module projects, but we would like to introduce them.

Logically, we already have "groups" of projects, i.e. someone responsible for (say) 50 projects which are closely related. This someone regularly publishes a BOM which contains recent, coherent versions of these 50 projects.

Now it would make a lot of sense to grab these 50 projects and put them into one large multi-module project. Still, it would be necessary to publish a BOM because other projects (outside our group) should have coherent versions.

So, summarised, we need a BOM that contains the versions of all 50 projects that are part of the multi-module project. I wonder what would be the "Maven way" to create such a BOM. What I can think of:

The bom is the 51st project of the multi-module project. The versions of the dependencies are set by properties in the parent pom.

The bom is generated from the information present in the multi-module project and published as side artifact (this probably requires us to write a Maven plugin for this).

What would be advisable?

答:
I've never seen 2K of commercial Java projects, so will base my answer on how open source works:

Libraries shouldn't be grouped by people - they should be grouped by the problems that they solve. Often open source projects have multiple libs e.g. Jackson has jackson-databind, jackson-datatype-jsr310, etc. These libs tightly relate to each and may depend on each other.

Such groups shouldn't be too big. Some projects may have 1, others - 5 or 10. 50 libs in a group sounds way too much.

It's easier if libs in a group are released all at the same time (even if only one is updated). This makes it straightforward to keep track of versions in the apps that use multiple libs from a group.

There should be no dependencies between groups! And this is probably the most important rule. Deep hierarchy of libraries that depend on each other is not acceptable because now you need to keep compatibility between many projects and libs. This just doesn't scale. Which means there will be occasional copy-paste code between libs - this is the lesser evil.

There could be some exceptions to the last rule (maybe a lib that is used everywhere) but those must keep backward compatibility of the public API until there are no projects that depend on the old API. Such libs are very hard to maintain and it's better to opensource them.

Standalone projects now can depend on libraries from the same or different groups, but because the version within the group is the same, it's easy to set it as a property just once. Alternatively:

You can look at <scope>import</scope> which allows importing <dependencyManagement> sections from other POM files like parent POMs within a group (for some reason never worked for me).

Or at xxx-all modules - a module that depends on all other modules within group and thus when you depend on it, you also depend on others transitively.


问:
Remove contents of custom properties in Word 2010 with Open XML SDK 2.0 or Linq
I'm trying to remove sensitive information from word-files before they are sent from our system.
Below is an example of the custom properties in a file that is going to be sent. I would like to remove the contents of filePath and templateFilePath.

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name="docId">
        <vt:lpwstr>123</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="3" name="verId">
        <vt:lpwstr>1</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="4" name="templateId">
        <vt:lpwstr>321</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="5" name="fileId">
        <vt:lpwstr>123</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="6" name="filePath">
        <vt:lpwstr>I want to remove this</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="7" name="templateFilePath">
        <vt:lpwstr>I want to remove this</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="8" name="filePathOneNote">
        <vt:lpwstr>\</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="9" name="fileName">
        <vt:lpwstr>test.docx</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="10" name="comment">
        <vt:lpwstr>Test comment</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="11" name="sourceId">
        <vt:lpwstr>12345</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="12" name="module">
        <vt:lpwstr>Document</vt:lpwstr>
    </property>
</Properties>
</code>```

I got this code from the Open XML SDK productivity tool:

```<code>private static void ChangeCustomFilePropertiesPart(CustomFilePropertiesPart customFilePropertiesPart)
{
    CustomProperties.Properties properties = customFilePropertiesPart.Properties;

    CustomProperties.CustomDocumentProperty customDocumentProperty1 = properties.Elements<CustomProperties.CustomDocumentProperty>().ElementAt(4);
    CustomProperties.CustomDocumentProperty customDocumentProperty2 = properties.Elements<CustomProperties.CustomDocumentProperty>().ElementAt(5);

    VariantTypes.VTLPWSTR vTLPWSTR1 = customDocumentProperty1.GetFirstChild<VariantTypes.VTLPWSTR>();
    vTLPWSTR1.Text = "";

    VariantTypes.VTLPWSTR vTLPWSTR2 = customDocumentProperty2.GetFirstChild<VariantTypes.VTLPWSTR>();
    vTLPWSTR2.Text = "";

}
</code>```

But I can't trust that the properties I want to remove are number four and five, so I have to find them by the name attribute before I remove the text. Can anyone help me? I would like to use linq or the Open XML SDK in some way.

Thanks!

答:
Here is the code I came up with:</p>

```<code>private void ChangeCustomFilePropertiesPart(CustomFilePropertiesPart customFilePropertiesPart)
{
    var props = from n in customFilePropertiesPart.Properties.Elements<CustomProperties.CustomDocumentProperty>()
                where n.Name == "filePath" || n.Name == "templateFilePath"
                select n;

    foreach (var prop in props)
    {
        VariantTypes.VTLPWSTR value = prop.GetFirstChild<VariantTypes.VTLPWSTR>();
        value.Text = "";
    }
}
</code>```

Body:
I'm trying to remove sensitive information from word-files before they are sent from our system.
Below is an example of the custom properties in a file that is going to be sent. I would like to remove the contents of filePath and templateFilePath.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name="docId">
        <vt:lpwstr>123</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="3" name="verId">
        <vt:lpwstr>1</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="4" name="templateId">
        <vt:lpwstr>321</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="5" name="fileId">
        <vt:lpwstr>123</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="6" name="filePath">
        <vt:lpwstr>I want to remove this</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="7" name="templateFilePath">
        <vt:lpwstr>I want to remove this</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="8" name="filePathOneNote">
        <vt:lpwstr>\</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="9" name="fileName">
        <vt:lpwstr>test.docx</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="10" name="comment">
        <vt:lpwstr>Test comment</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="11" name="sourceId">
        <vt:lpwstr>12345</vt:lpwstr>
    </property>
    <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="12" name="module">
        <vt:lpwstr>Document</vt:lpwstr>
    </property>
</Properties>

I got this code from the Open XML SDK productivity tool:

private static void ChangeCustomFilePropertiesPart(CustomFilePropertiesPart customFilePropertiesPart)
{
    CustomProperties.Properties properties = customFilePropertiesPart.Properties;

    CustomProperties.CustomDocumentProperty customDocumentProperty1 = properties.Elements<CustomProperties.CustomDocumentProperty>().ElementAt(4);
    CustomProperties.CustomDocumentProperty customDocumentProperty2 = properties.Elements<CustomProperties.CustomDocumentProperty>().ElementAt(5);

    VariantTypes.VTLPWSTR vTLPWSTR1 = customDocumentProperty1.GetFirstChild<VariantTypes.VTLPWSTR>();
    vTLPWSTR1.Text = "";

    VariantTypes.VTLPWSTR vTLPWSTR2 = customDocumentProperty2.GetFirstChild<VariantTypes.VTLPWSTR>();
    vTLPWSTR2.Text = "";

}

But I can't trust that the properties I want to remove are number four and five, so I have to find them by the name attribute before I remove the text. Can anyone help me? I would like to use linq or the Open XML SDK in some way.

Thanks!

Body:
Here is the code I came up with:

private void ChangeCustomFilePropertiesPart(CustomFilePropertiesPart customFilePropertiesPart)
{
    var props = from n in customFilePropertiesPart.Properties.Elements<CustomProperties.CustomDocumentProperty>()
                where n.Name == "filePath" || n.Name == "templateFilePath"
                select n;

    foreach (var prop in props)
    {
        VariantTypes.VTLPWSTR value = prop.GetFirstChild<VariantTypes.VTLPWSTR>();
        value.Text = "";
    }
}


问:
How to convert from Hashbytes function's SHA2_256 encryption datatype to varchar(256) in SQL Server 2012
I want to implement a password encryption system using SQL in SQL Server 2012.

The HASHBYTES method must have only nvarchar, varbinary datatype.

```<code>update members
set passwd = cast(HASHBYTES('SHA2_256', 'asd123123') as varchar(256)),
    pwchangedat = GETDATE()
where userid = 'abcd1234'
</code>```

The unexpected result of the Select query applied above update query:

```<code>?lZX?갅4磎?닽뙷?I?#?뚭?
</code>```

I want to fix this varchar(256) data type string 'asd123123' applied SHA-256 encryption.

I want:

```<code>c82a6c7f5a58a915814334cda5a2ef88ab8cba922f49ec1623e2248ceabf7ddc
</code>```

How can I get a solution?

Regards,

答:
I think this is what you are looking for...

```<code>select convert(varchar(256),HASHBYTES('SHA2_256','asd123123'),2)
</code>```

See the Binary Styles Section (since Hashbytes returns varbinary)

Thus....

```<code>update members set
    passwd = convert(varchar(256),HASHBYTES('SHA2_256','asd123123'),2),
    pwchangedat = GETDATE()
    where userid = 'abcd1234'
</code>```

Body:
I want to implement a password encryption system using SQL in SQL Server 2012.

The HASHBYTES method must have only nvarchar, varbinary datatype.

update members
set passwd = cast(HASHBYTES('SHA2_256', 'asd123123') as varchar(256)),
    pwchangedat = GETDATE()
where userid = 'abcd1234'

The unexpected result of the Select query applied above update query:

?lZX?갅4磎?닽뙷?I?#?뚭?

I want to fix this varchar(256) data type string 'asd123123' applied SHA-256 encryption.

I want:

c82a6c7f5a58a915814334cda5a2ef88ab8cba922f49ec1623e2248ceabf7ddc

How can I get a solution?

Regards,

Body:
I think this is what you are looking for...

select convert(varchar(256),HASHBYTES('SHA2_256','asd123123'),2)

See the Binary Styles Section (since Hashbytes returns varbinary)

Thus....

update members set
    passwd = convert(varchar(256),HASHBYTES('SHA2_256','asd123123'),2),
    pwchangedat = GETDATE()
    where userid = 'abcd1234'


问:
Batching of Dataset Spark scala
I am trying to create batches of rows of Dataset in Spark.
For maintaining the number of records sent to service I want to batch the items so that i can maintain the rate at which the data will be sent.
For,

```<code>case class Person(name:String, address: String)
case class PersonBatch(personBatch: List[Person])
</code>```

For a given Dataset[Person] I want to create Dataset[PersonBatch]

For example if input Dataset[Person] has 100 records the output Dataset should be like Dataset[PersonBatch] where every PersonBatchshould be list of n records (Person).

I have tried this but it din't work.

```<code>object DataBatcher extends Logger {

  var batchList: ListBuffer[PersonBatch] = ListBuffer[PersonBatch]()
  var batchSize: Long = 500  //default batch size

  def addToBatchList(batch: PersonBatch): Unit = {
    batchList += batch
  }

  def clearBatchList(): Unit = {
    batchList.clear()
  }

  def createBatches(ds: Dataset[Person]): Dataset[PersonBatch] = {

    val dsCount = ds.count()
    logger.info(s"Count of dataset passed for creating batches : ${dsCount}")
    val batchElement = ListBuffer[Person]()
    val batch = PersonBatch(batchElement)
    ds.foreach(x => {
      batch.personBatch += x
      if(batch.personBatch.length == batchSize) {
        addToBatchList(batch)
        batch.requestBatch.clear()
      }
    })
    if(batch.personBatch.length > 0) {
      addToBatchList(batch)
      batch.personBatch.clear()
    }
    sparkSession.createDataset(batchList)
  }
}
</code>```

I want to run this job on Hadoop cluster.
Can some help me with this ?

答:
rdd.iterator has grouped function may be useful for you.

for example :

iter.grouped(batchSize)

Sample code snippet which does batch insert with iter.grouped(batchsize) here its 1000 and Im trying to insert in to database

```<code>   df.repartition(numofpartitionsyouwant) // numPartitions ~ number of simultaneous DB connections you can planning to give...
def insertToTable(sqlDatabaseConnectionString: String,
                  sqlTableName: String): Unit = {

  val tableHeader: String = dataFrame.columns.mkString(",")
  dataFrame.foreachPartition { partition =>
    //NOTE : EACH PARTITION ONE CONNECTION (more better way is to use connection pools)
    val sqlExecutorConnection: Connection =
      DriverManager.getConnection(sqlDatabaseConnectionString)
    //Batch size of 1000 is used since some databases cant use batch size more than 1000 for ex : Azure sql
    partition.grouped(1000).foreach { group =>
      val insertString: scala.collection.mutable.StringBuilder =
        new scala.collection.mutable.StringBuilder()

      group.foreach { record =>
        insertString.append("('" + record.mkString(",") + "'),")
      }

      sqlExecutorConnection
        .createStatement()
        .executeUpdate(f"INSERT INTO [$sqlTableName] ($tableHeader) VALUES "
          + insertString.stripSuffix(","))
    }

    sqlExecutorConnection.close() // close the connection so that connections wont exhaust.
  }
}
</code>```

Title: Batching of Dataset Spark scala

Body:
I am trying to create batches of rows of Dataset in Spark.
For maintaining the number of records sent to service I want to batch the items so that i can maintain the rate at which the data will be sent.
For,

case class Person(name:String, address: String)
case class PersonBatch(personBatch: List[Person])

For a given Dataset[Person] I want to create Dataset[PersonBatch]

For example if input Dataset[Person] has 100 records the output Dataset should be like Dataset[PersonBatch] where every PersonBatchshould be list of n records (Person).

I have tried this but it din't work.

object DataBatcher extends Logger {

  var batchList: ListBuffer[PersonBatch] = ListBuffer[PersonBatch]()
  var batchSize: Long = 500  //default batch size

  def addToBatchList(batch: PersonBatch): Unit = {
    batchList += batch
  }

  def clearBatchList(): Unit = {
    batchList.clear()
  }

  def createBatches(ds: Dataset[Person]): Dataset[PersonBatch] = {

    val dsCount = ds.count()
    logger.info(s"Count of dataset passed for creating batches : ${dsCount}")
    val batchElement = ListBuffer[Person]()
    val batch = PersonBatch(batchElement)
    ds.foreach(x => {
      batch.personBatch += x
      if(batch.personBatch.length == batchSize) {
        addToBatchList(batch)
        batch.requestBatch.clear()
      }
    })
    if(batch.personBatch.length > 0) {
      addToBatchList(batch)
      batch.personBatch.clear()
    }
    sparkSession.createDataset(batchList)
  }
}

I want to run this job on Hadoop cluster.
Can some help me with this ?

Body:
rdd.iterator has grouped function may be useful for you.

for example :

iter.grouped(batchSize)

Sample code snippet which does batch insert with iter.grouped(batchsize) here its 1000 and Im trying to insert in to database

   df.repartition(numofpartitionsyouwant) // numPartitions ~ number of simultaneous DB connections you can planning to give...
def insertToTable(sqlDatabaseConnectionString: String,
                  sqlTableName: String): Unit = {

  val tableHeader: String = dataFrame.columns.mkString(",")
  dataFrame.foreachPartition { partition =>
    //NOTE : EACH PARTITION ONE CONNECTION (more better way is to use connection pools)
    val sqlExecutorConnection: Connection =
      DriverManager.getConnection(sqlDatabaseConnectionString)
    //Batch size of 1000 is used since some databases cant use batch size more than 1000 for ex : Azure sql
    partition.grouped(1000).foreach { group =>
      val insertString: scala.collection.mutable.StringBuilder =
        new scala.collection.mutable.StringBuilder()

      group.foreach { record =>
        insertString.append("('" + record.mkString(",") + "'),")
      }

      sqlExecutorConnection
        .createStatement()
        .executeUpdate(f"INSERT INTO [$sqlTableName] ($tableHeader) VALUES "
          + insertString.stripSuffix(","))
    }

    sqlExecutorConnection.close() // close the connection so that connections wont exhaust.
  }
}


问:
How to get all public posts using Instagram API?
I'm trying to get all public posts using Instagram API.

There are some existing apps like Geofeedia, COEverywhere and TrackinU which can get public posts of social networking sites.

Is there any way to get public posts just like in Twitter Stream API?

答:
I wrote a proxy API for this exact purpose: https://github.com/whizzzkid/instagram-proxy-api

Let's take an example of #nyc:
Instagram's tag explorer: https://www.instagram.com/explore/tags/nyc

Getting the same results as JSON: https://igpi.ga/explore/tags/nyc/media

You can find more examples in the repo. Here is the code that does all this: https://github.com/whizzzkid/instagram-reverse-proxy/blob/master/app.js

A demo application using jquery will be:

```<code>$.ajax({
  url: "https://igpi.ga/explore/tags/yyc/media",
  dataType: "jsonp",
  data: { count: 3 },
  success: function (json){
    for(var i in json.posts) {
      var img = document.createElement("IMG");
      img.src = json.posts[i].display_url;
      document.body.appendChild(img);
    }
  }
});
</code>```

Demo: http://plnkr.co/edit/4oCwpbMm6p9cyJb1UWld?p=preview

hope this helps.

Body:
I wrote a proxy API for this exact purpose: https://github.com/whizzzkid/instagram-proxy-api

Let's take an example of #nyc:
Instagram's tag explorer: https://www.instagram.com/explore/tags/nyc

Getting the same results as JSON: https://igpi.ga/explore/tags/nyc/media

You can find more examples in the repo. Here is the code that does all this: https://github.com/whizzzkid/instagram-reverse-proxy/blob/master/app.js

A demo application using jquery will be:

$.ajax({
  url: "https://igpi.ga/explore/tags/yyc/media",
  dataType: "jsonp",
  data: { count: 3 },
  success: function (json){
    for(var i in json.posts) {
      var img = document.createElement("IMG");
      img.src = json.posts[i].display_url;
      document.body.appendChild(img);
    }
  }
});

Demo: http://plnkr.co/edit/4oCwpbMm6p9cyJb1UWld?p=preview

hope this helps.