问:
Angular 4, how to keep footer at bottom with dynamic page content
my app.component.html code is as follows

```<code><div class='container-fluid'>
<div class='row'>
    <div class='col-sm-3'>
        <nav-menu></nav-menu>
    </div>
    <div class='col-sm-9 body-content'>
        <router-outlet></router-outlet>
    </div>
</div>
<div class="row">
    <footer></footer>
</div>
</code>```

my footer.component.html code is:

```<code><div class="footer">
<div class="col-sm-10">
    © {{currentYear}} - <a href="">UMD</a> IP PTY LTD
</div>
<div>{{environment}}</div>
</code>```

The CSS which I used to show the footer at the bottom of the page is

```<code>   footer {
    position: absolute;
    bottom: 0;
    left: 25%;
    width: 75%;
    height: 50px;
}
</code>```

Now the issue is angular loads the data dynamically on the page. Initially footer is at the bottom of the page but when data is added to the page and the controls added at runtime on the page exceeds the initial page height my footer remains at the initial page which ends up somewhere in between the page.

How to fix this?

In the picture below controls are added dynamically using reactive form which results in footer being show between the controls.

答:
You are using footer as class but you are declaring styles as footer which refers to tag

Replace footer to .footer

```<code>.footer {
    position: absolute;
    bottom: 0;
    left: 25%;
    width: 75%;
    height: 50px;
}
</code>```

Body:
my app.component.html code is as follows

        <router-outlet></router-outlet>

my footer.component.html code is:

    © {{currentYear}} - UMD IP PTY LTD

{{environment}}

The CSS which I used to show the footer at the bottom of the page is

   footer {
    position: absolute;
    bottom: 0;
    left: 25%;
    width: 75%;
    height: 50px;
}

Now the issue is angular loads the data dynamically on the page. Initially footer is at the bottom of the page but when data is added to the page and the controls added at runtime on the page exceeds the initial page height my footer remains at the initial page which ends up somewhere in between the page.

How to fix this?

In the picture below controls are added dynamically using reactive form which results in footer being show between the controls.

Body:
You are using footer as class but you are declaring styles as footer which refers to tag

Replace footer to .footer

.footer {
    position: absolute;
    bottom: 0;
    left: 25%;
    width: 75%;
    height: 50px;
}


来源: stackexchange

问:
How to set the current day color in FullCalendar?
I would like to change the color of the current day but only when the calendar is in the day agenda view. My users say they're having a hard time seeing the lines or something. I looked through the documentation as well as the css/js and didn't find a quick way of doing it. Is this even possible without major code changes?</p>

答: I honestly don't really know what you're talking about, but the jQuery UI fullcalendar widget uses the CSS class .fc-today to style the current day. If your changes aren't visible, try to use !important — it might be that one of the many other classes overrides your styles elsewhere.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Convert date and time to only year in php
I have a variable is which the value coming is Date along with time in php. How do I convert it into a variable to get only the year? I do not need automatic updation but the format change is needed. Normal answers are giving it about date but my variable is containing time as well. </p>

```<code>The format coming by now is 2017-12-11 4:06:37 and i need only 2017
</code>```

答:
Use like this:</p>

```<code><?php echo date('Y',strtotime('now'));?>
</code>```

Body:
I have a variable is which the value coming is Date along with time in php. How do I convert it into a variable to get only the year? I do not need automatic updation but the format change is needed. Normal answers are giving it about date but my variable is containing time as well.

The format coming by now is 2017-12-11 4:06:37 and i need only 2017

Body:
Use like this:

<?php echo date('Y',strtotime('now'));?>


问:
sqlite3 column does not exist
I am trying to run queries on an sqlite3 db/table i have made but i keep getting the error

Error: near line 4: no such column: number_of_officers_employed

Error: near line 6: no such column: year

Error: near line 8: no such column: year

Error: near line 10: no such column: year

My create-table code looks like this:

```<code>CREATE TABLE IF NOT EXISTS lwenfemp(year INTEGER PRIMARY KEY, us_population INTEGER, number_of_officers_employed INTEGER, percent_change INTEGER, officers_per_100000_residents INTEGER);
</code>```

Any idea why this might be? i am fairly new to sqlite3 and apologise if i missed something that is obvious

My queries look like this:

```<code>SELECT year WHERE officers_per_100000_residents > '245';
</code>```

答:
Try add FROM table name:

```<code>SELECT year FROM lwenfemp WHERE officers_per_100000_residents > '245';
</code>```

It will be fine, when using the backticks ``

```<code>SELECT `year` FROM lwenfemp WHERE officers_per_100000_residents > '245';
</code>```

Title: sqlite3 column does not exist

Body:
I am trying to run queries on an sqlite3 db/table i have made but i keep getting the error

Error: near line 4: no such column: number_of_officers_employed

Error: near line 6: no such column: year

Error: near line 8: no such column: year

Error: near line 10: no such column: year

My create-table code looks like this:

CREATE TABLE IF NOT EXISTS lwenfemp(year INTEGER PRIMARY KEY, us_population INTEGER, number_of_officers_employed INTEGER, percent_change INTEGER, officers_per_100000_residents INTEGER);

Any idea why this might be? i am fairly new to sqlite3 and apologise if i missed something that is obvious

My queries look like this:

SELECT year WHERE officers_per_100000_residents > '245';

Body:
Try add FROM table name:

SELECT year FROM lwenfemp WHERE officers_per_100000_residents > '245';

It will be fine, when using the backticks ``

SELECT `year` FROM lwenfemp WHERE officers_per_100000_residents > '245';


问:
FusedLocationProviderClient.removeLocationUpdates always returns failure
I have an activity that extends a base class called LocationAwareActivity all this LocationAwareActivity activity does is creates a location service client

LocationServices.getFusedLocationProviderClient and listens to
location updates.

Source for this activity is here
https://github.com/snijsure/MultiActivity/blob/master/app/src/main/java/com/example/subodhnijsure/multiactivity/LocationAwareActivity.java

And when activity is destroyed it calls removeLocationUpdates . What I am finding is

removeLocationUpdate returns a task that always returns not-successful

More concerning is because location activities is not removed, the activity is not getting being garbage collected.

- So if I start the any activity that inherits from LocationAwareActivity that activity always stays on heap.

So the question is what is the correct way to stop receiving location updates thus allowing activity to be garbage collected.

Entire source for this project can be accessed here - https://github.com/snijsure/MultiActivity

答:
The reason why the Task object returns false is in your stopLocationUpdates method, you are again creating a local **LocationCallback** reference and then using this reference to as an argument in locationProviderClient.removeLocationUpdates(cL);
where your local LocationCallBack is never present in the locationProviderClient

So what you have to do is , instead of creating another LocationCallBack object ,you have to pass the same global object which you are instantiating in your startLocationUpdates method

your code should be like this

```<code>final Task<Void> voidTask = locationProviderClient.removeLocationUpdates(locationCallback);
</code>```

Body:
The reason why the Task object returns false is in your stopLocationUpdates method, you are again creating a local **LocationCallback** reference and then using this reference to as an argument in locationProviderClient.removeLocationUpdates(cL);
where your local LocationCallBack is never present in the locationProviderClient

So what you have to do is , instead of creating another LocationCallBack object ,you have to pass the same global object which you are instantiating in your startLocationUpdates method

your code should be like this

final Task<Void> voidTask = locationProviderClient.removeLocationUpdates(locationCallback);

ContentLicense: CC BY-SA 4.0


问:
How is called use of duck typing
How should I call process of using duck typing? What should I say "I'm performing duck typing" or "I'm checking if it's a duck:)".

Duck checking doesn't sounds good and type checking is just plain wrong name for it.

答: I am using duck typing, I would say. It's along the same kind of lines as 'I am using static typing', though they are different things.

Title: How is called use of duck typing


问:
Convert from CL8ISO8859P5 encoding to ASCII in Java
probably you may give me some hints what can I do/see in my case:)

There is an Oracle code that converts given hexadecimal input in AMERICAN_AMERICA.CL8ISO8859P5 to ASCII: utl_raw.cast_to_varchar2(utl_raw.convert(hextoraw('31383831303891353080853737303338385A5A'), 'AMERICAN_AMERICA.CL8ISO8859P5', 'AMERICAN_AMERICA.RU8PC866'))

Example input: 31383831303891353080853737303338385A5A, example output: 188108С50АЕ770388ZZ

My pain is to solve how can I do it in Java:) Prerequisite: I have no connection to the database and can't execute prepared SQL statement in order to call this function in Oracle package...
I am able to parsing everything except specific bytes (91 -> 'C1', 8085 -> 'B0B5', 5A -> 'Z') with the following code:

```<code>new String(DatatypeConverter.parseHexBinary("31383831303891353080853737303338385A5A"))
</code>```

I've also tried all standards encodings in String constructor with encoding but there were no positive results:(

Do you know if there are encodings in Java that are identical to AMERICAN_AMERICA.CL8ISO8859P5? Or do you know some libraries or Java functions that are able to make this conversion (AMERICAN_AMERICA.CL8ISO8859P5 to ASCII) ?

Many thanks to you in advance!

答:
AMERICAN_AMERICA.RU8PC866 Oracle encoding is IBM-866 encoding in Java (hint from @kfinity). My issue solved by using

```<code>new String(DatatypeConverter.parseHexBinary(input), "IBM-866")
</code>```

CP866 worked as well.

Body:
probably you may give me some hints what can I do/see in my case:)

There is an Oracle code that converts given hexadecimal input in AMERICAN_AMERICA.CL8ISO8859P5 to ASCII: utl_raw.cast_to_varchar2(utl_raw.convert(hextoraw('31383831303891353080853737303338385A5A'), 'AMERICAN_AMERICA.CL8ISO8859P5', 'AMERICAN_AMERICA.RU8PC866'))

Example input: 31383831303891353080853737303338385A5A, example output: 188108С50АЕ770388ZZ

My pain is to solve how can I do it in Java:) Prerequisite: I have no connection to the database and can't execute prepared SQL statement in order to call this function in Oracle package...
I am able to parsing everything except specific bytes (91 -> 'C1', 8085 -> 'B0B5', 5A -> 'Z') with the following code:

new String(DatatypeConverter.parseHexBinary("31383831303891353080853737303338385A5A"))

I've also tried all standards encodings in String constructor with encoding but there were no positive results:(

Do you know if there are encodings in Java that are identical to AMERICAN_AMERICA.CL8ISO8859P5? Or do you know some libraries or Java functions that are able to make this conversion (AMERICAN_AMERICA.CL8ISO8859P5 to ASCII) ?

Many thanks to you in advance!

Body:
AMERICAN_AMERICA.RU8PC866 Oracle encoding is IBM-866 encoding in Java (hint from @kfinity). My issue solved by using

new String(DatatypeConverter.parseHexBinary(input), "IBM-866")

CP866 worked as well.


问:
Cannot use 'pyside-rcc' to compile .qrc file
I am working on python project and I have a problem with pyside-rcc. First, let I explain briefly about my project.

I created my project GUI in QtDesigner and also use the image in the GUI. Then, I generate .py from .ui file using pyside-uic and it works! Then I have to generate my resource file, .qrc file, to .py file to use with my project.

The problem is when I use pyside-rcc to generate a resource file, it shows an error.

"'pyside-rcc' is not recognized as an internal or external command, operable probram or batch file." (As shown below)

You can see in the bottom of Python folder. There is pyside-rcc.exe file. I do not know why pyside-rcc is not work (pyside-uic still work).

Thank you for answer. :)

答:
or else you could mention full path of pyside-rcc.exe like:</p>

```<code>C:/python/lib/../../pyside-rcc.exe -o input.qrc output.py
</code>```

Body:
or else you could mention full path of pyside-rcc.exe like:

C:/python/lib/../../pyside-rcc.exe -o input.qrc output.py


答:
By using DateTime class

```<code>$date = new \DateTime('2017-12-11 4:06:37');
echo $date->format('Y');
</code>```

Title: Convert date and time to only year in php

Body:
By using DateTime class

$date = new \DateTime('2017-12-11 4:06:37');
echo $date->format('Y');


问:
Android sms with link to application or Google play
I am trying to create an application that will send sms with link to the following:
If application already installed on the phone, the link will open it.
If the app is not installed, the link will open Google play store on the app page...</p>

答:
Ex: Your link will be something like https://example.com and you have the intent filter in Android Manifest as below:

```<code><activity
    android:name="com.droid.MainActivity"
    android:label="@string/app_name" >

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
            android:host="example.com"
            android:scheme="https" />
    </intent-filter>
</activity>
</code>```

Use the URL Mapping editor to easily add URL intent filters to your Activities with Android App Links (Android Studio > Tools > Android App Links).

Body:
Ex: Your link will be something like https://example.com and you have the intent filter in Android Manifest as below:

<activity
    android:name="com.droid.MainActivity"
    android:label="@string/app_name" >

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
            android:host="example.com"
            android:scheme="https" />
    </intent-filter>
</activity>

Use the URL Mapping editor to easily add URL intent filters to your Activities with Android App Links (Android Studio > Tools > Android App Links).


答:
Provide your Application web Url with the SMS.

In that page Redirect to Playstore.

In Your Application Create DeepLink with that Your URL

Whenever the URL is Encountered the Application will be opened if it is installed. Otherwise, it will redirect to the Play store from the page.

You Can use the Playstore Url of App. But It is not recommended since playstore and other store application may also catch the same link.

DeepLinking In Android Application

Example

```<code><activity
    android:name="com.package.MainActivity"
    android:label="@string/app_name" >

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
            android:host="weburl"
            android:scheme="https" />
    </intent-filter>
</activity>
</code>```

Title: Android sms with link to application or Google play

Body:
I am trying to create an application that will send sms with link to the following:
If application already installed on the phone, the link will open it.
If the app is not installed, the link will open Google play store on the app page...

Body:
Provide your Application web Url with the SMS.

In that page Redirect to Playstore.

In Your Application Create DeepLink with that Your URL

Whenever the URL is Encountered the Application will be opened if it is installed. Otherwise, it will redirect to the Play store from the page.

You Can use the Playstore Url of App. But It is not recommended since playstore and other store application may also catch the same link.

DeepLinking In Android Application

Example

<activity
    android:name="com.package.MainActivity"
    android:label="@string/app_name" >

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
            android:host="weburl"
            android:scheme="https" />
    </intent-filter>
</activity>


问:
CosmosDB: Enforce unique constraints
Is it possible to enforce unique constraints on Azure CosmosDB's graph model? If I'm registering new users and need to ensure only unique email addresses/usernames/etc. are used, how can this be accomplished there?</p>

答:
We recently launched unique key support for Cosmos DB. This should work seamlessly for graph collections as well.

https://learn.microsoft.com/en-us/azure/cosmos-db/unique-keys

Just, create a graph with desired unique key path. After that adding a vertex with the same unique key compared to an existing vertex, should fail.

Title: CosmosDB: Enforce unique constraints


问:
How to read Unicode input and compare Unicode strings in Python?
I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of raw_input?

Also, I would like to test Unicode strings for equality and it looks like a standard == does not work.

答:
It should work. raw_input returns a byte string which you must decode using the correct encoding to get your unicode object. For example, the following works for me under Python 2.5 / Terminal.app / OSX:

```<code>>>> bytes = raw_input()
日本語 Ελληνικά
>>> bytes
'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e \xce\x95\xce\xbb\xce\xbb\xce\xb7\xce\xbd\xce\xb9\xce\xba\xce\xac'

>>> uni = bytes.decode('utf-8') # substitute the encoding of your terminal if it's not utf-8
>>> uni
u'\u65e5\u672c\u8a9e \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac'

>>> print uni
日本語 Ελληνικά
</code>```

As for comparing unicode strings: can you post an example where the comparison doesn't work?

Body:
It should work. raw_input returns a byte string which you must decode using the correct encoding to get your unicode object. For example, the following works for me under Python 2.5 / Terminal.app / OSX:

>>> bytes = raw_input()
日本語 Ελληνικά
>>> bytes
'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e \xce\x95\xce\xbb\xce\xbb\xce\xb7\xce\xbd\xce\xb9\xce\xba\xce\xac'

>>> uni = bytes.decode('utf-8') # substitute the encoding of your terminal if it's not utf-8
>>> uni
u'\u65e5\u672c\u8a9e \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac'

>>> print uni
日本語 Ελληνικά

As for comparing unicode strings: can you post an example where the comparison doesn't work?

OwnerDisplayName: dF

LastEditorDisplayName: dF


问:
Does Facebook know I'm scraping it with PhantomJS and can it change its website to counter me?
So, maybe I'm being paranoid.

I'm scraping my Facebook timeline for a hobby project using PhantomJS. Basically, I wrote a program that finds all of my ads by querying the page for the text Sponsored with XPATH inside of phantom's page.evaluate block. The text was being displayed as innerHTML of html a elements.

Things were working great for a few days and it was finding tons of ads.

Then it stopped returning any results.

When I logged into Facebook manually to inspect the elements again, I found that the word Sponsored was now appearing on the page in an ::after pseudoclass element with the css property content: sponsored. This means that an XPATH query for the text no longer yields any results. No joke, Facebook seemed to have changed the way they rendered this word after being scraped for a couple days.

Paranoid. I told you.

So, I offer this question to the community of Javascript, Web-Scraping, and PhantomJS developers out there. What the heck is going on. Can Facebook know what my PhantomJS program is doing inside of the page.evaluate block?

If so, how? Would my phantom commands appear in a key logger program embedded in the page, for instance?

What are some of your theories?

答:
It is perfectly possible to detect PhantomJS even if the useragent is spoofed.
There are plenty of litte ways in which it differs from other browsers, among others:

Wrong order of headers

Lack of media plugins and latest JS capabilities

PhantomJS-specific methods, like window.callPhantom

PhantomJS name in the stack trace

and many others.

Please refer to this excellent article and presentation linked there for details: https://blog.shapesecurity.com/2015/01/22/detecting-phantomjs-based-visitors/

Maybe puppeteer would be a better fit for your needs as it is based on a real cutting-edge Chromium browser.


问:
How do I sort a bunch of letters and their corresponding frequencies from a string?
I am trying to write a function that can analyze a string and print the letters in the string and their corresponding frequencies. This part isn't too much of a challenge because I can just use ascii_lowercase to sort through the string then the count() method available in ascii. The difficult part is sorting the frequencies so that the most frequent letter is the beginning, and the least frequent is at the end. Here is what I have written so far:

```<code>def analyze(codebook):
lst = []
tmp = []
for c in ascii_lowercase:
   count = codebook.count(c)
   print("('%s', %d)" % (c.upper(), count), end=" ")
   lst.append(count)
   tmp.append(c)
lst.sort()
lst.reverse()
print(lst)
print(tmp)
</code>```

All this does is print the letter and it's corresponding frequencies in the order of the alphabet. Here is an example of the string that I am using:

```<code>pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq
</code>```

And here is an example of my desired output:

```<code>('Q', 10) ('W', 9) ('E', 8) ('R', 7) ('T', 6) ('Y', 5) ('U', 4) ('I', 3)

('O', 2) ('P', 1) ('A', 0) ('B', 0) ('C', 0) ('D', 0) ('F', 0) ('G', 0)

('H', 0) ('J', 0) ('K', 0) ('L', 0) ('M', 0) ('N', 0) ('S', 0) ('V', 0)

('X', 0) ('Z', 0)
</code>```

I have also tried using collections; however, that got confusing very quickly. Any help would be appreciated!

答:
If you want to do it without (marginal) imports, a map is your best friend. </p>

```<code>from string import ascii_lowercase

s = "pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq"
m = {}
for char in s:
    if char not in m:
        m[char] = 0
    m[char] += 1
# Make your list of tuples
res = []
for c in ascii_lowercase:
    res.append((c.upper(), m[c] if c in m else 0))
</code>```

Body:
I am trying to write a function that can analyze a string and print the letters in the string and their corresponding frequencies. This part isn't too much of a challenge because I can just use ascii_lowercase to sort through the string then the count() method available in ascii. The difficult part is sorting the frequencies so that the most frequent letter is the beginning, and the least frequent is at the end. Here is what I have written so far:

def analyze(codebook):
lst = []
tmp = []
for c in ascii_lowercase:
   count = codebook.count(c)
   print("('%s', %d)" % (c.upper(), count), end=" ")
   lst.append(count)
   tmp.append(c)
lst.sort()
lst.reverse()
print(lst)
print(tmp)

All this does is print the letter and it's corresponding frequencies in the order of the alphabet. Here is an example of the string that I am using:

pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq

And here is an example of my desired output:

('Q', 10) ('W', 9) ('E', 8) ('R', 7) ('T', 6) ('Y', 5) ('U', 4) ('I', 3)

('O', 2) ('P', 1) ('A', 0) ('B', 0) ('C', 0) ('D', 0) ('F', 0) ('G', 0)

('H', 0) ('J', 0) ('K', 0) ('L', 0) ('M', 0) ('N', 0) ('S', 0) ('V', 0)

('X', 0) ('Z', 0)

I have also tried using collections; however, that got confusing very quickly. Any help would be appreciated!

Body:
If you want to do it without (marginal) imports, a map is your best friend.

from string import ascii_lowercase

s = "pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq"
m = {}
for char in s:
    if char not in m:
        m[char] = 0
    m[char] += 1
# Make your list of tuples
res = []
for c in ascii_lowercase:
    res.append((c.upper(), m[c] if c in m else 0))


问:
BadMapError - Elixir/Phoenix
I'm trying to make a custom validation, so I've made a function that runs in a changeset but I'm getting an error that doesn't seem to make much sense to me at the moment.

Here is my model:

```<code>@required_fields ~w(commissioner user_id league_id)a

  def changeset(struct, params \\ %{}) do
    struct
      |> cast(params, @required_fields)
      |> validate_required(@required_fields)
      |> duplicate_check
  end

  def duplicate_check(_struct) do
    IEx.pry
  end
</code>```

But when I run this code I get this error:

ERROR:

```<code>expected a map, got: :ok

BadMapError at GET /leagues/new
</code>```

答:
duplicate_check returns the return value of IEx.pry which is :ok which means changeset now returns :ok which causes that error to be thrown. You need to return the struct from duplicate_check:

```<code>def duplicate_check(struct) do
  IEx.pry
  struct
end
</code>```

Also, you might want to call the variable changeset because after cast you'll have a Changeset, not a struct of the current module.

Title: BadMapError - Elixir/Phoenix

Body:
I'm trying to make a custom validation, so I've made a function that runs in a changeset but I'm getting an error that doesn't seem to make much sense to me at the moment.

Here is my model:

@required_fields ~w(commissioner user_id league_id)a

  def changeset(struct, params \\ %{}) do
    struct
      |> cast(params, @required_fields)
      |> validate_required(@required_fields)
      |> duplicate_check
  end

  def duplicate_check(_struct) do
    IEx.pry
  end

But when I run this code I get this error:

ERROR:

expected a map, got: :ok

BadMapError at GET /leagues/new

Body:
duplicate_check returns the return value of IEx.pry which is :ok which means changeset now returns :ok which causes that error to be thrown. You need to return the struct from duplicate_check:

def duplicate_check(struct) do
  IEx.pry
  struct
end

Also, you might want to call the variable changeset because after cast you'll have a Changeset, not a struct of the current module.


问:
How can I get username or id of currently logged in user in UWP App
I found this article: Get The Username/User Id Of Currently Logged In User In A UWP App

to get the username of current user logged in in uwp app , but when I tried the accepted answer , it returns null/empty , is there any updated version of that?

NOTE: Iam using a microsoft account

UPDATE: All properties from "KnownUserProperties" returns empty string except for "First Name" & "Last Name"

Thanks

答:
```<code>private async void Page_Loaded(object sender, RoutedEventArgs e)
{
    IReadOnlyList<User> users = await User.FindAllAsync();

    var current = users.Where(p => p.AuthenticationStatus == UserAuthenticationStatus.LocallyAuthenticated &&
                                p.Type == UserType.LocalUser).FirstOrDefault();

    // user may have username
    var data = await current.GetPropertyAsync(KnownUserProperties.AccountName);
    string displayName = (string)data;

    text1.Text = displayName;
}
</code>```


问:
Query for Merge values from 3 column and merge as Primary Key in Oracle
In one table few columns are there and in 3 columns i want to merge values from these 3 columns and generate as Primary key after merging these 3 values.
Col1 having Datatype length 4, While col2 & col3 having datatype length 5 & 3 respectively. In col2 & col3 if any values are less than the maximum length then use LPAD with 0 and then after Merge into the Primary Key.

Ex- If col1 = 1234, col2 = 142, col3 = 32 then after merging It should be like "123400142032" as Primary Key.

答:
You probably need something like this.

```<code>CREATE TABLE yourtable
(
   col1   NUMBER,
   col2   NUMBER,
   col3   NUMBER
);

    ALTER TABLE yourtable ADD (ID NUMBER GENERATED ALWAYS AS ( LPAD(col1,4,0)||LPAD(col2,5,0)||LPAD(col3,3,0) ) );
    ALTER TABLE yourtable ADD CONSTRAINT t_test_pk PRIMARY KEY (ID) USING INDEX;
</code>```

You may then insert only 3 columns and the column id gets automatically populated with a number such as 123400142032.

```<code>INSERT INTO yourtable (col1, col2, col3)
     VALUES (1234, 142, 32);
</code>```

Note : The create table script is just for understanding. You may not need it since you already have an existing table.

The virtual column syntax GENERATED .. AS works only in 11g and above. For lower versions, you may require a before insert trigger and a sequence.

Body:
You probably need something like this.

CREATE TABLE yourtable
(
   col1   NUMBER,
   col2   NUMBER,
   col3   NUMBER
);

    ALTER TABLE yourtable ADD (ID NUMBER GENERATED ALWAYS AS ( LPAD(col1,4,0)||LPAD(col2,5,0)||LPAD(col3,3,0) ) );
    ALTER TABLE yourtable ADD CONSTRAINT t_test_pk PRIMARY KEY (ID) USING INDEX;

You may then insert only 3 columns and the column id gets automatically populated with a number such as 123400142032.

INSERT INTO yourtable (col1, col2, col3)
     VALUES (1234, 142, 32);

Note : The create table script is just for understanding. You may not need it since you already have an existing table.

The virtual column syntax GENERATED .. AS works only in 11g and above. For lower versions, you may require a before insert trigger and a sequence.


问:
Get area name from ActionExecutingContext
I'm writing an ActionFilter and need to get area name from ActionExecutingContext parameter (I want to implement quick-and-dirty login based security). Is it possible?</p>

答:
Usage

```<code>@Html.Controller();
@Html.Action();
@Html.Id();
@Html.Area();
</code>```

Code

```<code>public static class HtmlRequestHelper
{
    public static string Id(this HtmlHelper htmlHelper)
    {
        var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

        if (routeValues.ContainsKey("id"))
            return (string)routeValues["id"];
        else if (HttpContext.Current.Request.QueryString.AllKeys.Contains("id"))
            return HttpContext.Current.Request.QueryString["id"];

        return string.Empty;
    }

    public static string Controller(this HtmlHelper htmlHelper)
    {
        var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

        if (routeValues.ContainsKey("controller"))
            return (string)routeValues["controller"];

        return string.Empty;
    }

    public static string Action(this HtmlHelper htmlHelper)
    {
        var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

        if (routeValues.ContainsKey("action"))
            return (string)routeValues["action"];

        return string.Empty;
    }

    public static string Area(this HtmlHelper htmlHelper)
    {
        var dataTokens = HttpContext.Current.Request.RequestContext.RouteData.DataTokens;

        if (dataTokens.ContainsKey("area"))
            return (string)dataTokens["area"];

        return string.Empty;
    }
}
</code>```

Body:
Usage

@Html.Controller();
@Html.Action();
@Html.Id();
@Html.Area();

Code

public static class HtmlRequestHelper
{
    public static string Id(this HtmlHelper htmlHelper)
    {
        var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

        if (routeValues.ContainsKey("id"))
            return (string)routeValues["id"];
        else if (HttpContext.Current.Request.QueryString.AllKeys.Contains("id"))
            return HttpContext.Current.Request.QueryString["id"];

        return string.Empty;
    }

    public static string Controller(this HtmlHelper htmlHelper)
    {
        var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

        if (routeValues.ContainsKey("controller"))
            return (string)routeValues["controller"];

        return string.Empty;
    }

    public static string Action(this HtmlHelper htmlHelper)
    {
        var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

        if (routeValues.ContainsKey("action"))
            return (string)routeValues["action"];

        return string.Empty;
    }

    public static string Area(this HtmlHelper htmlHelper)
    {
        var dataTokens = HttpContext.Current.Request.RequestContext.RouteData.DataTokens;

        if (dataTokens.ContainsKey("area"))
            return (string)dataTokens["area"];

        return string.Empty;
    }
}


问:
Xcode 9: SKEditorReference doesn't allow animations?
I can't seem to get sprite nodes that have been added by reference (drag/drop one sks file into another sks file in Xcode 9) to animate. This seems allowable, as you can physically do such a thing, but I'm unsure why the sub-nodes won't animate.

Example
1. Start with standard spritekit template
2. add a HUD.sks file, and add a color sprite somewhere, name it "hudSpriteNode"
3. drag the HUD.sks file into the GameScene.sks scene - center it at zero
4. find the hudSpriteNode (by name)
5. move it with .position (works!)
6. move it with animation (fails!)

HUD.sks

GameScene.sks

Add this code to GameScene.swift

```<code>if let testSpriteNode = childNode(withName: "//hudSpriteNode") as? SKSpriteNode {
  print("Found test sprite node")
  print("Test node position 1: \(testSpriteNode.position)")
  testSpriteNode.position = CGPoint.zero
  print("Test node position 2: \(testSpriteNode.position)")
  testSpriteNode.run(SKAction.moveBy(x: 200, y: 200, duration: 4))
}
</code>```

Run... position is moved correctly, but animation fails.

答:
See link by @Marcel in the comments. The post he pointed me to mostly did the trick with some additional updates/validation on my part. The only way I was able to get this to work, though, was to put the isPaused on the exact sprite node I was trying to animate (within my ref node).

I tried isPaused=false at the top level, main scene didMove to view, but to no effect, and then added isPaused=false to the main reference node, to no effect. It worked only when I added isPaused=false the actual sprite (within the ref node I had added) I was trying to animate. I removed isPaused=false from the the main & ref nodes, and as long as isPaused=false was still on the sprite node in question (the one within the ref node I was trying to animate): success.

Bottom line seems to be that isPaused=false is required on any sprites contained within reference nodes.

Body:
I can't seem to get sprite nodes that have been added by reference (drag/drop one sks file into another sks file in Xcode 9) to animate. This seems allowable, as you can physically do such a thing, but I'm unsure why the sub-nodes won't animate.

Example
1. Start with standard spritekit template
2. add a HUD.sks file, and add a color sprite somewhere, name it "hudSpriteNode"
3. drag the HUD.sks file into the GameScene.sks scene - center it at zero
4. find the hudSpriteNode (by name)
5. move it with .position (works!)
6. move it with animation (fails!)

HUD.sks

GameScene.sks

Add this code to GameScene.swift

if let testSpriteNode = childNode(withName: "//hudSpriteNode") as? SKSpriteNode {
  print("Found test sprite node")
  print("Test node position 1: \(testSpriteNode.position)")
  testSpriteNode.position = CGPoint.zero
  print("Test node position 2: \(testSpriteNode.position)")
  testSpriteNode.run(SKAction.moveBy(x: 200, y: 200, duration: 4))
}

Run... position is moved correctly, but animation fails.


问:
Joining LoginHistory to User using implicit parent-child relationship
I have been trying to bring in fields from the User object in my LoginHistory query. I keep getting an error saying the relationship is not understood even though there is a parent-child relationship.

select Userid, user.Username  from loginHistory

The above is not working and to me it seems its the simplest query. What am I doing wrong?

答:
LoginHistory.UserId.getDescribe() shows "null" as the "relationshipName".
You can not join LoginHistory with User. I tried it but no luck. I fetched data locally and then applied the join.


问:
Number of indices is less than the number of dimensions of the indexed array when using Do Until Loop
```<code>Private Sub TxtCoin_TextChanged(sender As Object, e As EventArgs) Handles TxtCoin.TextChanged
    ' declare a six row six column array for coin value ranges
    Static dblCoins(,) As Double = {{"0", "10"},
        {"10.01", "50"},
        {"50.01", "100"},
        {"100.01", "500"},
        {"500.01", "5000"},
        {"5000.01", "1000000000
        "}}
    ' declare parellel array
    Static strMsgVal() As String =
        {"Cheap", "Average", "Above Average", "Valuable", "Very Valuable", "Extremely Valuabele"}

    ' display the coin value message
    Dim strMessage As String
    Dim dblCoinVal = dblCoins
    Dim strMessa = strMsgVal.ToString

    strMessage = TxtCoin.Text

    ' search dblCoins for the amount
    ' continue searching until the end of
    ' the array or the amount is found

    Do Until dblCoinVal = dblCoins.Length OrElse
            strMessage = dblCoins(dblCoinVal)
        dblCoinVal += 1
    Loop

    If strMessa = dblCoinVal.ToString Then
        lblCoinDescriptions.Text = strMessa.ToString
    Else
        MessageBox.Show("Please enter an integer")
    End If
</code>```

Trying to get my label to display a message when the user enters a certain value in the text box range in my array and am getting an error.

Visual basic

答:
Don't put the code in the TextedChanged event because it will run every time the users enters a single digit.

```<code>Private Sub butOK_Click(sender As Object, e As EventArgs) Handles butOK.Click
        Dim dblCoins(,) As Double = {{0, 10},
        {10.0, 50},
        {50.0, 100},
        {100.0, 500},
        {500.0, 5000},
        {5000.0, 1000000000}}
        Dim strMsgVal() As String =
       {"Cheap", "Average", "Above Average", "Valuable", "Very Valuable", "Extremely Valuabele"}
        Dim x As Double
        If Double.TryParse(txtCoin.Text, x) Then
            For i As Integer = 0 To 5
                If x > dblCoins(i, 0) And x <= dblCoins(i, 1) Then
                    MessageBox.Show($"The value of {x:c} has the Apprasal Value of {strMsgVal(i)}")
                    Exit Sub
                End If
            Next
            MessageBox.Show("Cannot evaluate a negative number or 0.")
        Else
            MessageBox.Show("Please enter a number between 0 and 1000000000 without any commas or dollar signs.")
        End If
    End Sub
</code>```

I think this code forces the arrays to be parallel. Please mark as answered if this helps you.

Body:
Private Sub TxtCoin_TextChanged(sender As Object, e As EventArgs) Handles TxtCoin.TextChanged
    ' declare a six row six column array for coin value ranges
    Static dblCoins(,) As Double = {{"0", "10"},
        {"10.01", "50"},
        {"50.01", "100"},
        {"100.01", "500"},
        {"500.01", "5000"},
        {"5000.01", "1000000000
        "}}
    ' declare parellel array
    Static strMsgVal() As String =
        {"Cheap", "Average", "Above Average", "Valuable", "Very Valuable", "Extremely Valuabele"}

    ' display the coin value message
    Dim strMessage As String
    Dim dblCoinVal = dblCoins
    Dim strMessa = strMsgVal.ToString

    strMessage = TxtCoin.Text

    ' search dblCoins for the amount
    ' continue searching until the end of
    ' the array or the amount is found

    Do Until dblCoinVal = dblCoins.Length OrElse
            strMessage = dblCoins(dblCoinVal)
        dblCoinVal += 1
    Loop

    If strMessa = dblCoinVal.ToString Then
        lblCoinDescriptions.Text = strMessa.ToString
    Else
        MessageBox.Show("Please enter an integer")
    End If

Trying to get my label to display a message when the user enters a certain value in the text box range in my array and am getting an error.

Visual basic

Body:
Don't put the code in the TextedChanged event because it will run every time the users enters a single digit.

Private Sub butOK_Click(sender As Object, e As EventArgs) Handles butOK.Click
        Dim dblCoins(,) As Double = {{0, 10},
        {10.0, 50},
        {50.0, 100},
        {100.0, 500},
        {500.0, 5000},
        {5000.0, 1000000000}}
        Dim strMsgVal() As String =
       {"Cheap", "Average", "Above Average", "Valuable", "Very Valuable", "Extremely Valuabele"}
        Dim x As Double
        If Double.TryParse(txtCoin.Text, x) Then
            For i As Integer = 0 To 5
                If x > dblCoins(i, 0) And x <= dblCoins(i, 1) Then
                    MessageBox.Show($"The value of {x:c} has the Apprasal Value of {strMsgVal(i)}")
                    Exit Sub
                End If
            Next
            MessageBox.Show("Cannot evaluate a negative number or 0.")
        Else
            MessageBox.Show("Please enter a number between 0 and 1000000000 without any commas or dollar signs.")
        End If
    End Sub

I think this code forces the arrays to be parallel. Please mark as answered if this helps you.


问:
TextField takes unicode in Django
I am trying to save a string contains characters whose ordinal is not in range(128) into database. The field is declared as TextField in model and when I called the save() method, an exception was thrown:

```<code>File "/Library/Python/2.6/site-packages/django/db/models/base.py", line 434, in save self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Library/Python/2.6/site-packages/django/db/models/base.py", line 500, in save_base rows = manager.using(using).filter(pk=pk_val)._update(values)
File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 491, in _update return query.get_compiler(self.db).execute_sql(None)
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 861, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 717, in execute_sql sql, params = self.as_sql()
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 826, in as_sql val = field.get_db_prep_save(val, connection=self.connection)
File "/Library/Python/2.6/site-packages/django/db/models/fields/subclassing.py", line 28, in inner return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/fields/subclassing.py", line 28, in inner return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 276, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/Library/Python/2.6/site-packages/django/db/models/fields/subclassing.py", line 53, in inner return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 652, in get_db_prep_value value = self.get_prep_value(value)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 647, in get_prep_value return self.to_python(value)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 610, in to_python if not ansi_date_re.search(value):
TypeError: expected string or buffer
</code>```

Here is what I did:

```<code>str_unicode = str.encode('utf-8')
m = MyModel.new(str = str_unicode)
m.save()
</code>```

So what should I do to enable the unicode compatibility?

Updated: I am currently using sqlite3 for development, python 2.6.1 and Django 1.2.4 on Mac

答:
utf-8 is not unicode! This line:

```<code>str_unicode = str.encode('utf-8')
</code>```

does the opposite of what you intended. It takes unicode, and converts it to utf-8. Don't do this.

Title: TextField takes unicode in Django

Body:
I am trying to save a string contains characters whose ordinal is not in range(128) into database. The field is declared as TextField in model and when I called the save() method, an exception was thrown:

File "/Library/Python/2.6/site-packages/django/db/models/base.py", line 434, in save self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Library/Python/2.6/site-packages/django/db/models/base.py", line 500, in save_base rows = manager.using(using).filter(pk=pk_val)._update(values)
File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 491, in _update return query.get_compiler(self.db).execute_sql(None)
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 861, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 717, in execute_sql sql, params = self.as_sql()
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 826, in as_sql val = field.get_db_prep_save(val, connection=self.connection)
File "/Library/Python/2.6/site-packages/django/db/models/fields/subclassing.py", line 28, in inner return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/fields/subclassing.py", line 28, in inner return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 276, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/Library/Python/2.6/site-packages/django/db/models/fields/subclassing.py", line 53, in inner return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 652, in get_db_prep_value value = self.get_prep_value(value)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 647, in get_prep_value return self.to_python(value)
File "/Library/Python/2.6/site-packages/django/db/models/fields/__init__.py", line 610, in to_python if not ansi_date_re.search(value):
TypeError: expected string or buffer

Here is what I did:

str_unicode = str.encode('utf-8')
m = MyModel.new(str = str_unicode)
m.save()

So what should I do to enable the unicode compatibility?

Updated: I am currently using sqlite3 for development, python 2.6.1 and Django 1.2.4 on Mac

Body:
utf-8 is not unicode! This line:

str_unicode = str.encode('utf-8')

does the opposite of what you intended. It takes unicode, and converts it to utf-8. Don't do this.


问:
hbase when particular region server fails, read the data from the replicated cluster
As I'm new to hbase file storage, is there any option available to read particular regions from the replicated cluster when the region server fails

For example, In hbase cluster, with replication mode enabled master-master mode(data cluster with separate zookeeper) it has 1 Master  and 5 region servers. In that one region server fails, in this case shall I able to read data belongs to that region server from replicated cluster?  Like the concept proposed by facebook

https://code.facebook.com/posts/321111638043166/hydrabase-the-evolution-of-hbase-facebook/

or else if we face issues with many region server in the main cluster then we need to change the read and write to be served from the replicated server. (Main cluster becomes replicated cluster and vice versa)

For this, what configuration we need to do this work apart from the zookeeper quorum connection via Java API?

答:
In Hbase [With HDFS storage & replication enabled] if a region server fails, the regions served by this failed region server will get reassigned to other region servers [Since the HFiles and WAL are replicated in HDFS, you will not lose your data]. Due to the nature of failover in Hbase, this reassignment will result in splitting and replaying the contents of WAL which lengthens the time of recovery.

However in Hydrabase, each region is served by a quorum of region servers and all the read and writes from the clients are served by the leader in quorum. Each hosting region server synchronously writes to the WAL corresponding the modified region. If the leader goes down, one of the follower will get elected as the leader and will continue to serve the read and write requests.

Both Hbase and Hydrabase ensure the data availability in case of region server failure. Hydrabase ensures the reduction of downtime due to region server failure.


问:
Passing some id from Dropzone using Laravel
I'm having a Modal to upload images into the gallery like this:

```<code><div id="imagesModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title"></h4>
            </div>
            <div class="modal-body">
            <form name="imagesForm" id="addImages" class="form-horizontal dropzone" role="form" method="POST" action="{{ route('images.add') }}" enctype="multipart/form-data">
                {{ csrf_field() }}
                {{ method_field('POST') }}
            </form>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</code>```

and here's my jquery script:

```<code>$( "#addImages" ).click(function(event) {
                event.preventDefault();
                save_method = 'add';
                $('input[name=_method]').val('POST');
                $('#imagesModal').modal("show");
                $('#imagesForm')[0].reset();
                $('.modal-title').text('Add Images')
            });

            Dropzone.options.addImages = {
                paramName: "images", // The name that will be used to transfer the file
                maxFilesize: 2, // MB
            };

and i already add the route and the function

   public function store(Request $request)
    {
        $gallery = Gallery::find($request->id);
        $path = 'public'.'/'.str_slug($gallery->name);

        foreach ($request->images as $file) {
            $image = new Image();
            $image->gallery_id = $gallery->id;
            $image->name = $file->getClientOriginalName();
            $image->extension = $file->extension();
            $image->size = $file->getClientSize();
            $image->save();

            // Or any custom name as the third argument
            Storage::putFileAs($path, $file, $file->getClientOriginalName());
        }

    }
</code>```

My problem is i don't know how i can pass the gallery id so i can access it into the function? I have some idea to put it on data-gallery-id in the button, but how can pass that data so it's going to be sent with the images?

答:
As per their Documentation

params: Can be an object of additional parameters to transfer to the server, or a Function that gets invoked with the files, xhr and, if it's a chunked upload, chunk arguments. In case of a function, this needs to return a map.
  The default implementation does nothing for normal uploads, but adds relevant information for chunked uploads.

So you could modify your dropzone configuration as

```<code>Dropzone.options.addImages = {
    paramName: "images", // The name that will be used to transfer the file
    maxFilesize: 2, // MB

    // Whether to send multiple files in one request.
    // If this it set to true, then the fallback file input element will
    // have the multiple attribute as well.
    uploadMultiple: TRUE,

    params: {
        'gallery_id' : 1 // Your gallery Id
    }
};
</code>```

This is the same as adding hidden input fields in the form element.

Body:
I'm having a Modal to upload images into the gallery like this:

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

            <form name="imagesForm" id="addImages" class="form-horizontal dropzone" role="form" method="POST" action="{{ route('images.add') }}" enctype="multipart/form-data">
                {{ csrf_field() }}
                {{ method_field('POST') }}
            </form>

and here's my jquery script:

$( "#addImages" ).click(function(event) {
                event.preventDefault();
                save_method = 'add';
                $('input[name=_method]').val('POST');
                $('#imagesModal').modal("show");
                $('#imagesForm')[0].reset();
                $('.modal-title').text('Add Images')
            });

            Dropzone.options.addImages = {
                paramName: "images", // The name that will be used to transfer the file
                maxFilesize: 2, // MB
            };

and i already add the route and the function

   public function store(Request $request)
    {
        $gallery = Gallery::find($request->id);
        $path = 'public'.'/'.str_slug($gallery->name);

        foreach ($request->images as $file) {
            $image = new Image();
            $image->gallery_id = $gallery->id;
            $image->name = $file->getClientOriginalName();
            $image->extension = $file->extension();
            $image->size = $file->getClientSize();
            $image->save();

            // Or any custom name as the third argument
            Storage::putFileAs($path, $file, $file->getClientOriginalName());
        }

    }

My problem is i don't know how i can pass the gallery id so i can access it into the function? I have some idea to put it on data-gallery-id in the button, but how can pass that data so it's going to be sent with the images?

Body:
As per their Documentation

params: Can be an object of additional parameters to transfer to the server, or a Function that gets invoked with the files, xhr and, if it's a chunked upload, chunk arguments. In case of a function, this needs to return a map.
  The default implementation does nothing for normal uploads, but adds relevant information for chunked uploads.

So you could modify your dropzone configuration as

Dropzone.options.addImages = {
    paramName: "images", // The name that will be used to transfer the file
    maxFilesize: 2, // MB

    // Whether to send multiple files in one request.
    // If this it set to true, then the fallback file input element will
    // have the multiple attribute as well.
    uploadMultiple: TRUE,

    params: {
        'gallery_id' : 1 // Your gallery Id
    }
};

This is the same as adding hidden input fields in the form element.


问:
How to print all jar results into a file using bash script
I've been trying to do this simple script that I wrote where it runs an executable jar file that I made. The command of the script are as follows:

```<code>#!/bin/bash
msisdn=$1

java -cp /home/support/phuzca/Migration/PostpaidXMigration_lib/ -jar /home/support/phuzca/Migration/PostpaidXMigration.jar $msisdn /home/support/phuzca/Migration/config.properties /opt/tomcat9/webapps/axis2/WEB-INF/classes/META-INF/PlanID.xml
</code>```

The jar file works as expected and I receive the expected results:

The idea that I've been trying to figure out is how to prevent those texts from appearing when I run my script, and instead, print them in a file so it can be reviewed later. I hope you could open up some ideas for me. Thank you very much.

答:
Redirect the output to a file:

```<code>migrateToPstopaidX.sh > output.log
</code>```

if you want to redirect stderr use this

```<code>  migrateToPstopaidX.sh &> output.log
</code>```

you can use this >> to append the log  instead of >

Body:
I've been trying to do this simple script that I wrote where it runs an executable jar file that I made. The command of the script are as follows:

#!/bin/bash
msisdn=$1

java -cp /home/support/phuzca/Migration/PostpaidXMigration_lib/ -jar /home/support/phuzca/Migration/PostpaidXMigration.jar $msisdn /home/support/phuzca/Migration/config.properties /opt/tomcat9/webapps/axis2/WEB-INF/classes/META-INF/PlanID.xml

The jar file works as expected and I receive the expected results:

The idea that I've been trying to figure out is how to prevent those texts from appearing when I run my script, and instead, print them in a file so it can be reviewed later. I hope you could open up some ideas for me. Thank you very much.

Body:
Redirect the output to a file:

migrateToPstopaidX.sh > output.log

if you want to redirect stderr use this

  migrateToPstopaidX.sh &> output.log

you can use this >> to append the log  instead of >


问:
jenkins dsl in single line doesn't work

Need help on understanding the Jenkins DSL formatting and how it can affect the job creation/ execution

Lets take an example of the below DSL script

```<code>job('readyForIntegration'){ displayName('Good For Integration Testing')
parameters{ stringParam('param1') } }
</code>```

If I have a job with the above text, the job fails with error "Processing provided DSL script
java.lang.NullPointerException: Cannot invoke method parameters() on null object".

But if I write the same script with below indentation/ formatting the job works

```<code>job('readyForIntegration'){
 displayName('Good For Integration Testing')
 parameters{
  stringParam('param1')
 }
}
</code>```

答:
This is more to do with Groovy. In Groovy we can leave out semicolons at the end of the line as long as we use one statement per line. If we use multiple statements on a line we must use a semicolon to separate the statements.

Hence, if you want your code to be in a single line, you should do

```<code>job('readyForIntegration'){displayName('Good For Integration Testing') ;parameters{ stringParam('param1') } }
</code>```

Title: jenkins dsl in single line doesn't work

Body:
Need help on understanding the Jenkins DSL formatting and how it can affect the job creation/ execution

Lets take an example of the below DSL script

job('readyForIntegration'){ displayName('Good For Integration Testing')
parameters{ stringParam('param1') } }

If I have a job with the above text, the job fails with error "Processing provided DSL script
java.lang.NullPointerException: Cannot invoke method parameters() on null object".

But if I write the same script with below indentation/ formatting the job works

job('readyForIntegration'){
 displayName('Good For Integration Testing')
 parameters{
  stringParam('param1')
 }
}

Body:
This is more to do with Groovy. In Groovy we can leave out semicolons at the end of the line as long as we use one statement per line. If we use multiple statements on a line we must use a semicolon to separate the statements.

Hence, if you want your code to be in a single line, you should do

job('readyForIntegration'){displayName('Good For Integration Testing') ;parameters{ stringParam('param1') } }


问:
React deleteing from state array
I'm working on my first to do app with React. Trying to create delete function that allows a user to click the task and have it removed from the array and UI.

I've been trying a couple of different things following other's tutorials, but no luck. (Check commented out sections)
My console.log within the deleteItem function is showing undefined, so I know that it's not receiving the right data. I'm lost as to why.

App.js:

```<code>import React, { Component } from 'react';
import { List } from './list';

export class Todo extends Component {
    constructor(props) {
        super(props);
        this.state = {
            term: '',
            items: []
        };
        this.deleteItem = this.deleteItem.bind(this);
    }
    onChange = (e) => {
        this.setState({term: e.target.value});
    }
    onSubmit = (e) => {
        e.preventDefault()
        if (this.state.term === "") {
            alert("You must enter something!");

        } else {
            this.setState({
                term: '',
                items: [...this.state.items, this.state.term]
            })
        }
    }

    deleteItem(index){
        // var filteredItems = this.state.items.filter(function (item) {
        // return(item.index !== index);
        // });
        // console.log(filteredItems);
        // this.setState({
        // itmes: filteredItems
        // })

        this.setState({items: this.state.items.filter(function(item){
            console.log(item.index)
            return item !== item.index
        })})
        console.log(this.state.items)
        // if (item.index === index) {
        //     var indArr = this.state.items.indexOf(item.index);
        //     this.state.items.splice(indArr, 1);
        // }

    }

    render() {
        return(
            <div>
                <h3>You currently have {this.state.items.length} things to do.</h3>
                <form className="Todo" onSubmit={this.onSubmit}>
                    <input placeholder="Enter task" value={this.state.term} onChange={this.onChange} />
                    <button>add</button>
                </form>
                <List items={this.state.items} delete={this.deleteItem}/>
            </div>
        )
    }
}
</code>```

List.js

```<code>import React, { Component } from 'react';

export class List extends Component {
    constructor(props) {
        super(props);
        this.delete = this.delete.bind(this);
    }
    delete(key) {
        this.props.delete(key);
    }
    render() {
        return(
            <ul>
                {
                    this.props.items.map((item, key) => <div class="listItems"
                        onClick={(e) => this.delete(item.key)}
                        key={key}>{item}</div>)
                }
            </ul>
        )
    }
}
</code>```

Any help would be deeply appreciated.

答:
I found there are some problems in your code.

TD:LR

```<code>// List.js
onClick={(e) => this.delete(item.key)
// instead =>
onClick={() => this.delete(item)

// App.js
return item !== item.index
// instead =>
return item !== index
</code>```

This is my code link, you can have a look:
https://stackblitz.com/edit/react-n2uy9z

1. Pass wrong value to this.delete in List.js

```<code>onClick={(e) => this.delete(item.key)
</code>```

The item.key is array index, you should pass item which you want to delete. And the params e is not need because you use item.

2. The filter callback function is not right

```<code>this.setState({items: this.state.items.filter(function(item){
      console.log(item.index)
    return item!== item.index
})})
</code>```

The item.index is undefined, because item is a value in array, it has no index property. The value will be deleted is index which is passed to function deleteItem, so you should use return item !== index.

3. Invalid DOM property class.

This is a waring in <div class="listItems": 'Warning: Invalid DOM property class. Did you mean className?'.

So use className instead of class.

Title: React deleteing from state array

Body:
I'm working on my first to do app with React. Trying to create delete function that allows a user to click the task and have it removed from the array and UI.

I've been trying a couple of different things following other's tutorials, but no luck. (Check commented out sections)
My console.log within the deleteItem function is showing undefined, so I know that it's not receiving the right data. I'm lost as to why.

App.js:

import React, { Component } from 'react';
import { List } from './list';

export class Todo extends Component {
    constructor(props) {
        super(props);
        this.state = {
            term: '',
            items: []
        };
        this.deleteItem = this.deleteItem.bind(this);
    }
    onChange = (e) => {
        this.setState({term: e.target.value});
    }
    onSubmit = (e) => {
        e.preventDefault()
        if (this.state.term === "") {
            alert("You must enter something!");

        } else {
            this.setState({
                term: '',
                items: [...this.state.items, this.state.term]
            })
        }
    }

    deleteItem(index){
        // var filteredItems = this.state.items.filter(function (item) {
        // return(item.index !== index);
        // });
        // console.log(filteredItems);
        // this.setState({
        // itmes: filteredItems
        // })

        this.setState({items: this.state.items.filter(function(item){
            console.log(item.index)
            return item !== item.index
        })})
        console.log(this.state.items)
        // if (item.index === index) {
        //     var indArr = this.state.items.indexOf(item.index);
        //     this.state.items.splice(indArr, 1);
        // }

    }

    render() {
        return(

You currently have {this.state.items.length} things to do.

                <form className="Todo" onSubmit={this.onSubmit}>
                    <input placeholder="Enter task" value={this.state.term} onChange={this.onChange} />
                    <button>add</button>
                </form>
                <List items={this.state.items} delete={this.deleteItem}/>

        )
    }
}

List.js

import React, { Component } from 'react';

export class List extends Component {
    constructor(props) {
        super(props);
        this.delete = this.delete.bind(this);
    }
    delete(key) {
        this.props.delete(key);
    }
    render() {
        return(

                {
                    this.props.items.map((item, key) =>
 this.delete(item.key)}
                        key={key}>{item}
)
                }

        )
    }
}

Any help would be deeply appreciated.

Body:
I found there are some problems in your code.

TD:LR

// List.js
onClick={(e) => this.delete(item.key)
// instead =>
onClick={() => this.delete(item)

// App.js
return item !== item.index
// instead =>
return item !== index

This is my code link, you can have a look:
https://stackblitz.com/edit/react-n2uy9z

1. Pass wrong value to this.delete in List.js

onClick={(e) => this.delete(item.key)

The item.key is array index, you should pass item which you want to delete. And the params e is not need because you use item.

2. The filter callback function is not right

this.setState({items: this.state.items.filter(function(item){
      console.log(item.index)
    return item!== item.index
})})

The item.index is undefined, because item is a value in array, it has no index property. The value will be deleted is index which is passed to function deleteItem, so you should use return item !== index.

3. Invalid DOM property class.

This is a waring in <div class="listItems": 'Warning: Invalid DOM property class. Did you mean className?'.

So use className instead of class.


问:
Gitlab-cl server and memory usage
we are running gitlab-cl 10.0.1 installed from repository on centos 6.9

We have a physical server with 65GB of RAM.
We had slow performances on the web interface, so looking at the memory we saw that the server is swapping a bit and all the memory is used.

There is no active process using it and free -m confirms it is cached :

```<code>             total       used       free     shared    buffers     cached
 Mem:         64412      64179        232        140          1        176
 -/+ buffers/cache:      64001        410
 Swap:        15999       2679      13320
</code>```

The strange thing is that all memory is allocated on DirectMap2M

```<code>cat /proc/meminfo
MemTotal:       65957916 kB
MemFree:          242364 kB
Buffers:            1132 kB
Cached:           193548 kB
SwapCached:       853032 kB
Active:          6302692 kB
Inactive:        1729836 kB
Active(anon):    6276560 kB
Inactive(anon):  1704824 kB
Active(file):      26132 kB
Inactive(file):    25012 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:      16383996 kB
SwapFree:       13580524 kB
Dirty:              1576 kB
Writeback:             0 kB
AnonPages:       7595904 kB
Mapped:           162376 kB
Shmem:            144312 kB
Slab:           57184100 kB
SReclaimable:      35132 kB
SUnreclaim:     57148968 kB
KernelStack:       12912 kB
PageTables:        59144 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:    49362952 kB
Committed_AS:   18168608 kB
VmallocTotal:   34359738367 kB
VmallocUsed:      395428 kB
VmallocChunk:   34323721400 kB
HardwareCorrupted:     0 kB
AnonHugePages:   3260416 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:        7652 kB
DirectMap2M:    67088384 kB
</code>```

Do you know why this is happening?
Is that normal with gitlab?

I read about few commands to remove cache from the memory :

```<code># sync; echo 1 > /proc/sys/vm/drop_caches
# sync; echo 2 > /proc/sys/vm/drop_caches
# sync; echo 3 > /proc/sys/vm/drop_caches
</code>```

Are they safe to run on a production machine running gitlab?

Thanks a lot

答:
Can't say exactly why all memory is used up but the fact is that it is. At first I expected the standard https://www.linuxatemyram.com/ but I can see that in your case you are actually using 64001 kb of memory.
The commands listed are pointless, what they do is just delete disk blocks that are cached in memory causing an io hit next time same block is needed.

To find out what's going on you need to see what process that uses up all the memory. It is several ways to get that info

```<code>ps -e -o pid,vsz,comm= | sort -n -k 2
</code>```

or to get the arguments also

```<code>ps -e -o pid,vsz,command= | sort -n -k 2|cut -b1-$COLUMNS
</code>```

you can start "top" and hit uppercase "M" to sort by memory user.

Title: Gitlab-cl server and memory usage

Body:
we are running gitlab-cl 10.0.1 installed from repository on centos 6.9

We have a physical server with 65GB of RAM.
We had slow performances on the web interface, so looking at the memory we saw that the server is swapping a bit and all the memory is used.

There is no active process using it and free -m confirms it is cached :

             total       used       free     shared    buffers     cached
 Mem:         64412      64179        232        140          1        176
 -/+ buffers/cache:      64001        410
 Swap:        15999       2679      13320

The strange thing is that all memory is allocated on DirectMap2M

cat /proc/meminfo
MemTotal:       65957916 kB
MemFree:          242364 kB
Buffers:            1132 kB
Cached:           193548 kB
SwapCached:       853032 kB
Active:          6302692 kB
Inactive:        1729836 kB
Active(anon):    6276560 kB
Inactive(anon):  1704824 kB
Active(file):      26132 kB
Inactive(file):    25012 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:      16383996 kB
SwapFree:       13580524 kB
Dirty:              1576 kB
Writeback:             0 kB
AnonPages:       7595904 kB
Mapped:           162376 kB
Shmem:            144312 kB
Slab:           57184100 kB
SReclaimable:      35132 kB
SUnreclaim:     57148968 kB
KernelStack:       12912 kB
PageTables:        59144 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:    49362952 kB
Committed_AS:   18168608 kB
VmallocTotal:   34359738367 kB
VmallocUsed:      395428 kB
VmallocChunk:   34323721400 kB
HardwareCorrupted:     0 kB
AnonHugePages:   3260416 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:        7652 kB
DirectMap2M:    67088384 kB

Do you know why this is happening?
Is that normal with gitlab?

I read about few commands to remove cache from the memory :

# sync; echo 1 > /proc/sys/vm/drop_caches
# sync; echo 2 > /proc/sys/vm/drop_caches
# sync; echo 3 > /proc/sys/vm/drop_caches

Are they safe to run on a production machine running gitlab?

Thanks a lot

Body:
Can't say exactly why all memory is used up but the fact is that it is. At first I expected the standard https://www.linuxatemyram.com/ but I can see that in your case you are actually using 64001 kb of memory.
The commands listed are pointless, what they do is just delete disk blocks that are cached in memory causing an io hit next time same block is needed.

To find out what's going on you need to see what process that uses up all the memory. It is several ways to get that info

ps -e -o pid,vsz,comm= | sort -n -k 2

or to get the arguments also

ps -e -o pid,vsz,command= | sort -n -k 2|cut -b1-$COLUMNS

you can start "top" and hit uppercase "M" to sort by memory user.


问:
Packet problem - Not receiving anything after the first few packets
I'm trying to use the following code to build a simple chat program in Actionscript. Unfortunately, not everything seems to be transmitted correctly, because it doesn't receive any packets after the first few packets (so not all of the text updates get received). I used Wireshark and saw that all of the packets were being transmitted, so I'm not sure why Flash isn't processing all of them. Here's my code:

```<code><fx:Declarations>
    <!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<mx:Canvas id="login">
    <mx:TextInput id="host" text="Host name"></mx:TextInput>
    <mx:TextInput id="pswd" text="Key 1" keyDown="changePSWD()" y="30"></mx:TextInput>
    <mx:TextInput id="key" text="Key 2" keyDown="changeKey()" y="60"></mx:TextInput>
    <mx:TextInput id="port" text="Port" y="90"></mx:TextInput>
    <s:Button label="Connect" y="90" x="150" click="doConnect()"></s:Button><s:Button y="120" label="Listen for connections (Don't worry. We'll automatically reconfigure your router)" click="listen()"></s:Button>
</mx:Canvas>
<mx:Canvas id="chatScreen" visible="false">
    <s:TextArea id="mainchat" keyUp="sendTxt()" width="500" height="500"></s:TextArea>
</mx:Canvas>
<fx:Script>
    <![CDATA[
   import flash.events.Event;
   import flash.external.ExternalInterface;
   import flash.net.Socket;
   import flash.system.Security;
   import flash.utils.ByteArray;
   private var nativeSocket:Socket = new Socket();
    private function init():void {
        Security.allowDomain("*");
        nativeSocket.addEventListener(Event.CONNECT, connected);

        nativeSocket.connect("localhost", 337);

        }
        private function sendTxt():void {
            //Send update signal
            var buffer:ByteArray = new ByteArray();
            //Signal type
            buffer.writeByte(0);
            //Signal data
            buffer.writeUTF(mainchat.text);
            buffer.position = 0;
            securesocket.Write(buffer);
            securesocket.Flush();
        }
        private var securesocket:NativeSocket;
        private function changeKey():void {
            key.displayAsPassword = true;
        }
        private function changePSWD():void {
            pswd.displayAsPassword = true;
        }

        private function fail():void {
            ExternalInterface.call("alert", "Failed to establish a connection to the remote host.");
        }
        private function success(socket:NativeSocket):void {
            login.visible = false;
            chatScreen.visible = true;

            securesocket = socket;
            securesocket.onRecv = parseData;
            securesocket.ReadAsync(4086);
        }
        private function doConnect():void {
            nativeInterface.openSocket(host.text, int(port.text), pswd.text, key.text, success, fail);

        }
        private function parseData(buffer:ByteArray, sender:NativeSocket):void {
            try {
            buffer.position = 0;
            var opcode:int = buffer.readByte();
            if (opcode == 0) {
                mainchat.text = buffer.readUTF();
            }
            }catch (Exception:Error) {

            }
            securesocket.ReadAsync(9077);
        }
        private function clientConnectedToServer(endpoint:String, socket:NativeSocket):void {
            try {
            ExternalInterface.call("alert", endpoint + " has connected to Chat. The server listening socket will now close and you may begin your secure chat session.");
            }catch (Exception:Error) {

            }
            mainserv.Stop();
            //Begin chat
            securesocket = socket;
            securesocket.onRecv = parseData;
            securesocket.ReadAsync(999999);
            chatScreen.visible = true;
        }
        private var mainserv:server;
        private function serverConnected(socket:server):void {
            socket.clientConnect = clientConnectedToServer;
        mainserv = socket;

        login.visible = false;

            }
        private function listen():void {
            nativeInterface.listenSocket(int(port.text), "xChat-server" + port.text, pswd.text, key.text, serverConnected);
        }
        private var nativeInterface:NativeInterface;
        private function connected(evt:Event):void {
            nativeInterface = new NativeInterface(nativeSocket);
            }
    ]]>
</fx:Script>
</code>```

答:
Flash/Flex applications communicate correctly after implementing a cross-domain policy

file which you communicate with on port #843

Take a look at Cross-domain Policy File Specifications

This is a sample policy-file:

```<code><?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM
"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">

<cross-domain-policy>
    <site-control permitted-cross-domain-policies="master-only"/>
    <allow-access-from domain="*"/>
    <allow-http-request-headers-from domain="*" headers="SOAPAction"/>
</cross-domain-policy>
</code>```

Body:
I'm trying to use the following code to build a simple chat program in Actionscript. Unfortunately, not everything seems to be transmitted correctly, because it doesn't receive any packets after the first few packets (so not all of the text updates get received). I used Wireshark and saw that all of the packets were being transmitted, so I'm not sure why Flash isn't processing all of them. Here's my code:

<fx:Declarations>

</fx:Declarations>
<mx:Canvas id="login">
    <mx:TextInput id="host" text="Host name"></mx:TextInput>
    <mx:TextInput id="pswd" text="Key 1" keyDown="changePSWD()" y="30"></mx:TextInput>
    <mx:TextInput id="key" text="Key 2" keyDown="changeKey()" y="60"></mx:TextInput>
    <mx:TextInput id="port" text="Port" y="90"></mx:TextInput>
    <s:Button label="Connect" y="90" x="150" click="doConnect()"></s:Button><s:Button y="120" label="Listen for connections (Don't worry. We'll automatically reconfigure your router)" click="listen()"></s:Button>
</mx:Canvas>
<mx:Canvas id="chatScreen" visible="false">
    <s:TextArea id="mainchat" keyUp="sendTxt()" width="500" height="500"></s:TextArea>
</mx:Canvas>
<fx:Script>
    <![CDATA[
   import flash.events.Event;
   import flash.external.ExternalInterface;
   import flash.net.Socket;
   import flash.system.Security;
   import flash.utils.ByteArray;
   private var nativeSocket:Socket = new Socket();
    private function init():void {
        Security.allowDomain("*");
        nativeSocket.addEventListener(Event.CONNECT, connected);

        nativeSocket.connect("localhost", 337);

        }
        private function sendTxt():void {
            //Send update signal
            var buffer:ByteArray = new ByteArray();
            //Signal type
            buffer.writeByte(0);
            //Signal data
            buffer.writeUTF(mainchat.text);
            buffer.position = 0;
            securesocket.Write(buffer);
            securesocket.Flush();
        }
        private var securesocket:NativeSocket;
        private function changeKey():void {
            key.displayAsPassword = true;
        }
        private function changePSWD():void {
            pswd.displayAsPassword = true;
        }

        private function fail():void {
            ExternalInterface.call("alert", "Failed to establish a connection to the remote host.");
        }
        private function success(socket:NativeSocket):void {
            login.visible = false;
            chatScreen.visible = true;

            securesocket = socket;
            securesocket.onRecv = parseData;
            securesocket.ReadAsync(4086);
        }
        private function doConnect():void {
            nativeInterface.openSocket(host.text, int(port.text), pswd.text, key.text, success, fail);

        }
        private function parseData(buffer:ByteArray, sender:NativeSocket):void {
            try {
            buffer.position = 0;
            var opcode:int = buffer.readByte();
            if (opcode == 0) {
                mainchat.text = buffer.readUTF();
            }
            }catch (Exception:Error) {

            }
            securesocket.ReadAsync(9077);
        }
        private function clientConnectedToServer(endpoint:String, socket:NativeSocket):void {
            try {
            ExternalInterface.call("alert", endpoint + " has connected to Chat. The server listening socket will now close and you may begin your secure chat session.");
            }catch (Exception:Error) {

            }
            mainserv.Stop();
            //Begin chat
            securesocket = socket;
            securesocket.onRecv = parseData;
            securesocket.ReadAsync(999999);
            chatScreen.visible = true;
        }
        private var mainserv:server;
        private function serverConnected(socket:server):void {
            socket.clientConnect = clientConnectedToServer;
        mainserv = socket;

        login.visible = false;

            }
        private function listen():void {
            nativeInterface.listenSocket(int(port.text), "xChat-server" + port.text, pswd.text, key.text, serverConnected);
        }
        private var nativeInterface:NativeInterface;
        private function connected(evt:Event):void {
            nativeInterface = new NativeInterface(nativeSocket);
            }
    ]]>
</fx:Script>

Body:
Flash/Flex applications communicate correctly after implementing a cross-domain policy

file which you communicate with on port #843

Take a look at Cross-domain Policy File Specifications

This is a sample policy-file:

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM
"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">

<cross-domain-policy>
    <site-control permitted-cross-domain-policies="master-only"/>
    <allow-access-from domain="*"/>
    <allow-http-request-headers-from domain="*" headers="SOAPAction"/>
</cross-domain-policy>


问:
VBA excel trying to create a macro that imports data from file then if the data is equal to a specific value put one cell into a sheet on the new file
I'm trying to get a spreadsheet that will import data from another file, scan the file for certain values in column D and then paste specific cells (not the whole row) into the first row that has a blank cell in column F in the new spreadsheet.

This is my updated code now

```<code>Sub GetAmazonData()

Dim counter As Integer
Dim LastRow As Long
Dim Adspend As Workbook
Dim A As String
Dim Amazon As Workbook
Dim sourceSheet As Worksheet
Dim targetSheet As Worksheet

Set Adspend = ActiveWorkbook

Application.ScreenUpdating = False
Application.DisplayAlerts = False

'Specify data export file

A = Application.GetOpenFilename(Title:="Select File To Be Processed")
Set Amazon = Application.Workbooks.Open(A)

counter = 2

' While Not Amazon.Worksheets(1).Range("D" & counter) = ""

     If Amazon.Worksheets(1).Range("D" & counter) = "B01GB3HZ34" Then

        Set targetSheet = Adspend.Worksheets("DirtyDom")
        Set sourceSheet = Amazon.Worksheets(1)

        LastRow = Adspend.Worksheets("DirtyDom").Cells(Adspend.Worksheets("DirtyDom").Rows.Count, "F").End(xlUp).Row

        targetSheet.Range("F" & LastRow).Value = sourceSheet.Range("D" & counter).Value

     Else

        LastRow = Adspend.Worksheets("DirtyDom").Cells(Adspend.Worksheets("DirtyDom").Rows.Count, "F").End(xlUp).Row
        targetSheet.Range("F" & LastRow).Value = sourceSheet.Range("D4").Value

    End If

  '   ActiveCell.Offset(1, 0).Active

' Wend
Amazon.Close

End Sub
</code>```

I expect this bit of code to paste what is in the imported file's first sheet cell D1 into the sheet called DirtyDom in cell F1 since 1 is the first cell blank in column F.

I get the error Object variable or With block variable not set.

Thank you!

答:
Try something like this, it also puts your loop back in and resets your screen updating and alerts - untested.</p>

```<code>Sub GetAmazonData()

Dim Adspend As Workbook
Dim Amazon As Workbook
Dim Targetsheet As Worksheet
Dim Amazonsheet As Worksheet
Dim Amazonfilename As String
Dim lastAmazonrow As Long
Dim lastTargetrow As Long

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Set Adspend = ActiveWorkbook
    Set Targetsheet = Adspend.Worksheets("DirtyDom")

    'Specify data export file
    Amazonfilename = Application.GetOpenFilename(Title:="Select File To Be Processed")
    Set Amazon = Application.Workbooks.Open(Amazonfilename)
    Set Amazonsheet = Amazon.Worksheets(1)

    lastAmazonrow = Amazonsheet.Cells(Amazonsheet.Rows.Count, "D").End(xlUp).Row
    lastTargetrow = Targetsheet.Cells(Targetsheet.Rows.Count, "F").End(xlUp).Row + 1

    For counter = 1 To lastAmazonrow
        If Amazonsheet.Range("D" & counter) = "B01GB3HZ34" Then
            Targetsheet.Range("F" & lastTargetrow).Value = Amazonsheet.Range("D" & counter).Value
        Else
            Targetsheet.Range("F" & lastTargetrow).Value = Amazonsheet.Range("D4").Value
        End If

        lastTargetrow = lastTargetrow + 1
    Next i
    Amazon.Close

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub
</code>```

Body:
I'm trying to get a spreadsheet that will import data from another file, scan the file for certain values in column D and then paste specific cells (not the whole row) into the first row that has a blank cell in column F in the new spreadsheet.

This is my updated code now

Sub GetAmazonData()

Dim counter As Integer
Dim LastRow As Long
Dim Adspend As Workbook
Dim A As String
Dim Amazon As Workbook
Dim sourceSheet As Worksheet
Dim targetSheet As Worksheet

Set Adspend = ActiveWorkbook

Application.ScreenUpdating = False
Application.DisplayAlerts = False

'Specify data export file

A = Application.GetOpenFilename(Title:="Select File To Be Processed")
Set Amazon = Application.Workbooks.Open(A)

counter = 2

' While Not Amazon.Worksheets(1).Range("D" & counter) = ""

     If Amazon.Worksheets(1).Range("D" & counter) = "B01GB3HZ34" Then

        Set targetSheet = Adspend.Worksheets("DirtyDom")
        Set sourceSheet = Amazon.Worksheets(1)

        LastRow = Adspend.Worksheets("DirtyDom").Cells(Adspend.Worksheets("DirtyDom").Rows.Count, "F").End(xlUp).Row

        targetSheet.Range("F" & LastRow).Value = sourceSheet.Range("D" & counter).Value

     Else

        LastRow = Adspend.Worksheets("DirtyDom").Cells(Adspend.Worksheets("DirtyDom").Rows.Count, "F").End(xlUp).Row
        targetSheet.Range("F" & LastRow).Value = sourceSheet.Range("D4").Value

    End If

  '   ActiveCell.Offset(1, 0).Active

' Wend
Amazon.Close

End Sub

I expect this bit of code to paste what is in the imported file's first sheet cell D1 into the sheet called DirtyDom in cell F1 since 1 is the first cell blank in column F.

I get the error Object variable or With block variable not set.

Thank you!

Body:
Try something like this, it also puts your loop back in and resets your screen updating and alerts - untested.

Sub GetAmazonData()

Dim Adspend As Workbook
Dim Amazon As Workbook
Dim Targetsheet As Worksheet
Dim Amazonsheet As Worksheet
Dim Amazonfilename As String
Dim lastAmazonrow As Long
Dim lastTargetrow As Long

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Set Adspend = ActiveWorkbook
    Set Targetsheet = Adspend.Worksheets("DirtyDom")

    'Specify data export file
    Amazonfilename = Application.GetOpenFilename(Title:="Select File To Be Processed")
    Set Amazon = Application.Workbooks.Open(Amazonfilename)
    Set Amazonsheet = Amazon.Worksheets(1)

    lastAmazonrow = Amazonsheet.Cells(Amazonsheet.Rows.Count, "D").End(xlUp).Row
    lastTargetrow = Targetsheet.Cells(Targetsheet.Rows.Count, "F").End(xlUp).Row + 1

    For counter = 1 To lastAmazonrow
        If Amazonsheet.Range("D" & counter) = "B01GB3HZ34" Then
            Targetsheet.Range("F" & lastTargetrow).Value = Amazonsheet.Range("D" & counter).Value
        Else
            Targetsheet.Range("F" & lastTargetrow).Value = Amazonsheet.Range("D4").Value
        End If

        lastTargetrow = lastTargetrow + 1
    Next i
    Amazon.Close

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub


问:
Convert date and time to only year in php
I have a variable is which the value coming is Date along with time in php. How do I convert it into a variable to get only the year? I do not need automatic updation but the format change is needed. Normal answers are giving it about date but my variable is containing time as well. </p>

```<code>The format coming by now is 2017-12-11 4:06:37 and i need only 2017
</code>```

答:
You can code like this (working perfectly):</p>

```<code>$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y') . "\n";
</code>```

Body:
I have a variable is which the value coming is Date along with time in php. How do I convert it into a variable to get only the year? I do not need automatic updation but the format change is needed. Normal answers are giving it about date but my variable is containing time as well.

The format coming by now is 2017-12-11 4:06:37 and i need only 2017

Body:
You can code like this (working perfectly):

$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y') . "\n";


问:
Do you need to call CoInitialize() when using Direct3D9?
My understanding was since D3D is using COM, the answer is yes. But in the Ogre rendering engine, it appears this is never called. Is this fine or an oversight - if so could it have some actual consequences?</p>

答: It is not.  You don't use CoCreateInstance(), the interface types are not declared in IDL, you have to link to a .lib</p>


答:
You can you simple DateTime function and date_formate() function for displaying separate year, month and date.

For that you have to first convert in Object of your current Date time string by using :

```<code>$date = new \DateTime('2017-12-11 4:06:37');
</code>```

And then you can use date format function by using below code:

```<code>echo date_format($date, "Y"); //for Display Year
echo date_format($date, "m"); //for Display Month
echo date_format($date, "d"); //for Display Date
</code>```

Body:
You can you simple DateTime function and date_formate() function for displaying separate year, month and date.

For that you have to first convert in Object of your current Date time string by using :

$date = new \DateTime('2017-12-11 4:06:37');

And then you can use date format function by using below code:

echo date_format($date, "Y"); //for Display Year
echo date_format($date, "m"); //for Display Month
echo date_format($date, "d"); //for Display Date


问:
Android app Keystore password reset
How to reset Keystore password for android. I can't update application on play store.
How to resolve this problem?
When I tried to update the application with the new key then play store rejected it.
I have the old Keystore file but the password is not accepting.

答:
I use this one for bruteforce at the moment: Android keystore password recover

There are 3 Methods to recover your keystore password:

```<code>- Simply Bruteforce
- Dictionary Attack
- Smart Wordlist Attack
</code>```

https://code.google.com/archive/p/android-keystore-password-recover/

Useful links:

http://www.icaninfotech.com/android-keystore-password-recovery/

https://discuss.kotlinlang.org/t/forgot-android-alias-key-password/1873

https://www.codeproject.com/Questions/1094759/Reset-keystore-password-without-entering-old-passw

Hope this works.

Title: Android app Keystore password reset

Body:
I use this one for bruteforce at the moment: Android keystore password recover

There are 3 Methods to recover your keystore password:

- Simply Bruteforce
- Dictionary Attack
- Smart Wordlist Attack

https://code.google.com/archive/p/android-keystore-password-recover/

Useful links:

http://www.icaninfotech.com/android-keystore-password-recovery/

https://discuss.kotlinlang.org/t/forgot-android-alias-key-password/1873

https://www.codeproject.com/Questions/1094759/Reset-keystore-password-without-entering-old-passw

Hope this works.