text:
Q: Prolog find all positions in a list of the minimum element everyone!
I'am having some problems with finding all the occurence positions of the minimum element in a list.
My source code is like this:
**
findPos([], _, []).
findPos([_],_,[1]).
findPos([H1|Tail], Pos, [Pos|Ta]):-
% "Pos" is the current position in the list
       findMin([H1|Tail], V),
       V=[H1],
       Pos2 is Pos+1,
       findPos([Tail], Pos2, [Ta]).

findPos([H1|Tail], Pos, [Ta]):-
       findMin([H1|Tail], V),
       not(V=[H1]),
       Pos2 is Pos+1,
       findPos([Tail], Pos2, [Ta]).**

where, findMin receives as first argument a list and returns using the second parameter, the minimum element of that list.
The problem is that, every input list I would give(except the void one for which the answer is []), the answer is always 1 ... and I can't see what I am missing.. Any answer would be appreciated :D Thank you!

A: Note that your program each time recalculates the minimum of the remaining list; therefore a list with [1,7,1,2,3] will see [1,1,2,3] as the list of "minima". Furthermore this process is rather expensive.
Another aspect is that you make some syntax errors with respect to the syntactical sugar of lists which will result in errors.
A solution is - which is common in computer science - to separate concerns. I propose that findPos will only aim to find the indices of a given item. Such findPos/3 predicate could look like:
findPos(X,L,Is) :-
    findPos(0,X,L,Is).

findPos(_,_,[],[]).
findPos(I,X,[Y|T],MIT) :-
    (X == Y -> MIT = [I|IT];MIT=IT),
    I1 is I+1,
    findPos(I1,X,T,IT).

The predicate uses an accumulator I that keeps track of the index, and each time increments the index.
Now you need to make a predicate that finds the indices of the minimum elements:
findMinPos(L,Is) :-
    findMin(L,M),
    findPos(M,L,Is).


text:
Q: How to show that a space has the homotopy type of wedge of spheres ? Let me try and put the question in context. I am studying certain subsets of the tangent bundle of a sphere. I also have a regular CW complex which is a deformation retract of such a subset. Hence I have a description of the cells and the information that tells me which cell is in the boundary of which other cell. Fortunately this cell complex is a homotopy colimit of a diagram of spaces. As a result I can compute the cohomology groups (but not the product).
All my examples concerning $S^1$ and $S^2$ show that these subsets have the homotopy type of wedge of copies of $S^1$ and $S^2$ respectively. Hence I am trying to prove that this is the case in all dimensions. In this process the only thing I was able to prove that there is a retraction from these subsets to the underlying sphere.
So I would like to know about various methods to show that a space is a wedge of spheres.
I understand that this question might sound vague and the information too little.

A: (If I remember correctly) a shellable (simplicial) complex automatically has the homotopy type of a wedge of spheres: if you could find a shellable triangulation you should be done.
Of course, this'll only work if you're lucky enough that the structure you have admits nice combinatorial structures that happen to be shellable — but it's one way you can get to a wedge of spheres.

A: To follow up a bit on Mikael's answer, the notion of non-pure shellability is probably more relevant to your situation.  Shellable simplicial complexes are wedges of spheres of equal dimension, but non-purity allows different dimensional spheres.  You should look at papers by Michelle Wachs and Anders Bjorner if you're interested.  However, this will require finding a simplicial decomposition of your space, which may be a challenge.
Added: Since this is now the accepted answer, I figure I should give the precise references.  Both papers are on JSTOR (follow the links).
Björner, Anders; Wachs, Michelle L.
Shellable nonpure complexes and posets. I.
Trans. Amer. Math. Soc.  348  (1996),  no. 4, 1299–1327.
http://www.jstor.org/stable/i311403
Björner, Anders; Wachs, Michelle L.
Shellable nonpure complexes and posets. II.
Trans. Amer. Math. Soc. 349 (1997), no. 10, 3945–3975.
http://www.jstor.org/stable/i311413

A: There is an algorithm that sometimes can be useful.
 You can reduce the number of cells of a CW-complex obtaing a new CW-complex homotopy
equivalent to the first. This is done collapsing certain pairs of consecutive cells.
The exact procedure is too long to explain. You can find it in "Combninatorial algebraic topolgy" by Kozlov chapter 11.The result you  may need it's the main theorem of discrete
Morse theory.
http://www.springer.com/mathematics/geometry/book/978-3-540-71961-8

redpajama_set_name: RedPajamaStackExchange


text:
Q: (angular directive) bind an object to all property Say I have an object {propA: 'valueA', propB: 'valueB'} on the controller instance ctrl as dirProps and I want to bind this object to all the attribute on a directive. I can't change the definition of the directive. I have to write
<my-dir
  prop-a="ctrl.dirProps.propA"
  prop-b="ctrl.dirProps.propB"
></my-dir>

Is there a way to improve this because my object that binds to the directive might be dynamic.
Something like this
<my-dir
  all-attr="ctrl.dirProps"
></my-dir>

would be nice.


text:
Q: How to create the sectional listview with the help of Layout Inflater? How can I accomplish this without extending BaseAdapter?

A:         final int count = array.size();

    /* layout to draw  list */
    LinearLayout list = (LinearLayout) findViewById(R.id.list);

    LayoutInflater mInflater = null;
    mInflater = LayoutInflater.from(this);

    for (int i = 0; i < count; i++) {

        /* row of the  list  - XML File */
        View convertView = mInflater.inflate(R.layout.item_list, null);

        /* holder class to hold row information to display on screen */
        Holder holder = new Holder();

        convertView.setId(array.get(i).getId());

        holder.icon = (ImageView) convertView.findViewById(R.id.icon);

        holder.iconName = (TextView) convertView.findViewById(R.id.name);

        holder.msg = (TextView) convertView.findViewById(R.id.msg);

        convertView.setTag(holder);

        RelativeLayout.LayoutParams parms = new RelativeLayout.LayoutParams(48, 48);
        holder.icon.setLayoutParams(parms);

        holder.iconName.setText( " your code " );

        holder.msg.setText(" your message ");

        /* add row to the list */
        list.addView(convertView);

        convertView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                /* show details */
                showDetails(v.getId());
            }
        });
    }


text:
Q: Time series analysis in R (figuring out trends) I have a dataset of tweets from 2013 to 2017. I have coded for certain message features(coded 0 as absence and 1 as presence), and was trying to figure out if there is a trend (i.e., the occurrence of message feature going up/down gradually) in my dataset. How should I do it in R?

A: You could try a linear model, such as one of the answer given in here.
#for reproducing
set.seed(200)
library(ggplot2)
#simple example. Assume your data is simple binomial variable with probability 0.3
data <- data.frame(time = 1:200, val=sample(c(0,1), size = 200, replace = T, prob = c(0.3, 0.7)))

#plot using ggplot and add linear regression and confidence interval
ggplot(data, aes(x = time, y=val)) + geom_smooth(method=lm) +geom_point()

#Now we can try to create linear regression
y = data$time
    x = data$val
fitData <- lm(x ~ y)
predict(fitData, newdata = data.frame(y=201:224), interval="confidence")

#You can also take advantage of geom_smooth that find the best model if your don't specify any:
ggplot(data, aes(x = time, y=val)) + geom_smooth() +geom_point()

#Here, it seems that loess would be better

Some code to do a loess regression in R here.
Good luck!


text:
Q: Global query scope , Multi-tenant architecture I'm trying modify the existing code to do Global query scoping in Laravel 3!! for multi-tenant architecture.
Need some idea in terms of, how multi-tenant architecture is achievable in laravel 3
Thanks in advance :)


text:
Q: creating a new entity for shopware 6 and access it through store api i need help creating custom entity please, i have created an extension
inside the Apps directory with AppName/Manifisto.xml and
AppName/Resources/entities.xml and activated the extension in admin
dashboard but i can't see anything new on dashboard no entity, and i
can't access it thought store-api or admin api
i used the templates provided in the documentation:
AppName/Manifisto.xml
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/shopware/platform/trunk/src/Core/Framework/App/Manifest/Schema/manifest-1.0.xsd">
<meta>
<name>MyExampleApp</name>
Label
Name
<description>A description</description>
<description lang="de-DE">Eine Beschreibung</description>
<author>Your Company Ltd.</author>
<copyright>(c) by Your Company Ltd.</copyright>
<version>1.0.0</version>
<icon>Resources/config/plugin.png</icon>
<license>MIT</license>
</meta>
</manifest>

AppName/Resources/entities.xml
<?xml version="1.0" encoding="utf-8" ?>
<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/shopware/platform/trunk/src/Core/System/CustomEntity/Xml/entity-1.0.xsd">
<entity name="custom_entity_bundle">
<fields>
<string name="name" required="true" translatable="true"
store-api-aware="true" />
<price name="discount" required="true" store-api-aware="true"/>
<many-to-many name="products" reference="product" store-api-aware="true" />
</fields>
</entity>
</entities>

A: After you installed and activated the app you should be able to use the Admin-API at the api/custom-entity-bundle resource to POST new entries or PATCH existing ones or GET multiple or a single bundle, like you can do for all "core" entities. This API is automatically generated for you.
To check if your custom entity was registered successfully during plugin installation you can check the DB and check that the custom_entity_bundle was created in the DB.
The store-API won't be generated automatically for you, but you can add a custom store-api endpoint to retrieve the data you need via App Scripts.
The administration UI also won't be generated for you (as of now), so you have to create your own custom module there if you want that the merchant can edit the custom entities himself.


text:
Q: Trigger a child view model method in the parent view : MarionetteJs I have a Marionette view SingleCategoryView that takes a collection and renders a Collection view optionsView.
the optionsView is a list of an itemView optionView.
In my SingleCategory view I have to do a test onRender
 "onRender": function()
 {
   if(optionsView.hasOnlyExtraOption(optionsView.collection.models)) {
   var noResultsAvailableMsg =
   this.model.getLocalisationModel().getNoResultsAvailableMsg();

   var myModel = new noResultsAvailableModel({noResultsAvailableMsg:
   "noResultsAvailableMsg"});
   this.conflictMessageRegion.show(new noResultsAvailableView({ 'model' :
   myModel}))}
 }

here is the code of the hasOnlyExtraOptions located in the optionsView file
"hasOnlyExtraOption": function(data) {
    return data.every(function(currentValue) {
        return
         currentValue.get(
         MODEL_VIEW_CONSTANTS.ctaDisplayConflicted.selectors.cfgExtraOptions
          ListItem) ||
           currentValue.get(
        MODEL_VIEW_CONSTANTS.ctaDisplayConflicted.properties.isExtraOption);
                });

            }

My problem is when I am doing the test even if the singleCategory is render the css class ( isExtraOption cfgExtraOptionslistItem ) are not setted yet so the result of the test is undefined.
Actually these css class are setted by the optionViewModel here :
"onConfigurationStepsComplete": function() {
 // some code
  this.setIsExtraOption();
  //some code }

to be more explicit :  optionView has as parent optionsView, witch has singleCategoryView as parent. My aim is to trigger the change of the attribute isExtraoption by the optionViewModel from the singleCategoryView.
Thank you in advance .

A: You can use child event bubbling for the collection view and item view. i.e trigger a method from the child view once the configuration is fetched, and execute code in parent view in turn. for eg, in child view:
// optionView
doSomething() {
   this.triggerMethod('did:something', this);
}

And you can listen to this in the parent view like:
 // optionsView
 onChildviewDidSomething(childView) {
    console.log('Something was done to ' + childView);
 }

Above will propagate the event until optionsView in your case.
You can then use normal trigger and listen mechanism to propagate it further up.
For eg, trigger another event from optionsView like:
// optionsView
onChildviewDidSomething(childView) {
    console.log('Something was done to ' + childView);
    this.triggerMethod('collectionview:did:something', this);
 }

And you can listen to this event from the parent view, which in your case is singleCategoryView, something like:
// singleCategoryView
this.optionsView.on('collectionview:did:something', this.handler);


text:
Q: Golang syscall.NewLazyDLL in Linux Is there any way to load the syscall.NewLazyDLL in Ubuntu?
I tried:
GOOS=windows GOARCH=amd64 go build -ldflags "-w -s" -o myFileName *.go

but the syscall.NewLazyDLL is not found.
var (
    mod               = syscall.NewLazyDLL("user32.dll")
    procGetWindowText = mod.NewProc("GetWindowTextW")
)

My goal is to load the "windows" syscall functions, but from my main Ubuntu OS,
so I dont need to switch to Windows to code. Is there any way Ubuntu can call the Windows functions from syscall.NewLazyDLL or do I have to write code in Windows for this?

A: Of course you have to be on Windows, you are wanting to develop for Windows and not Linux using syscall.NewLazyDLL("user32.dll").
Install a virtual machine.


text:
Q: How to change mouse cursor within Toggle button I have a ToggleButton and when clicking this button, the processing time could take a while, like 3 to 5 seconds. During that time, I'd like to give a feedback to the user changing the cursor to the Wait state.
The click of the ToggleButton is handled by a Command, because I'm using the MVVM pattern so, I don't handle the click event and can't change that using code behind.
Is there a way to that using only xaml?
I tried this but it does not work:
<Style.Triggers>
  <Trigger Property="IsMouseCaptureWithin" Value="True">
    <Setter Property="Cursor" Value="Wait"></Setter>
  </Trigger>
</Style.Triggers>

A: You can bind the IsChecked property on the ToggleButton to your ViewModel or use a Command, when the value changes or the command is executed you can change a second Property (call it something like IsBusy). Then create a DataTrigger like:
<Style.Triggers>
  <DataTrigger Binding="{Binding IsBusy}" Value="True">
    <Setter Property="Cursor" Value="Wait"></Setter>
  </DataTrigger>
</Style.Triggers>


text:
Q: Полноэкранный режим. Мерцания. Доброго вечера! Разрабатываю 2д игру на Delphi + OpenGl. Имеется карта размером, например, 40х40, а на мониторе выводится некоторая часть карты 20х20. Вывод карты делаю двумерным массивом, что собственно должно наоборот повысить фпс игры. Все отлично работает, но когда перехожу в полноэкранный режим при движении, на карте появляются некие "мерцания", как будто вывод у меня не успевает за движением. Но это лишь кажется на первый взгляд.

Если поставить размер формы не в полноэкранный режим, а например так:

Frmgl.Height:=Screen.Height;
Frmgl.Width:=Screen.Width-1;

то все работает безупречно! Вся проблема заключается в том, что я перевожу приложением в полноэкранный режим. Михаил Фленов писал на счет этого бага и выход из него он нашел, просто в создании формы пишем:
WindowState := wsMaximized;

Скидывал игру одному человеку и у него, как он мне говорил, ничего не мерцало, а у другого есть... Хотя сам тестировал на 3-х компьютерах с разной конфигурацией и ничего не изменилось, мерцания остаются, из-за чего - уже второй день понять не могу.
Дабы вы поняли в чем дело я залил ссылку:
http://narod.ru/disk/38902687001/0.0.1BA.zip.html
P.S в файле Options в первой строке пишем:
BorderStyle=BsSingle, если хотим не полноэкранный режим, а если же наоборот то BorderStyle=BsNone
A: Вся проблема заключалась в неправильной двойной буферизации. Вроде все верно, но не работало... И работало без мерцания у людей с включенной двойной буферизацией в настройках видеокарты. Быть может кому-то в будущем поможет)


text:
Q: Js and bootstrap are not working when the file is in folder. Laravel When i am including the file head.blade.php in views.home, JS and Bootstrap are working properly. But when i am trying to include head.blade.php in views.posts.create JS and bootstrap are not working. I found in previous questions  that i shoult include them like that:
   <link rel="stylesheet" href="rel="stylesheet" {{URL::asset('css/responsive.css')}}"> but didn't helped.

This are my routes:
 <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/font-awesome.min.css" rel="stylesheet">
    <link href="css/animate.min.css" rel="stylesheet">
    <link href="css/prettyPhoto.css" rel="stylesheet">
    <link href="css/main.css" rel="stylesheet">
    <link href="css/responsive.css" rel="stylesheet">

how it is
How should be

A: Try adding a / to the front of your url:
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/css/font-awesome.min.css" rel="stylesheet">
<link href="/css/animate.min.css" rel="stylesheet">
<link href="/css/prettyPhoto.css" rel="stylesheet">
<link href="/css/main.css" rel="stylesheet">
<link href="/css/responsive.css" rel="stylesheet">

Note: folder path should be "project/public/css/"
This can also be done with the url() helper function:
<link href="{{ url('/css/responsive.css') }}" rel="stylesheet">

Take a look at the Laravel URL helper functions documentation for more information.


text:
Q: Reduce repeated string search from quadratic to faster Apologies if the title was not accurate enough of a description.
I have a program that searches a string for vowels, but it does it over sliding windows of specific sizes across the string. I want to compute the density of vowels. Pretend that I don't care about there being whitespace and symbols; it's just left there. The obvious solution I have coded as follows:
s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit ... consequat."
# assume s continues after the "..."
v = "aeiou"
v_dict = {}
max_win_size = 100
if max_win_size > len(s): max_win_size = len(s)

for i in range(1, max_win_size):
    v_dict[i] = {}
    for j in range(0, i+1):
        v_dict[i][j] = 0 # set counts to zero
    for j in range(1, len(s)-i+1):
        s_slice = s[j:j+i].lower()
        v_count = sum([s_slice.count(c) for c in v])
        v_dict[i][v_count] += 1

This gives eventually gives me the frequency of vowels at different sliding windows from 1 to size of the string. This program works as I want it to, but the problem is that it is very slow. It's clearly quadratic, and I would like to improve the efficiency, because as text gets larger the program takes exponentially more time. The problem is that I am unsure how to transform the problem space into a more efficient algorithm.
Does anyone have any ideas as to how to make this, say, loglinear?
Edit:
I tried the answer by Ben Voigt implemented by cr1msonB1ade. It worked as advertised. In addition, I thought I would include empirical evidence to the speed claims.
First is the run time for increasing string size. Both functions perform linearly, however the overhead of using pure python to implement it results in a significantly greater coefficient on the linear run time.

Second is the run time for increasing window size. I fixed the window size and ran larger and larger window sizes. This time, the quadratic rate of my function revealed itself, while the numpy cumulative sum function remained linear.

A: Rewrite the algorithm based on cumulative counts.
The count of occurrences between position i and j (inclusive) is just cumul_count(j) - cumul_count(i-1), and the computation necessary doesn't increase with the window size.

A: In terms of theoretical run time you are calculating max_win_size * (len(s)-max_win_size+1) values, so there is no way to get below o(max_win_size*len(s)) run time.
In terms of actual computational run time there are a couple issues with your current code. First there is no reason to do letter matching on each string. You should first convert your string into a TRUE FALSE list and then query that instead.
Second you can dynamically update the sums when moving your sliding window. In other words you only have to query the letter you are dropping and the one you are adding to get the number of vowels in the next substring.
Also you don't really need a dictionary for the second level of your data structure. You know exactly how long the list is and you will be indexing with integer values, so just use a list.
I'm sure there may be some other efficiencies that could be added, but putting these  together we have:
s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit ... consequat."
# assume s continues after the "..."
v = list("aeiou")
isVowel = [l in v for l in s]
v_dict = {}
max_win_size = 100
if max_win_size > len(s): max_win_size = len(s)

for i in range(1, max_win_size):
    v_dict[i] = [0,] * (i+1)
    curr_vowels = sum(isVowel[:i])
    v_dict[i][curr_vowels]  += 1
    for curr_pos in range(1, len(s)-i):
        # add next letter position and subtract letter falling out of window
        curr_vowels += isVowel[curr_pos + i] - isVowel[curr_pos - 1]
        v_dict[i][curr_vowels] += 1

EDIT: Using cumulative method as @Ben recommends:
import numpy as np
s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit ... consequat."
# assume s continues after the "..."
v = list("aeiou")
cumVowels = [0,] + np.cumsum([l in v for l in s])
v_dict = {}
max_win_size = 100
if max_win_size > len(s): max_win_size = len(s)

for i in range(1, max_win_size):
    v_dict[i] = [0,] * (i+1)
    for pos in range(0, len(s)-i):
        v_dict[i][cumVowels[pos + i] - cumVowels[pos]] += 1


text:
Q: Парсинг методом рекурсивного спуска Привет! Это мой не первый пост по поводу парсера, но все же. Собственно, проблема такова: есть список(вектор) токенов(указателей на них) и на его основе необходимо сделать выражение(класс Expression). Давайте глянем код:
Допустим имеем выражение: 2 + 2 - 2
Expression* parse(){
    Expression* result = primary(); // Взяли, к примеру, NmberExpression(2)
    while(true){
        if(match(TokenType::PLUS){ // "Пропускаем" токен ПЛЮС, если он стоит после двойки в нашем выражении
            result = new BinaryExpression('+', result, primary());
        ... что дальше - не важно: принцип один и тот же...

}

Expression* primary(){
    return new NumberExpression(число из текущего токена);
    ... ну, либо эксепшн :D ...
}

Естественно, в моем проекте реализована логика уничтожения указателей, но она ломается на 6 строчке приведенного кода, и вы поймете почему.

Прошу не бить палками - дочитайте пост до конца.
Как видите, алгоритм и логика проста: мы просто "откусываем" в класс Expression часть выражения, а остальное дальше продолжаем парсить. Давайте я подробно разберу, что происходит, чтобы подтолнуть вас к моей идее:

*

*Имеем выражение 2 + 2 - 2

*Берем первую двоечку, как Expression

*Пропускаем плюс

*теперь в переменную result записываем новый класс BinaryExpression, который сформирован на основе этой же переменной!

Т.е. суть такова - формирование рекурсивно класса в переменную, где аргументом этого класс является эта же переменная.
Конечно, я понимаю, что так делать, как код выше - упомрачительно. Работа с указателями довольно тонкая. Поэтому я хочу услышать ваше мнение по этому поводу. Как лучше реализовать это дело:

*

*Перелопатить программу, изменив все указатели на умные

*Использовать какой-то другой метод парсинга и составления AST. (Если так, то подскажите, какой именно паттерн или логику сделать, так как я не нашел ничего годного для своей задачи. Есть много разных пример на Java, Python и других языках, но там такое можно сделать, ибо оператор "new" там работает по-другому)
Заранее благодарю!

P.S. если Вы не поняли, почему удаление объекта по указателю ломается, то объясняю: мы создаем новый экземпляр класса на основе существующей переменной, и теперь та самая переменная хранит этот новый экземпляр(BinaryExpression), но если мы вызовем в BinaryExpression деструктор, где происходит удаление этих 2-х Expression, которые пришли как аргументы, то вылетит ошибка о доступе к памяти, т.к. мы создали класс BinaryExpression на основе переменной, а потом эту же переменную перезаписываем, то попытка удалить указатель (тот самый первый аргумент) не закончиться успехом, т.к. это тоже самое, что написать в классе delete this;


text:
Q: WebClient UploadFile The remote server returned an error: (400) Bad Request Trying to upload an xml file, this particular server is returning an error (exception above).
I have tried another url, on another server (https://posttestserver.com/post.php), and the code worked.
My co-worker was able to upload the same xml file via a Perl Script.
My question is: Is there another way to upload the contents of the file? Tried UploadData, UploadString, got the same error.
// Create the xml document file
Byte[] buffer = new Byte[ms.Length];
buffer = ms.ToArray();
xmlOutput = System.Text.Encoding.UTF8.GetString(buffer);
string filePath = @"c:\my.xml");
File.WriteAllText(filePath, xmlOutput);

try
{
    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

    using (WebClient client = new WebClient())
    {
        byte[] rawResponse = client.UploadFile(url, filePath);
        string response = System.Text.Encoding.ASCII.GetString(rawResponse);
    }
}
catch (WebException ex)
{
}
catch (Exception ex)
{
}

A: Using UploadString and adding a header fixed the 400 error.
Then had to add the utf8 encoding parameter to fix a 500 error.
client.Headers.Add("Content-Type", "text/xml");
client.Encoding = Encoding.UTF8;
string response = client.UploadString(CRMIntegrationURL, "POST", xmlOutput);

    string s = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
    "<Program xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"loyalty.xsd\">" +
    "</Program>";

    string test = client.UploadString(url, s);

Using Fiddler, I could see that the Requests types are different.
UploadFile:
Content-Disposition: form-data; name="file"; filename="test1.txt" Content-Type: text/xml

UploadString:
Content-Type: text/xml

A: I had the same problem with posting a text file of measurements to InfluxDB. The accepted answer helped a lot, but I also had to get rid of \r characters in the text content to eliminate the 400 Bad Request error. I don't know if this is a general rule for InfluxDB or if this is only the case when InfluxDB is installed on a unix system (Ubuntu in my case).
You can either set the line breaks before writing as described here: https://stackoverflow.com/a/7841819/5823275
or you can remove \r afterwards with text = text.Replace("\r", "");.


text:
Q: why is scala method serialisable while function not? I have a spark RDD defined like this:
val dataset = CreateRDD(data.filter(someFilter))

I observed the following:
//if filter is defined as function, such as following,
//then spark will throw spark `task not serialisable exception`
val someFilter = (some) => true
//if filter is defined as method, such as following then everything will be fine
def someFilter(some) => true

why ?
yes, function/method are all defined as members in the test spec

A: The problem is that this:
val isNegative = (num: Int) => num < 0

is merely syntactic sugar for this:
val isNegative = new Function1[Int, Boolean] {
  def apply(num: Int): Boolean = num < 0
}

Function1 is a Trait and the anonymous function created is not serializable. When you have something like this:
object Tests {
  def isNegative(num: Int): Boolean = num < 0
}

Now isNegative is a member of Tests which is serializable. When you call this:
val dataset = CreateRDD(data.filter(isNegative))

Spark needs to serialize isNegative before shipping it out to each node. Since objects are serializable if all it's members are serializable, when you use def it works fine, however when you use val Spark will instead try and serialize the value of isNegative, which is a non-serializable anonymous function and fail.


text:
Q: Parsing files from a different server - using threads I have this scenario. OS is UNIX. There are a bunch of files on Server A. The need is to FTP these files(they are in XML format) to server B, parse them and store the values retrieved from specific tags to a DB. Current implementation of the parser in perl is such that the files are processed sequentially. Can a multi-threading concept in java be used here so that the fetching can be made faster?

A: The fetching and the processing are distinct steps.
For the fetching step, fetching more than one file at a time would give you increased speed only if the files are small.  Otherwise, you will be limited by the bandwidth of the connection between the two machines even when transferring only one file at once.
For the processing step: if the files are not related, yes, you will see a speed up by processing more than one in unison (if the server is not itself an older single-core non-hyperthreaded machine).
Neither of these changes require switching to Java.  That is a separate concern.

A: Yes, it will increase performance significantly. You have two I/O operations (FTP, database access) and some threads can use processor cores for parsing while others are waiting during I/O operations.

A: I had to do almost same task in Java. High Level Concurrency Objects helped me a lot. Particularly I used ThreadPoolExecutor through Executors.newFixedThreadPool(concurrentCount);.
Each FTP-file was downloaded using a new FTP connection. Advantage is that you save time of connection initiation and file requesting as another process is using your bandwidth at that time.
For FTP-related tasks I used org.apache.commons.net.ftp.FTPClient
Edit: you can start XML processing immediately after download is complete by using Future.get() method.


text:
Q: How to Remove Pop-up Messages from VBS App I downloaded this vbs script that is designed to block time wasting websites such as Facebook and YouTube. It works perfectly fine but I want it to run completely silent. When the application is executed, a Wscript message comes up asking if I want to run the file, and after clicking yes another message comes up stating that websites have been blocked.
After reviewing the code, I commented out the messages stating websites blocked/unblocked which prevented them from coming up but then the websites don't get blocked. What changes need to be made to the code so that nothing pops up at all and therefore other users cannot tell an application is blocking websites.
'Add the list of time wasting websites here
WebsitesToBlock = Array("twitter.com", "www.youtube.com", "www.facebook.com")

If WScript.Arguments.length =0 Then
    Set objShell = CreateObject("Shell.Application")
    objShell.ShellExecute "wscript.exe", Chr(34) & WScript.ScriptFullName & Chr(34) & " RunAsAdministrator", "", "runas", 1
Else
    Const ForReading = 1, ForWriting = 2

    Set shell = CreateObject("WScript.Shell")
    root = shell.ExpandEnvironmentStrings("%systemroot%")
    hostFile = root & "\system32\drivers\etc\hosts"
    tempFile = hostFile & ".bak"

    blocked = 0
    towrite = false

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f1 = fso.OpenTextFile(hostFile, ForReading, True)
    Set f2 = fso.OpenTextFile(tempFile, ForWriting, True)

    Do Until f1.AtEndOfStream

        line = f1.Readline
        towrite = true

        For Each URL in WebsitesToBlock
            If instr(line, URL) Then
                If blocked = 0 Then
                    If left(line, 1) = "#" Then blocked = 1 Else blocked = 2
                End If
            towrite = false
            End If
        Next

        If towrite Then f2.WriteLine line
    Loop

    For Each URL in WebsitesToBlock
        If blocked <> 2 Then
            f2.WriteLine "127.0.0.1" & vbTab & vbTab & URL
        End If
    Next

    fso.Copyfile tempFile, hostFile

    f1.Close
    f2.Close

    If blocked = 2 Then
        WScript.echo "Time wasting websites have now been unblocked on this computer"
    Else
        WScript.echo "Time wasting websites are now blocked on this computer!"
    End If

End If


text:
Q: Large list FlatMap Java Spark I have a large list in JavaPairRDD<Integer, List<String>> and I want to do a flatMap to get all possible combinations of list entries so that I end up with JavaPairRDD<Integer, Tuple2<String,String>>. Basically if i have something like
(1, ["A", "B", "C"])
I want to get:
(1, <"A","B">)
 (1, <"A", "C">)
 (1, <"B", "C")
The problem is with large lists as what I have done is created a large list of Tuple2 objects by having a nested loop over the input list. Sometimes this list does not fit in memory. I found this, but not sure how to implement it in Java:
Spark FlatMap function for huge lists

A: You may want to flatMap the list and then join the RDD on itself before filtering equal values:
JavaPairRDD<Integer, List<String>> original = // ...
JavaPairRDD<Integer, String> flattened = original.flatMapValues(identity());
JavaPairRDD<Integer, Tuple2<String, String>> joined = flattened.join(flattened);
JavaPairRDD<Integer, Tuple2<String, String>> filtered =
    joined.filter(new Function<Tuple2<Integer, Tuple2<String, String>>, Boolean> () {
        @Override
        public Boolean call(Tuple2<Integer, Tuple2<String, String>> kv) throws Exception {
            return kv._2()._1().equals(kv._2()._2());
        }
    });

A: depends on how big of your datasets, in my job it usually have to process 100-200GB datasets used the FlatMap and flatMapToPair both is works properly for high intensive computation. example below
JavaPairRDD<Integer, List<String>>= DatasetsRDD.
    .flatMapToPair(x->{
    return xx;
    });

Also if your datasets are huge you could try to use spark persistance to disk
Storage Level

    MEMORY_ONLY
    MEMORY_ONLY_SER
    MEMORY_AND_DISK_SER
    DISK_ONLY
    MEMORY_ONLY_2

References: https://spark.apache.org/docs/latest/rdd-programming-guide.html


text:
Q: Place a draggable image above marker in google maps Is there a way to do this? I've got markers placed on the map, but above it, I want to add an image, that looks exactly like the marker, that I can drag. I want to achieve effect that I drag the image to the defined place simultaneously the marker will still stay there so I'm actually operating with copy of this marker.
Thanks.


text:
Q: Consultar base de datos desde la memoria interna estoy trabajando en una app y necesito utilizar una BD SQlite(ya creada) desde la memoria interna del movil. He buscado y no encuentro, ya se como seria crear la BD desde cero en  la propia app o copiar una BD a la carpeta assets y de ahi trabajar con ella, pero no logro encontrar nada sobre como utilizar la BD ya creada desde la memoria del telefono...o sea aplicacion por un lado y BD en /scard/AplicacionX/basedatosx.bd/

A: con esta clase resolvi el problema
public class MiBaseDatos extends SQLiteOpenHelper {

    //Ruta por defecto de las bases de datos en el sistema Android
    private static String DB_PATH = "/FelixDroyd/";
    private static String DB_NAME = "etecsa.db";
    private SQLiteDatabase myDataBase;
    private final Context myContext;

    //contructor con referencia a la memoria interna del movil

   // Environment.getExternalStorageDirectory().getPath() hace referencia a /storage/emulated/0
   //    "/storage/external_SD" este e pa la externa

    public MiBaseDatos(Context context) {
        super(context, "/storage/external_SD" +DB_PATH + DB_NAME, null, 1);
        this.myContext = context;

    }
    /**
     * Comprueba si la base de datos existe
     *
     * @return true si existe, false si no existe
     */
   public boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {

            String myPath = "/storage/external_SD" +DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
//si llegamos aqui es porque la base de datos no existe todavía.
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }

    @Override
    public synchronized void close() {
        if (myDataBase != null)
            myDataBase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public Persona recuperarPERSONA(String numero) {
        SQLiteDatabase db = getReadableDatabase();
        String[] valores_recuperar = {"number","name","address","identification","province"};
        Cursor c = db.query("movil", valores_recuperar, "number=" +"'"+ numero+"'",
                null, null, null, null, null);
        Persona cuerpo = null;
        if (c != null && c.moveToFirst()) {

           cuerpo = new Persona(c.getString(0), c.getString(1), c.getString(2), c.getString(3), c.getInt(4));
            db.close();
            c.close();
        }else{
          cuerpo = new Persona(" "," ", " ", " ", 1);
        }

        return cuerpo;
    }
}

y con el metodo recuperarPERSONA() ago las consultas....


text:
Q: BizTalk 2010 Output File Routing Based on Element Value I have an XML to XML map which output beautifully. The issue is we want to route the output based on this one element/field coming into the map (there are 2 different values which can populate the same field).
The problem is the field repeats in the output so the field can't be promoted in the outbound map. We can only seem to get it to output in both locations if we apply a filter to the Send Ports.
I have tried defining a variable based on the field after making the field in the source file both Distinguished and Promoted. I have tried custom receive pipelines as well as send pipelines: currently the closest I come is outputting to both locations.
I know this is child's play for most of you but am stymied myself. Any assistance is appreciated.

A: Have a canonical schema that is used internally that has the element used for routing as a promoted property.
Map the incoming message to the canonical schema.
Have your send ports subscribing to the promoted property on the canonical schema.
Have a map on each of your send ports that maps from the canonical schema to the desired outgoing schema.


text:
Q: Meaning of (AppDelegate *) Can someone explain what (AppDelegate *) in the following snippet means?
(AppDelegate *)[[UIApplication sharedApplication] delegate] iPad]

A: [[UIApplication sharedApplication] delegate] returns an id. So you can't access e.g. window property of it (because id object doesn't have it).
(AppDelegate *) statement causes to 'convert' id to AppDelegate object, so you can access its components.
It's like having NSObject *obj1; and NSString *obj2; - you can't do -substringToIndex: with obj1...

A: That code is casting the return value of [[UIApplication sharedApplication] delegate] to the type AppDelegate *.
This is not strictly necessary, but it will prevent compiler warnings when you call the method iPad on a class that may not support that method call. Assuming, of course, that AppDelegate has a method called iPad.

A: The delegate method returns an id (an unclassed object), so the compiler has no information about the object returned, and in particular doesn't know whether it has an iPad method. This is okay, but it leaves things sort of vague (dynamic typing). By casting the returned object explicitly to the AppDelegate class, you're telling the compiler that you know that the returned delegate object is an AppDelegate instance. This allows the compiler to check that your AppDelegate class does have an iPad method (static typing). This is good, because now the compiler can do more accurate error-checking. The compiler just believes your cast, though, so don't lie! If you do lie, and send the iPad message to an object that does not have an iPad method, your app can crash at runtime.

A: It is simply the class, and is used to cast the delegate to AppDelegate


text:
Q: How To Store and Retrieve Secrets From Hashicorp Vault using Docker-Compose? I have setup an instance of Hashicorp Vault. I have successfully written and read secrets to and from it. Getting Vault up and running and is the easy part. Now, how do I use Vault as a store to replace the .env file in docker-compose.yml? How do I read secrets from Vault in all of my docker-compose files?
Even more difficult: how do I dynamically generate keys to access access the secrets in Vault, then use those keys in my docker-compose.yml files, without editing those files each time I restart a stack? How is that process automated? In short, just exactly how can I leverage Hashicorp Vault to secure the secrets that are otherwise exposed in the .env files?
I have read all of their literature and blog posts, and haven't been able to find anything that outlines that process. I am stuck and any tips will be greatly appreciated.
Note: This is not a question about running a Hashicorp Vault container with docker-compose, I have successfully done that already.
Also Note: I cannot modify the containers themselves; I can only modify the docker-compose.yml file

A: You would need to query the vault API to populate either your .env file or in the entrypoint of your container. My preference would be the container entrypoint at worst, and ideally directly in your application. The reason is because vault secrets could be short lived, and any container running for longer than that period would need to refresh it's secrets.
If you go with the worst case of doing this in the entrypoint, there are a few tools that come to mind. confd from Kelsey Hightower, and gomplate.
confd can run as a daemon and restart your app inside the container when the configuration changes. My only concern is that it is an older and less maintained project.
gomplate would be run by your entrypoint to expand a template file with the needed values. That file could just be an env.sh that you then source into your environment if you needed env vars. Or you can run it within your command line as a subshell, e.g.
your-app --arg "$(gomplate ...sometemplate...)"

If you only use these tools to set the value once and then start your app, make sure to configure a healthcheck and/or graceful exit your app when the credentials expire. Then run your container with orchestration (Kubernetes/Swarm Mode) or set a restart policy so that it restarts after any credentials expire to get the new credentials.


text:
Q: Is it more efficient to declare helper functions outside the main function? When I debug step by step this kind of function:
foo <- function(x) {
  helper <- function(x) x^2
  2 * helper(x)
}

I see that the helper function definition is evaluated each time. Is it the same, when no in debug mode? Is it bad in terms of time execution?

A: You can try it yourself.  I didn't see much of a difference. inside or outside was faster on different runs when I tried it.
library(microbenchmark)

foo1 <- function(x) {
  helper <- function(x) x^2
  2 * helper(x)
}

helper <- function(x) x^2
foo2 <- function(x) {
  2 * helper(x)
}

microbenchmark(
  inside = foo1(1:1000),
  outside = foo2(1:1000),
  times = 1000
)

A: Based on @John Coleman comment I have tried this:
library(microbenchmark)

foo1 <- function(x) {
  helper <- function(x) {
    nested_helper <- function(y) {
      depper_helper <- function(z) {
        z + z
      }
      3 * depper_helper(y)
    }
    nested_helper(x) ^ 2
  }
  2 * helper(x)
}

nested_helper <- function(y) {
  3 * depper_helper(y)
}
depper_helper <- function(z) {
  z + z
}
helper <- function(x) {
  nested_helper(x) ^ 2
}
foo2 <- function(x) {
  2 * helper(x)
}

microbenchmark(
  inside = foo1(1:1000),
  outside = foo2(1:1000),
  times = 1000000
)

I ran it two times and obtain the same results:
Unit: microseconds
    expr min  lq     mean median  uq     max neval
  inside 5.0 5.4 8.822796    5.8 8.5 50905.9 1e+06
 outside 4.9 5.2 8.559778    5.6 8.3 47797.3 1e+06

Inside definition seems a little bit slower but not in a significant way. There must be some kind of optimization by the JIT compiler. I would like confirmation of this.


text:
Q: How to use .swf in c# with Transparent background
is there's a way  to use flash file inside WPF c# application with Transparent  back ground ?  i tried this

  public  Form1()
    {
        InitializeComponent();
        getdata();
        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        axShockwaveFlash1.Movie = @"c:\users\ahmed\documents\visual studio 2013\Projects\WindowsFormsApplication1\WindowsFormsApplication1\loading10.swf";
        axShockwaveFlash1.Play();

    }

and this

            axShockwaveFlash1.BackgroundColor =0;

and many below ! any idea ? i still get back color behind the file .

A: You can't do it by code at runtime.
Solution : Set (WMode) transparency via menu in the component settings (in Designer).
Find similar options to as shown in VB picture below:


text:
Q: $y'' + y' -2y = x^2$, find $A, B$, & and $C$ such that $y = Ax^2+Bx+C$ satisfies this equation. I am doing an extra credit problem for college. I don't expect anyone to solve it for me, but I would really appreciate being given some hints.
The problem:

$y'' + y' -2y = x^2$, find $A, B$, & and $C$ such that the function $y = Ax^2+Bx+C$ satisfies this equation.

I understand how to find derivatives if I know the function, but this is stumping me.

A: If you plug the quadratic polynomial into your differential equation you will get
$$2A+(2Ax+B)-2(Ax^2+Bx+C)=x^2.$$
Compare the coefficients and determine $A$, $B$, $C$.

A: Assuming that $y = y(x)$ is of the given form, we need only substitute $y$ into the differential equation
$$
y^{\prime\prime} + y^\prime  - 2y = x^2
$$
and solve for $A,B$ and $C$. Now, we have
\begin{align}\label{eq:1}\tag{1}
y^\prime(x) = 2Ax + B \quad \text{and} \quad y^{\prime\prime}(x) = 2A.
\end{align}
So, if $y$ solves the differential equation, then
\begin{align}
x^2 = y^{\prime\prime} + y^\prime  - 2y &= 2A + (2Ax+B) -2\left(Ax^2 + Bx + C \right)\label{eq:2}\tag{2}\\
&= -2Ax^2 + (2A-2B)x + \left( 2A + B -2C\right)\label{eq:3}\tag{3}.
\end{align}
Comparing the coefficients of this equation, we find that
\begin{align*}
\begin{cases}
-2A = 1,\\
2A-2B = 0,\\
2A+B-2C = 0.
\end{cases}
\end{align*}
Solving this system will give the explicit values of $A,B$ and $C$ required.

A: With
$y = Ax^2 + Bx + C, \tag 1$
we may substitute $y$, $y'$, and $y''$ into
$y'' + y' - 2y = x^2, \tag 2$
viz,
$y' = 2Ax + B, \tag 3$
$y'' = 2A, \tag 4$
$y'' + y' - 2y = 2A + (2Ax + B) - 2(Ax^2 + Bx + C) = x^2; \tag 5$
we group together like powers of $x$:
$-2Ax^2 + 2(A - B) x + (2A + B -2C) = x^2, \tag 5$
from which we infer
$-2A = 1, \tag 6$
$2(A - B) = 0, \tag 7$
$2A + B - 2C = 0; \tag 8$
thus
$A = B = -\dfrac{1}{2}, \tag 9$
$C = -\dfrac{3}{4}, \tag{10}$
and of course
$y = -\dfrac{1}{2}x^2 - \dfrac{1}{2}x - \dfrac{3}{4}. \tag{11}$
We Check:
From (11),
$y' = -x - \dfrac{1}{2}, \tag{12}$
$y'' = -1, \tag{13}$
$y'' + y' - 2y$
$= -1 - x - \dfrac{1}{2} - 2(-\dfrac{1}{2}x^2 - \dfrac{1}{2}x - \dfrac{3}{4}) = -1 - x - \dfrac{1}{2} + x^2 + x + \dfrac{3}{2} = x^2. \tag{14}$

A: Consider $z^2+z-2=(z+2)(z-1)=-2(1+\frac{1}{2}z)(1-z)$. Its inverse (as a formal power series) is
$$
-\frac{1}{2}(1+z+z^2+\dotsb)\left(1-\frac{1}{2}z+\frac{1}{4}z^2+\dotsb\right)
=-\dfrac{1}{2}-\dfrac{1}{4}z-\dfrac{3}{8}z^2+\dotsb
$$
Interpret $z$ as the differentiation operator and "multiply" by $x^2$ (that's why we can discard higher order terms):
$$
-\dfrac{1}{2}x^2-\dfrac{1}{4}2x-\dfrac{3}{8}2=-\dfrac{1}{2}x^2-\dfrac{1}{2}x-\dfrac{3}{4}
$$


text:
Q: how do access web service in .net? Application db connection in web service. i haveto connect the db using that web service.
can u help

A: Not the clearest of questions, but right clicking on references and choosing Add Web Reference should help?

A: If you are using visual studio 2008:

*

*Right click on references and click Add Service Reference.

*In the "Address" box, put the location of the wsdl of the web service you are trying to connect to and click go.

*Give it a namespace to put the proxy objects in.

*This will give you a set of objects in the namespace you entered previously including one "ServiceNameClient", use this to call the service.

If you are using visual studio 2005:

*

*Right click on references and click Add Web Reference.

*In the "URL" box, put the location of the wsdl of the web service you are trying to connect to and click go.

*Give it a name, this will be a namespace to put the proxy objects in.

*This will give you a set of objects in the namespace you entered previously including one "ServiceName", use this to call the service.

A: Try adding the reference of the webservice you want to use. The wsdl file will give you the name of the method and the parameters to that method and its return type.
Create the instance of the webservice and invoke the method you want to use as you would have done in case of a normal method.
You should be able to consume the webservice easily as the marshalling, unmarshalling, sending and receiving  the data on the network is all done by the .net framework.
Kalpak

A: You can go through this good starting point tutorial from Scott. It explains step by step how to create and consume web service.


text:
Q: Cannot Create Post I am unable to create a post, I am a beginner so apology in advance if my question sounds stupid
Heres The Picture Of My Form Before Hitting Submit:-

Heres The Picture After Hitting Submit:-

I cant seem to find any error
Here's My Controller:-
  public function store(Request $request)
    {
      $data = request()->validate([
        'title' => 'required',
        'body' => 'required',
      ]);

       auth()->user()->profile()->post()->create($data
       );
       return redirect('/h');

And I do need to pass in "user_id" in it
Please Help and Thanks in advance

A: Your controller validation seems correct.
You are redirected back to your form since the request doesn't contain the 'title' and 'body' values. These values are 'required' according to your validation array.
Add this line to your controller to debug and see what the request actually contains:
dd(request()->all());
In your view, make sure your html form inputs have their respective name attributes set correctly:
<form method="POST" action="/your-route">
  @csrf
  <input name="title" ...>
  <input name="body" ...>
</form>

And to answer your last question: No, you do not need to add the user_id to your $data array; Laravel will do it for you since you are chaining the create() method from the authenticated user instance with this line: auth()->user()->profile()->post()->create($data);
You could also call the create() method directly from the Post class, in which case the user_id should be specified:
Post::create([
    'user_id' => 1,
    'title' => 'My title',
    'body' => 'My body',
]);


text:
Q: How to view name and profile of site guest user I have sites in my Salesforce org. How do I view the name and profile of the giest user?

A: Click Public Access Settings button on the Site record in Setup. That will give you the Profile. To get to the User, click Assigned Users button in the Profile.


text:
Q: Does playframework 1.x handle cross site scripting (xss)? I'm using the playframework with version 1.2.5 and I have just a simple Question.
If I use for example:
public static User findByUsername(String username) {
    return User.find("username = ?", username).first();
}

So if I perform this call, does the "JPAQuery find()" or the playframework prevent cross site scripting and such things?
If not, what do I have easily to do for preventing it in all my database interactions?
Thanks a lot.
Cheers,
Marco

A: Since version 1.0.1, Play's template engine automatically escapes string.
More details on this page: playframework owasp top 10

A: Cross-site scripting does not quite apply to the code you posted, so I suppose you mean SQL injection. In that case, the code you posted should be safe. (The wrong way would be to build the query by concatenating Strings with + operator.)
See here: http://www.playframework.org/documentation/1.2.5/security#sql


text:
Q: Fetch Zendesk Tickets into SQL (JSON Handling) In the Zendesk Developer Blog i found a helpfull Entry(https://developer.zendesk.com/blog/getting-and-creating-tickets-with-.net).
I used the Code from the Article in an C# ConsoleApp for testing:
using System;
using ConsoleApplication1.Properties;
using Newtonsoft.Json.Linq;
using RestSharp;
using RestSharp.Authenticators;

namespace ConsoleApplication1
{
    public class Ticket
    {
        public int id { get; set; }
        public string url { get; set; }
        public string external_id { get; set; }
        public string type { get; set; }
        public string subject { get; set; }
        public string description { get; set; }
        public string priority { get; set; }
        public string status { get; set; }
        public string recipient { get; set; }
        public int requester_id { get; set; }
        public int submitter_id { get; set; }
        public int assignee_id { get; set; }
        public int organization_id { get; set; }
        public int group_id { get; set; }
    }

    internal class Program
    {
        private static readonly string requestUri = "https://xxx.zendesk.com/";
        private static readonly string username = Settings.Default.Username;
        private static readonly string password = Settings.Default.Password;

        private static void Main(string[] args)
        {
            var client = new RestClient(requestUri);
            client.Authenticator = new HttpBasicAuthenticator(username, password);
            var request = new RestRequest("/api/v2/tickets.json", Method.GET);
            client.AddDefaultHeader("Accept", "application/json");

            var response = client.Execute(request);
            var content = response.Content;

            var ticket = JObject.Parse(content);

            foreach (var pair in ticket)
            {
                Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
            }
        }
    }
}

It works, and i receive the following Data:
tickets: [
  {
    "url": "xxx.zendesk.com/api/v2/tickets/1.json",
    "id": 1,
    "external_id": null,
    "via": {
      "channel": "sample_ticket",
      "source": {
        "from": {},
        "to": {},
        "rel": null
      }
    },
    "created_at": "2015-10-12T12:08:25Z",
    "updated_at": "2015-10-12T18:15:13Z",
    "type": "incident",
    "subject": "Beispielticket: erster Blick auf das Ticket",
    "raw_subject": "Beispielticket: erster Blick auf das Ticket",
    "description": "Hallo xxx,\n\nE-Mails, Chats, Voicemails und Tweets werden in Zendesk in Form von Tickets erfasst. Geben Sie oben Ihre Antwort
ein und klicken Sie dann auf "Einreichen", um sie zu senden. Um auszuprobieren, wie eine E-Mail zu einem Ticket wird, senden Sie eine Nachricht an sup
port@xxx.zendesk.com.\n",
    "priority": "normal",
    "status": "open",
    "recipient": null,
    "requester_id": 1371652071,
    "submitter_id": 1371651941,
    "assignee_id": null,
    "organization_id": null,
    "group_id": 24976891,
    "collaborator_ids": [],
    "forum_topic_id": null,
    "problem_id": null,
    "has_incidents": false,
    "due_at": null,
    "tags": [
      "zendesk-beispiel"
    ],
    "custom_fields": [
      {
        "id": 28089621,
        "value": null
      },
      {
        "id": 28087191,
        "value": null
      },
      {
        "id": 28087201,
        "value": null
      }
    ],
    "satisfaction_rating": null,
    "sharing_agreement_ids": [],
    "fields": [
      {
        "id": 28089621,
        "value": null
      },
      {
        "id": 28087191,
        "value": null
      },
      {
        "id": 28087201,
        "value": null
      }
    ],
    "brand_id": 782281
  },
  {
    "url": "xxx.zendesk.com/api/v2/tickets/2.json",
    "id": 2,
    "external_id": null,
    "via": {
      "channel": "web",
      "source": {
        "from": {},
        "to": {},
        "rel": null
      }
    },
    "created_at": "2015-10-12T20:26:13Z",
    "updated_at": "2015-10-12T20:26:13Z",
    "type": "question",
    "subject": "test",
    "raw_subject": "test",
    "description": "test 1234",
    "priority": "normal",
    "status": "open",
    "recipient": null,
    "requester_id": 1371651941,
    "submitter_id": 1371651941,
    "assignee_id": 1371651941,
    "organization_id": 157600651,
    "group_id": 24976891,
    "collaborator_ids": [],
    "forum_topic_id": null,
    "problem_id": null,
    "has_incidents": false,
    "due_at": null,
    "tags": [
      "jpa"
    ],
    "custom_fields": [
      {
        "id": 28089621,
        "value": "jpa"
      },
      {
        "id": 28087191,
        "value": null
      },
      {
        "id": 28087201,
        "value": null
      }
    ],
    "satisfaction_rating": null,
    "sharing_agreement_ids": [],
    "fields": [
      {
        "id": 28089621,
        "value": "jpa"
      },
      {
        "id": 28087191,
        "value": null
      },
      {
        "id": 28087201,
        "value": null
      }
    ],
    "brand_id": 782281
  }
]
next_page:
previous_page:
count: 2

But now i did not know how to load the received data in Ticket Objects.
I Need something like that:
foreach(Ticket t in [Received Data])
{
    ... do something
}

to replace the "Console.WriteLine("{0}: {1}", pair.Key, pair.Value);" part.
These are my first steps in JSON, some how-to or first step link could be helpfull too.
(tried to get hints on http://www.newtonsoft.com/json but without sucess)
Update 1:
After the Comment from dbc (thx, for the very helpful Link) i testet a Little bit more. The variable "content":
var content = response.Content;

contains a Valid JSON string:
{
    "tickets": [
        {
            "url": "https://xxx.zendesk.com/api/v2/tickets/2.json",
            "id": 2,
            "external_id": null,
            "via": {
                "channel": "web",
                "source": {
                    "from": {},
                    "to": {},
                    "rel": null
                }
            },
            "created_at": "2015-10-12T20:26:13Z",
            "updated_at": "2015-10-12T20:26:13Z",
            "type": "question",
            "subject": "test",
            "raw_subject": "test",
            "description": "test 1234",
            "priority": "normal",
            "status": "open",
            "recipient": null,
            "requester_id": 1371651941,
            "submitter_id": 1371651941,
            "assignee_id": 1371651941,
            "organization_id": 157600651,
            "group_id": 24976891,
            "collaborator_ids": [],
            "forum_topic_id": null,
            "problem_id": null,
            "has_incidents": false,
            "due_at": null,
            "tags": [
                "jpa"
            ],
            "custom_fields": [
                {
                    "id": 28089621,
                    "value": "jpa"
                },
                {
                    "id": 28087191,
                    "value": null
                },
                {
                    "id": 28087201,
                    "value": null
                }
            ],
            "satisfaction_rating": null,
            "sharing_agreement_ids": [],
            "fields": [
                {
                    "id": 28089621,
                    "value": "jpa"
                },
                {
                    "id": 28087191,
                    "value": null
                },
                {
                    "id": 28087201,
                    "value": null
                }
            ],
            "brand_id": 782281
        },
        {
            "url": "https://xxx.zendesk.com/api/v2/tickets/3.json",
            "id": 3,
            "external_id": null,
            "via": {
                "channel": "web",
                "source": {
                    "from": {},
                    "to": {},
                    "rel": null
                }
            },
            "created_at": "2015-10-13T12:22:39Z",
            "updated_at": "2015-10-13T12:22:39Z",
            "type": null,
            "subject": "Test 2",
            "raw_subject": "Test 2",
            "description": "test content",
            "priority": null,
            "status": "open",
            "recipient": null,
            "requester_id": 1371651941,
            "submitter_id": 1371651941,
            "assignee_id": 1371651941,
            "organization_id": 157600651,
            "group_id": 24976891,
            "collaborator_ids": [],
            "forum_topic_id": null,
            "problem_id": null,
            "has_incidents": false,
            "due_at": null,
            "tags": [],
            "custom_fields": [
                {
                    "id": 28089621,
                    "value": ""
                },
                {
                    "id": 28087191,
                    "value": null
                },
                {
                    "id": 28087201,
                    "value": null
                }
            ],
            "satisfaction_rating": null,
            "sharing_agreement_ids": [],
            "fields": [
                {
                    "id": 28089621,
                    "value": ""
                },
                {
                    "id": 28087191,
                    "value": null
                },
                {
                    "id": 28087201,
                    "value": null
                }
            ],
            "brand_id": 782281
        }
    ],
    "next_page": null,
    "previous_page": null,
    "count": 2
}

but, only if there is NO double Quotation mark in the description (and i think in other fields too). Seems that Zendesk API does no escaping for the Quotation Marks !?!
But anyway i have valid JSON now, how can i load the JSON string in the Ticket object?

A: HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://92logics.zendesk.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key"); // or your basic authentication
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

string path = "api/v2/tickets.json?page=1";

ZenDeskTickets list = null;
                HttpResponseMessage response = await client.GetAsync(path);
                if (response.IsSuccessStatusCode)
                {
                    long SkippedId = 1;
                    string SkippedUrl = "";
                    list = await response.Content.ReadAsAsync<ZenDeskTickets>();
        }

You need to add namespace System.Net.Http to access ReadAsAsync.
It is available as dll and also as web api package files
Here is ZenDeskTickets Calls for you.
public class ZenDeskTickets
{
    [JsonProperty("tickets")]
    public Ticket[] Tickets { get; set; }

    [JsonProperty("next_page")]
    public object NextPage { get; set; }

    [JsonProperty("previous_page")]
    public object PreviousPage { get; set; }

    [JsonProperty("count")]
    public int Count { get; set; }
}

Same way you can define Ticket Class.
Each property/column will map automatically to right location and data will be filled.


text:
Q: Security Exception: Permission Denial The app used to run. However, just recently it began to stop working. The device is running Android Nutella. Below is the LogCat.
 java.lang.SecurityException: Permission Denial: reading com.google.android.music.store.ConfigContentProvider uri content://com.google.android.music.ConfigContent/one-key/2/ExplicitRestrictedByParentControl from pid=2500, uid=10373 requires the provider be exported, or grantUriPermission()

The app crashes in the the following code snippet on the last line(contained in a SongParser method).
 String[] projection2 = {MediaStore.Audio.Media.ARTIST};
    Uri songUri=null;
    try {
        songUri = Uri.parse("content://com.google.android.music.MusicContent/audio");
    } catch (NullPointerException e){
        e.printStackTrace();
    }
    if (songUri!=null) {
        CursorLoader cl2 = new CursorLoader(context,
                songUri, projection2, null, null, null);
        cursor = cl2.loadInBackground();

I grant the Uri permissions in the following method after asking for permissions through the runtime permissions methods.
 private void startService() {
    //start intent to RssService for feedback
    intent = new Intent(getActivity(), SongService.class);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    getContext().grantUriPermission("xxx.xxx.xxx.SongService",Uri.parse("content://com.google.android.music.MusicContent/audio"),Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.putExtra(SongService.RECEIVER, resultReceiver);
    getActivity().startService(intent);

}

Here is where SongService calls SongParser.
@Override
protected void onHandleIntent(Intent intent) {

        List<String> eventItems= null;
    if (haveNetworkConnection()) {
        parser = new SongParser();
        eventItems = parser.getAllArtists(getApplicationContext());
    }
        Bundle bundle = new Bundle();
        bundle.putSerializable(ITEMS, (Serializable) eventItems);
        ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
        receiver.send(0, bundle);}}

I have contained the permissions in the manifest as well. Again, this exception seemingly happened on its own.
<permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

A: What's happening is that for some reason, the (exported) MusicContent provider will redirect to ConfigContentProvider, which is not exported.
It seems that the way to solve it is to open Google Play Music. If you haven't launched it in a while, it will redirect to com.google.android.music.store.ConfigContentProvider and trigger a SecurityException. It's kind of problematic but at least I can tell my users what to do. Let me know if you can come up with something better.
It might also be a good idea to file a bug.

A: You do not have access to that ContentProvider. It is not exported, and that app did not pass you a Uri that you can use to access it.
Since presumably the Uri is from an app that you did not write, apparently an update to that app changed this behavior.


text:
Q: Communcation .NET application fails after upgrading TLSv1 to TLSv1_2016 I'm no SSL/TLS expert. but encounter the following
We make a connection to a webservice from a supplier and the "security policy" were TLSv1, and everything worked like a charm.
This supplier upgraded there security policy to TLSv1_2016.
And since then communcication fails. When they've rolled back all works again.
Now, after looking at the way how we make a connection, I get more confused.
we use .NET (Framework 4.7.0XXX)
and use the following class System.ServiceModel.Channels.CustomBinding
according to documentation this should (by default) support Ssl3, Tls, Tls1.1, Tls1.2. https://technet.microsoft.com/en-us/system.servicemodel.channels.sslstreamsecuritybindingelement.sslprotocols(v=vs.96)
Which seems sufficient.
On AWS i found following overview
TLSv1.2 support is enough for SSLv3 TLSv1.0 TLSv1_2016  TLSv1.1_2016    TLSv1.2_2018
TLSv1.1 support is enough for SSLv3 TLSv1.0 TLSv1_2016  TLSv1.1_2016
TLSv1 support is enough for SSLv3   TLSv1.0 TLSv1_2016
so looking at this info. i would guess that our way of making a connection via System.ServiceModel.Channels.CustomBinding should be sufficient to be able to interact with their upgraded (to TLSv1_2016) policy (even if it is TLSv1.1_2016 it should work, i am taking into account a typo in their communication :-) )
Has anyone encountered this issue? or has any idea where to investigate further.
Thanks in advance,
Regards,
Joe

A: The document you read on MSDN is not correct.
Please do visit the latest at Microsoft Docs, like the Best Practices,
https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls?view=netframework-4.7.2
You did not reveal enough (like your WCF code), but based on Microsoft's information, WCF on older .NET Framework versions by default uses SSL 3.0/TLS 1.0, and you must explicitly choose TLS 1.2 in your code if you cannot upgrade .NET Framework version. (Too many "if else" in that article, so do spend enough time on every relevant paragraphs and carry out experiments accordingly.)
Most importantly, "retarget your assemblies", meaning recompile your assemblies against .NET Framework 4.6.x or 4.7.x.

A: All,
thank you for all your help and suggestions, like I was looking for an  answer and could not find it, it is my own fault :-(
I was told we were on Framework 4.7.0, and all of the things I found made no sense, now it seems that our build server was using 4.5.2 framework... and now it all makes sense.
SSL3 and TLS1 and no other possibility in WCF and framework 452...
again, thank you for the assistance and guidance.
Now we are looking to retarget to FW 472.. but there are some issues...


text:
Q: Getting extent of raster in ArcMap to 12 decimal places I have a raster file in arcmap and want to get the extent of the raster to 12 decimal places, the extent in properties gives 9 places.
Does anyone know how I can increase it?


text:
Q: Python piping on Windows: Why does this not work? I'm trying something like this
Output.py
print "Hello"

Input.py
greeting = raw_input("Give me the greeting. ")
print "The greeting is:", greeting

At the cmd line
Output.py | Input.py

But it returns an EOFError.  Can someone tell me what I am doing wrong?
Thanks for your help.
EDIT
Patrick Harrington solution works but I don't know why...

A: Change it to:
Output.py | python Input.py

The output will be:

Give me the greeting. The greeting is: hello

A: I tested this on my Windows machine and it works if you specify the Python exe:
C:\>C:\Python25\python.exe output.py | C:\Python25\python.exe input.py
Give me the greeting. The greeting is: hello

But I get an EOFError also if running the commands directly as:
output.py | input.py

I'm not sure exactly why that is, I'm still looking into this one but at least this should provide you with a workaround for now. It may have something to do with the way the file handler is invoked for .py files.
UPDATE: well, what do you know. Looks like this is actually a bug in Windows where stdin/stdout redirection may not work properly when started from a file association. So the workaround is as noted by myself and Patrick, you need to specify "python" will be running input.py, otherwise it will not redirect stdout from output.py to the stdin for input.py correctly.
Reference:
http://mail.python.org/pipermail/python-bugs-list/2004-August/024923.html
http://support.microsoft.com/default.aspx?kbid=321788
UPDATE 2:
To change this behavior and make Windows pipes work as expected for stdin/stdout redirection, you can add this value to the registry (tested on my box and verified this works as desired).

*

*Start Registry Editor.

*Locate and then click the following key in the registry:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer

*On the Edit menu, click Add Value, and then add the following
  registry value:
Value name: InheritConsoleHandles
    Data type: REG_DWORD
    Radix: Decimal
    Value data: 1

*Quit Registry Editor.

A: Here's why you get the EOFError (from the documentation on raw_input):

The function then reads a line from
  input, converts it to a string
  (stripping a trailing newline), and
  returns that. When EOF is read,
  EOFError is raised.

http://docs.python.org/library/functions.html?highlight=raw_input#raw_input
You may want to use sys.stdin, it provides a file object from which you can use the read, readlines methods.
import sys
for greeting_line in sys.stdin.readlines():
    print "The greeting is:", greeting_line.strip()


text:
Q: Laravel 5.2 return no response as JSON If i try to return a JSON-String by using return response()->json($categorie); i get an empty response.
If i replace the return for echo, so i will get
HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json {"id":5,"name":"blah","parent":4,"visible":"yes","position":0,"created_at":"2016-06-29 15:23:25","updated_at":"2016-06-29 15:23:25"} as Browser output.
I'm using Laravel 5.2.
Here's the complete code:
namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Categories;

class ApiController extends Controller
{
    public static function categorieGetById($id) {
        $categorie = Categories::find($id);
        echo response()->json($categorie);
        // return response()->json($categorie);
    }
}

UPDATE: the controller returns nothing. every return produce an empty output.
why?

A: You should use toJson() method.
$categorie = Categories::find($id)->toJson();
echo $categorie;  // your json output
return $categorie; // same json output

The toJson method converts the collection into JSON.

in your current code,
$categorie = Categories::find($id);
return response()->json($categorie);  // your json output with return

Note:- You must write return here.
In above code if you write echo,
echo response()->json($categorie);

then it will show
HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json {"id":5,"name":"blah","parent":4,"visible":"yes","position":0,"created_at":"2016-06-29 15:23:25","updated_at":"2016-06-29 15:23:25"}

A: A qoute from http://laravel-tricks.com/tricks/return-json-response:

In the official docs : http://laravel.com/docs/responses#special-responses, need to do Response::json(...) to create json response. Actually, if the returned value is an array or instance of arrayableinterface or jsonableinterface such as eloquent model, you could just return it, it'll be a json, magically.


text:
Q: Oversized parentheses around tabular I'm having the following problem. I'm using a tabular environment to create a phrase structure rule (linguistics stuff, don't care about it) and I need parentheses for those parts in the rule which are optional. This is a demo code of what I'm using:
\documentclass{article}

\newcommand{\symb}[2]{%
\begin{tabular}[t]{c}
\normalsize{#1}\\
\footnotesize{#2}
\end{tabular}}
% Optional rule support
\newcommand{\opt}[1]{\ensuremath{\left(#1\right)}}
% Macros
\newcommand{\ra}{\ensuremath{\rightarrow}}
\newcommand{\ua}{\ensuremath{\uparrow}}
\newcommand{\da}{\ensuremath{\downarrow}}
\newcommand{\blank}{\ensuremath{\quad}}

\begin{document}
    \symb{IP}{}\blank
    \symb{\ra}{}\blank
    \opt{
        \begin{tabular}[t]{c}
            \normalsize{TopicP}\\
            \footnotesize{{\sc (\ua topic) = \da}}\\
            \footnotesize{{\sc (\ua topic) = (\ua TopicPath)}}
        \end{tabular}
    }\blank
    \opt{\symb{IP}{\ua = \da}}
\end{document}

I know the code isn't the most elegant thing you'll ever see. It's because I've had to modify a somewhat well-known macro used for LFG phrase structure rules... which sadly doesn't support more than one annotation. Thus, I'm using the tabular in order to have more than one annotation under the phrasal category (NP, IP, whatever).
Thanks!

A: Remove the position specifier [t] in \begin{tabular}{c} everywhere:
\documentclass{article}

\newcommand{\symb}[2]{%
\begin{tabular}{c}
\normalsize{#1}\\
\footnotesize{#2}
\end{tabular}}
% Optional rule support
\newcommand{\opt}[1]{\ensuremath{\left(#1\right)}}
% Macros
\newcommand{\ra}{\ensuremath{\rightarrow}}
\newcommand{\ua}{\ensuremath{\uparrow}}
\newcommand{\da}{\ensuremath{\downarrow}}
\newcommand{\blank}{\ensuremath{\quad}}

\begin{document}
    \symb{IP}{}\blank
    \symb{\ra}{}\blank
    \opt{
        \begin{tabular}{c}
            \normalsize{TopicP}\\
            \footnotesize{{\sc (\ua topic) = \da}}\\
            \footnotesize{{\sc (\ua topic) = (\ua TopicPath)}}
        \end{tabular}
    }\blank
    \opt{\symb{IP}{\ua = \da}}
\end{document}

The specifier [t] will align the tabular at the top, [c] at the center and [b] at the bottom as noted by cyberSingularity.

A: Delete the optional [t] positioning argument from the tabulars; to keep the alignment of IP -> with the first line of the you can use another three row tabular, having \symb{IP}{}\blank\symb{\ra}{}\blank in the first row and two other empty rows:
\documentclass{article}

\newcommand{\symb}[2]{%
\begin{tabular}{c}
\normalsize #1\\
\footnotesize #2
\end{tabular}}
% Optional rule support
\newcommand{\opt}[1]{\ensuremath{\left(#1\right)}}
% Macros
\newcommand{\ra}{\ensuremath{\rightarrow}}
\newcommand{\ua}{\ensuremath{\uparrow}}
\newcommand{\da}{\ensuremath{\downarrow}}
\newcommand{\blank}{\quad}

\begin{document}
    \begin{tabular}{@{}c@{}}
    \symb{IP}{}\blank
    \symb{\ra}{}\blank \\ \\
    \end{tabular}%
    \opt{
        \begin{tabular}{c}
            \normalsize{TopicP} \\
            \footnotesize \scshape (\ua topic) = \da\\
            \footnotesize \scshape (\ua topic) = (\ua TopicPath)
        \end{tabular}
    }\blank
    \opt{\symb{IP}{\ua = \da}}

\end{document}

I also changed the obsolete \sc to \scshape and suppressed some superfluous braces (\fontnotesize, \normalsize and \schape don't take arguments). Also, as egreg mentions in his comment, since \quad is not a math mode command, \newcommand{\blank}{\quad} is a more correct definition.

A: If you want top aligned tables with delimiters you can use delarray

\documentclass{article}

\usepackage{delarray}

\newcommand{\symbx}[4]{%
\begin{tabular}[t]#1{c}#2
\normalsize{#3}\\
\footnotesize{#4}
\end{tabular}}
\newcommand\symb{\symbx{}{}}
\newcommand\bsymb{\symbx()}
% Optional rule support
\newcommand{\opt}[1]{\ensuremath{\left(#1\right)}}
% Macros
\newcommand{\ra}{\ensuremath{\rightarrow}}
\newcommand{\ua}{\ensuremath{\uparrow}}
\newcommand{\da}{\ensuremath{\downarrow}}
\newcommand{\blank}{\ensuremath{\quad}}

\begin{document}
    \symb{IP}{}\blank
    \symb{\ra}{}\blank
        \begin{tabular}[t]({c})
            \normalsize{TopicP}\\
            \footnotesize{{\sc (\ua topic) = \da}}\\
            \footnotesize{{\sc (\ua topic) = (\ua TopicPath)}}
        \end{tabular}
    \blank
    \bsymb{IP}{\ua = \da}
\end{document}


text:
Q: I used javascript/jquery to allow images on my website to popup, but it does not seem to work When i click on an image, the popup does not seem to work, and there are no error messages as well. I searched google for examples but it doesnt work.
Here is my javascript code:
function eventHandlers(){
$(".img-thumbnail").click(togglePopup);}
function togglePopup(e){
var popup = document.getElementById("id_popup");

if (popup === null)
{

    popup = document.createElement("span");
    popup.id = id_popup;
    popup.setAttribute("class","image-popup");

    var thumbnail = e.target;
    var small_image = thumbnail.src;
    var large_image = small_image.replace("_small","_large");
    popup.innerHTML = '';

    thumbnail.insertAdjacentElement("afterend",popup);
} else
{
    $('#' + id_popup).remove();
}}

Code in the main file:

     <span id="id_popup"

Standard Test

And my css code:
.image-popup {
border: 5px solid lightgrey;
margin-left: 25%;
margin-top: -60%;
height: 40vh;}

Additionally is there a way that i can modify my javascript file to allow the popup to close when clicked anywhere on the screen?
Help will be really appreciated. Thanks.


text:
Q: Find the stray number Practicing some katas in Code Wars and ran into this "Find the stray number" - I thought this was a pretty simple exercise (thank God I am started to feel comfortable with these challenges), but I am failing one of the test. Not sure why I am failing the test, nor does the site give me any ideas of what the array is they are passing
Below is the code that I used - if anyone can help me out that would be great.
Here is the link to the challenge & question

https://www.codewars.com/kata/find-the-stray-number/train/javascript

You are given an odd-length array of integers, in which all of them are the same, except for one single number.
Complete the method which accepts such an array, and returns that single different number.
The input array will always be valid! (odd-length >= 3)
Examples
[1, 1, 2] ==> 2
[17, 17, 3, 17, 17, 17, 17] ==> 3

function stray(numbers) {
let strayChar = numbers[0];

 for(let i = 1; i < numbers.length; i++){
  if(strayChar !== numbers[i]){
  return strayChar = numbers[i];
   }
 }
       return 0;
 }

A: Here, we do a find to find an element, using the evaluator filter and test is simple. Find an element that has a filtered array length of 1.

let testArrays = [[1, 1, 2], [17, 17, 3, 17, 17, 17, 17]];

function stray(numbers) {
  return numbers.find((e) => numbers.filter((v) => v===e).length === 1);
}

testArrays.forEach(arr => {
  console.log(stray(arr));
});

A: You could do something like this by using Set, Map, Array#from, Array#slice, and Array#find.
Use Set to find the unique numbers in the list. Then simply only loop through the first 3 elements of the list. If one of the unique numbers has a count greater than 1, that means the other unique number must be the odd one.

const data = [17, 17, 3, 17, 17, 17, 17];

function stray(numbers){
  //find unique numbers and set their count to 0
  const map = new Map(Array.from(new Set(numbers)).map(v=>([v,0])));

  //take first three numbers from numbers array
  return Array.from(
      numbers.slice(0,3).reduce((a,c)=>{
        //update the count
        return map.set(c, map.get(c) + 1);
      }, map)
      //find the number with a count of 0 or 1
  ).find(([,v])=>v<=1)[0];
}

const res = stray(data);

console.log(res);

One of the more impressive solutions offered on code wars is:

const data = [17, 17, 3, 17, 17, 17, 17];
const stray = nums => nums.reduce((a, b) => a ^ b);

const res = stray(data);

console.log(res);

A: int stray(numbers) {
  numbers.sort();
  int ans = (numbers[0] == numbers[1]) ? numbers.last : numbers.first;

  return ans;
}

A:

function stray(numbers) {
    //take first element
    let strayChar = numbers[0];

    // see if it is different from the next 2
    if (strayChar !== numbers[1] && strayChar !== numbers[2]) return strayChar;

    // if not find the first value that is different
    for(let i = 1; i < numbers.length; i++){
      if(strayChar !== numbers[i])return numbers[i];
    }
 }

 const data = [17, 17, 3, 17, 17, 17, 17];
 console.log(stray(data));

A: const stray = numbers => {
  let number = 0

  numbers.forEach(x => numbers.indexOf(x) ? number = x : null)
  return number
}
console.log(stray([17, 17, 3, 17, 17, 17, 17]))

A:

function stray(numbers) {
    const result =  numbers.find(number => numbers.indexOf(number) === numbers.lastIndexOf(number));
    console.log(result)
}
stray([1, 1, 2])

A: i know it's been more than year but the error you had was just because the extra '=' in the if statement


text:
Q: Unable to launch DynamoDB after installation on AWS-ec2 instance Hi I Have launched EC2 instance and followed thw installation procedure of dynamoDB as shown in the below link
https://garywoodfine.com/how-to-install-dynamodb-on-local-ubuntu-development/

I was able to successfully install DynamoDB as shown below:
Initializing DynamoDB Local with the following configuration:
Port:   8000
InMemory:       false
DbPath: null
SharedDb:       false
shouldDelayTransientStatuses:   false
CorsParams:     *

but when i try to launch with DynamoDb using a browser with the link as shown in the document
http://localhost:8000/shell/

it's not launching
I have done the following:

*

*I have changed the localhost to vm's public IP as shown below
http://x.xxx.xx.xx:8000/shell/

*inbound and outbound rule are set correctly to allow all traffic, http, https
still not nothing is working.
I want to open dynamoDB UI on the browser
Kindly suggest what to do.

A: DynamoDB Local Web Shell was deprecated with version 1.16.X and is not available any longer from 1.17.X to latest. Refer Dynamodb local web shell does not load for more detail.
The latest solution that AWS offers for the same is NoSQL Workbench for DynamoDB.
More details here - NoSQL Workbench for DynamoDB


text:
Q: Client's computer Not Connecting to Server I am working on a project for a company, everything is working fine when I use the server computer to test it, but when I try using the the employees computer to login, its not connecting.

Here's the am getting from chrome developer tools::: Access to XMLHttpRequest at 'http://localhost/smarthrapi/api/auth' from origin 'http://hrm' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
OPTIONS http://localhost/smarthrapi/api/auth 500 (Internal Server Error)

services.AddCors(o => o.AddPolicy("SmartHRCorsPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

Cors is already enabled and this is the usage here
[EnableCors("SmartHRCorsPolicy")]
public class AuthController : Controller
{ mycode here

*

*If I use http://localhost/hrmanager/HR/login to log in on the server, its working fine, but when I try http://servername/hrmanager/HR/login on the employees computer, its not working. its as if its not seeing my Code or can't access the database.

*All the views are working fine, like when I try http://servername/hrmanager/HR/anotherpage the page is showing but nothing is working.

Is it that they're some restrictions on the server or is the problem from my code, I don't really know please help me. I wrote the code with MVC, I have APIs I called using ajax and am using sqlserver. Please the app need to be Live tomorrow, which means I need to fix it today. Thanks

A: Looking at the error message you're receiving, it's definitely a CORS issue. To further investigate it, Are you sure that the API is hosted or available on each client's http://localhost/ as mentioned in the error message? If yes, then setting up CORS may help.
If no, are they hosted on http://servername/ ? Then please check the API URLs, they should point to  http://servername/ and not point to localhost in that case. Possible areas to look at are View (.cshtml/.vbhtml) files and Javascript code if any.


text:
Q: How to pull and display parent div I'm a jQuery noob. I'd like to iterate through a list of html classes and for each class display the name of the parent div. Specifically, I'd like to iterate through the food_type classes below and display the parent id for each (e.g., 'chicken'). So something like this...
$(".food_type").each(function() {
      alert(...)

100

Chicken

100

Eggs

100

Pork

A: Inside the each method, this keyword regards to the element being iterated through. So you wrap it into a jQuery object (by doing $(this) ) and get its parent. Finally, you get the parent's id attribute. Put it all together and you have this:
$(".food_type").each(function() {
    alert($(this).parent().attr("id"));
}

Further reading:

*

*http://api.jquery.com/each/

*http://api.jquery.com/parent/

*http://api.jquery.com/attr/

A: Try
$(".food_type").each(function() {
  alert($(this).parent().attr("id"));
});

A: $(".food_type").each(function() {
    alert($(this).parent().prop("id"));
}

A: You can do:
$(".food_type").each(function() {
    alert($(this).parent().attr("id"));
}

parent() gets the element's parent, and attr("id") gets the element's ID. each just iterates through the array generated by $(".food_type").

A: $(".food_type").each(function() {
      var category = $(this).parent().attr('id');
});


text:
Q: Eclipse StatEt echo every line twice? Here is the code I tried to send to R console in Eclipse:
distuni = setRefClass("DistUniform",
        c("a", "b"),
        methods = list(
                mean = function() {
                    (a+b)/2
                }
                )
        )

Here is a screenshot of the result:

As you can see, every line is echoed twice, very annoying. Any suggestions how to solve this?


text:
Q: vim find lines with only 1 occurrence of quote How can I find lines with only one occurrence of double quote in Vim?
I managed to find it by grep:
grep "\"" file|grep -v "\".*\""

but I need to get it on Vim. To be  able to modify those lines.

A: Grep in your shell, get the result in Vim

*

*Make the output of your command more useful by adding the filename and the line numbers:
$ grep -nH "\"" file | grep -v "\".*\""

Output:
file:7:lsytdlyusdtlsu"ydtsuoduystdosytslodyu
file:10:lsytdlyusdtlsuydtsuodu"ystdosytslodyu

See $ man grep for -n and -H.

*Use Vim's :help -q and your shell's process substitution to populate Vim's quickfix:
$ vim -q <(grep -nH "\"" file | grep -v "\".*\"")

This creates a quickfix list…

*

*through which you can navigate with :help :cnext/:help :cNext,

*on which you can operate, item by item, with :help :cdo,

*that you can display in its own special window with :help :cwindow.

*Operate on each item in the quickfix list:
This command:
:cdo s/$/---hello

would append ---hello to each line with a single ":
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsuydtsuodu"ystdo"sytslodyu
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsu"ydtsuoduystdosytslodyu---hello
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsuydtsuodu"ystdosytslodyu---hello

Alternatively, you can do the grepping first, and then do the following:
$ vim -q <(!!)

which will rerun the last command and pass its output to Vim.
Do it from within Vim
:cexpr system('grep -nH "\"" file | grep -v "\".*\""')

which has the same outcome as step #2 above.
See :help :cexpr and :help system().
Operate directly on the matching lines
:help :global and :help :vglobal have similar semantics to grep and grep -v: the former marks lines that match and the latter marks lines that don't.
So, with file opened in Vim, doing the following should print the lines you are after because that's what :g and :v do by default:
:g/"/v/".*"

It doesn't exactly works the same but, in essence, it is the same logic as your grep chain: match quotes and then filter out multiple quotes.
Now it is up to you to decide what <command> to execute on the given lines:
:g/"/v/".*"/<command>

For example:
:g/"/v/".*"/s/$/---hello

would do the same as the :cdo example above:
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsuydtsuodu"ystdo"sytslodyu
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsu"ydtsuoduystdosytslodyu---hello
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsuydtsuoduystdosytslodyu
lsytdlyusdtlsuydtsuodu"ystdosytslodyu---hello

A: I found it, based on your comments
/^[^"]*"[^"]*$

This regexp will find a line starting with no double quote then one double quote then no double quote to the end.


text:
Q: How do I reset a git branch to a given previous commit and fix the detached HEAD? I needed to reset my branch to an earlier working state (commit) so I did:
git reset --hard c70e611

Now I see
HEAD detached at c70e611
nothing to commit, working directory clean

How to fix / understand / get around the detached head message and push so that c70e611 is now the latest commit I am using and represents the HEAD of the branch I am working in (not master).

A: HEAD is where your workspace is currently in the tree of git commits; detached means that it doesn't correspond to a branch. To fix this, you should create a new branch with git checkout -b branch (replacing branch with the name you want to give your new branch).
If you want to drop the commits following the one you reset to, you can delete the master branch and re-create it:
git branch -D master
git checkout -b master

If you're working on a repository which is pushed elsewhere you'll need to do more work to fix things up, possibly forcing a push (and telling every one else to re-clone their workspace). If you have shared state, you should really create a revert commit; take a look at git revert (starting from master and reverting all the commits starting with the one following c70e611).

A:
HEAD detached at c70e611

This is because when you did the git reset --hard, you were not on any branch at that time. You had a detached HEAD, and that detached head got moved with the git reset --hard command, along with a rewrite of your working tree to that state.
If you want some branch foo to be c70611, then:
git checkout foo
git reset --hard c70611

If this is considered to be a good state to push to foo's upstream then just git push <remote-name> foo.
There is a more direct way to force foo to c70611 without checking it out to be the current branch. Namely, you can rewrite what foo points to using the git update-ref command.
Before doing any of the above, I would pause and try to see how I had ended up in a detached state without noticing. Perhaps it was an unfinished rebase or whatever. Step one is to review the last few entries in the git reflog to help jog your memory.


text:
Q: How to convert Wifi RSSI to level of Wifi strength in menu bar in Mac OSX? I can get the value of Wifi RSSI. but don't know how to convert it into level of Wifi strength as we can see in the menubar in Mac OSX (If I receive a strong Wifi, the wifi status will be bold black on all 4 lines of wifi icon).
Is there any methods or library that I can use to do this? Thx in advance.

A: I don't think you'll find anything in the API to do this.
I think you might have to Use Science™ and do a manual check, literally walking away from your WiFi access point with laptop in hand, noting down the RSSI values at which the WiFi signal indicator icon changes. Do this a few times and you'll likely find a correlation. I can't imagine it would take more than ten or fifteen minutes to get a good range of sample values.
It's probably worth trying it with more than one type of Mac, if possible.

A: There is no public API for this.  You'll have to figure it out yourself. You might be able to use something simple like (RSSI+100)/8 and then clamp the result between 0 and 4 bars.
Also, you'll want to use a rolling average over a few seconds to keep the bars from jumping around if the signal ends up at a boundary case or jumps around.
PS: AFAIK, Apple uses a more complex algorithm which takes Transmit Rate into consideration.


text:
Q: C++ Code not building with build project (F6) in Visual Studio 2008 I have a large solution that contains C# and C++ projects. After I code in my classes or functions I run a build to have the parser check syntax. What I have noticed is that when I press F6 the entire solution will build and get parsed except for the C++ files that I'm working on.
This seems like it's not the intended function of the editor so is there a way I can force this to happen when I perform a build?
Thanks,
P.S. I know I can go to rebuild project and force a build that way. I'm looking for a way to have the editors treatment of C++ and C# files be consistent.

A: In the solution properties, under "Configuration Properties", make sure the C++ projects are set to build.  Also, make sure the project dependencies are setup properly.
These two things control which projects are built when you run a build.