text:
Q: Bottom Share Sheet in Android When sharing data in an Android application I have seen multiple applications use a bottom sheet (Google I/O 2015 for ex.) to indicate apps to perform an action rather than the standard dialog which includes apps to handle your intent.
For example:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TITLE, "Some title..");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Some text");
startActivity(Intent.createChooser(shareIntent, "Share via.."));

does not do the trick since the OS version picks the display of the chooser.
Any way to change this code to get the Share Bottom sheet per the material design https://www.google.com/design/spec/components/bottom-sheets.html#bottom-sheets-content
Does anyone know of third party libraries to do just this on older API versions?
I have found https://github.com/soarcn/BottomSheet
but this only lets me create a menu from the bottom sheet. I guess in reality, i can lookup all the apps that can perform the action I am trying to do and manually add Menu Items on top of this library, but i was hoping for something a little simpler since it is not a deal breaking feature.

A: Our BottomSheet implementation has a commons component you can use that lets you specify an intent/filter/etc for the sheet and it will behave fairly similarly to the system version on Lollipop
https://github.com/flipboard/bottomsheet

A: I used a combination of the two answers above: Using the built in Bottom Sheet in M+ and https://github.com/flipboard/bottomsheet for API levels below M.
I prefer the built in Bottom Sheet that Android provides with the share intent because it slides in partially then the user can slide it all the way up.  The third party Bottom Sheet library provides backwards compatibility without having to roll your own so you can drop it in quickly.  However, I prefer the built in.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  Intent sendIntent = new Intent();
  sendIntent.setAction(Intent.ACTION_SEND);
  sendIntent.putExtra(Intent.EXTRA_TEXT, "Content");
  sendIntent.setType("text/plain");
  this.startActivity(sendIntent);
}else {
  Intent intent = new Intent(Intent.ACTION_SEND);
  intent.setType("text/*");
  intent.putExtra(Intent.EXTRA_TEXT, "Content");
  BottomSheet share = BottomSheet.createShareBottomSheet(MainActivity.this, intent, "Title");
  share.show();
}

A: Here is that same exact bottom sheet on a Nexus 5 running Android 6.0.
This may be different on older or modified versions of Android. (i.e. Samsung Devices etc)

Code
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Check out this dope website! - https://mikemiller.design/"); // Simple text and URL to share
sendIntent.setType("text/plain");
this.startActivity(sendIntent);

Result

A: If someone is looking for a Kotlin implementation
val shareIntent = Intent(Intent.ACTION_SEND).apply {
    type = "text/plain"
    putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name))
    val shareMessage = "The message you want to sent with this."
    putExtra(Intent.EXTRA_TEXT, shareMessage)
}
startActivity(Intent.createChooser(shareIntent, "Select app to share with"))


text:
Q: NativeCrypto.SSL_write() hangs intermittently in Android I am trying to upload photos to a web service from an Android app. I'm using the third-party library Retrofit to interact with the service.
I'm using a TypedByteArray as the body of my request, like so:
        String contentType = String.format(Locale.US, "multipart/form-data; boundary=%s", BOUNDARY);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        StringBuilder prefix = new StringBuilder();
        prefix.append("--").append(BOUNDARY).append("\r\n");
        prefix.append("Content-Disposition: form-data; name=\"rawimage\"; filename=\"picture.jpg\"\r\n");
        prefix.append("Content-Type: image/jpg\r\n\r\n");
        byte[] buffer = prefix.toString().getBytes("UTF-8");
        os.write(buffer);

        boolean success = bitmap.compress(CompressFormat.JPEG, 50, os);

        if (!success) {
            Log.e(LOG_TAG, "Could not write image to request");
        }

        String suffix = String.format(Locale.US, "\r\n--%s--\r\n", BOUNDARY);
        buffer = suffix.getBytes("UTF-8");
        os.write(buffer);

        byte[] body = os.toByteArray();

        TypedByteArray myBody = new TypedByteArray(contentType, body);

And the upload method interface looks like this:
    @POST("/image/upload")
    @Headers("Accept-Version: 2.0.0")
    void uploadRawImage(@Body TypedByteArray body, Callback<String> callback);

Sometimes this works, and sometimes it doesn't. I haven't been able to identify the pattern. It doesn't seem to be related to the specific image I try to upload, since has worked and failed with the same image. When it fails, I never get any response back, because the Retrofit request thread just hangs with the stack:
NativeCrypto.SSL_write(long, FileDescriptor, NativeCrypto$SSLHandshakeCallbacks, byte[], int, int, int) line: not available [native method]
OpenSSLSocketImpl$SSLOutputStream.write(byte[], int, int) line: 728
FixedLengthOutputStream.write(byte[], int, int) line: 41
FixedLengthOutputStream(OutputStream).write(byte[]) line: 82
TypedByteArray.writeTo(OutputStream) line: 66
UrlConnectionClient.prepareRequest(HttpURLConnection, Request) line: 89
UrlConnectionClient.execute(Request) line: 48
...

This is driving me absolutely mad. If anyone has any ideas what could be wrong, or how to fix it, please help!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to generate and store correlative numbers in django I'm working with ldapdb for django. When adding I must generate an uid number for the new entry. For that, I want to know how to store a correlative number in my database (or somewhere else) since django manages my database automatically. Thus, I have a correlative in 300, the new uid would be 301 and I would do something like employee.uid = 301.
@login_required
def add(request):
    if request.method == 'POST':
        form = EmployeeForm(request.POST)
        if form.is_valid():
            employee = form.save(commit=False)
            '''for property, value in vars(employee).iteritems():
                print property, ": ", value'''
            employee.dn = ''

            employee.photo = None
            employee.save()
            return HttpResponseRedirect('/employees/')
        else:
            messages.error(request,'Damn!!!')
    else:
        form = EmployeeForm()
    return render(request, 'employees/detail.htm', {'form':form, 'action': 'add'})

A: uid doesn't serial number feel free to use md5 hash or something else. But if you want get next serial number just get all objects at the table and pass this list to len function, I dont know django ORM good but I think this is a must like
len(models.employes.all()) + 1


text:
Q: SharePoint As Network Shared Drive: How To Get Users To Use SharePoint as SharePoint We're facing a problem where users aren't using SharePoint as SharePoint - they get a site, then they use explorer view to drag a bunch of folders/ files into "Shared Documents", they add a few people and that's it. No usage of Calendars, metadata, discussion boards, workflows, etc. In essence, they receive no benefit over using a network drive.
We've tried to combat this by:

*

*Making potential site owners watch tutorials and complete practical
tests to make sure they can use metadata, etc.

*Creating a tutorials site with a lot of video tutorials (>100) accessible to everyone, as well as podcasts etc.

*Offering SharePoint education sessions: quick lunch and learns as well as involved full
afternoon courses

*Establishing governance on how SharePoint is to be used (collaborative environment, 'living' documents, etc).

*Periodically trimming (deleting or archiving) old content

Try as we might, there are many, many people who just pump 'n dump some documents in via Explorer View and don't use any other aspect of SharePoint.
You can lead a horse to water, but you can't get them to drink. How are you getting your horses to drink? (The SharePoint Kool-aid)

A: Your focus shouldn't be on getting people to use SharePoint as SharePoint, because the goal shouldn't be to use SharePoint.
Instead the focus should be on helping the users getting their business problems solved. Some of these problems may be solved by using SharePoint as SharePoint in which case they should have help doing that. If you keep focusing on helping the users solve their problems and hopefully are able to show them that a lot of it can be done by using SharePoint, then at some point some of them may start wanting to explore/extend SharePoint themselves, at that point you should be ready to give the guidance and help.

A: Here are some other ideas you can use to increase SharePoint usage:
0)  Force the users home page to go to the portal via group policy (you will see why below)
1)  If you can get upper management to use it, then the rest of the crowd will be more willing to use it:  See if you can convince upper management to use an Announcement list that goes out to everyone's email instead of a direct email employees.  Put this announcement on the portal home page.  Everyone will see the announcements because of step 0 and once this happens over time, they will grow accustomed to this.
2)  On this same home page - talk to the human resources and public affairs people to keep fresh pictures of employees or local org events on this page.  Sometimes an employee of the month, or employee spotlight.  Highlight people doing good things in your organization and keep the content fresh.  Ask managers to highlight the people doing good things and getting recognition among their peers.  Change the story every week or so.  People will read this because if step 0 and you will have a backlog of stories because everyone wants their people to be on the front page.
3)  Get your portal site structure and global navigation to mimic your organizations org chart.  The closer you can do this, the more sense your site will make to people and they will start navigating to other areas and checking out content.  Keep on top of this every month - users hate to see stale links or an old group name.  Don't be afraid to archive content that isn't used anymore and get rid of the old names.  Because of step 0, they will likely want to see what is new areas of the organization they care about.
4) Take advantage of the social pieces :  presence, My Sites.  If they are forced to go there with step 0 - they will see who else is there or was there recently.  You can make a nice knowledge base of employee skills with the My Sites.  Also with correct clean active directory, you can have your employee org chart display on the my sites pages.  Pass the digital camera around and make everyone put their picture up.  The helps people put faces with names.
5) There are ways to change desktops to search SharePoint using connectors.  The more people search your portal, the more they will find on it and return to it in the future.  http://technet.microsoft.com/en-us/library/ff899315.aspx
By forcing them to go to the portal throughout the day (searches, browser home page, notes from management) and keeping the content fresh and relevant, the users will get used to going back and eventually will contribute to the kool aid party.
Hope this helps.

A: As Per Jakobsen said, you should advertise SharePoint as their answer to the business problems. But furthermore, find ways that will make SharePoint look attractive by showing them that SharePoint can centralize data, keep it safe and cost effective, and easy to use.
You don't want to wow them with all the features SharePoint has to offer until you connect with them on how they can use it. Most users won't see the connecting dots until you explain how to connect them. Don't tell them what SharePoint can add for them, but tell them what SharePoint can solve or simplify specific business processes.
What has worked for our company is designate SharePoint delegates that act as SharePoint content owners in each department/division, that will help others to get on board. Train them fully and get them excited about SharePoint. They might see a problem that SharePoint can solve better because they will know how the dept does its process.
Have you established a successful navigation tree?

A: Oooops, guys, are you serious in discussing how to hate IT and and IT-related professions?
It is not the IT personnel that invent unwarranted and unasked things and impose how to make happy others, it is managers on the basis of business analysis (with the help biz analysts) and underlying biz processes and discovered necessities  decide what IT workers should implement and support as well as stipulate what their subordinates use.


text:
Q: Объединение строк разных столбцов
К примеру, имеем такой DataFrame. Можно ли с помощью внутренних методов объединить состав заказов, если дата покупки совпадает?
my_df = pd.DataFrame({'Дата заказа № 1': ['10.02.19', '09.11.19', '15.01.19'],
 'Состав заказа № 1': ['рыба', 'бананы', 'гречка'],
 'Дата заказа № 2': ['11.02.19', '09.11.19', '21.02.19'],
 'Состав заказа № 2': ['fish', 'beans', 'bread'],
 'Дата заказа № 3': ['01.12.19', '09.11.19', '25.03.19'],
 'Состав заказа № 3': ['конфеты', 'мёд', 'молоко'],
 'Дата заказа № 4': ['01.12.19', '12.11.19', '27.05.19'],
 'Состав заказа № 4': ['овощи', 'макароны', 'птица'],
 'Дата заказа № 5': ['01.12.19', '12.11.19', '25.09.19'],
 'Состав заказа № 5': ['мясо', 'фасоль', 'хлеб']},
 columns=['Дата заказа № 1', 'Состав заказа № 1','Дата заказа № 2', 'Состав заказа № 2','Дата заказа № 3', 'Состав заказа № 3','Дата заказа № 4', 'Состав заказа № 4','Дата заказа № 5', 'Состав заказа № 5'])'

По-хорошему, мне надо получить лист листов с заказами:
my_list=[['рыба'], ['fish'], ['конфеты','овощи','мясо'], ['бананы', 'beans', 'мёд'], ['макароны', 'фасоль'], ['гречка'], ['bread'], ['молоко'], ['птица'], ['хлеб']]

Но я пришёл к выводу (возможно, ошибочному), что проще сначала объединить заказы в самом фрейме данных, а уже потом "выцепить" их циклом.
Ориентировочно, хотелось бы получить такой фрейм, но итоговый результат может и отличаться от приведенного ниже: для меня достаточно объединить заказы одной даты в одну строчку:

A: Работать с данными в таком (широком) формате очень неудобно. Лучше сделать UNPIVOT и получить фрейм с двумя столбцами Date и Item - с таким форматом работать будет гораздо проще:
df.columns = df.columns.str.replace("\s*№.*$", "", regex=True)
t = pd.DataFrame({
    "Date": df.loc[:, "Дата заказа"].stack().reset_index()[0],
    "Item": df.loc[:, "Состав заказа"].stack().reset_index()[0]
})

промежуточный результат:
In [214]: t
Out[214]:
        Date      Item
0   10.02.19      рыба
1   11.02.19      fish
2   01.12.19   конфеты
3   01.12.19     овощи
4   01.12.19      мясо
5   09.11.19    бананы
6   09.11.19     beans
7   09.11.19       мёд
8   12.11.19  макароны
9   12.11.19    фасоль
10  15.01.19    гречка
11  21.02.19     bread
12  25.03.19    молоко
13  27.05.19     птица
14  25.09.19      хлеб

теперь эти данные можно легко сгруппировать:
res = t.groupby("Date")["Item"].apply(list).reset_index()

результат:
In [216]: res
Out[216]:
       Date                    Item
0  01.12.19  [конфеты, овощи, мясо]
1  09.11.19    [бананы, beans, мёд]
2  10.02.19                  [рыба]
3  11.02.19                  [fish]
4  12.11.19      [макароны, фасоль]
5  15.01.19                [гречка]
6  21.02.19                 [bread]
7  25.03.19                [молоко]
8  25.09.19                  [хлеб]
9  27.05.19                 [птица]


text:
Q: Android selector item precedence My question is wether in Android you can have a selector item have precedence over another. I'm having the problem that the last item is being selected over the second item. In my code I use a listView and in both onItemClick and LongItemClick I have coded view.setHovered(true); which works only when the view is not activated. If it's activated @color/black is used instead of @color/white. Thanks in advance!
<item android:state_activated="false" android:state_hovered="false" android:color="@color/gray_light"/>
<item android:state_hovered="true" android:color="@color/white"/>
<item android:state_activated="true" android:state_hovered="false" android:color="@color/black"/>

Edit1: Maybe this is the problem: Does it matter in which order v.setActivated / v.setHovered is called?
Edit2: I've put all v.setHovered(true) calls after v.setActivated(true) calls but it still chooses @color/black.

A: Change the order. As stated by the API guide

During each state change, the state list is traversed top to bottom and the first item that  matches the current state is used—the selection is not based on the "best match," but simply the first item that meets the minimum criteria of the state.


text:
Q: How can I use google or-tools in ruby for my rails app? I need to solve tsp problem in my rails application.
I want to use google or-tools for solving this problem of tsp.
The documentation1 tells about using or-tools in c++, c#, java and python.
The code for solving tsp using or-tools in python is working fine.
But I need to use or-tools in ruby for my rails app.
How can I do this?

A: or-tools uses SWIG to wrap it for those other languages.  You could probably reuse the code for Ruby.  A few classes are probably easy, the whole API probably non-trivial.
Otherwise you could go through one of the supported languages -With jruby for example.


text:
Q: PostgreSQL: Returning the most recent rows grouping by a foreign key column I have a table that looks similar to this:
credit
+---------+----------------+-------------+--------------+-------------------------+
| id (PK) | person_id (FK) | transaction | total credit |        date_time        |
+---------+----------------+-------------+--------------+-------------------------+
|     345 |              1 |       -1.00 |        34.50 | 2018-08-29 12:00:00.000 |
|     897 |              1 |        5.45 |        39.95 | 2018-08-29 12:34:00.000 |
|     378 |              2 |        0.01 |         0.01 | 2018-08-29 08:00:00.000 |
|     789 |              2 |       20.00 |        20.01 | 2018-08-29 09:00:00.000 |
+---------+----------------+-------------+--------------+-------------------------+

How would I write a query in Postgres to return only the most recent (by date_time DESC) row grouped by each unique person_id in the table, like this?
+---------+----------------+-------------+--------------+-------------------------+
| id (PK) | person_id (FK) | transaction | total credit |        date_time        |
+---------+----------------+-------------+--------------+-------------------------+
|     897 |              1 |        5.45 |        39.95 | 2018-08-29 12:34:00.000 |
|     789 |              2 |       20.00 |        20.01 | 2018-08-29 09:00:00.000 |
+---------+----------------+-------------+--------------+-------------------------+

A: You can try this.
use ROW_NUMBER with window function to make row number split by person_id  and order by date_time  in subquery then get row number is 1
CREATE TABLE credit(
   id int,
   person_id int,
   transaction float,
   "total credit" float,
   date_time timestamp
);

INSERT INTO credit values (345,1 ,-1.00,34.50, '2018-08-29 12:00:00.000');
INSERT INTO credit values (897,1 ,5.45 ,39.95, '2018-08-29 12:34:00.000');
INSERT INTO credit values (378,2 ,0.01 ,0.01 , '2018-08-29 08:00:00.000');
INSERT INTO credit values (789,2 ,20.00,20.01, '2018-08-29 09:00:00.000');

Query 1:
SELECT * FROM (
    SELECT *,ROW_NUMBER() OVER (PARTITION BY person_id  ORDER BY date_time DESC) rn
    FROM credit
) t1
where rn = 1

Results:
|  id | person_id | transaction | total credit |            date_time | rn |
|-----|-----------|-------------|--------------|----------------------|----|
| 897 |         1 |        5.45 |        39.95 | 2018-08-29T12:34:00Z |  1 |
| 789 |         2 |          20 |        20.01 | 2018-08-29T09:00:00Z |  1 |

A: Use distinct on:
select distinct on (person_id) t.*
from t
order by person_id, date_time desc


text:
Q: Leetcode--3 find the longest substring without repeating character The target is simple--find the longest substring without repeating characters,here is the code:
 class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int ans = 0;
        int dic[256];
        memset(dic, -1, sizeof(dic));
        int len = s.size();
        int idx = -1;

        for (int i = 0;i < len;i++) {
            char c = s[i];
            if (dic[c] > idx)
                idx = dic[c];

            ans = max(ans, i - idx);

            dic[c] = i;
        }
        return ans;
    }

};

From its concise expression,I think this is a high-performance method,and we can get that its Time Complexity is just O(n).But I'm confused about this method,though I came up with some examples to understand,can anyone give some tips or idea to me?

A: What it is doing is recording the position where each character was last seen.
As you step through, it takes each new encountered character and the length of non-repeat goes back at least as far as that last-seen, but for future indices can't go back further, as we have now seen a duplicate.
So we are maintaining in idx, the start index of the latest-seen highest-starting duplicate, which is the candidate for the start of the longest non-duplicating sequence.
I'm certain that the ans = max() code code be optimised slightly, as after encountering a new duplicate, you have to go forward at least ans chars from the start of that duplicate before ans can be improved again. You still need to do the rest of the work maintaining dic and idx, but you could avoid that particular test for ans for a few iterations. You would have to do a lot of unrolling to benefit, though.


text:
Q: List of error cases in use _userManager.CreateAsync(user, password) UserManager.CreateAsync Method (TUser, String) doesn't mention about errors.
In controller, I jsut edit something like:
public async Task<ObjectResult> Register(RegisterViewModel model, string returnUrl = null)
{
    IDictionary<string, object> value = new Dictionary<string, object>();
    value["Success"] = false;
    value["ReturnUrl"] = returnUrl;

    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { Id = Guid.NewGuid().ToString(), UserName = model.Email, Email = model.Email };

        var result = await _userManager.CreateAsync(user, model.Password);

        if (result.Succeeded)
        {
            await _signInManager.SignInAsync(user, isPersistent: false);
            value["Success"] = true;
        }
        else
        {
            value["ErrorMessage"] = result.Errors;
        }
    }

    return new ObjectResult(value);
}

In client:
$scope.registerForm_submit = function ($event, account) {
    $event.preventDefault();

    if (registerForm.isValid(account)) {

        // registerForm.collectData returns new FormData() which contains
        // email, password, confirmpassword, agreement, returnurl...

        let formData = registerForm.collectData(account),
            xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function () {
            if (xhttp.readyState === XMLHttpRequest.DONE) {
                let data = JSON.parse(xhttp.responseText);

                if (data['Success']) {
                    window.location = '/'
                } else {
                    if (data['ErrorMessage'][0]['code'] === 'DuplicateUserName') {
                        let li = angular.element('<li/>').text(`Email ${account['email']} already exists.`);
                        angular.element('div[data-valmsg-summary=true] ul').html(li);
                    }
                }
            }
        }

        xhttp.open('POST', '/account/register');
        xhttp.send(formData);
    }
};

I've tried to register new account with an existing email and got the code:
data['ErrorMessage'][0]['code'] === 'DuplicateUserName'

My question: how to check other cases?

A: The error codes defined in ASP.NET Identity are found at https://aspnetidentity.codeplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.Core/Resources.Designer.cs - I've extracted them out to this list:

*

*DefaultError

*DuplicateEmail

*DuplicateName

*ExternalLoginExists

*InvalidEmail

*InvalidToken

*InvalidUserName

*LockoutNotEnabled

*NoTokenProvider

*NoTwoFactorProvider

*PasswordMismatch

*PasswordRequireDigit

*PasswordRequireLower

*PasswordRequireNonLetterOrDigit

*PasswordRequireUpper

*PasswordTooShort

*PropertyTooShort

*RoleNotFound

*StoreNotIQueryableRoleStore

*StoreNotIQueryableUserStore

*StoreNotIUserClaimStore

*StoreNotIUserConfirmationStore

*StoreNotIUserEmailStore

*StoreNotIUserLockoutStore

*StoreNotIUserLoginStore

*StoreNotIUserPasswordStore

*StoreNotIUserPhoneNumberStore

*StoreNotIUserRoleStore

*StoreNotIUserSecurityStampStore

*StoreNotIUserTwoFactorStore

*UserAlreadyHasPassword

*UserAlreadyInRole

*UserIdNotFound

*UserNameNotFound

*UserNotInRole

ASP.NET Core Identity has these codes defined:

*

*DefaultError

*ConcurrencyFailure

*PasswordMismatch

*InvalidToken

*LoginAlreadyAssociated

*InvalidUserName

*InvalidEmail

*DuplicateUserName

*DuplicateEmail

*InvalidRoleName

*DuplicateRoleName

*UserAlreadyHasPassword

*UserLockoutNotEnabled

*UserAlreadyInRole

*UserNotInRole

*PasswordTooShort

*PasswordRequiresNonAlphanumeric

*PasswordRequiresDigit

*PasswordRequiresLower

*PasswordRequiresUpper

So, it's possible that not all of the former error codes will actually show up in an IdentityResult. I don't use either, so this is just what I gather from skimming the available source code. Caveat emptor...
Seems like this should be documented somewhere...
I like to have strings of this nature defined in one place, so I typically do something like:
public class IdentityErrorCodes
{
    public const string DefaultError                    = "DefaultError";
    public const string ConcurrencyFailure              = "ConcurrencyFailure";
    public const string PasswordMismatch                = "PasswordMismatch";
    public const string InvalidToken                    = "InvalidToken";
    public const string LoginAlreadyAssociated          = "LoginAlreadyAssociated";
    public const string InvalidUserName                 = "InvalidUserName";
    public const string InvalidEmail                    = "InvalidEmail";
    public const string DuplicateUserName               = "DuplicateUserName";
    public const string DuplicateEmail                  = "DuplicateEmail";
    public const string InvalidRoleName                 = "InvalidRoleName";
    public const string DuplicateRoleName               = "DuplicateRoleName";
    public const string UserAlreadyHasPassword          = "UserAlreadyHasPassword";
    public const string UserLockoutNotEnabled           = "UserLockoutNotEnabled";
    public const string UserAlreadyInRole               = "UserAlreadyInRole";
    public const string UserNotInRole                   = "UserNotInRole";
    public const string PasswordTooShort                = "PasswordTooShort";
    public const string PasswordRequiresNonAlphanumeric = "PasswordRequiresNonAlphanumeric";
    public const string PasswordRequiresDigit           = "PasswordRequiresDigit";
    public const string PasswordRequiresLower           = "PasswordRequiresLower";
    public const string PasswordRequiresUpper           = "PasswordRequiresUpper";

    public static string[] All = {
        DefaultError,
        ConcurrencyFailure,
        PasswordMismatch,
        InvalidToken,
        LoginAlreadyAssociated,
        InvalidUserName,
        InvalidEmail,
        DuplicateUserName,
        DuplicateEmail,
        InvalidRoleName,
        DuplicateRoleName,
        UserAlreadyHasPassword,
        UserLockoutNotEnabled,
        UserAlreadyInRole,
        UserNotInRole,
        PasswordTooShort,
        PasswordRequiresNonAlphanumeric,
        PasswordRequiresDigit,
        PasswordRequiresLower,
        PasswordRequiresUpper
    };
}

This lets you be consistent in the keys you're using as lookups, and the last field, All, gives you an array you can enumerate through, if necessary.
Using your code, you can do this:
if(data['ErrorMessage'][0]['code'] == IdentityErrorCodes.DuplicateUserName)
{
}

And so on.

A: For ASP.NET Core you can find the different error types in the IdentityErrorDescriber class under the namespace Microsoft.AspNetCore.Identity.
As you can see, the error codes are generated via nameof(), e.g:
Code = nameof(DuplicateUserName)

So you could also use that for your cases:
data['ErrorMessage'][0]['code'] == nameof(IdentityErrorDescriber.DuplicateUserName)

This way you don't have to curate a list of error codes as suggested in another answer to your question.


text:
Q: Google Code Prettify has been officially discontinued; it's time for SE to maintain their own highlighter On April 21, 2020, Google announced that their Prettify syntax highlighter, that Stack Exchange uses, has been discontinued and is no longer being maintained. The repository has been marked read-only as well.
As such, no more languages will be added to the highlighter, and existing bugs with the highlighter will no longer be fixed.
Now that this highlighter is officially deprecated and no longer maintained, can Stack Exchange please either switch to another highlighter that is being maintained, or begin maintaining their own highlighter (possibly a fork of Prettify)?
In my opinion, the best thing to do would be to begin maintaining the syntax highlighter internally. This way, bugs and feature requests with it can be filed and tracked on meta sites, and changes to it can be made more quickly. Under the old system, bugs with it would take a long time to be resolved (since it was only maintained by random people on occasion), and when they were, it would take a lot of time for it for SE to eventually handle a feature request to deploy an updated version. The whole process would be drawn out and take 6-8 months-years. (As a matter of fact, I filed an issue with it back in 2014 and it still hadn't been resolved as of the discontinuation date.)
The best way to handle this would be to make an internal fork of Prettify, and start off with that.
I noticed some people would prefer using Highlight.js, which is actively maintained, but a prior request to change to that highlighter was declined for performance reasons.
This is not a duplicate of google-code-prettify seems dead since that was back in 2014 and the project simply languished (as opposed to being officially discontinued), and a few months after that question was posted, the project was back in action. However, that can't happen as the repository has been marked read-only, and probably won't happen anyway due to the official discontinuation.

To address animuson's comment:

I imagine that someone is simply going to fork this away and maintain it separately. To be clear: that hasn't been maintained by Google in many years. It was maintained by regular users who wanted to contribute to it and make it better. Nothing is stopping them from doing it somewhere else. [...] Some random Google employee archiving it doesn't break anything.

With the repository's archival, there is no longer a centralized effort to maintain the highlighter. It's quite possible that newer fixes might just end up in several independent forks that would have to be manually merged by SE.

A: We've officially switched to highlight.js network-wide. See the announcement post for more details.

A: Why not use the same stack as the one used by GitHub flavored markdown?
According to GitHub doc they use Linguist as language detector, which has a pretty long list of supported languages.


text:
Q: Submit PHP form with 6000 rows data Actually I have a form which is taking approx 6000 data and when i submit to insert these 6000 rows for insert into mySq-DB then its taking much time and most of time its get hanged.
Note : Rows Are Created By Excel Upload And After Upload Of Excel Its Created Rows(6000) On PHP Script (view) Page. And after that we click on submit button to store these rows data into my mysql-DB.
My PHP/HTML Page Contains:
prod_id prod_name prod_sku  Created_on  Created_by  Modified_on Modified_by
  1     Samsung   XYZ       2015-07-17    1         2015-08-18    1
  2     Micromax  ABC       2015-07-17    1         2015-08-18    1
  3     HTC Des   PQR       2015-07-17    4         2015-08-18    4
  4     HTC FLY   MVC       2015-07-17    44        2015-08-18    44
  5     LG G2     UVW       2015-07-17    66        2015-08-18    66
  6     LG G4     XYZ       2015-07-17    22        2015-08-18    22
  7     Sony      LMN       2015-07-17    44        2015-08-18    44
  8     Dell      DEF       2015-07-17    1         2015-08-18    1

Image for Excel

A: For loading huge amounts of data into MySQL, LOAD DATA INFILE is by far the fastest option.
[Approx- 40,000 Rows]
First, convert your Excel file into a CSV.
These steps can be used to emulate this functionality:

*

*Create a new temporary table.
CREATE TEMPORARY TABLE temporary_table LIKE target_table;

*Optionally, drop all indices from the temporary table to speed things up.
SHOW INDEX FROM temporary_table;
DROP INDEX `PRIMARY` ON temporary_table;
DROP INDEX `some_other_index` ON temporary_table;

*Load the CSV into the temporary table
LOAD DATA INFILE 'your_file.csv'
INTO TABLE temporary_table
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
(field1, field2);

*Copy the data using ON DUPLICATE KEY UPDATE
SHOW COLUMNS FROM target_table;
INSERT INTO target_table
SELECT * FROM temporary_table
ON DUPLICATE KEY UPDATE field1 = VALUES(field1), field2 = VALUES(field2);

*Remove the temporary table
DROP TEMPORARY TABLE temporary_table;

Using SHOW INDEX FROM and SHOW COLUMNS FROM this process can be automated for any given table.


text:
Q: How do I create a component by reference? Suppose I have:
import MyComponent from "../somewhere"

I can create an instance of it by doing:
<MyComponent myprops={myprops} />

But can I create one programmatically from MyComponent and add props?

For example, I have a list of component references:
import comp1 from "somewhere"
import comp2 from "somewhere"
import comp3 from "somewhere"

var myComponents = [
    comp1, comp2, comp3
];

And now I have to take one of them and put in the view:
var randomComponent = myComponents[Math.random() * 3 | 0];

// render
render(){
    return randomComponent; // this doesn't work and certain props have to be added
}

Is there a way to avoid doing the following and achieve the same?
var myComponents = [
    <comp1 props=... />, <comp2 props=... />, <comp3 props=... />
];

A: You can do the following:
var RandomComponent = myComponents[Math.random() * 3 | 0];

render() {
    return <RandomComponent props={foobar} />;
}

The above is demonstrated at the React Docs where the following is mentioned:

You cannot use a general expression as the React element type. If you do want to use a general expression to indicate the type of the element, just assign it to a capitalized variable first. (emphasis mine)

The reason why the component's name must be capitalized is because it will be treated as a built-in component (DOM component) if not. This works because it's just transpiled into this:
React.createElement(RandomComponent, { props: foobar });

And RandomComponent still refers to a random selected component. If randomComponent is not capitalized, you can just do it without JSX like so:
React.createElement(randomComponent, { props: foobar });

You just won't be able to do it with JSX because randomComponent is lowercase and will incidentally be transpiled into this:
React.createElement("randomComponent", { props: foobar });

Which is problematic as "randomComponent" does not refer to randomComponent.

A: see Create react component dynamically
var component = myComponents[Math.random()*3 |0];
return React.createElement(component, props);

A: Thought I would share. I had a very specific use case for this using imported svg files, but I believe this would work with components as well. I wanted to have a button component that would load different svg icons given a prop type.
import LightBulb from '../my-icons/Lightbulb.svg';

const ICON_TYPES = {
  LightBulb: 'LightBulb',
};

const ICON_TYPE_FILES = {
  [ICON_TYPES.LightBulb]: LightBulb,
};

export default function IconButton({iconType}) {
  const IconComponent = ICON_TYPE_FILES[iconType];
  return (
    <Icon>
      <IconComponent />
    </Icon>
   );
};
IconButton.ICON_TYPES = ICON_TYPES

Using component:
<IconButton
  iconType={IconButton.ICON_TYPES.LightBulb}
/>


text:
Q: I2C setting MCU as both slave and master at the same time Hello everyone I'm working on a new project with the TI MSP432P401R microcontroller. I want to have 2 separate I2C buses. I2C bus 1 will set the MCU as the master, whereas the DAC and the pressure sensor as slaves. Then I2C bus 2 will set the same MCU as the slave, and the SmartPort as the master (more specifically a device that we connect to the SmartPort will be the master). I'm not sure how can I make the MCU both a slave and a master at the same time. What I tried to do was, I defined 2 different eUSCI_b modules
void I2C_init(void)
{
/* Initialize USCI_B3 and I2C Master to communicate with slave devices*/
I2C_initMaster(EUSCI_B3_BASE, &i2cConfig);

/* Disable I2C module to make changes */
I2C_disableModule(EUSCI_B3_BASE);

/* Enable I2C Module to start operations */
I2C_enableModule(EUSCI_B3_BASE);

/* Initialize USCI_B3 and I2C Master to communicate with slave devices*/
I2C_initMaster(EUSCI_B0_BASE, &i2cConfig);

/* Disable I2C module to make changes */
I2C_disableModule(EUSCI_B0_BASE);

/* Enable I2C Module to start operations */
I2C_enableModule(EUSCI_B0_BASE);

return;
}

where i2cConfig is
const eUSCI_I2C_MasterConfig i2cConfig =
{
    EUSCI_B_I2C_CLOCKSOURCE_SMCLK,          // SMCLK Clock Source
    48000000,                               // SMCLK = 48MHz
    EUSCI_B_I2C_SET_DATA_RATE_400KBPS,      // Desired I2C Clock of 100khz
    0,                                      // No byte counter threshold
    EUSCI_B_I2C_NO_AUTO_STOP                // No Autostop
};

and then tried to use this function for each module I defined to add slaves. But the thing is, the function only allows me to enter one slave address, but for my I2C bus1, I have 2 slaves: DAC and the pressure sensor.
extern void I2C_initSlave(uint32_t moduleInstance, uint_fast16_t slaveAddress,
    uint_fast8_t slaveAddressOffset, uint32_t slaveOwnAddressEnable);

I would be very grateful if someone can help me with this problem or show me a better way to implement the same MCU as both a slave and a master at the same time. I'm new to programming with the I2C protocol and I'd appreciate any help. Thank you and have a great day.

A: You are not thinking about the problem quite right. You are not setting the MCU to be a slave, you are setting one I2C interface module (one eUSCI) to be a master and another eUSCI to be a slave. The MSP432 itself is neither master nor slave, it just talks to the two eUSCI blocks.
There are two notions of slave address. One is the slave address that the master (you) uses to communicate with some other device, like a temperature sensor. That slave address is used just for the duration of the communication with the particular slave, and then is loaded with a different value when you want to talk to some other sensor or peripheral device. There is no need to store the addresses of all slave devices in eUSCI registers.
The other notion of a slave address is used when your eUSCI is acting as a slave device and some other gadget will be the master. In this case the slave address is more or less permanent and must be defined as part of the initialization, so that the eUSCI can recognize when the external master is sending a message to it.
So, you can treat the two eUSCI modules as being completely independent. Their SCL and SDA signals are independent, and the operation of the two I2C busses can be completely different.


text:
Q: SSMS SQL SERVER Management Studio 2012 startup freeze I have a strange situation. IT installed SSMS on my laptop and it runs well the first time, connected to my SQL servers remotely etc.   But then it's frozen.   I forced quit and then started SSMS again.  Now it's totally frozen, no popup window at all to enter the server-connection text string.  Then I did a force quit and got a pop up window (see it here ).
Microsoft SQL Server Management Studio has detected that an operation is blocking user input. This can be caused by an active modal dialog or a task that needs to block user interaction. Would you like to shut down anyway?
Has anyone seen this before?  My IT department has no clue.

A: Often this is due to the new connection dialog being off screen (usually due to changing monitor setup e.g. 1 to 2 monitors or resolution change etc).
If so the really easy fix (if your connection dialog just needed approval without changing fields) is :

*

*Focus on SSMS and Hit Enter/Return

..or the easy fix (if above does not work - as your last connection is not ready to go) is:

*

*Alt Tab to SSMS

*Alt + Space - context menu

*M - select Move (in offscreen context menu)

*Arrow Key(s) - to move it back onto screen

As per answers here from @Eirik Toft and here from @Lee Chetwynd

A: I just had this same situation, with two additional screens connected to my laptop. SQL Server Management Studio was opened on the third screen, with the modal dialog nowhere to be seen.
Two options:

*

*Press tab three times and enter. This cancels the dialog. Now you can move the window to another screen.

*Set Windows to only use one or two screens. SSMS opens on the first and should still open there when you move back to using three screens.

When SSMS is on your primary or secondary screen, the modal dialog opens on the first and should be usable.

A: It was because multi screen display. Turning off multiscreen to single one resolved it. Reenabled multi screen display after ssms started working

A: Fixed an issue which presented the same on my machine today by renaming a entry in my registry:
After some digging there seems to be multiple issues that can produce the same error (Application, settings, registry). This blog entry covers it pretty well:
http://www.armedia.com/blog/2012/08/sql-server-management-studio-freeze/
In my case deleteing the SQL server management studio folder under AppData ( c:\users\%userName%Appdata\raoming\microsoft\ ) didn't work.
However I was successfully after deleting / renaming the regisitry entry:
[HKEY_CURRENT_USER\Software\Microsoft\Microsoft SQL Server]
(update)
Worked out the underlying issue on my laptop - was using additional 2 screens with much higher resolutions which caused windows / SSMS to open up the connect to new data source dialog off all of them. If your using multiple screens try returning to just use the native laptop screen to see if you can find the dialog that SSMS is waiting on your input for.

A: In my case, "Run as Administrator" option worked like charm. I was accessing my server screen with the windows RDP. And when I open SQL Server Management Studio and Visual Studio 2010 user hangs at the moment and wont operate unless sign off r disconnected by administrator.
But when I set compatibility mode of both the application to the "run as Administrator", it starts working fine.

A: the problem also occurs if you have a touch screen. I fixed this by disabling the local thouch screen when I switch to RDP.


text:
Q: Few general questions about JavaFX capabilities I'm using JavaFX to build a GUI for the software I'm working on. I call it software but it's actually a series of automated steps, compiled into a standalone .exe file. I have about 6 of these executable files, which is why I'm building a GUI to act as the front-end, main menu of sorts.
Ideally I'd have the entire package (GUI, exes) combined into one file Jar which I'd then send to clients, or wrap it with JSmooth or Launch4j.
Questions:
1) Is it possible to combine all 6 .exe files into a package along with the GUI.? So if I click button 2 on the GUI, it runs .exe #2, etc. Which concepts should I understand?
2) Is this best practice, or is there a better method? I'm new to Java which is why I haven't built the entire software with it, just the GUI.
3) I've read that its best to extract the exe from the parent jar (or exe?) into a temp file on the users PC. Is this correct? Even for multiple wrapped exes?
Any answer is helpful. I'm trying to avoid building something only to realize I can't do what I needed. Thanks

A: It would be much easier to write an answer if you were a bit more specific regarding what those 6 .exe files do. Nevertheless, a few things can be pointed out. Answers are in the same order as questions.

*

*Yes, you can package exe files into a jar. No, you can't run exe from within the jar. A common solution is to unpack exe either temporarily (while your application is active) or permanently, and then tell OS to execute it.

*I'm not entirely sure what "best practice" refers to in your question. Ideally, your logic (back-end) code would be written in Java and all your 6 exe files would be a part of a single Java application. I respect that you are new to Java, so in your particular case having a front-end to your executables is perfectly fine. However, do keep in mind that your solution is Windows specific, unless you plan to provide other OS executables too.

*Yes, you will need to extract the exe files. It doesn't really matter what parent executable you use (exe or jar). For the sake of simplicity, I'd go with the jar, because you won't need to use any 3rd party software to build such a jar.

Just to sum up, considering your situation, package your JavaFX app and the .exe files into a single executable jar. When the user needs to execute an ".exe", extract that ".exe" into the same directory where JavaFX is running from. When the app exits, delete all ".exe" files from that directory


text:
Q: Change date in a SQL query to reference a cell in Excel I have the following code that returns the needed data into excel and manually changing the date will change the returned data; however, I'd like to reference a cell with a formula that will make the query a bit more user friendly.
I've tried using my limited knowledge of referencing a cell but none have worked. This information is in cell A1 and the query is placed in cell A2 with the following equation: =wwQuery("STKAP03", $A$1)
SET QUOTED_IDENTIFIER OFF
SELECT * FROM OPENQUERY(INSQL, "SELECT DateTime, [40_MOTORS.MI436423.CIN], [40_MOTORS.MI436425.CIN]
FROM WideHistory
WHERE [40_MOTORS.MI436423.CIN] IS NOT NULL
AND wwRetrievalMode = 'Delta'
AND wwVersion = 'Latest'
AND DateTime >='20120409 07:00:00' These two dates/times I'd like to reference cells on a different sheet
AND DateTime <= '20120416 07:00:00'")


text:
Q: Using xPath on SimpleXmlElement to get single string result I am trying to get some data from a GoogleCheckout response.  I am using a SimpleXmlElement and xpath to search for the data.  One of the problems is that the response from xpath is an array of SimpleXmlElements - all I want is the string data.  The other is that the response may contain multilpe instances of the TAG name - for example, <email> is shown at least twice but I only want a singe result.
Here is what I have so far
            $notifyData = array();
            $notifyData['buyerEmail'] = $data->xpath('buyer-billing-address//email')[0];
            $notifyData['buyerName'] = $data->xpath('buyer-billing-address//contact-name');
            $notifyData['transactionId'] = $data->xpath('/new-order-notification/google-order-number');
            $notifyData['itemName'] = $data->xpath('//item-name');
            $notifyData['amount'] = $data->xpath('//unit-price');
            $notifyData['currency'] = $notifyData['amount'][0]['currency'];//$data->xpath('//@currency[1]');

here is the response from print_r() on $notifyData
Array
(
    [buyerEmail] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [0] => sandbox@mysite.com
                )

        )

    [buyerName] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [0] => Mr Sandbox Buyer
                )

        )

    [transactionId] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [0] => 271578474675716
                )

        )

    [itemName] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [0] => My Item
                )

        )

    [amount] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [currency] => USD
                        )

                    [0] => 3.99
                )

        )

    [currency] => SimpleXMLElement Object
        (
            [0] => USD
        )

)

What i want is for the data to show like this after print_r()
Array
(
    [buyerEmail] => sandbox@mysite.com
    ...
    [currency] => USD

Here is an example of an xml response
<new-order-notification xmlns="http://checkout.google.com/schema/2" serial-number="654578974677716-00001-7">

  <buyer-billing-address>

    <address1>19 sandbox st</address1>

    <address2></address2>

    <phone></phone>

    <email>sandbox@mysite.com</email>

    <company-name></company-name>

    <contact-name>Mr Sandbox Buyer</contact-name>

    <fax></fax>

    <country-code>AU</country-code>

    <city>Buyers Town</city>

    <region>VIC</region>

    <postal-code>3460</postal-code>

  </buyer-billing-address>

  <timestamp>2010-10-24T04:25:41.723Z</timestamp>

  <google-order-number>298578974677716</google-order-number>

  <shopping-cart>

    <items>

      <item>

        <digital-content>

          <key is-encrypted="true">PWWoqHo+FtfTi5vHmquOFTFNb4DwNjInAxkW89PLxtU=</key>

          <description>Follow the instructions</description>

          <url>http://mysite.com</url>

        </digital-content>

        <item-name>my product</item-name>

        <item-description>my product</item-description>

        <unit-price currency="USD">3.99</unit-price>

        <quantity>1</quantity>

      </item>

    </items>

  </shopping-cart>

  <order-adjustment>

    <merchant-codes />

    <total-tax currency="USD">0.0</total-tax>

    <adjustment-total currency="USD">0.0</adjustment-total>

  </order-adjustment>

  <buyer-id>634168749882822</buyer-id>

  <buyer-marketing-preferences>

    <email-allowed>true</email-allowed>

  </buyer-marketing-preferences>

  <buyer-shipping-address>

    <address1>19 sandbox st</address1>

    <address2></address2>

    <phone></phone>

    <email>sandbox@mysite.com</email>

    <company-name></company-name>

    <contact-name>Mr Sandbox Buyer</contact-name>

    <fax></fax>

    <country-code>AU</country-code>

    <city>Buyers Town</city>

    <region>VIC</region>

    <postal-code>3460</postal-code>

  </buyer-shipping-address>

  <order-total currency="USD">3.99</order-total>

  <fulfillment-order-state>NEW</fulfillment-order-state>

  <financial-order-state>REVIEWING</financial-order-state>

</new-order-notification>

A: use typecasting:
$notifyData['buyerName'] = (string)$data->xpath('buyer-billing-address//contact-name');

A: You don't necessarily need xpath here. E.g.
$notifyData = array(
  'buyerEmail' => (string)$data->{'buyer-billing-address'}->email[0],
  'buyerName' => (string)$data->{'buyer-billing-address'}->{'contact-name'}[0],
  'transactionId' => (string)$data->{'google-order-number'}[0]
);
var_dump($notifyData);

function getData() {
  return <<< eox
<new-order-notification xmlns="http://checkout.google.com/schema/2" serial-number="654578974677716-00001-7">
...
</new-order-notification>
eox;
}

prints
array(3) {
  ["buyerEmail"]=>
  string(18) "sandbox@mysite.com"
  ["buyerName"]=>
  string(16) "Mr Sandbox Buyer"
  ["transactionId"]=>
  string(15) "298578974677716"
}

and via foreach you can also handle multiple elements like e.g. <item>


text:
Q: Adding comments to video with jQuery I want to comment dynamically on a video with jQuery, but when I comment on what I'm doing, the old comment changes and all comments receive the same text. The value I get from the input is written to all comments. How can I fix this?

$(document).ready(function() {
  $("#addCommentBtn").click(function() {
    var comment = $("#commentText").val();
    if (comment === "") {
      $("#error-msg").fadeIn();
      setTimeout(function() {
        $("#error-msg").fadeOut();
      }, 3000);
    } else {
      $('

André Potchinka

00

<input type="text" class="responseText border-b focus:outline-none bg-transparent mt-4" placeholder="Please login to leave a comment...">

<button class="responseBtn text-right mt-2 text-gray-500">Answer</button>

').appendTo(".comments");
      $(".comment-content").text(comment);
      $("#commentText").val("");
      $("#valid-msg").fadeIn();
      setTimeout(function() {
        $("#valid-msg").fadeOut();
      }, 3000);
    }
  });
});
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>

      <input type="text" required id="commentText" class="pt-4 flex-1 focus:outline-none border-b border-gray-500 py-1 px-2 bg-transparent" placeholder="Please login to leave a comment...">

      Cancel
      <button id="addCommentBtn" class="focus:outline-none bg-black px-6 border border-black py-1 rounded-full text-gray-500 flex items-center pt-3">Comment</button>

André Potchinka

Nice work, congragulations.

              0
              0

              <input type="text" class="responseText border-b focus:outline-none bg-transparent mt-4" placeholder="Please login to leave a comment...">

Yoruma yanıt verildi :)

                <button class="responseBtn mt-2 text-gray-500 w-24 text-center">Answer</button>

A: With the selector .comment-content, you are selecting all the elements with that class, so of course all comments' text content will be overwritten. Save your new element into a variable and restrict the class selector on that new element instead:

$(document).ready(function() {
  $("#addCommentBtn").click(function() {
    var comment = $("#commentText").val();
    if (comment === "") {
      $("#error-msg").fadeIn();
      setTimeout(function() {
        $("#error-msg").fadeOut();
      }, 3000);
    } else {
      let newComment = $('

André Potchinka

00

<input type="text" class="responseText border-b focus:outline-none bg-transparent mt-4" placeholder="Please login to leave a comment...">

<button class="responseBtn text-right mt-2 text-gray-500">Answer</button>

').appendTo(".comments");
      $(".comment-content", newComment).text(comment);
      $("#commentText").val("");
      $("#valid-msg").fadeIn();
      setTimeout(function() {
        $("#valid-msg").fadeOut();
      }, 3000);
    }
  });
});

      <input type="text" required id="commentText" class="pt-4 flex-1 focus:outline-none border-b border-gray-500 py-1 px-2 bg-transparent" placeholder="Please login to leave a comment...">

      Cancel
      <button id="addCommentBtn" class="focus:outline-none bg-black px-6 border border-black py-1 rounded-full text-gray-500 flex items-center pt-3">Comment</button>

André Potchinka

Nice work, congragulations.

              0
              0

              <input type="text" class="responseText border-b focus:outline-none bg-transparent mt-4" placeholder="Please login to leave a comment...">

Yoruma yanıt verildi :)

                <button class="responseBtn mt-2 text-gray-500 w-24 text-center">Answer</button>


text:
Q: Which screenshot annotation tool (if any) was used to create this attached screenshot? [Of course, I checked that it was not a tool cited in this or any other superuser question prior to posting]
Do you recognize the tool used to create this nice-looking annotated screenshot? Or do you think it's just a custom image (e.g. Photoshoped)?

Thanks!

A: Photoshoped one, but somme good anotations tools are available on here !
But you can easily make a Photoshop Scripts for semi-auto screenshot edit ! =)


text:
Q: how to access the web ip camera on the opentopia? I am viewing an ip camera from http://www.opentopia.com/webcam/16031, I have two questions
1. how it is streaming through the web page on the opentopia website,

*is it possible to access and record the stream of that camera through ffmpeg or some other software ?

A: This site uses an mjpeg, stream. any program that can do http requests can download it.


text:
Q: How to mock answers of the Google App Engine services (e.g. blobstore) I'm trying to create a unit test for my Google App Engine project. The use case is as follows: a client queries the API for an upload URL, as the data needs to be stored in the blobstore, the client recieves a JSON encoded structure with the URL. The client then uploads the data to that URL.
The implementation of the servlet is fairly simple:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    Gson gson = new Gson();
    Map<String, String> result = new HashMap<String, String>();
    result.put("uploadurl", BlobstoreServiceFactory.getBlobstoreService()
            .createUploadUrl("/api/v1/import"));
    gson.toJson(result, resp.getWriter());
}

In good fashion there should be a test to see whether the client does indeed receive the right data. So there should be a counter JUnit test. I was hoping to mock the blob store service so that it would return a fixed upload url, which the test then can check.
However, I have no idea how to overrule the blobstore service. Using Mockito I can't mock the static getBlobstoreService(), using the LocalBlobstoreServiceTestConfig I have no idea how I can overrule the answer to createUploadUrl().
My attempt to write a test was something like this:
public class ImportServletTest {
   public static class Response {
    String uploadurl;

    void setUploadurl(String url) {
        this.uploadurl = url;
    }
}

private LocalBlobstoreServiceTestConfig blobstoreConfig = new LocalBlobstoreServiceTestConfig();

private LocalServiceTestHelper helper = new LocalServiceTestHelper(blobstoreConfig);
@Test
public void getsUploadURL() throws IOException, ServletException {
    ImportServlet servlet = new ImportServlet();

    HttpServletResponse response = mock(HttpServletResponse.class);
    try (CharArrayWriter output = new CharArrayWriter();
            PrintWriter writer = new PrintWriter(output);) {
        when(response.getWriter()).thenReturn(writer);

        servlet.doGet(null, response);
        writer.flush();

        Response apiResponse = new Gson().fromJson(output.toString(), Response.class);
        assertEquals("http://mysite/_ah/theurl", apiResponse.uploadurl);
    }
}

@Before
public void setupGae() throws IOException {
    helper.setUp();
}

@After
public void teardownGae() {
    helper.tearDown();
}
}

A: Mocking static classes/methods is in general very dangerous (http://googletesting.blogspot.it/2008/12/static-methods-are-death-to-testability.html), but in a similar case I had some success using PowerMock (https://code.google.com/p/powermock/) to override the behavior of static classes that were not under my control. I guess you'll have to mock the entire method chain:
BlobstoreServiceFactory.getBlobstoreService().createUploadUrl()

to return a custom URL instead of that generated by the BlobStore.


text:
Q: How much memory of a process is paged out? Is there a Performance Counter which indicates how much of memory of a specific process is paged out? I have a server which has 40 GB of available RAM (of 128 GB physical memory) but the paged out amount of data is over 100 GB.
How can I find out which of my processes are responsible for that huge page file consumption?
It would be also ok to have some xperf tracing to see when the page out activity happens. But apart from many writes to the page file I cannot see from which processes the memory is written to the page file.
Reference Set Tracing shows me only as far as I understand it how big the physical memory consumption of my process is. But it does not seem to track page out activity.
Update
The OS is Windows Server 2012 R2

A: The ETW provider "Microsoft-Windows-Kernel-Memory" has a keyword "KERNEL_MEM_KEYWORD_WS_SWAP" ("0x80"). Here there are some events that occur when data are paged out/paged in:
     <event value="4" symbol="WorkingSetOutSwapStart" version="0" task="WorkingSetOutSwap" opcode="win:Start" level="win:Informational" keywords="KERNEL_MEM_KEYWORD_WS_SWAP" template="WorkingSetOutSwapStartArgs"/>
     <event value="4" symbol="WorkingSetOutSwapStart_V1" version="1" task="WorkingSetOutSwap" opcode="win:Start" level="win:Informational" keywords="KERNEL_MEM_KEYWORD_WS_SWAP" template="WorkingSetOutSwapStartArgs_V1"/>
     <event value="5" symbol="WorkingSetOutSwapStop" version="0" task="WorkingSetOutSwap" opcode="win:Stop" level="win:Informational" keywords="KERNEL_MEM_KEYWORD_WS_SWAP" template="WorkingSetOutSwapStopArgs"/>
     <event value="5" symbol="WorkingSetOutSwapStop_V1" version="1" task="WorkingSetOutSwap" opcode="win:Stop" level="win:Informational" keywords="KERNEL_MEM_KEYWORD_WS_SWAP" template="WorkingSetOutSwapStopArgs_V1"/>
     <event value="6" symbol="WorkingSetInSwapStart" version="0" task="WorkingSetInSwap" opcode="win:Start" level="win:Informational" keywords="KERNEL_MEM_KEYWORD_WS_SWAP" template="WorkingSetOutSwapStartArgs"/>
     <event value="6" symbol="WorkingSetInSwapStart_V1" version="1" task="WorkingSetInSwap" opcode="win:Start" level="win:Informational" keywords="KERNEL_MEM_KEYWORD_WS_SWAP" template="WorkingSetOutSwapStartArgs_V1"/>
     <event value="7" symbol="WorkingSetInSwapStop" version="0" task="WorkingSetInSwap" opcode="win:Stop" level="win:Informational" keywords="KERNEL_MEM_KEYWORD_WS_SWAP" template="WorkingSetInSwapStopArgs"/>

Here you get some data like the number of pages accessed (PagesProcessed):
<template tid="WorkingSetOutSwapStartArgs">
  <data name="ProcessId" inType="win:UInt32"/>
 </template>
 <template tid="WorkingSetOutSwapStopArgs">
  <data name="ProcessId" inType="win:UInt32"/>
  <data name="Status" inType="win:HexInt32"/>
  <data name="PagesProcessed" inType="win:UInt32"/>
 </template>
 <template tid="WorkingSetInSwapStopArgs">
  <data name="ProcessId" inType="win:UInt32"/>
  <data name="Status" inType="win:HexInt32"/>
 </template>
 <template tid="WorkingSetOutSwapStartArgs_V1">
  <data name="ProcessId" inType="win:UInt32"/>
  <data name="Flags" inType="win:HexInt32"/>
 </template>
 <template tid="WorkingSetOutSwapStopArgs_V1">
  <data name="ProcessId" inType="win:UInt32"/>
  <data name="Status" inType="win:HexInt32"/>
  <data name="PagesProcessed" inType="win:Pointer"/>
  <data name="WriteCombinePagesProcessed" inType="win:Pointer"/>
  <data name="UncachedPagesProcessed" inType="win:Pointer"/>
  <data name="CleanPagesProcessed" inType="win:Pointer"/>
 </template>

Play with it if it includes all data you need.

A: In Xperf you want to look for Hard Faults - note that this is a type of Page Fault, but page faults can often be handled in software without touching the drive. You can add a column in Task Manager to show page faults for each process.
You can get some information on a process by using a tool like https://technet.microsoft.com/en-us/sysinternals/vmmap.aspx which will tell you for each block of memory in the process address space what type it is, and how much is committed. However, it's the committed memory that can be paged out, and VirtualQueryEx() doesn't tell you about that.
It's also worth noting that a large quantity of paged out memory isn't always a bad thing - it's the hard faults that are slow.
Edit: Hmm, if you want an intrusive one-off test I guess there's the hacky option of combining VirtualQueryEx() and ReadProcessMemory() to touch every committed page in a process so you can count the hard faults!


text:
Q: Undefined accessing jquery selector with object property I have an issue using an object property as jquery selector
define(["models/security/user", 'text!templates/security/registration.html'], function(SecurityUserModel, Template){

    var SecurityRegistrationView;

    SecurityRegistrationView = Backbone.View.extend({
        initialize: function(){
            // setting model
            this.model = new SecurityUserModel();

            // binding validation
            Backbone.Validation.bind(this);
            this.model.bind("validated:valid", this.valid);
            this.model.bind("validated:invalid", this.invalid);

            this.render();
        },
        form: {
            "username": "#_user_username"
            , "email": "#_user_email"
            , "password": "#_user_password"
        },
        render: function(){
            $(this.el).append(Template);
        },
        events: {
            "submit form": "submit"
        },
        submit: function(e){
            e.preventDefault();

            this.model.set("username", $(this.form.username).val());
            this.model.set("password", $(this.form.email).val());
            this.model.set("email", $(this.form.password).val());
            this.model.validate();

            if (this.model.isValid) {
                this.model.save();
            }
        },
        valid: function(model, attrs){
            console.log(attrs[0]);
            $(this.form[attrs[0]]).parent("div.control-group").addClass("success");
        },
        invalid: function(model, attrs){
            console.log(attrs[0]);
            $(this.form[attrs[0]]).parent("div.control-group").addClass("error");
        }
    });

    return SecurityRegistrationView;
});

Console output in chromium:
username registration.js:45
Uncaught TypeError: Cannot read property 'username' of undefined registration.js:46
password registration.js:45
Uncaught TypeError: Cannot read property 'password' of undefined registration.js:46
email registration.js:45
Uncaught TypeError: Cannot read property 'email' of undefined registration.js:46
username registration.js:45
Uncaught TypeError: Cannot read property 'username' of undefined registration.js:46

$(this.form.username).val(); // works
$(this.form[someVar]); // does not work

A: this in your valid and invalid callbacks probably doesn't refer to your view. Modify the bindings in your initialize method to the proper scope:
this.model.bind("validated:valid", this.valid, this);
this.model.bind("validated:invalid", this.invalid, this);

A: Try to replace:
$(this.form.username)

With:
$(this.form['username'])

Or, without "this":
$(form['username'])

*

*The same for "password" and "email".


text:
Q: malformed Java Net URL I am making a url like this
url = new URL("http","localhost",9080,"/path/to/my/resource/myAction.action");

instead of making the url:
http://localhost:9080/path/to/my/resource/myAction.action

its making the request to:
http://www.localhost.com/path/to/my/resource/myAction.action

A: try this:
url = new URL("http://localhost:9080/path/to/my/resource/myAction.action");


text:
Q: Explanation of return code from SHFileOperation() Is there a reason SHFileOperation() returns 32?
My scenario is:

*

*My current path is c:\foo\bar.

*My file is in c:\foo

*That file is going to the Recycle Bin.

This code is not listed as possible return value in here, and I don't know where to find the cause.
I am trying it on Windows 7 64-bit with MSVC 2010 Professional.
Could someone please explain where I can find the returned values documentation or some explanation for a reason of that failure?

A: SHFileOperation returns errors, which match to Winerror.h error values.
32 is defined as ERROR_SHARING_VIOLATION, meaning "The process cannot access the file because it is being used by another process." This means that another process accesses the file you want to change by calling SHFileOperation.
You might as well use Process Explorer's find-feature to find out, which process accesses the file you want to change.

A: From my testing (so verify yourself)
32 = File in use or perhaps file locked/protected.
(Created an excel wkbk, opened, typed text, tried to delete)
2 = not found
0 = no issues
4, 8, 16 return codes seem likely


text:
Q: Project Tango onPoseAvailable() and getPoseAtTime() discrepancies I am seeing significant discrepancies between the poses from the onPoseAvailable() callback and Tango.getPoseAtTime(). I wrote a test program where in onPoseAvailable() I logged the delivered pose and used getPoseAtTime() to request the pose using the timestamp from 2 callbacks earlier. KEY_BOOLEAN_SMOOTH_POSE is configured false. Here is the code that does that (the timestamps_ member variable is a LinkedList<Double>):
@Override
public void onPoseAvailable(TangoPoseData poseData) {
   if (poseData != null && poseData.statusCode == TangoPoseData.POSE_VALID) {
      Log.v("bug",
         String.format("onPoseAvailable t: %f, base: %d,  target %d, p: (%f, %f, %f)",
            poseData.timestamp,
            poseData.baseFrame,
            poseData.targetFrame,
            poseData.translation[0], poseData.translation[1], poseData.translation[2]));
      timestamps_.add(poseData.timestamp);
      if (timestamps_.size() > 3)
         timestamps_.remove();
   }

   if (timestamps_.isEmpty())
      return;

   TangoCoordinateFramePair framePair = new TangoCoordinateFramePair(
      TangoPoseData.COORDINATE_FRAME_START_OF_SERVICE,
      TangoPoseData.COORDINATE_FRAME_DEVICE);
   poseData = tango_.getPoseAtTime(timestamps_.getFirst(), framePair);
   if (poseData != null && poseData.statusCode == TangoPoseData.POSE_VALID) {
      Log.v("bug",
         String.format("getPoseAtTime t: %f, base: %d,  target %d, p: (%f, %f, %f)",
            poseData.timestamp,
            poseData.baseFrame,
            poseData.targetFrame,
            poseData.translation[0], poseData.translation[1], poseData.translation[2]));
   }
}

Here is an excerpt from an actual log (I have deinterleaved the logged calls for clarity):
onPoseAvailable t: 2732.762486, base: 2,  target 4, p: (0.280245, 0.412468, 0.562201)
onPoseAvailable t: 2732.802553, base: 2,  target 4, p: (0.296951, 0.420919, 0.599938)
onPoseAvailable t: 2732.852638, base: 2,  target 4, p: (0.317444, 0.429809, 0.646445)
onPoseAvailable t: 2732.882689, base: 2,  target 4, p: (0.330845, 0.434106, 0.676810)
onPoseAvailable t: 2732.932774, base: 2,  target 4, p: (0.350995, 0.439777, 0.723639)
onPoseAvailable t: 2732.962825, base: 2,  target 4, p: (0.363319, 0.442731, 0.754508)
onPoseAvailable t: 2732.992875, base: 2,  target 4, p: (0.373911, 0.445289, 0.784786)
onPoseAvailable t: 2733.032943, base: 2,  target 4, p: (0.387709, 0.448182, 0.822682)
onPoseAvailable t: 2733.062994, base: 2,  target 4, p: (0.398502, 0.450481, 0.852662)
onPoseAvailable t: 2733.073011, base: 2,  target 4, p: (0.401869, 0.451084, 0.862530)
onPoseAvailable t: 2733.103062, base: 2,  target 4, p: (0.411136, 0.452486, 0.890441)

getPoseAtTime t: 2732.712401, base: 2,  target 4, p: (0.269301, 0.410911, 0.549182)
getPoseAtTime t: 2732.732435, base: 2,  target 4, p: (0.277217, 0.415130, 0.567040)
getPoseAtTime t: 2732.762486, base: 2,  target 4, p: (0.288928, 0.421914, 0.595162)
getPoseAtTime t: 2732.802553, base: 2,  target 4, p: (0.305241, 0.429648, 0.632158)
getPoseAtTime t: 2732.852638, base: 2,  target 4, p: (0.324359, 0.437655, 0.680300)
getPoseAtTime t: 2732.882689, base: 2,  target 4, p: (0.332997, 0.442538, 0.712727)
getPoseAtTime t: 2732.932774, base: 2,  target 4, p: (0.353665, 0.447269, 0.759725)
getPoseAtTime t: 2732.962825, base: 2,  target 4, p: (0.369174, 0.451645, 0.790263)
getPoseAtTime t: 2732.992875, base: 2,  target 4, p: (0.382584, 0.454754, 0.819555)
getPoseAtTime t: 2733.032943, base: 2,  target 4, p: (0.396857, 0.456922, 0.856626)
getPoseAtTime t: 2733.062994, base: 2,  target 4, p: (0.409672, 0.460060, 0.888748)

Take a look at the last getPoseAtTime() entry, with timestamp 2733.062994. Note that its position values do not match the pose from onPoseAvailable with the identical timestamp. Something isn't right here.
I did consider that a spline fit of pose would not necessarily need to pass through the control points, but I don't think that is an acceptable explanation. First of all it doesn't make a lot of sense to have an API that delivers different values for the same measurement. But in addition the actual numbers don't back that conjecture.
Look at the getPoseAtTime() Y value, 0.460060. This is outside the Y range of all the onPoseAvailable() Y values, both before and after (over the entire log as a matter of fact). No reasonable interpolation model can produce this value.
I guess the question is what is going on here? The poses are inconsistent so at least one of them is wrong (if not both). My guess would be that the onPoseAvailable() is more likely to be correct.
Here is a graph of Y position versus time of the two pose methods (Nash release) with the tablet stationary in its dock:

The blue line is the onPoseAvailable() callback and the red line is the getPoseAtTime() polling. These results are kind of strange. If the poses are going to be different at all, I would expect that the polled value would be smoother because it could be filtered using contributions from samples before and after the poll time, while the callback value would either be unfiltered or filtered only using prior samples. But that isn't what we see - the polled value appears much noisier.
Here's a similar graph captured while I moved the tablet up and down. The polled value still has more high frequencies, and the two signals don't track particularly closely.

A: Thanks rhashimoto for pointing that out!
EDIT
I have to edit my previous post. I claimed that I had a greater drift while using GetPoseAtTime instead of the pose of the OnPoseAvailable callback.
It's just the other way round. I get much better results with GetPoseAtTime.
I made a scan by spinning 360° on my chair. I started and stopped at my desk as you can see in the picture.
start and end of the scanning cycle (click it for greater resolution)

The point clouds above use poses GetPoseAtTime and the point clouds below use pose by the OnPoseAvailable callback. Both captured at the same time. The drift with GetPoseAtTime is marginal, but with OnPoseAvailable callback really huge.
What I found out so far is that GetPoseAtTime uses a pose graph and corrects the poses if a loop closure is detected see this article. I tested if the results getting better, if I access the pose immediately with an available point cloud or just at the end while I'm merging all point clouds.
And indeed the result is way better. So my experience so far is:
OnPoseAvailabe callback < GetPoseAtTime immediately with an available point cloud < GetPoseAtTime at the end of scanning


text:
Q: Image ratio option changing after render, to most recent ratio selection I modified an image cropper so that it allows you to pre-select which crop ratio option you would like to use, before or after the image to crop is selected. The issue is that when I set the ratio that is selected into the URL which is submitted through the API, it is changing if the user renders an image, but before submitting the image with its ratio, the user selects a different ratio option to test, before submitting the previous render. I need a way to lock in the original ratio to the URL being submitted, without it being changed by selecting another crop option.
This is the code that renders the final image after cropping, along with the submission functionality:
    // As soon as the user clicks the render button...
    // Listen for "Render final image" click
    renderButton.click(function (event) {
        var dataUrl;
        $(".result, .share-link").empty();
        $(".submit, .remove").remove();

        imgly.renderToDataURL("image/jpeg", {
            size: "1200"
        }, function (err, dataUrl) {
            // `dataUrl` now contains a resized rendered image

            //Convert DataURL to Blob to send over Ajax
            function dataURItoBlob(dataUrl) {
                // convert base64 to raw binary data held in a string

                var byteString = atob(dataUrl.split(',')[1]);

                // separate out the mime component
                var mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];

                // write the bytes of the string to an ArrayBuffer
                var ab = new ArrayBuffer(byteString.length);
                var ia = new Uint8Array(ab);
                for (var i = 0; i < byteString.length; i++) {
                    ia[i] = byteString.charCodeAt(i);
                }
                // write the ArrayBuffer to a blob, and you're done
                //var bb = new BlobBuilder();
                //bb.append(ab);
                //return bb.getBlob(mimeString);
                return new Blob([ab], {
                    type: 'image/jpeg'
                });
            }

            var blob = dataURItoBlob(dataUrl);
            //console.log("var blob: " + blob);
            //var fd = new FormData(document.forms[0]);
            var image = $("
").attr({
                src: dataUrl
            });

            image.appendTo($(".result"));

            $submitButton = $('

')
                .text('Submit ' + imageid.value).appendTo($(".submit-well"))
                .on('click', function () {
                var imageid = $("#imageid").val();
                var saveImage = encodeURIComponent(dataUrl);
                var bearerToken = localStorage.getItem('Authorization');

                //IF TESTING ON LOCALHOST
                if (document.domain == 'localhost') {
                    url = "http://localhost:7777/proxy/staging/rest/v1/cms/story/id/" + imageid + "/image/orientation/" + orientation;
                } else {
                    //IF IN PRODUCTION
                    url = "/cropper/admin/cropv2/rest/v1/cms/story/id/" + imageid + "/image/orientation/" + orientation;
                };

                jQuery.ajax({
                    method: "PUT",
                    dataType: 'json',
                    callback: null,
                    url: url,
                    headers: {
                        "Authorization": bearerToken
                    },
                    data: saveImage,
                    success: function (response) {
                        $("#renderButton").css("display", "hidden");
                        var obj = response;
                        $(".search-results").empty();
                        $(".submit").remove();
                        for (var property in obj.entity.entries) {
                            if (obj.entity.entries.hasOwnProperty(property)) {
                                $(".search-results").append($("

" + obj.entity.entries[property].orientation + "

"));
                            }
                        }
                        $(".share-link").html("

The asset " + imageid + " now has a " + orientation + " image associated with it.

");
                        $("#imageid, .assetid").css("border-color", "#ccc");
                    },
                    error: function (data) {
                        $("#renderButton").hide();
                        $(".share-link").html("

Image submission error. Asset ID missing or invalid. Please check asset ID, re-render and try again.

");
                        $("#imageid, .assetid").css("border-color", "red");
                    }
                });
            });
        });
    });
});

This is the function with dropdown selector and switch case that controls the orientation selection:
    CropOperation.prototype.setSize = function(size) {
  //SHOW/HIDE CROP OPTIONS BASED ON SELECTION
  $(".imgly-controls-item-square").hide(); // Hide square crop before images are even loaded
  $("#renderButton").hide();
  $('#crop').on('change', function () {
    $(".submit").hide();
  //$('.imgly-controls-list-with-buttons').show();
        if (this.value == 'now'){
          $(".imgly-controls-item-16-9").click();
          $(".imgly-canvas-cropping-center").css('background-image', 'url("crop-landscape.png")');
            $(".imgly-controls-button-back, .imgly-controls-item-16-9, .imgly-controls-item-9-16, .imgly-controls-button-done").show();
            $(".imgly-controls-item-square").hide(); // hide square crop option after user selects livefeeds, then back to now
        } else if (this.value == 'livefeeds') {
            // SET CROP RATIO TO SQUARE
            $(".imgly-controls-item-square").click();
            //
          $(".imgly-canvas-cropping-center").css('background-image', 'url("crop-square.png")');
            $(".imgly-controls-item-square, .imgly-controls-button-back, .imgly-controls-button-done").show();
            $(".imgly-controls-item-16-9, .imgly-controls-item-9-16").hide();
        } else if(this.value == 'default'){
            $(".imgly-controls-item-16-9, .imgly-controls-item-9-16, .imgly-controls-item-square, .imgly-controls-button-back, .imgly-controls-button-done").hide();
        }

    });
    var h, height, w, width, _ref;
    _ref = this.app.ui.getCanvas().getImageData(), width = _ref.width, height = _ref.height;
    this.options.size = size;
    this.options.start.set(0.1, 0.1);
    this.options.end.set(0.9, 0.9);
    switch (size) {
      case "9:16":
        this.options.ratio = 9 / 16;
        orientation = "PORTRAIT";
        $(".imgly-canvas-cropping-center").css('background-image', 'url("crop-portrait.png")');
        break;
      case "square":
        this.options.ratio = 1;
        orientation = "SQUARE";
        $(".imgly-canvas-cropping-center").css('background-image', 'url("crop-square.png")');
        break;
      case "16:9":
        this.options.ratio = 16 / 9;
        orientation = "LANDSCAPE";
        $(".imgly-canvas-cropping-center").css('background-image', 'url("crop-landscape.png")');
        break;
    }
    if (this.options.ratio) {
      if (width / height <= this.options.ratio) {
        this.options.start.x = 0.1;
        this.options.end.x = 0.9;
        h = 1 / height * (width / this.options.ratio * 0.8);
        this.options.start.y = (1 - h) / 2;
        this.options.end.y = 1 - this.options.start.y;
      } else {
        this.options.start.y = 0.1;
        this.options.end.y = 0.9;
        w = 1 / width * (this.options.ratio * height * 0.8);
        this.options.start.x = (1 - w) / 2;
        this.options.end.x = 1 - this.options.start.x;
      }
    }
    return this.emit("updateOptions", this.options);
  };

A: The solution was to set var ratio = orientation; within the renderButton function, and replace the URL being submitted as + ratio +, instead of + orientation +. This keeps the orientation in the url from being changed every time a different orientation is clicked, regardless of whether it is being submitted as that newly clicked orientation or not.


text:
Q: Node JS server proxy using additional paths not working I have a simple node js server like this:
var express  = require('express');
var app      = express();
var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();
var serverOne = 'http://<address>:<port>/sap/opu/odata/sap/Z_ATTENDANCE_SRV/';

    app.use(express.static('webapp'));
    app.use(express.static('./'));

app.all("/attendance/*", function(req, res) {
    console.log('redirecting to Server1: ' + serverOne);
    apiProxy.web(req, res, {target: serverOne});
});
app.listen(3000);

So address localhost:3000/attendance should redirect me to http://<address>:<port>/sap/opu/odata/sap/Z_ATTENDANCE_SRV/ but it is not, I am getting 404.
I was able to make it work when I set the proxy path as "/*" instead of "/attendance/*", but when I wanted to access entity set "AttendanceSet" via localhost:3000/AttendanceSet it also gave me 404. Do I need to create proxy for all my paths? Shouldn't the /* do that?
When I check initialisation of oDataModel in SAPUI5 app I can see such a request (In this case I have set "/*" for the proxy):
Request URL: http://localhost:3000/$metadata?sap-language=EN
Request Method: GET
Status Code: 200 OK (from disk cache)
Remote Address: [::1]:3000
Referrer Policy: no-referrer-when-downgrade

By this logic, I should be able to access entity set AttendanceSet, but I guess I am missing something.
Thanks.

A: For urls like localhost:3000/AttendanceSet or localhost:3000/Attendance you have to remove the / you have in you endpoint like this.
app.all("/attendance*", function(req, res) {
    console.log('redirecting to Server1: ' + serverOne);
    apiProxy.web(req, res, {target: serverOne});
});

A: Looks like problem was with cache. I deleted browser cache and also, when running node js server I used addition -c-1 to do no caching.


text:
Q: Python package import works in Spyder but not VS Code I know there are dozens of Python package import questions, but I can't seem to find an answer that works. Most answers seem to be about the missing __init__.py to make a package, but I've got one in the base of the project (and I've tried in the sub-folders as well).
I have a project of the form
package
+-- __init__.py
+-- weasel.py
+-- badgers
|   +-- __init__.py
|   +-- a.py

where weasel.py just contains a test function
def test_function():
    return "HELLO"

and I want to be able to call test_function from a.py, I've attempted (all with and without the init.py in the folder badgers) and none of which seem to work.
import weasel -> ModuleNotFoundError: No module named 'weasel'
from . import weasel -> ImportError: attempted relative import with no known parent package
import package.weasel -> ModuleNotFoundError: No module named 'package'
from package import weasel

The hack I've managed to employ thus far, which works fine in Spyder and in my production environment; project is a Dash App (so Flask) deployed to render.
import sys
sys.path.append("..")
import weasel

But this just throws ModuleNotFoundError in VS Code.
I'm not adverse to a hack :S but the needs of the current project kinda make life much, much, easier if I could build the project in VS Code.
Please, I implore the stackoverflow community could someone please let me know what I'm doing wrong? Or a hack that will work in VS Code?
Thank you,

A: This is caused by the path. The path of vscode running file is not the current file path. You need to add it manually.
import sys
sys.path.append("your package's Path")  #for example, my path is "C:/my_python/package"
import weasel

Here is my directory structure.

Tips:
Do not use "..", it will really adds two commas to path instead of parent directory.


text:
Q: Limiting emails for google signin api What i wanna do is ..I am creating a application which accept only google sign in. But issue is that i want that only specific person get login with the google sign in.
like example only this kind of email like:
xyz@company.edu.in

able to sign in having @company.edu.in at last but with google sign in. Not local sign in.

A: For now, your best option is to maintain the list on your side and once you get the id_token from Google, check to see if you want them to sign-in. If no then display an error message. At this point you can not add these restrictions to Google's side. If you know the domain of the users, you can pass the "hd" parameter in the oauth url. This will help users but they can still sign-in with a different account and you need to rely on the check on your side.
Soon using firebase auth, you will be able to add restriction on which accounts can sign-in. So you should check that out as well.


text:
Q: How to Center align Menu in Twenty ten default WordPress theme? IS it possible to align menu item center? Actually my website has a lot many menus, So menus are appearing on second line from left so I want to show them as center aligned.Any suggestions?
Please find below my Css. This is edited style sheet of default twenty ten wordpress theme. I am using full width layout.
Thanks.

#access {
 background:#cc0000;
 margin: 0 auto;
 width: 100%;
  padding: 0px 0px;
  border-top:2px solid #eb9999;
 border-bottom:12px solid #000000;
 clear:both;
 margin-bottom:5px;
}
#access .menu-header,
div.menu {
 font-size: 13px;
 margin: 0 auto;
 width: 1024px;
}
#access .menu-header ul,
div.menu ul {
 list-style: none;
 margin: 0;
}
#access .menu-header li,
div.menu li {
 float: left;
 position: relative;
}
#access a {
 color: #aaa;
 display: block;
 line-height: 20px;
 padding: 0 10px;
 text-decoration: none;
}
#access ul{display:inline-block;}
#access ul ul {
 box-shadow: 0px 3px 3px rgba(0,0,0,0.2);
 -moz-box-shadow: 0px 3px 3px rgba(0,0,0,0.2);
 -webkit-box-shadow: 0px 3px 3px rgba(0,0,0,0.2);
 display: none;
 position: absolute;
 top: 38px;
 left: 0;
 float: left;
 width: 180px;
 z-index: 99999;
}
#access ul ul li {
 min-width: 180px;
}
#access ul ul ul {
 left: 100%;
 top: 0;
}
#access ul ul a {
 background: #333;
 line-height: 1em;
 padding: 10px;
 width: 160px;
 height: auto;
}


text:
Q: What would you call a course provided by a company to give extra qualifications to its employees? I was thinking something like integrative/supplementary/auxiliary/subsidiary courses/classes/lessons/training. I'm not sure which one would be best.
What I mean is a course that would give an employee extra knowledge in order to step up the career ladder and gain new responsabilities.
thanks

A: I would call it "career development training" or "skills development training".  The term "course" or "programme" could also be used instead of "training".
From mbaskool.com

Career development is the series of activities or the on-going/lifelong process of developing one's career. Career development usually refers to managing one's career in an intra-organizational or inter-organizational scenario. It involves training on new skills, moving to higher job responsibilities, making a career change within the same organization, moving to a different organization or starting one's own business.

From td.org:

Your company can develop its own unique career development programs to increase employee retention—and hopefully increase productivity and profits

From learn.org:

Many employers include career development training in their benefits packages, giving employees the opportunity to further their professional education and advance their skills.

From Abundant Sun:

we have carefully developed a suite of personal skills development programmes to help employers assist their employees to overcome career barriers and reach more senior levels in their respective organisations.

A: Refresher course may fit your description:

A refresher course is a training course in which people improve their knowledge or skills and learn about new developments that are related to the job that they do.

(Collins)
Career advancements courses  can be referred to as:
Professional development courses:

development courses give education opportunities to indivduals seeking advancement in their career.


text:
Q: Функция onscroll JS. Как убрать подергивания? Имеется следующий код:
  $(window).scroll(function (e) {
      var body = document.body,
    html = document.documentElement;

var height = Math.max( body.scrollHeight, body.offsetHeight,
                       html.clientHeight, html.scrollHeight, html.offsetHeight );

dtcur = new Date();
dtcur=dtcur.getTime();
dtdiff = parseInt((dtcur-dt));
    var currentscrolled=parseInt($(this).scrollTop());
var browswidth = document.body.clientWidth+17;
var item1=parseInt($('#item-1').offset().top);
var item2=parseInt($('#item-2').offset().top);
var item3=parseInt($('#item-3').offset().top);
var item4=parseInt($('#item-4').offset().top);
var item5=parseInt($('#item-5').offset().top);
var item6=parseInt($('#item-6').offset().top);

if(browswidth<1100)
  {}
else{
  if((currentscrolled>item1&&currentscrolled<item2)||(currentscrolled>=item6) || currentscrolled==0)
    {$('#navbar').hide();}else{$('#navbar').show();}
if(dtdiff>1000 &&flag==0){

if(currentscrolled<0){$('body, html').animate({scrollTop:0},0);
}else{}

if(currentscrolled>scrolledlast){

if(posmax>pos){
  pos++;
}
var blockps = $('div.bg--'+pos).offset().top;
blockps=parseInt(blockps);
scrolledlast=currentscrolled
$('body, html').animate({scrollTop:blockps},800);

  }
  else{
if(posmin<pos){
  pos=pos-1;
}
if(pos==1){
$('body, html').animate({scrollTop:0},800);

}else{
   var blockps = $('div.bg--'+pos).offset().top;
blockps=parseInt(blockps);
scrolledlast=currentscrolled
$('body, html').animate({scrollTop:blockps},800);

}
  }

 dt= new Date();
  dt = dt.getTime();
}else{flag=0;}
scrolledlast=currentscrolled;
}}

Сделан он для того, чтобы сделать поблочный скролл- один div размером с экран монитора.
При быстрой и/или частой прокрутке экран начинает дёргаться - как этого избежать?
Ссылка на сайт : http://lendsale.ru/stackoverflow/

A: Сложно разобраться, что именно не так с вашим кодом. Вот пример такого слайдера: https://jsfiddle.net/CLackyM/fcksq4L1/
Скорость реакции на окончание скролла вот здесь:
window.mainSliderScrollTimeout = setTimeout(function(){
    window.goNearestSlide();
},500);

А скорость анимации вот здесь:
$('html').animate({
    scrollTop:o
}, 500,"easeOutQuad", function () {
    console.log('scrll complete');
});

Чтобы сделать кнопки вперёд назад можно создать переменную для хранения текущего слайда и через функцию window.goSlide(x) переключать слайды


text:
Q: How to pass the second parameter of ObjectTemplate::New in Google V8? I know creating an ObjectTemplate and we can do several things to it. But my question is not about those well-known things.
I want to know how to pass the second parameter.
As the official guide said:

Each function template has an associated object template. This is used to configure objects created with this function as their constructor.

And the second parameter of ObjectTemplate::New is a constructor typed by FunctionTemplate.
static Local<ObjectTemplate> New(Isolate *isolate, Local<FunctionTemplate> constructor = Local<FunctionTemplate>());

That means something like this:
void Constructor(const FunctionCallbackInfo<Value>& args)
{
    // ...
}

Local<FunctionTemplate> _constructor = FunctionTemplate::New(isolate, Constructor);
Local<ObjectTemplate> tpl = ObjectTemplate::New(isolate, _constructor);

Who can give me a demo that how to implement the Constructor function.
I tried this, but failed:
void Constructor(const FunctionCallbackInfo<Value>& args)
{
    Isolate* isolate = args.GetIsolate();
    args.This()->Set(String::NewFromUtf8(isolate, "value"), Number::New(isolate, 233));
    args.GetReturnValue().Set(args.This());
}

By the way, I know the use case of accessors and so on, I just want to know how to use the second parameter.

A: There's an example for the second ObjectTemplate::New parameter in V8's API tests at https://chromium.googlesource.com/v8/v8/+/master/test/cctest/test-api.cc#1901:
LocalContext env;
Local<v8::FunctionTemplate> fun = v8::FunctionTemplate::New(isolate);
v8::Local<v8::String> class_name = v8_str("the_class_name");
fun->SetClassName(class_name);
Local<ObjectTemplate> templ1 = ObjectTemplate::New(isolate, fun);
templ1->Set(isolate, "x", v8_num(10));
templ1->Set(isolate, "value", v8_num(233));  // From your last snippet.
Local<v8::Object> instance1 =
    templ1->NewInstance(env.local()).ToLocalChecked();
CHECK(class_name->StrictEquals(instance1->GetConstructorName()));

As you can see, there's no need to implement property creation indirectly via a FunctionTemplate, that's what the ObjectTemplate is for. See the "x" and "value" properties in the above example.
The quote you mentioned refers to something else. When you instantiate a function from a FunctionTemplate, then JavaScript code can use that function as a constructor. The mentioned ObjectTemplate can be used to configure the objects that will be created that way.


text:
Q: Who has been denied membership in United Federation of Planets? During the TNG series, several planets are shown in various stages of the application process for membership with the UFP but we don't see the final outcome of those applications, but it doesn't look good.
The Anticans applied for membership to the United Federation of Planets. The Enterprise-D transported their delegates to the planet Parliament to help resolve a long-standing dispute with their sister planet, Selay, as part of the admission process. (TNG: 1x07, "Lonely Among Us")
The Angosians applied but were apparently turned down.
Picard tells the Angosian government that they must make a decision regarding the fate of their veterans and that he has all the information he needs for his report, and, if they wish to reapply for Federation membership, their application will be given all due consideration...
(TNG: 3x11, "The Hunted")
Looks like the Angosians got shut down and the Anticans were a real longshot for acceptance. Have there been others who have been denied membership?

A: The most obvious answers (within the TV canon) are;
Kesprytt III:
As a result of their internal disputes Riker (in the TNG Episode "Attached") strongly indicates that his recommendation will be to refuse admission;

RIKER : As First Officer of the Enterprise I think I can promise you that is not going to happen. The Kes will be denied membership.

Deneb IV
The Bandi homeworld was refused Federation entry after it became clear that their 'starbase building technology' required the subjugation of sentient creatures in "Encounter at Farpoint, Part I+II"
Beta Renner II + Angosia III
You've already mentioned Beta Renner II from the epsiode "Lonely Among us" and Angosia III from "The Hunted" as worlds that were told to get their acts together before reapplying.

Moving down the canon scale to the EU books, there are a number of references to worlds denied Federation membership;
Parath'aa is refused entry in the TOS book The Disinherited due to the "brutality of their leaders"
The Planet Halka (originally seen in TOS: "Mirror, Mirror") was granted entry into the Federation after multiple refusals. It's notable that they are referred to as being the main trading partner between the Federation and Halka I, IV and IX which were refused Federation membership. Halka itself is referenced in the TOS novel "Preserver" as being 'aligned with the Federation', suggesting their membership was never fully confirmed.