text:
Q: Trying to make a div disappear with javascript I am trying to make a div disappear with javascript. It just doesn't work. What am I doing wrong?

  Text.
  link

A: Try and throw a document ready around your code.
And if you are loading jquery you can just do $('#des').css('visibility', 'hidden'); or $('#des').hide()

A: You are trying to get the element with id = "des", before it's created.

    Text.
link

This should work.

A: You should wrap the script in a $(document).ready block because you are calling the script before the DOM is loaded.
So,You will have to do it like this

A: this worked for me when I placed the javascript code in a function and load it when the body loads e.g

    test

A: Why not to use JQuery hide() method, as you already using JQuery and obiviously code to be included either in $(document).ready(function(){\\some code}) or $(window).load(function(){\\some code});
$('#des').hide()

in JS, you can achieve by
document.getElementById("des").style.display = "none";

A: It's:
document.getElementById("des").style.display = "none";

you can also use:
document.getElementById("des").style.display = "block";

to make it visible again.
That's my preferred method, at any rate.

A: You need to wait for the document to be ready. Try using:
$( document ).ready(function() {
    document.getElementById("des").style.visibility = "hidden";
});
or you could use JQuery:
$(documet).ready(function() {
   $( ".des" ).hide();
});

A: You are running the script before the DOM has loaded.
If you put the script after the div, it works

A: Javascript is an interepreter based language, in case you want to write script first and use later, add a function instead.

  Text.
  link

Cheers !!


text:
Q: Перевод отдельных элементов панели администратора Всем привет. Для окончания работы с сайтом на WP нужно перевести некоторые элементы панели администратора (для custom post type страниц) с английского на русский:
1) Статусы записей "Draft" и "Pending". Вроде перевели строки в post.php, но эти два статуса остаются на английском, хотя вкладки статусов вверху страницы теперь отображаются на русском.

2) Фильтры по дате и категории (тоже для страниц кастомного типа).

3) Выбор категории страницы кастомного типа.

Прошу подсказки, в каких файлах искать нужные строки. Всем заранее большое спасибо за любую оказанную помощь!

A: Модифицировать файлы ядра (а я смотрю, вы взялись за /wp-includes/post.php - последнее дело. Все слетит при обновлении.
Править надо файлы .po, которые находятся в ядре, в темах, в плагинах. Для этого используется редактор poedit. При сохранении файла .po он создает .mo, который и надо поместить в нужные папки.
Но мне непонятно, почему вы правите ядро - оно же на 100% переведено на русский.
Файлы .po находятся:

*

*для ядра - в папке /wp-content/languages/ru_RU.po

*для плагинов - в папке /wp-content/languages/plugins с именами текстовый-домен-ru_RU.po

*для тем - в папке /wp-content/languages/themes  с именами текстовый-домен-ru_RU.po

A: *

*Трогать файлы ядра категорически нельзя!

См https://codex.wordpress.org/%D0%A7%D0%90%D0%92%D0%9E/%D0%98%D0%B7%D0%BC%D0%B5%D0%BD%D0%B5%D0%BD%D0%B8%D0%B5_%D1%81%D1%82%D0%B0%D0%BD%D0%B4%D0%B0%D1%80%D1%82%D0%BD%D1%8B%D1%85_%D1%84%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D0%B9

*Чтобы у юзера было всё по-русски в админке достаточно в настройках профиля юзера выбрать русский язык.

*Перевод в ВП основан на gettext и осуществляется в лангпаках. Для самого ВП всё переведено. Плагины и темы - не все.
См https://translate.wordpress.org/locale/ru
https://make.wordpress.org/polyglots/handbook/tools/glotpress-translate-wordpress-org/
https://ru.wordpress.org/support/topic/%D0%BA%D0%B0%D0%BA-%D0%BF%D0%B5%D1%80%D0%B5%D0%B2%D0%B5%D1%81%D1%82%D0%B8-%D1%82%D0%B5%D0%BC%D1%83-%D0%B8%D0%BB%D0%B8-%D0%BF%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I wait until data from Preferences DataStore is loaded? I'm trying to make a LibGDX Live Wallpaper. But I think that is unrelated to the problem I'm having at the moment. Basically, I'm storing the wallpaper's settings inside a Preferences DataStore. Now, if you need to retrieve data from the DataStore, you need to retrieve a Kotlin Flow and use it to get the preferences. Inside LibGDX's ApplicationListener inside the onCreate() method, I need to create a KtxScreen object. I decided to pass all the preferences inside a constructor of my Screen. However, since a Flow's data can only be obtained inside a coroutine, I cannot construct my KtxScreen object with the user preferences as a constructor parameter because I need to wait until my Flow emits the values. I solved this with a very very dirty while (userPreferences == null) Unit piece of code which basically blocks the whole app until the preferences are emitted so I can construct my KtxScreen. What would be a good way to solve this?

A: It is acceptable in libGDX to block the rendering thread. This is a separate thread from the Android main thread, so it won't freeze the Android UI or put you at risk of an ANR (application not responding error). It will freeze any game/wallpaper rendering while blocking, but that's OK when you're still loading the scene.
So, it would be acceptable to use runBlocking in create() or render() to wait for the first batch of settings. Since KtxScreen doesn't use create(), you could block directly at the property initialization. You can call first() on a Flow to get just one item from it, which would be fine for initial setup of your KtxScreen class.
If you're using the ktx-async library from libKtx, you can collect your flow on the rendering thread, so then if the user updates the settings while your wallpaper is running, it will safely update your settings.
Here's one example of how you might achieve this (I didn't test it), but there are many acceptable different ways it could be handled. Note: this is assuming you instantiate this screen on the rendering thread, not the Android main thread. The rendering thread is what is used to call create() on your game class, which is the typical place to instantiate your first screen.
class MyScreen(
    val settingsFlow: Flow<UserPreferences>
): KtxScreen {

    var prefs: UserPreferences = runBlocking { settingsFlow.first() }

    init {
        settingsFlow
            .drop(1) // the first one should be the value we already got above
                     // unless the user changed them impossibly fast
            .onEach { prefs = it }
            .launchIn(KtxAsync)
    }

    //...
}

If you want to show some sort of initial loading image in your wallpaper, you could use if/else in your render function like this. But I don't think it should be necessary because preferences will take probably less than half a second to load.
class MyScreen(
    val settingsFlow: Flow<UserPreferences>
): KtxScreen {

    var _prefs: UserPreferences? = null

    init {
        settingsFlow
            .onEach { _prefs = it }
            .launchIn(KtxAsync)
    }

    override fun render() {
        val prefs = _prefs // for the sake of smart-casting
        if (prefs == null) {
            renderLoadingImage()
        } else {
            renderScene(prefs)
        }
    }

    //...

    private fun renderScene(prefs: UserPreferences) {
        //...
    }
}


text:
Q: Froala ImageUploadToS3 - AngularJS On their site, froala have the below;

 $('.selector').froalaEditor({
  imageUploadToS3: {
    bucket: 'editor',
    // Your bucket region.
    region: 's3-us-east-1',
    keyStart: 'uploads/',
    callback: function (url, key) {
      // The URL and Key returned from Amazon.
      console.log (url);
      console.log (key);
    },
    params: {
      acl: 'public-read', // ACL according to Amazon Documentation.
      AWSAccessKeyId: 'ACCESS_KEY', // Access Key from Amazon.
      policy: 'POLICY_STRING', // Policy string computed in the backend.
      signature: '', // Signature computed in the backend.
    }
  }
});

I know how to generate all the params. But how do I implement this code in AngularJS?


text:
Q: Problems using memcpy to copy from a string to void pointer I want to use memcpy to copy a string to a void pointer (the reason I'm copying to a void pointer is that in my actual application I could be copying a variety of types, so I'm trying to be general), but using the bit of example code below I run into a problem:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main( void ){
  char *str1 = strdup("Hello");

  void *str2 = malloc(strlen(str1)+1);

  fprintf(stdout, "str1 = %s\n", str1);

  memcpy(str2, str1, strlen(str1)+1);

  fprintf(stderr, "str2 = %s\n", *(char **)str2);

  free(str1);

  fprintf(stderr, "str2 = %s\n", *(char **)str2);

  return 0;
}

In this example I get a Segmentation Fault when trying to print out str2. Does anyone know why this does not work? Is it a problem with casting the void pointer to a char, or something more fundamental with memcpy? However, if I change the memcpy line to memcpy(str2, &str1, strlen(str1)+1) I can print out str2 before freeing str1, but after freeing str1 str2 has also disappeared.
I do know that it will all work if I declare str2 with char* rather than void* (and remove the casting in the output print statements), but I'd like to avoid that if possible.
Update: I've change the example code to avoid an initial memory leak.

A: Your cast is wrong. You don't want *(char **), you just want (char *), and even that isn't really necessary.
Also, your initial malloc is nothing but a memory leak, strdup allocates its own memory.


text:
Q: How to get member function's quoting type?
Possible Duplicate:
Is it possible to emulate template<auto X>?

Following C++ code worked in vc2010
template<class T, DWORD (T::*memFnPtr)() >
static DWORD WINAPI ThreadProcAdapter( __in LPVOID lpParameter )
{
    T* pThis = reinterpret_cast<T*>(lpParameter);
    return (pThis->*memFnPtr)();
}

class FooClass
{
public:

    DWORD ThreadProcFoo()
    {
        return 0;
    }
};

void fooUse()
{
    FooClass foo;
    CreateThread(NULL, 0, ThreadProcAdapter<FooClass, &FooClass::ThreadProcFoo>, &foo, 0, NULL);
}

Question: Can we make ThreadProcAdapter<> template to use only one parameter?? If so, it will be relatively easy for client to use our adapter.
template<class T>
static DWORD WINAPI ThreadProcAdapter2( __in LPVOID lpParameter )
{
    //typedef
    //theClass* pThis = reinterpret_cast<theClass*>(lpParameter);
    //return (pThis->*memFnPtr)();
    return NULL;
}

void fooUse2()
{
    FooClass foo;
    CreateThread(NULL, 0, ThreadProcAdapter2<&FooClass::ThreadProcFoo>, &foo, 0, NULL);
}

Specifically:
If we have a member function pointer
&FooClass::ThreadProcFoo

can we cacluate out its class's type
FooClass


text:
Q: Retrofit @Patch method (Updating an object, which contains an ArrayList) Note: Newbie here, please let me know if i need to provide more information or clarify on anything.
To give you some context: I am practising building a Messenger-clone application with lots of Retrofit methods. For that purpose, i am using a small local JSON server, with which the application communicates.
When a user of the application creates an account, the application creates a profile object in the JSON server using the following method:
@FormUrlEncoded
@POST("profiles")
suspend fun createProfile(@Field("username") username: String?,
                            @Field("picture") picture: String?,
                            @Field(value = "nickname") nickname: String?,
                            @Field(value = "contacts") contacts: ArrayList<String?>,
                            @Field(value = "status") status: Int?): Response<Profile>

Initially, the contacts ArrayList is empty, because the user has not yet added any contacts. Creating a random profile with an empty ArrayList() for the contacts parameter, this is the result inside the JSON server:
{
    "username": "username.example",
    "picture": "picture's URL",
    "nickname": "Nikola",
    "status": 1,
    "id": 4
}

The class that represents the Profile model inside the application is this:
class Profile(
    val username: String? = "",
    var picture: String? = "",
    var nickname: String? = "",
    var contacts: ArrayList<String?>? = ArrayList(),
    var status: Int? = 1,
    val id: Int? = 0
)

Once the profile is created, naturally the user can add new contacts, which happens using the following method:
@FormUrlEncoded
@PATCH("profiles/{id}")
suspend fun addContact(@Path("id") id: Int?,
                        @Field("contacts") contacts: ArrayList<String?>?): Response<Profile>

And here is where the problem occurs, on the very first contact added. The ArrayList, which is sent to server contains just one item and the result inside the JSON server looks like this:
{
    "username": "username.example",
    "picture": "picture's URL",
    "nickname": "Nikola",
    "status": 1,
    "id": 4,
    "contacts": "first.contact"
}

Basically, because the arraylist contains just one item, it saves it as a String. This creates all kinds of problems later on because, once the application uses a @GET method for that profile, it expects an ArrayList for the contacts attribute, but it receives a String.
What can i do to make the the JSON profile look like this:
{
    "username": "username.example",
    "picture": "picture's URL",
    "nickname": "Nikola",
    "status": 1,
    "id": 4,
    "contacts": ["first.contact"]
}

The contacts parameter needs to be an array, even when there is only one item in it.

A: Use @Body instead of @Form and @FormUrlEncoded:
data class ProfileContacts(val contacts: List<String>)

@PATCH("profiles/{id}")
suspend fun addContact(@Path("id") id: Int?, @Body contacts: ProfileContacts): Response<Profile>

and add a converter, if you haven't already had one, a Gson one for example:
// build.gradle
dependencies {
    implementation 'com.squareup.retrofit2:converter-gson:2.6.1' // latest version
}

// Retrofit Builder
val retrofit = Retrofit.Builder()
    ... // other methods
    .addConverterFactory(GsonConverterFactory.create())
    .build()

@Body lets you define the request body as a Kotlin class, which will eventually get serialized using the provided Converter (in case of Gson, it will be converted to JSON). @Field on the other hand is used for sending data as application/x-www-form-urlencoded (as the required @FormUrlEncoded annotation also suggests). This means that the body of your request will be encoded into a list of key-value pairs, separated by '&', e.g. (based on the createProfile method):
username=username.example&picture=picture%27s%20URL&nickname=Nikola&status=1&id=4

You can POST an array as application/x-www-form-urlencoded by using the same key more than once. That's what basically happens when you annotate a list with the Retrofit @Field annotation - every element from the list is paired with the common key, e.g.:
@FormUrlEncoded
@PATCH("profiles/{id}")
suspend fun addContact(@Path("id") id: Int?,
                       @Field("contacts") contacts: ArrayList<String?>?): Response<Profile>

// ...
addContact(1, arrayListOf("first.contact", "second.contact"))

// request body:
contacts=first.contact&contacts=second.contact

So when you try to update the profile using only one element contacts list, a single "contacts" pair gets created (contacts=first.contact), and it's treated like a string value.


text:
Q: style object in TextRun returning blank I have a slide with two text boxes, one with 25 point font another with 18, and I want that style info returned from
const res = await slides.presentations.get({
presentationId: '12sx74Cfsssssj88idssggggtqYVkIiajOPk',
fields: "slides" // or"slides/pageElements/shape/text/textElements/textRun/style/fontSize"
});

but the response contains blank style object:
"textRun": {
              "content": "Cool Header 25 point\n",
              "style": {}
            }

//or if masked used...

{"pageElements":[{"shape":{"text":{"textElements":[{},{"textRun":{"style":{}}}]}}},{"shape":{"text":{"textElements":[{},{"textRun":{"style":{}}}]}}},{"shape":{}},{}]}

Am I misunderstanding the style api?


text:
Q: Camel Cxf: How can I change the namespace of my incoming message? I have to change the namespace of the incoming messages to our webservice.
The consumer route looks like the following:
from("cxf:/myservice?serviceClass=myServiceClass")...

I've tried to add somehow an interceptor to this(parameter properties.in, properties.inInterceptors?), but I don't get it how to configure it to my route.
We are not configuring our cxf endpoints in spring so I have to solve it with additional parameters to the route.
I think an interceptor with the transformation feature mentioned in the cxf documentation is the right solution, but I was not able to configure it correctly.
How can I add an interceptor to the route?
Or is there another way to change the namespace of the incoming message?
kind regards,
soilworker

A: I've found a solution:
It is possible to say something like from(endpoint), so I've created an instance of CxfEndpoint and there I can set the cxfEndpointConfigurer.
In this configurer I can add an interceptor which removes the namespace(see transformation feature of cxf).
Maybe it also works somehow with the from(uri) syntax, but I don't know how.


text:
Q: Use Yiinfinite-Scroll 2 times on 1 view I implemented the Yii infinite-scroll.
Now I was wondering of its possible to use the widget twice in 1 view like:

            <?php foreach($provider->getData() as $i => $item): ?>

                    <?php echo CHtml::image($item["ImageUrl"]); ?>

<?php echo $item["User"]; ?>

<?php echo $item["Message"]; ?>

<?php echo Yii::app()->dateFormatter->formatDateTime($item["Time"]); ?>

            <?php endforeach; ?>

        <?php $this->widget("ext.yiinfinite-scroll.YiinfiniteScroller", array(
                            "itemSelector" => "div.items1",
                            "pages" => $provider->pagination)); ?>

             <?php foreach($provider->getOtherData() as $i => $item): ?>

                     <?php echo CHtml::image($item["ImageUrl"]); ?>

<?php echo $item["User"]; ?>

<?php echo $item["Message"]; ?>

<?php echo Yii::app()->dateFormatter->formatDateTime($item["Time"]); ?>

             <?php endforeach; ?>

         <?php $this->widget("ext.yiinfinite-scroll.YiinfiniteScroller", array(
                                "itemSelector" => "div.items2",
                                "pages" => $provider->pagination)); ?>

When I use this, only the first infinite scroll works. How do I get the second to work?


text:
Q: Macro function with string of fprintf This code snippet:
#define ERROR_MSG_DETAIL(msg_str) \
   fprintf(stderr, (msg_str) "%s\n, at # %d, file: %s\n", strerror(errno), __LINE__, __FILE__)

I wish I just input the error message
ERROR_MSG_DETAIL("my errors")

Macro should be expend to
fprintf(stderr, "my errors" "%s\n, at # %d, file: %s\n", strerror(errno), __LINE__, __FILE__)

The result should look like:
my errors
at # 15, file: t.c

but I got this error message when compile
 error: expected ')' before string constant
   11 |  fprintf(stderr, (msg_str) "%s\n, at # %d, file: %s\n", strerror(errno), __LINE__, __FILE__)
      |                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~

How do I solve it?

A: You can only concatenate string literals if there is no parentheses between them, so you should change your macro removing parentheses around msg_str:
#define ERROR_MSG_DETAIL(msg_str) \
   fprintf(stderr, msg_str ": %s\n, at # %d, file: %s\n", strerror(errno), __LINE__, __FILE__)

A: A better approach could have been to define the macro like this:
#define ERROR_MSG_DETAIL(msg_str) \
    fprintf(stderr, "%s%s\n, at # %d, file: %s\n", (msg_str), strerror(errno), __LINE__, __FILE__)

Your approach (even if it was syntactically correct) would have resulted in undefined behaviour if the string denominated by msg_str contained a % character, which means
fprintf would attempt to interpret that character. The approach above will work for every string, independent of the contained characters. As an aside, msg_str doesn't have to be a string literal; this approach will also work if the msg_str is a pointer to char, provided that it points to a string.


text:
Q: Using the YouTube API when starting an Activity I have a problem with android, I want to play a video with youtube api, I created a activity in main that references is car.class, but when I compile show error
I have main class with the last code:
Intent i=new Intent(this,car.class);
                startActivity(i);

Moreover I have a car class with the last code:
public class car extends  Activity implements YouTubePlayer.OnInitializedListener{

  @Override
  public void onInitializationSuccess(Provider provider, YouTubePlayer player,boolean     wasRestored) {
            ytp=player;

            Toast.makeText(this, "Initialization  Success", Toast.LENGTH_LONG).show();
        }

Error is:
 FATAL EXCEPTION: main
    java.lang.NoClassDefFoundError: com.example.car
            at com.example.MainActivity.onClick(MainActivity.java:78)

What can I do?

A: Try to use following code:
Intent i = new Intent(YOUR_ACTIVITY_NAME.this, car.class);
startActivity(i);

This should solve the problem.

A: the error NoClassDefFoundError: maybe is that, you must define the activity in your Manifest file or you don't have import the correct library


text:
Q: how to set min month at bootstrap datepicker I have a web application which requires a month/year date to be entered.Currently i am using  bootstrap datepicker to show the month of the year.
var minDate = new Date();
minDate.setMonth(minDate.getMonth()-1, 1);
$("#datepicker").datepicker( {
      minDate: minDate,
    format: "mm-yyyy",
    viewMode: "months",
    minViewMode: "months"
});

The code above allow the user to select previous month or last month.How can i restrict the user to select previous month or last month by modify the code above?
JSFiddle

A: You can set a selectable range, using startDate and endDate
For further info, on the available options, check the docs https://bootstrap-datepicker.readthedocs.org/en/latest/options.html


text:
Q: Regex replace any occurence of any digit or any character with desired characters I need help sorting out a solution for a pattern generator.
I have an application that uses exchange formats with different patterns
like
00350-ABA-0NZ0:AXYA-11/11/2012 etc.,
that have numeric and alphanumeric data separated by '-','.',":" and '/'. Now what I want to do is convert this to a generic format like
nnnnn-ccc-nccn:cccc-nn/nn/nnnn where n is a digit and c is a character.
Any help/suggestions/ideas . . .
Thanks
CSK.

A: You can't do conditional replaces in a single regex. You need to do it in two steps (here's a Python example):
>>> s = "00350-ABA-0NZ0:AXYA-11/11/2012"
>>> s = re.sub(r"[A-Za-z]", "c", s)
>>> s
'00350-ccc-0cc0:cccc-11/11/2012'
>>> s = re.sub(r"\d", "n", s)
>>> s
'nnnnn-ccc-nccn:cccc-nn/nn/nnnn'

And you need to do it this way around - I just saw your solution in your comment, and if you look at it again, you'll see it won't work. Hint: You'll get 'ccccc-ccc-cccc:cccc-cc/cc/cccc' as a result...
Another solution would be to use a callback function that examines the match and chooses the replacement string accordingly. But that's not pure regex anymore:
>>> def replace(m):
...     return "n" if m.group(0).isdigit() else "c"
...
>>> s = re.sub(r"[A-Za-z0-9]", replace, s)
>>> s
'nnnnn-ccc-nccn:cccc-nn/nn/nnnn'


text:
Q: Conditional expectation conditioned on an Indicator variable Suppose I have a random variable $u$ that is standard uniformly distributed.
And I have an indicator variable $S_{i}=1\left(V_{i}>0.5\right)$.
Now I am interested in the following conditional expectation.
$\mathbb{E}\left[u\mid S_{i}=1\right]$.
Now $u$ is continuous whereas $S_i$ is discrete.
I do know that when X and Y are both continoious $E[X \mid Y=y]=\int_{-\infty}^{\infty} x f_{X \mid Y}(x \mid y) d x$. And if X and Y are both discrete $E[X \mid Y=y]=\sum_{x} x f_{X \mid Y}(x \mid y)$
However, I am not sure how to write $\mathbb{E}\left[u\mid S_{i}=1\right]$ as either a summation or integral.
I am trying to find
$\mathrm{ATET}=-\delta_0\cdot \mathbb{E}\left[u^2\mid S_{i}=1\right]+\delta_1\cdot \mathbb{E}\left[u\mid S_{i}=1\right]+\delta_2$
Where I know the joint distribution
\begin{equation}
F_{U, V}(u, v)=u v+\theta u(1-u) v(1-v)
\end{equation}
And u and v are uniformly distributed on [0,1]
When I follow your proposition I obtain
$\frac{1}{2}\int_0^1u*1du=\frac{1}{4}$
However this does not seem to be a right solution to me

A: "$S_i=1$" is exactly the event $E = \{V_i>0.5\}$ so the conditional expectation is given by
$$\mathbb{E}\left[u\mid S_{i}=1\right] = \frac{1}{\mathbb P(E)}\int_E xf(x)dx $$
Where $f$ is the pdf of $u$.


text:
Q: Variables aren't getting updated with the proper values I'm making a java program for the system used at Luas Station to purchase tickets. The Luas is a type of train in the Ireland.
I have a few different types of tickets which involves various prices etc. After a customer selects what ticket to buy I give them an option to return to the beginning of the 'chooseTickets' to buy more tickets. At the end, the program I have assigned the value of all of the customer's desired tickets as the completePrice variable. the idea is to allow for the customer to continue adding tickets and for that variable to continuously add the prices of them to the variable until they're ready to pay. It works except when I go back to purchase for tickets and it is the same type, i.e a standard adult ticket twice. The price of 2.50 is not added to another 2.50, it is overwritten by another 2.5. Below is the code for the same:
import java.util.Scanner; //imports the scanner class to allow for user input

public class ticketPurchase {
//Adding global variables to be used by various methods
static Scanner input = new Scanner(System.in);
static String menuChoice;
static double childTicket = 1.20;
static double adultTicket = 2.50;
static double studentTicket = 1.70;
static double adultFlexi = 12.00;
static double childFlexi = 8.00;
static double studentFlexi;
static String ticketType;
static String ticketChoice;
static int adultTicketQty;
static int childTicketQty;
static int studentTicketQty;
static String destinationZone;
static double adultFinalPrice;
static double childFinalPrice;
static double studentFinalPrice;
static double flexiAdultFinalPrice;
static double flexiChildFinalPrice;
static double completePrice;
static String moreTicketChoice2 = "0";

public static void main(String[] args) {
    menu(); //calling the menu method within the main method to start the process
}
public static void menu() {
    if(moreTicketChoice2.equals("1")){
        System.out.println("Press 2 to purchase Standard Tickets");
        System.out.println("Press 3 to purchase Flexi tickets");
        System.out.println("press 4 to purchase student tickets");
    }
    else if(moreTicketChoice2.equals("0")) {
        System.out.println("Press 1 for information");
        System.out.println("Press 2 to purchase Standard Tickets");
        System.out.println("Press 3 to purchase Flexi tickets");
        System.out.println("press 4 to purchase student tickets");
    }
    menuChoice = input.next(); //allowing user to choose what tickets to buy or just to see information of services

    switch(menuChoice) { //switch statement to record and output information based on users input
    case "1":{ //prints information regarding pricing, ticket age restrictions and support
        System.out.println("The standard ticket may be a single or return ticket for an adult (16+) or a child");
        System.out.println("The flexi ticket covers all journeys for one 24 hour period for either a child or an adult");
        System.out.println("A single ticket's price depends on the journey length, single or return and if it is for an adult or a child");
        System.out.println("a Flexi ticket for a child costs €8.00 and a Flexi ticket for an adult costs €12.00");
        System.out.println("Our Customer Care telephone number for this terminal is 0830462920, please call if further support is required");
        menu();
        break;
    }
    case "2":{
        ticketChoice = "standard"; //records the value of standard within the ticketChoice global variable
        chooseTickets(); //initiates the choose tickets method
        break;
    }
    case "3":{
        ticketChoice = "flexi"; //record the value of Flexi within the ticketChoice global variable
        chooseTickets();
        break;
    }
    case "4":{
        ticketChoice = "student";
        chooseTickets();
    }
    case "a":{ //allows user to enter the admin interface
        admin();
        break;
    }
    default:{ //allows for user to input a value outside of the options and notify's them to try again
        System.out.println("Invalid choice, please choose from 1 to 3");
        break;
    }
    }

}
public static void chooseTickets() { //payment method to choose quantity, destination zone and final price
    System.out.println("You have chosen to purchase " + ticketChoice + " ticket(s)");
    if(ticketChoice.equals("student")) { //allows user to purchase student's tickets
        ticketType = "student";
        System.out.println("Please enter the quantity of tickets: ");
        studentTicketQty = input.nextInt();
        System.out.print("please enter your destination zone (1, 2, 3, 4): ");
        destinationZone = input.next();
        ticketChoice = "student";
            studentFinalPrice = (studentTicket*studentTicketQty);
        switch(destinationZone){ //adjusts price to account for the destination's zone chosen by user
        case "1":{
            studentFinalPrice = studentFinalPrice + (studentTicketQty*0);
            break;
        }
        case "2":{
            studentFinalPrice = studentFinalPrice + (studentTicketQty*0.50);
            break;
        }
        case "3":{
            studentFinalPrice = studentFinalPrice + (studentTicketQty*1.0);
            break;
        }
        case "4":{
            studentFinalPrice = studentFinalPrice + (studentTicketQty*1.50);
            break;
        }
        default:{
            System.out.println("you have entered an invalid choice please choose from 1 to 4");
            chooseTickets();
            break;
        }
        }
        System.out.print("would you like to purchase more tickets? enter 1 if so, 2 if not: "); //allows user to purchase other tickets
        moreTicketChoice2 = input.next();
        if(moreTicketChoice2.equals("1")) {
            menu();
        }
        else if(moreTicketChoice2.equals("2")){
            System.out.println("you have chosen against purchasing more tickets");
            payment();
        }

    }
    else {
        System.out.print("please enter 1 for children's tickets and 2 for adult's: ");
        String ticketAgeGroup = input.next();
        switch(ticketAgeGroup) { //allows user to choose quantity and destination based on choice of adult or child
        case "2":{//case for adult tickets
            System.out.println("you have chosen adults ticket");
            ticketType = "adult";
            System.out.print("Please enter the quantity of tickets: ");
            adultTicketQty = input.nextInt();
            System.out.print("please enter your destination zone (1, 2, 3, 4): ");
            destinationZone = input.next();
            if(ticketChoice == "flexi") { //if statement to calculate the finalPrice variable value if the ticketChoice is Flexi
                flexiAdultFinalPrice = (adultFlexi*adultTicketQty);
            }
            else {
                adultFinalPrice = (adultTicket*adultTicketQty); //else calculates the finalPrice variable value if the ticketChoice is standard
            }
            switch(destinationZone){ // switch statement to calculate the final price depending on the destination's zone and their extra amount.
            case "1":{
                adultFinalPrice = adultFinalPrice + (adultTicketQty*0);
                break;
            }
            case "2":{
                adultFinalPrice = adultFinalPrice + (adultTicketQty*.50); //calculation to add the extra amount for the destination
                break;
            }
            case "3":{
                adultFinalPrice = adultFinalPrice + (adultTicketQty*1.0);
                break;
            }
            case "4":{
                adultFinalPrice = adultFinalPrice + (adultTicketQty*1.50);
                break;
            }
            default:{
                System.out.println("you have entered an invalid choice please choose from 1 to 4");
                break;
            }
            } //end of the switch statement

            System.out.print("Would you like to purchase more tickets? enter 1 if so, 2 if not: "); //allows user to purchase other tickets
            moreTicketChoice2 = input.next();
            if(moreTicketChoice2.equals("1")) { //if statement to allow a customer to purchase more tickets if required
                menu();
            }
            else {
                System.out.println("you have chosen against purchasing more tickets");
                payment(); //proceeds to the payment method
            }

            break;
        }

        case "1":{ //case for children's tickets
            System.out.println("you have chosen children's ticket");
            ticketType = "child";
            System.out.println("Please enter the quantity of tickets: ");
            childTicketQty = input.nextInt();
            System.out.print("please enter your destination zone (1, 2, 3, 4): ");
            destinationZone = input.next();
            if(ticketChoice == "flexi") { //adjusts the price if user chooses the flexi option
                flexiChildFinalPrice = (childFlexi*childTicketQty);
            }
            else {
                childFinalPrice = (childTicket*childTicketQty);
            }
            switch(destinationZone){ //adjusts price to account for the destination's zone chosen by user
            case "1":{
                childFinalPrice = childFinalPrice + (childTicketQty*0);
                break;
            }
            case "2":{
                childFinalPrice = childFinalPrice + (childTicketQty*.50);
                break;
            }
            case "3":{
                childFinalPrice = childFinalPrice + (childTicketQty*1.0);
                break;
            }
            case "4":{
                childFinalPrice = childFinalPrice + (childTicketQty*1.50);
                break;
            }
            default:{
                System.out.println("you have entered an invalid choice please choose from 1 to 4");
                chooseTickets();
                break;
            }
            }

            System.out.print("would you like to purchase more tickets? enter 1 if so, 2 if not: "); //allows user to purchase other tickets
            moreTicketChoice2 = input.next();
            if(moreTicketChoice2.equals("1")) {
                menu();
            }
            else if(moreTicketChoice2.equals("2")){
                System.out.println("you have chosen against purchasing more tickets");
                payment();
            }
            break;
        }
    }
    }
    }
public static void payment() { //method to complete the payment process for the purchase
    completePrice = adultFinalPrice + childFinalPrice + studentFinalPrice + flexiAdultFinalPrice + flexiChildFinalPrice;
    System.out.println("the total due is €" + completePrice);

}
public static void printTickets() { //method to notify the customer that their tickets are printing

}
public static void admin() { //method to control the admin's interface

}

}
In this photo i want an output of 2.4 not 1.2


text:
Q: PDF parser in pdfs with multiple images and formats with python and tabula (open to other options) So first off what im trying to do: create a pdf parser that will take ONLY tables out of any given pdf. I currently have some pdfs that are for parts manuals which contain an image of the part and then a table for details of the parts and I want to scrape and parse the table data from the pdf into a csv or similar excel style file(csv, xls etc)
What ive tried/trying: I am currently using python3 and tabula(i have no preference for either of these and open to other options) in which I have a py program that is able to scrape all the data of any pdf or directory of pdfs however it takes EVERYTHING including the image file code that has a bunch of 0 1 NaN(adding examples at the bottom). I was thinking of writing a filter function that removes these however that feels like overkill and was wondering/hoping there is a way to filter out the images with tabula or another library? (side note ive also attempted camelot however the module is not importing correctly even when it is in my pip freeze and this happens on both my mac m1 and mac m2 so assuming there is no arm support)
If anyone could help me or help guide me in a direction of a library or method of being able to iterate through all pages in a pdf and JUST grab the tables for export t csv that would be AMAZING!
current main file:
from tabula.io import read_pdf;
from traceback import print_tb;
import pandas as pd;
from tabulate import tabulate;
import os
def parser(fileName, count):
print("\nFile Number: ",count, "\nNow parsing file: ", fileName)
  df = read_pdf(fileName, pages="all") #address of pdf file
  for i in range(len(df)):
      df[i].to_excel("./output/test"+str(i)+".xlsx")
  print(tabulate(df))
  print_tb(df)
def reader(type):
  filecount = 1
  if(type == 'f'):
    file = input("\nFile(f) type selected\nplease enter full file name with path (ex. Users/Name/directory1/filename.pdf: ")
    parser(file, filecount)

  elif(type == 'd'):
    #directory selected
    location = input("\nPlease enter diectory path, if in the same folder just enter a period(.)")
    print("Opening directory: ", location)
    #loop through and parse directory
    for filename in os.listdir(location):
        f = os.path.join(location, filename)
        # checking if it is a file
        if os.path.isfile(f):
            parser(f, filecount)
            filecount + 1
        else:
            print('\n\n ERROR, path given does not contain a file or is not a directory type..')
else:
    print("Error: please select directory(d) or file(f)")

fileType = input("\n-----> Hello!\n----> Would you like to parse a directory(d) or file(f)?").lower()
reader(fileType)


text:
Q: list comprehension and repeated inner reference I wanted to reformat a text based on recognition by a regex.
so i basically made
regex= re.compile("(group1)(group2)(group3)(group4)")
text_groups=regex.search(text).groups()

text_groups is a list with enclosed groups.
I wanted to change the order in a constant manner.
I know that I can do it with
reordered_groups=np.array(text_groups)[[1,3,0]

but that's not my problem.
In order to avoid the conversion to np.array that would be computationally inefficient as string are involved, I preferred to use a list comprehension, with the added advantage to be able to filter based on condition:
reordered_groups=[ text_groups[i] if text_groups[i] is not None else "" for i in [2, 4, 1, 5] ]

I think that text_groups[i] repeat is ugly, and probably inefficient if you consider using similar technique on large lists, because you will call the index twice. How can we avoid that while not using for loops, which are inefficient on their own?

A: You want to use or - when text_groups[i] is None, or will return the right-side of the statement, so you could do:
reordered_groups = [text_groups[i] or '' for i in [2, 4, 1, 5]]

For example, the following:
text_groups = ['e', None, 'c', 'f', 'x', None]
reordered_groups = [text_groups[i] or '' for i in [2, 4, 1, 5]]

returns:
['c', 'x', '', '']


text:
Q: Dependent (Procedural) Unit Testing in Visual Studio 2012 In an MVC4 C# website, we are using Unit Testing to test our code. What we are currently doing is creating a mock database, then testing each layer:

*

*Test the Database - connecting, initializing, load, etc.

*Test the code accessing the database

*Test the view layer

I want these three categories to be run in order and only if the previous one passed. Is this the right way to go about it? The old way we were doing it was using a Dependency Injection framework was a weird approach to mock testing. We actually created a mock class for each data accessor, which sucks because we have to re implement the logic of each method, and it didn't really add any value because if we made a mistake with the logic the first time, we'll make it a second.

A:
I want these three categories to be run in order and only if the
  previous one passed. Is this the right way to go about it?

No. You should be test everything in isolation and because of that any failing data access code should be completely unrelated to the view. So the view unit tests should fail for a completely different reason and because of that you should always run all tests.
In general, tests should run in isolation, and should not depend on any other tests. It seems to me that the view layer still depends on the data access code, but that you only abstracted the layer below. In that case, from the view's perspective, you are mocking an indirect dependency, which makes your unit tests more complex than strictly needed.

The old way we were doing it was using a Dependency Injection
  framework was a weird approach to mock testing

I'm not sure if I get this, but it seems as if you were using the DI container inside your unit tests. This is a absolute no-no. Don't clutter your tests with any DI framework. And there's no need to. Just design your classes around the dependency injection principle (expose all dependencies as constructor arguments) and in your test you just manually new up the class under test with fake dependencies -or- when this leads to repetitive code, create a factory method in your test class that creates a new instance of the class under test.

We actually created a mock class for each data accessor, which sucks

I'm not sure, but it sounds as if there's something wrong with your design here. You would normally have a IRepository<T> interface for which you would have multiple implementations, such as a UserRepository : IRepository<User>, and OrderRepository : IRepository<Order>. In your test suite, you will have one generic FakeRespository<T> or InMemoryRepository<T> and you're done. No need to mock many classes here.
Here are two great books you should definitely read:

*

*The Art of Unit Testing

*Dependency Injection in .NET
Those books will change your life. And since you'll be reading anyway, do read this book as well (not related to your question, but code be a life changer as well).


text:
Q: PID torque control of motor I'm trying to control the motor torque. This I'm trying to accomplish by implementing a PID control on motor current and hence on the PWM. Higher PWM means higher torque.
I'm new to arduino-uno, hence would need help with the coding. I have written a code for the same but a bit unsure on its correctness. I'm still unsure about the value of the 'Integral' variable to be used though.
Any help is much appreciated
Thanks in advance
#include "RunningAverage.h"
 int m1 = 13;
int m2 = 12;
int me = 9;
int t = millis()+5000;
RunningAverage myRA(80);
int stat=0;
int pwmn=100;
int counter=0;
int kP;
int kI=0;
int kD=0;
int SetPt;
int Last;
int Actual;
int Error;
int Integral;
float P;
float I;
float D;
int Drive;
int ScaleFactor;

void motorRight(){
digitalWrite(m1,HIGH);
digitalWrite(m2, LOW);
}

void motorLeft(){
digitalWrite(m2,HIGH);
digitalWrite(m1, LOW);
}

void motorOff(){
digitalWrite(m2, LOW);
digitalWrite(m1, LOW);
}

void motorBrake(){
digitalWrite(m2, HIGH);
digitalWrite(m1, HIGH);
delay(10);
motorOff();
}

void setup() {
// put your setup code here, to run once:
pinMode(m1,OUTPUT);
pinMode(m2,OUTPUT);
pinMode(me,OUTPUT);
analogWrite(me,pwmn);
Serial.begin(115200);
motorRight();
}

void loop() {
// put your main code here, to run repeatedly:
myRA.addValue(analogRead(A1));
Serial.print(myRA.getAverage());
Serial.println(",500,600");
Actual = myRA.getAverage();
Error = SetPt - Actual;
P = Error*kP; // calc proportional term
I = Integral*kI; // integral term
D = (Last-Actual)*kD; // derivative term
Drive = P + I + D; // Total drive = P+I+D
Drive = Drive*ScaleFactor; // scale Drive to be in the range 0-255
//Serial.println(pwmn);
if(counter>10){
if(pwmn<250){
pwmn++;
}
counter=0;
}
counter++;
if (abs(Drive)>255) {
Drive=255;
}
analogWrite (me,Drive); // send PWM command to motor board
Last = Actual; // save current value for next time
// analogWrite(me,pwmn);
delay(50);
}'

A: You are correct, the integral calculation is wrong.  Integral (from integrate) means to add up.  What you want is
I = I + kI*Error;

You should also limit the Integral term (I) to some maximum and minimum value to avoid "wind-up" error.  This happens when the servo cannot reach is goal and since the I term is the sum of the errors it can get out of control.


text:
Q: Parsing Dates for from CSV for SQL I am using the LOAD DATA LOCAL INFILE function to pull log data from a csv into a mysql DB so I can use it in Rails.
Using the answer to this question:
Modify CSV field on import to mysql
The only issue I have is how to parse my date time field.
Thu Mar 01 11:49:16 +0000 2012
STR_TO_DATE(@csvdate, '??????????')

A: Try to use STR_TO_DATE function. For example -
SET @date = 'Thu Mar 01 11:49:16 2012';
SELECT STR_TO_DATE(@date, '%a %b %d %H:%i:%S %Y');

STR_TO_DATE function.


text: Q: why is it desirable to have fewer explanatory variables in the second stage of a Heckman test? My old lecturer recommended that the second stage of a henchman test should preferably contain at least one fewer explanatory variables than the first (selection) stage. what is the precise reasoning behind this and does it matter when the variable list is relatively large (17 explanatory variables)? thanks!


text:
Q: Collapse button not moving Got this resource from a friend ,  fiddled around the codes
i want to move this bar down because it is blocking the text, when i add padding-top you can see the image what happened.
    #header .header-btn-collapse-nav {
    outline: 0;
    display: block;
    position: relative;
    z-index: 1;
}

Thank you
bar

A: try using margin-top: 100px; instead of padding.

A: Padding creates "inner spacing" in between the parent and child elements, whereby margin is responsible for "outer spacing".
If you want to move the button downwards, without it taking up more screen space, you'll have to use margin-top: 100px; instead


text:
Q: How do I connect to a Local MSSQL Database EDIT: I've just tested it in ASP.NET and it works perfectly fine. So no issue with the connection string or anything. Guess Unity doesn't like this method? Maybe there's some more DLL's I need to copy? Any ideas?
So I'm making a game in Unity and I'm trying to use the System.Data.SqlClient library to connect to some stored procedures I have made for things such as registering a user.
I have copied the System.Data.dll from "C:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity" and that has all worked fine.
I'm currently using this connection string, which works fine on an ASP.NET application but just using a different mdf:
private string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\uppy8\Desktop\Computer Science Project\Mining Game\Assets\MineRace.mdf';Integrated Security = True";

The problem occurs when running this code:
using System.Data.SqlClient;
using System.IO;

public void Login()
{
    Crypto crypto = new Crypto();

    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        try
        {
            conn.Open();
        } catch (Exception e)
        {
            Debug.Log(e);
        }

        SqlCommand command = new SqlCommand("USERS_LOGIN_USER", conn);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@Username", usernameInputField.text));

        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                if (crypto.EncryptString(passwordInputField.text) == reader["password"].ToString())
                {
                    UserAccountManager.instance.userInfo = FetchUserInfo((int)reader["id"]);
                }
            }
        }
    }

The problem happens on the line "conn.Open()", where Unity gives me the error:
System.Net.Sockets.SocketException: No such host is known.

Furthermore, without the try catch, the error occurs where I create a new SqlDataReader, where I get this issue:
InvalidOperationException: ExecuteReader requires an open connection to continue. This connection is closed.

I understand that this is an issue with the connection, in that it's not running or the connection isn't working properly, however I can't seem to find a solution and I have a sneaky suspicion that it's something to do with Unity not supporting this library.
Some more clarification just before I end off:

*

*The user enters their credentials into the "usernameInputField" and "passwordInputField"

*The user presses Login, which runs the "Login" method shown above

*The error occurs.

If any more information is required please leave a comment.
Thanks!

A: What is the scope of connectionString?  Do you need to pass the connectionString to the Login() function?
public void Login(string connectionString)

I am a DBA, not a .Net developer, so forgive me if my questions are too basic or if my .Net syntax is wrong.

A: You can try this
string connectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog ='C:\USERS\uppy8\Desktop\Computer Science Project\Mining Game\Assets\MineRace.mdf'; Integrated Security = True; Connect Timeout = 30; Encrypt = False; TrustServerCertificate = True; ApplicationIntent = ReadWrite; MultiSubnetFailover = False"
        SqlConnection con = new SqlConnection();
                    if (con.State==ConnectionState.Open)
                    {
                        con.Close();
                        con.ConnectionString = connectionString;
                        con.Open();
                        cmd.Connection = con;
                    }
                    else
                    {
                        con.ConnectionString = connectionString;
                        con.Open();
                        cmd.Connection = con;
                    }


text: Q: How to not reinstall packages when installing a bunch of package? I saved the pacman -Qqe output from a previous arch install and now I'm using this list to install all the packages I had at once. However some of them are already installed and it wants to reinstall them which I fear will break things. Is there a pacman parameter to ignore the packages that are already installed? Or at least not to reinstall them but just update.


text:
Q: Conversion to Dalvik format failed with error 1 with a scary message in the Console view I've seen a few questions with this topic, but when I search for the other part I have in my error, I don't find anything, so I decided to post a question with the full explanation.
No errors are recognized in my code. Nowhere. All libraries are added, external library projects are successfully linked. There is no indication that anything should go wrong with a launch.
Yet, when I launch the application - Run, compile and build (automatically) - I get a pop up message stating that my project contains error(s) and that I should please fix them before attempting to launch the application again.
So I fiddle around with some properties, my colleague discovers that "Android Private Libraries" has to be checked in Properties -> Java Build Path -> Order and Export (which I've checked an unchecked along with the other check boxes, before). But when I run the application - same pop up, and the following in the Console view: (scary message)
[2013-06-22 20:55:03 - TheApplication] Dx
trouble processing "java/sql/Savepoint.class":

Ill-advised or mistaken usage of a core class (java.* or javax.*)
when not building a core library.

This is often due to inadvertently including a core library file
in your application's project, when using an IDE (such as
Eclipse). If you are sure you're not intentionally defining a
core class, then this is the most likely explanation of what's
going on.

However, you might actually be trying to define a class in a core
namespace, the source of which you may have taken, for example,
from a non-Android virtual machine project. This will most
assuredly not work. At a minimum, it jeopardizes the
compatibility of your app with future versions of the platform.
It is also often of questionable legality.

If you really intend to build a core library -- which is only
appropriate as part of creating a full virtual machine
distribution, as opposed to compiling an application -- then use
the "--core-library" option to suppress this error message.

If you go ahead and use "--core-library" but are in fact
building an application, then be forewarned that your application
will still fail to build or run, at some point. Please be
prepared for angry customers who find, for example, that your
application ceases to function once they upgrade their operating
system. You will be to blame for this problem.

If you are legitimately using some code that happens to be in a
core package, then the easiest safe alternative you have is to
repackage that code. That is, move the classes in question into
your own package namespace. This means that they will never be in
conflict with core system classes. JarJar is a tool that may help
you in this endeavor. If you find that you cannot do this, then
that is an indication that the path you are on will ultimately
lead to pain, suffering, grief, and lamentation.

[2013-06-22 20:55:03 - TheApplication] Dx 1 error; aborting
[2013-06-22 20:55:03 - TheApplication] Conversion to Dalvik format failed with error 1

Has anyone gotten this message before? Why am I getting it? Where should I go look for "hidden libraries" or "internal libraries" that I might not even be aware of?
I've checked with my boss and colleague - they all have the same libraries in the project (since we're working on it together we obviously have to have the same things). So where should I go looking to fix this problem?

A:
Has anyone gotten this message before?

Yes. Not since 2009, though.

Why am I getting it?

Because in the source code of your project, or in a JAR, you have another copy of the java.sql.Savepoint interface, other than the one that comes from the Android runtime.

Where should I go look for "hidden libraries" or "internal libraries" that I might not even be aware of?

Your Eclipse classpath. You may wish to edit your question with a screenshot of your "Order & Export" screen from the build path dialog.

A: I solve that removing android.jar in "Order and Export" tab in the proyect and in the libraries.

A: Had the same issue.
The following action helped me to get rid of this error message.
1) Go to Project--> properties-->Java Build Path
2) Select Order and Export tab
3) Deselect the Android Private Libraries and Android Dependencies and click ok

After this the application got launched successfully.


text:
Q: Make menu keep its css attribute after redirection to other page I made an accordion menu on Wordpress page. Parent of sub-menu has class "dropdown".
CSS
.dropdown .sub-menu {
    display: none;
}
.dropdown {
     list-style-type: square;
}

JQ
jQuery(document).ready(function(){

     jQuery('#menu-produkty_menu .dropdown a').click(function(e){
          if (jQuery(this).parent().children('.sub-menu:first').is(':visible')) {
               jQuery(this).parent().children('.sub-menu:first').hide();
          } else {
               jQuery(this).parent().children('.sub-menu:first').show();
          };
     });
});

Sub-menu is  and contains
* with hyperlink .
It works fine, but whenever i click on any hyperlink from sub-menu it redirects me to other page so it gets to the basic state => all sub-menus hidden. I want sub-menu to keep opened/closed after redirection. I have never worked with database/cookie etc. so I have no idea where to start. How do I achieve that css attribe keeps changed in all pages?

A: I think it would be easier to do this by adding a class instead of changing the css attribute
eg

title

After changing this you can add this "active" class in your php file generating your menu.
Could you provide some html code of your accordion menu or better a url of the page?
Upate:
After looking more carefully i discovered you dont need to edit any php file. The only thing you need to do is toggle the .current-menu-ancestor class for the selected li. Check the fiddle again.
jsFiddle


text:
Q: Spring MVC - Cannot mapping controllers correctly I'm new with Spring MVC and I have to create a project from scratch, I decided to use Spring MVC but have some problems to map the controllers in the servlet-dispatcher.xml and to access methods from the view.
The structure of my project is this:
project
My web.xml:
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
        </context-param>

        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>

        <servlet>
            <servlet-name>dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>*.htm</url-pattern>
        </servlet-mapping>

        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>

        <welcome-file-list>
            <welcome-file>redirect.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

My dispatcher-servlet.xml
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:simple="http://cxf.apache.org/simple"
    xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://cxf.apache.org/simple
        http://cxf.apache.org/schemas/simple.xsd
        http://cxf.apache.org/jaxws
        http://cxf.apache.org/schemas/jaxws.xsd">

    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
                <props>
                    <prop key="login.htm">loginController</prop>
                    <prop key="index.htm">indexController</prop>
                </props>
        </property>
    </bean>

    <bean id="viewResolver" p:prefix="/WEB-INF/pages/" p:suffix=".jsp" class="org.springframework.web.servlet.view.InternalResourceViewResolver" />

    <bean name="loginController" p:viewName="login" class="org.springframework.web.servlet.mvc.ParameterizableViewController" />

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
    <bean id="indexController" class="com.controller.IndexController" />

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="en" />
    </bean>
    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
            <property name="paramName" value="locale" />
        </bean>
    </mvc:interceptors>
</beans>

My Controller [LoginController.java]
    package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {

    @RequestMapping(value = "validar")
    public ModelAndView login(){
        System.out.println("Entro al controller de Login");
        ModelAndView model = new ModelAndView();
        model.setViewName("index"); //Go to Index after validating the user

        return model;
    }
}

My Login.jsp
<%@ taglib uri="http://www.springframework.org/tags" prefix="intl"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Creative - Bootstrap 3 Responsive Admin Template">
    <meta name="author" content="GeeksLabs">
    <meta name="keyword" content="Creative, Dashboard, Admin, Template, Theme, Bootstrap, Responsive, Retina, Minimal">
    <link rel="shortcut icon" href="img/favicon.ico">

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/bootstrap-theme.css" rel="stylesheet">

    <link href="css/elegant-icons-style.css" rel="stylesheet" />
    <link href="css/font-awesome.css" rel="stylesheet" />

    <link href="css/style.css" rel="stylesheet">
    <link href="css/style-responsive.css" rel="stylesheet" />

    <title>Admin Console</title>

        <form class="login-form" id="frmLogin" method="POST">

<intl:message code="label.appTitle" />

              <input type="text" class="form-control" placeholder="<intl:message code="label.username" />"  autofocus>

                <input type="password" class="form-control" placeholder="<intl:message code="label.password" />">

                <input type="checkbox" value="remember-me"><intl:message code="label.rememberMe" />

                    <select id="lang" onchange="onChange()">
                        <option value="es">Español</option>
                        <option value="en">Ingles</option>
                    </select>
                    <input type="hidden" id="lang"/>

            <button class="btn btn-primary btn-lg btn-block" type="submit"><intl:message code="label.loginText" /></button>

      </form>

I look that when you start the application, the Login.jsp view is loaded (this work) and pressing Login LoginController and then will go to index.jsp that is the view of the Dashboard from the aplication.
My mistake is that I can not access the LoginController and method "enter".
Could you please help me?

A: Your are missing the action in your <form class="login-form" id="frmLogin" method="POST">
It needs to be like:
<form class="login-form" id="frmLogin" action="validar" method="POST">


text:
Q: VSX - How to save options page data I've create a Custom Options Page with a few TextBoxes, ComboBoxes etc etc.
I have 2 questions though:

*

*I can see that the values I input in the fields remain there if I close/reopen the Options Windows but that doesnt happen if I close VS and reopen. How can I make sure the data is stored "for real?"

*How can I access these values from a Action Menu? For instance, I have a menu option Tools > MyButton that will take the values from the options and do some stuff.
Thanks in advance!


text:
Q: Ban local loop-back traffic with exception on a port on Ubuntu I would like to ban all the local loop-back traffic on my Ubuntu computer, with the exception that loop-back traffic to or from port 2947 (gpsd service port) should be allowed. How do I achieve this?
The command I used to ban loop-back traffic are:
iptables -A INPUT -i lo -j DROP
iptables -A OUTPUT -o lo -j DROP

A: iptables -A INPUT -i lo -p tcp --dport 2947 -j ACCEPT
iptables -A OUTPUT -o lo -p tcp --sport 2947 -j ACCEPT
iptables -A INPUT -i lo -j DROP
iptables -A OUTPUT -o lo -j DROP

(But remember: it will probably cause a bunch of mystical errors)


text:
Q: Adding an image to a div doesn't display unless there is content If I add a background image to a div using CSS, I can't view the image until I add some content/text inside of the div.
Why is that?

A: Because background image does not give div content.
An empty div without width/height defined will not show. A div does not have natural padding/margin so without content it has a height of 0 so you don't see it

A: i will assume that the div have no height, so it will take height: 0; in case no data.
try giving it height.

A: Add background-size property to div.
As background-image doesn't have height and width. Cross check your html in Developer console. You'll find that div is present.
background-size: 100% 200px


text:
Q: Java: crawl numbers I created a java phonebook (desktop app) , on my pc there's a program that outputs the number of the caller. it's an 8 digits number.
here's how it works
I want to crawl only 8 digits numbers from the popup, so lets say this is a popup:
    My name is someone like you, i am 22 years old, i was born in 19/10/1989,
    my phone number is 34544512
    my brother is someone like me he is 18 years old, born in 9101993
    his number is 07777666

in this example, i want to crawl 07777666 and 34544512 only.
I want to check the popup window every 2s for new numbers, if a caller calls me twice, his number will be already stored my db and if not I'll store
Note: if that's can't be done, then forget about the popup, lets say it's just a text being updated every 2 seconds, how to crawl it
This not a homework lol :D

A: Use Java regular expressions. Create a regex of 8 or more digits and use it. You will be able to extract these 2 phone numbers from your text sample.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String args[]) throws Exception {
        String testString = "My name is someone like you, i am 22 years old, i was born in 19/10/1989,"
                          + " my phone number is  34544512 3454451266"
                          + " my brother is someone like me he is 18 years old, born in 9101993 "
                          + " his number is 07777666";

        String[] pieces = testString.split("\\s+");
        String expression = "\\d{8,}";
        Pattern pattern = Pattern.compile(expression);
        for (int i = 0; i < pieces.length; i++) {
            if (pattern.matches(expression, pieces[i]))
                System.out.println(pieces[i]);
        }
    }
}

A: Haha... this is so obviously a homework exercise that you're cheating on!
Your professor probably expects you to use regular expressions.  If that's over your head, then just tokenize the strings and check each token with Long.parseLong().
Of course, both of these approaches assume that the data will be exactly like your example above, and not have dashes in the phone numbers.  If you need to account for dashes (or dots, spaces, etc), then the regex or manual logic gets pretty complex pretty quickly.
UPDATE:  If you do need to account for phone numbers with dashes or other characters in them, I would probably:

*

*tokenize the string,

*iterate through all tokens, using regex to remove all non-numeric characters, and finally

*use regex (or Long.parseLong() and String.length()) to determine whether what's left is an 8-digit number.

A: If you mean that you want to extract 8-digit numbers from a text String, then you can do that as follows:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex
{
    public static void main(String[] args)
    {
        Matcher m = Pattern.compile("\\b(\\d{8})\\b").matcher(
                "Hello 12345678 world 23456789");
        while (m.find())
        {
            System.out.println(m.group(1));
        }
    }
}

See http://docs.oracle.com/javase/tutorial/essential/regex/


text:
Q: Python broadcasting updated Web-socket data in a thread class function I created a simple python web-socket server like following
import asyncio
import json
import websockets
import threading
import queue
import time
import logging

logging.basicConfig()

STATE = {"value": 0}

USERS = set()

msg_queue = queue.Queue(256)
def state_event():
    return json.dumps({"type": "state", **STATE})

def users_event():
    return json.dumps({"type": "users", "count": len(USERS)})

async def notify_state():
    if USERS:  # asyncio.wait doesn't accept an empty list
        message = state_event()
        await asyncio.wait([user.send(message) for user in USERS])

async def notify_users():
    if USERS:  # asyncio.wait doesn't accept an empty list
        message = users_event()
        await asyncio.wait([user.send(message) for user in USERS])

async def register(websocket):
    USERS.add(websocket)
    await notify_users()

async def unregister(websocket):
    USERS.remove(websocket)
    await notify_users()

async def counter(websocket, path):
    # register(websocket) sends user_event() to websocket
    await register(websocket)
    try:
        await websocket.send(state_event())
        async for message in websocket:
            data = json.loads(message)
            if data["action"] == "minus":
                STATE["value"] -= 1
                await notify_state()
            elif data["action"] == "plus":
                STATE["value"] += 1
                await notify_state()
            else:
                logging.error("unsupported event: {}", data)
    finally:
        await unregister(websocket)

class clsSerialThread(threading.Thread):
    global STATE
    def __init__(self, threadID, name, job_queue):
        super().__init__()
        self.threadID = threadID
        self.name = name
        self.job_queue = job_queue

    def run(self):
        while(True):
            time.sleep(10)
            #broadcast an updated value every 10 seconds
            for ws in USERS:
                asyncio.create_task(ws.send(json.dumps({"value": STATE["value"]+10})))

if __name__ == "__main__":
    try:
        serial_thread = clsSerialThread(1, 'Serial', msg_queue)
        serial_thread.setDaemon(True)
        serial_thread.start()
    except Exception as e1:
        print("error communicating to mainboard ...: " + str(e1))

    asyncio.get_event_loop().run_until_complete(websockets.serve(counter, "localhost", "8081"))
    asyncio.get_event_loop().run_forever()

Testing my server using a HTML client as
<!DOCTYPE html>

        <title>WebSocket demo</title>

-

?

+

            ? online

However, the run function keep throwing out error like "Exception has occurred: RuntimeError no running event loop"
How do I update the web-socket data inside the thread run function? I added the async keyword to the function, it did not help

A: I found out that an event loop global instance needs to be shared to the thread class as following:
import asyncio
import json
import websockets
import threading
import queue
import time
import logging

logging.basicConfig()

STATE = {"value": 0}

USERS = set()

msg_queue = queue.Queue(256)

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

delay = 5
def state_event():
    global STATE
    STATE["value"] += delay
    return json.dumps({"type": "state", **STATE})

def users_event():
    return json.dumps({"type": "users", "count": len(USERS)})

async def notify_state():
    if USERS:  # asyncio.wait doesn't accept an empty list
        message = state_event()
        await asyncio.wait([user.send(message) for user in USERS])

async def notify_users():
    if USERS:  # asyncio.wait doesn't accept an empty list
        message = users_event()
        await asyncio.wait([user.send(message) for user in USERS])

async def register(websocket):
    USERS.add(websocket)
    await notify_users()

async def unregister(websocket):
    USERS.remove(websocket)
    await notify_users()

async def counter(websocket, path):
    # register(websocket) sends user_event() to websocket
    await register(websocket)
    try:
        await websocket.send(state_event())
        async for message in websocket:
            data = json.loads(message)
            if data["action"] == "minus":
                STATE["value"] -= 1
                await notify_state()
            elif data["action"] == "plus":
                STATE["value"] += 1
                await notify_state()
            else:
                logging.error("unsupported event: {}", data)
    finally:
        await unregister(websocket)

class clsSerialThread(threading.Thread):
    global STATE
    global loop
    def __init__(self, threadID, name, job_queue):
        super().__init__()
        self.threadID = threadID
        self.name = name
        self.job_queue = job_queue

    def run(self):
        while(True):
            time.sleep(delay)
            #broadcast an updated value every 'delay' seconds
            loop.create_task(notify_state())

if __name__ == "__main__":
    try:
        serial_thread = clsSerialThread(1, 'Serial', msg_queue)
        serial_thread.setDaemon(True)
        serial_thread.start()
    except Exception as e1:
        print("error communicating to mainboard ...: " + str(e1))

    loop.run_until_complete(websockets.serve(counter, "localhost", "8081"))
    loop.run_forever()

it seems like the broadcasting update is being call periodically now, but the websocket client web page's update frequency does not seem to match the delay setting. Is there a way to improve the latency?


text:
Q: Remove Google login button from map Has anyone an idea how i can remove the google login button from the map i created via JS? Haven't found anything in the docs so far.

var map;
var opt = {
  zoom: 10,
  center: new google.maps.LatLng('some adress'),
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("gmapdiv"), opt);

A: <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=false"></script>

JsFiddle: http://jsfiddle.net/anandgh/7bmpfesu/
You can read more about this on https://developers.google.com/maps/documentation/javascript/signedin


text:
Q: ManyToMany as Inline When trying to use a ManyToMany relation as an Inline in a ModelAdmin, cause the error admin.E105 at the bottom, but under normal circunstances, without inline, it works fine. Here is the code:
models.py
class Reference(models.Model):
    url = models.UrlField()
    ...

class BaseModel(models.Model):
    ...
    references = models.ManyToManyField(
            Reference,
            related_name="references_%(app_label)s_%(class)s_related",
        )

    class Meta:
        abstract=True

class Case(BaseModel)
    ...
    name = models.CharField(max_length=255)
    ...

admin.py
class InlineReference(admin.TabularInline):
    model = BaseModel.references.through

class CaseAdmin(admin.ModelAdmin):
    ...
    inlines = [InlineReference, ]
    exclude = ['references', ]
    ...

The error message is:
SystemCheckError: System check identified some issues:
ERRORS:
<class 'admin.CaseAdmin'>: (admin.E105) 'admin.InlineReference' must have a 'model' attribute.

I'm trying to follow the docs from here.

A: You must set model attribute Reference model.
class InlineReference(admin.StackedInline):
    model = Reference

class BaseAdmin(admin.ModelAdmin):
    ...
    inlines = [InlineReference, ]
    ...

admin.site.register(Base, BaseAdmin)


text:
Q: django-ckeditor doesn't show up on grappelli admin in Django I'm trying to use ckeditor on grappelli admin in Django. In local environment, it's working very well and it shows up well. However, after deploying it into production environment. The editor doesn't show up.
Like you see image below, it's just blank and nothing.

settings.py
DJANGO_APPS = [
    ...
    'ckeditor',
    'ckeditor_uploader'
]

CKEDITOR_UPLOAD_PATH = "ckeditor_uploads/"

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': [["Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker"],
                    ['NumberedList', 'BulletedList', "Indent", "Outdent", 'JustifyLeft', 'JustifyCenter',
                     'JustifyRight', 'JustifyBlock'],
                    ["Image", "Table", "Link", "Unlink", "Anchor", "SectionLink",
                        "Subscript", "Superscript"], ['Undo', 'Redo'], ["Source"],
                    ["Maximize"]],
    },
}

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

These are all settings for ckeditor in my Django app.
Does anyone know why it's happening?


text: Q: Simplification of the derivative of the mean curvature I'm using the RK method to calculate the thin film profile. there is a complex interface curvature term, as shown in 1, κ. The final formula is a fourth-order ordinary differential equation which requires the first and second curvature derivative terms, they are also listed in 1. However, I don't understand how it was simplified. Specifically, I don't know where does ln(r) come from. Can anybody explain it to me?


text:
Q: How to clear the contents of all the attributes of an entity? I have data recorded in the attributes of a entities in coredata.
I would like to erase the data saved in each attribute of an entity.
Please is there a way to do it and if so, how?
Thank you

A: Get the NSEntityDescription of that object (that's the entity property of the NSManagedObject).
And then you can simply iterate on the names (via the attributesByName property) and set all values to nil
for (name, attributes) in entity.attributesByName { setValue(nil, forKey: name) }

You can do the same for the relationships of that object (via the relationshipsByName property)
for (name, relationship) in entity.relationshipsByName { setValue(nil, forKey: name) }

With this methods you can also exclude specific properties  (if there are some you don't want to clear).


text:
Q: Optical interferometer using software I understand that optical interferometer is a technique by which we can combine light from multiple telescopes and combine them in optical interferometer to simulate effect of larger telescope with mirror diameter of largest distance between any two telescopes.
Currently telescopes use complex process of combining light obtained from different telescopes using beam combiner, this has limitation of telescopes to be colocated at the same place with interferometer arrangement in place.
Is it possible to combine the light collected from two telescopes via software to produce same effect as optical interferometer which can allow us to treat telescopes located at large distances as a single telescope? Is there any software solution already available for that?

A: It works fine with radio telescopes. The oscillating electric fields in the radio range can be measured as a function of time, displayed on oscilloscopes, waveforms can be digitized. After that one can do amazing things in software: http://www.lofar.org/
At the frequencies of visible light we cannot do that (yet). So interference has to be done in hardware.


text:
Q: Elasticsearch on Docker - Failed to create enrollment token when generating API key Going through the Elasticsearch docs for setting up Elasticsearch/Kibana with Docker, but I'm getting several errors. I follow the steps exactly. I'm running this on an Ubuntu 20.04 EC2 instance. What am I doing wrong?
Here's what I did:

*

*docker pull docker.elastic.co/elasticsearch/elasticsearch:8.0.0

*docker pull docker.elastic.co/kibana/kibana:8.0.0

*docker network create elastic

*docker run --name es01 --net elastic -p 9200:9200 -it docker.elastic.co/elasticsearch/elasticsearch:8.0.0
After step 4, Elasticsearch says:

A password is generated for the elastic user and output to the terminal, plus enrollment tokens for enrolling Kibana and adding additional nodes to your cluster.

I get neither. Instead, I get these error logs:
{"@timestamp":"2022-02-24T22:28:24.318Z", "log.level":"ERROR", "message":"Failed to create enrollment token when generating API key", "ecs.version": "1.2.0","service.name":"ES_ECS","event.dataset":"elasticsearch.server","process.thread.name":"elasticsearch[a178a1e9d98b][generic][T#4]","log.logger":"org.elasticsearch.xpack.security.enrollment.InternalEnrollmentTokenGenerator","elasticsearch.cluster.uuid":"mC4ceJ2nT7i9-QF6V537Zg","elasticsearch.node.id":"IthIKocaSACunHatZxePPw","elasticsearch.node.name":"a178a1e9d98b","elasticsearch.cluster.name":"docker-cluster","error.type":"org.elasticsearch.action.UnavailableShardsException","error.message":"[.security-7][0] primary shard is not active Timeout: [1m], request: [BulkShardRequest [[.security-7][0]] containing [index {[.security][fobYLX8BZdXU5J2_mb_p], source[{\"doc_type\":\"api_key\",\"creation_time\":1645741644265,\"expiration_time\":1645743444265,\"api_key_invalidated\":false,\"api_key_hash\":\"{PBKDF2}10000$PbPNTKm9i5HBuHO+W9snM/+0C1sf4OGjE3xC1m3xKew=$oQXD/UOSgR/hDNHz1IgNKoVOG4Zi0LkiPQW3IMPnRtA=\",\"role_descriptors\":{\"create_enrollment_token\":{\"cluster\":[\"cluster:admin/xpack/security/enroll/node\"],\"indices\":[],\"applications\":[],\"run_as\":[],\"metadata\":{},\"type\":\"role\"}},\"limited_by_role_descriptors\":{\"superuser\":{\"cluster\":[\"all\"],\"indices\":[{\"names\":[\"*\"],\"privileges\":[\"all\"],\"allow_restricted_indices\":false},{\"names\":[\"*\"],\"privileges\":[\"monitor\",\"read\",\"view_index_metadata\",\"read_cross_cluster\"],\"allow_restricted_indices\":true}],\"applications\":[{\"application\":\"*\",\"privileges\":[\"*\"],\"resources\":[\"*\"]}],\"run_as\":[\"*\"],\"metadata\":{\"_reserved\":true},\"type\":\"role\"}},\"name\":\"enrollment_token_API_key_fYbYLX8BZdXU5J2_mb_p\",\"version\":8000099,\"metadata_flattened\":null,\"creator\":{\"principal\":\"_xpack_security\",\"full_name\":null,\"email\":null,\"metadata\":{},\"realm\":\"__attach\",\"realm_type\":\"__attach\"}}]}] blocking until refresh]","error.stack_trace":"org.elasticsearch.action.UnavailableShardsException: [.security-7][0] primary shard is not active Timeout: [1m], request: [BulkShardRequest [[.security-7][0]] containing [index {[.security][fobYLX8BZdXU5J2_mb_p], source[{\"doc_type\":\"api_key\",\"creation_time\":1645741644265,\"expiration_time\":1645743444265,\"api_key_invalidated\":false,\"api_key_hash\":\"{PBKDF2}10000$PbPNTKm9i5HBuHO+W9snM/+0C1sf4OGjE3xC1m3xKew=$oQXD/UOSgR/hDNHz1IgNKoVOG4Zi0LkiPQW3IMPnRtA=\",\"role_descriptors\":{\"create_enrollment_token\":{\"cluster\":[\"cluster:admin/xpack/security/enroll/node\"],\"indices\":[],\"applications\":[],\"run_as\":[],\"metadata\":{},\"type\":\"role\"}},\"limited_by_role_descriptors\":{\"superuser\":{\"cluster\":[\"all\"],\"indices\":[{\"names\":[\"*\"],\"privileges\":[\"all\"],\"allow_restricted_indices\":false},{\"names\":[\"*\"],\"privileges\":[\"monitor\",\"read\",\"view_index_metadata\",\"read_cross_cluster\"],\"allow_restricted_indices\":true}],\"applications\":[{\"application\":\"*\",\"privileges\":[\"*\"],\"resources\":[\"*\"]}],\"run_as\":[\"*\"],\"metadata\":{\"_reserved\":true},\"type\":\"role\"}},\"name\":\"enrollment_token_API_key_fYbYLX8BZdXU5J2_mb_p\",\"version\":8000099,\"metadata_flattened\":null,\"creator\":{\"principal\":\"_xpack_security\",\"full_name\":null,\"email\":null,\"metadata\":{},\"realm\":\"__attach\",\"realm_type\":\"__attach\"}}]}] blocking until refresh]\n\tat org.elasticsearch.action.support.replication.TransportReplicationAction$ReroutePhase.retryBecauseUnavailable(TransportReplicationAction.java:1076)\n\tat org.elasticsearch.action.support.replication.TransportReplicationAction$ReroutePhase.doRun(TransportReplicationAction.java:872)\n\tat org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:26)\n\tat org.elasticsearch.action.support.replication.TransportReplicationAction$ReroutePhase$2.onTimeout(TransportReplicationAction.java:1031)\n\tat org.elasticsearch.cluster.ClusterStateObserver$ContextPreservingListener.onTimeout(ClusterStateObserver.java:345)\n\tat org.elasticsearch.cluster.ClusterStateObserver$ObserverClusterStateListener.onTimeout(ClusterStateObserver.java:263)\n\tat org.elasticsearch.cluster.service.ClusterApplierService$NotifyTimeout.run(ClusterApplierService.java:651)\n\tat org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:717)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)\n\tat java.base/java.lang.Thread.run(Thread.java:833)\n"}
{"@timestamp":"2022-02-24T22:28:47.612Z", "log.level":"ERROR", "message":"error downloading geoip database [GeoLite2-ASN.mmdb]", "ecs.version": "1.2.0","service.name":"ES_ECS","event.dataset":"elasticsearch.server","process.thread.name":"elasticsearch[a178a1e9d98b][generic][T#6]","log.logger":"org.elasticsearch.ingest.geoip.GeoIpDownloader","elasticsearch.cluster.uuid":"mC4ceJ2nT7i9-QF6V537Zg","elasticsearch.node.id":"IthIKocaSACunHatZxePPw","elasticsearch.node.name":"a178a1e9d98b","elasticsearch.cluster.name":"docker-cluster","error.type":"org.elasticsearch.action.UnavailableShardsException","error.message":"[.geoip_databases][0] primary shard is not active Timeout: [1m], request: [BulkShardRequest [[.geoip_databases][0]] containing [index {[.geoip_databases][GeoLite2-ASN.mmdb_0_1645741637264], source[n/a, actual length: [1mb], max length: 2kb]}]]","error.stack_trace":"org.elasticsearch.action.UnavailableShardsException: [.geoip_databases][0] primary shard is not active Timeout: [1m], request: [BulkShardRequest [[.geoip_databases][0]] containing [index {[.geoip_databases][GeoLite2-ASN.mmdb_0_1645741637264], source[n/a, actual length: [1mb], max length: 2kb]}]]\n\tat org.elasticsearch.action.support.replication.TransportReplicationAction$ReroutePhase.retryBecauseUnavailable(TransportReplicationAction.java:1076)\n\tat org.elasticsearch.action.support.replication.TransportReplicationAction$ReroutePhase.doRun(TransportReplicationAction.java:872)\n\tat org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:26)\n\tat org.elasticsearch.action.support.replication.TransportReplicationAction$ReroutePhase$2.onTimeout(TransportReplicationAction.java:1031)\n\tat org.elasticsearch.cluster.ClusterStateObserver$ContextPreservingListener.onTimeout(ClusterStateObserver.java:345)\n\tat org.elasticsearch.cluster.ClusterStateObserver$ObserverClusterStateListener.onTimeout(ClusterStateObserver.java:263)\n\tat org.elasticsearch.cluster.service.ClusterApplierService$NotifyTimeout.run(ClusterApplierService.java:651)\n\tat org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:717)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)\n\tat java.base/java.lang.Thread.run(Thread.java:833)\n"}
{"@timestamp":"2022-02-24T22:28:54.310Z", "log.level":"ERROR", "message":"Failed to generate credentials for the elastic built-in superuser", "ecs.version": "1.2.0","service.name":"ES_ECS","event.dataset":"elasticsearch.server","process.thread.name":"elasticsearch[a178a1e9d98b][generic][T#7]","log.logger":"org.elasticsearch.xpack.security.InitialNodeSecurityAutoConfiguration","elasticsearch.cluster.uuid":"mC4ceJ2nT7i9-QF6V537Zg","elasticsearch.node.id":"IthIKocaSACunHatZxePPw","elasticsearch.node.name":"a178a1e9d98b","elasticsearch.cluster.name":"docker-cluster","error.type":"org.elasticsearch.action.UnavailableShardsException","error.message":"[.security-7][0] primary shard is not active Timeout: [1m], request: [BulkShardRequest [[.security-7][0]] containing [index {[.security][reserved-user-elastic], source[{\"password\":\"ff1DWkSBw4Cju0b8U7PM\",\"enabled\":true,\"type\":\"reserved-user\"}]}] and a refresh]","error.stack_trace":"org.elasticsearch.action.UnavailableShardsException: [.security-7][0] primary shard is not active Timeout: [1m], request: [BulkShardRequest [[.security-7][0]] containing [index {[.security][reserved-user-elastic], source[{\"password\":\"ff1DWkSBw4Cju0b8U7PM\",\"enabled\":true,\"type\":\"reserved-user\"}]}] and a refresh]\n\tat org.elasticsearch.action.support.replication.TransportReplicationAction$ReroutePhase.retryBecauseUnavailable(TransportReplicationAction.java:1076)\n\tat org.elasticsearch.action.support.replication.TransportReplicationAction$ReroutePhase.doRun(TransportReplicationAction.java:872)\n\tat org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:26)\n\tat org.elasticsearch.action.support.replication.TransportReplicationAction$ReroutePhase$2.onTimeout(TransportReplicationAction.java:1031)\n\tat org.elasticsearch.cluster.ClusterStateObserver$ContextPreservingListener.onTimeout(ClusterStateObserver.java:345)\n\tat org.elasticsearch.cluster.ClusterStateObserver$ObserverClusterStateListener.onTimeout(ClusterStateObserver.java:263)\n\tat org.elasticsearch.cluster.service.ClusterApplierService$NotifyTimeout.run(ClusterApplierService.java:651)\n\tat org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingRunnable.run(ThreadContext.java:717)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)\n\tat java.base/java.lang.Thread.run(Thread.java:833)\n"}

They are long messages. Here's the error portion of the above:
"Failed to create enrollment token when generating API key"
"error downloading geoip database [GeoLite2-ASN.mmdb]"
"Failed to generate credentials for the elastic built-in superuser"
"error downloading geoip database [GeoLite2-City.mmdb]"

A: I assume your problem is because of the network, since you got failed when attempting to downloading geoip database and you use docker to run it.
https://www.elastic.co/blog/docker-networking

When running Elasticsearch, you will need to ensure it publishes to an
IP address that is reachable from outside the container; this can be
configured via the setting network.publish_host.

A: I did not have enough storage space.
A gentleman on the Elasticsearch Slack channel was kind enough to point out that this was the real culprit:
"error.type": "org.elasticsearch.action.UnavailableShardsException", "error.message": "[.security-7][0] primary shard is not active Timeout: [1m],
I looked at my available host system storage space and found there was only 17G available! Cleaning up my Trash bin fixed the issue. Works now. Hopefully this helps someone else!


text:
Q: Gradle Sync failed due to groovy.lang.MissingPropertyException I'm new to Android Studio. I am trying to make a new project.
But it always says that Gradle Sync failed and throws the exception:

groovy.lang.MissingPropertyException: Could not get unknown property
'com' for root project 'Assn1' of type org.gradle.api.Project.    at
org.gradle.internal.metaobject.AbstractDynamicObject.getMissingProperty(AbstractDynamicObject.java:85)

A: I guess you have initiated the task but not defined it in file
groovy.lang.MissingPropertyException this exception occurred when gradle not able to find a property. Gradle check these properties in sequence as below if not find out throw this exception.
1 - gradle.properties
2 - System environment variables
3 - command-line arguments to execute the build script
4 - build.gradle
You can refer to solve these issues from the link below https://facingissuesonit.com/2020/04/29/groovy-lang-missingpropertyexception-could-not-get-unknown-property-a-for-task-b-of-type-org-gradle-api-defaulttask/