text:
Q: Grails layoutResources equivalent for asset-pipeline I'm trying to setup a SiteMesh layout in grails v2.3.1 using the asset-pipeline plug-in (v1.0.4), but I'm not sure how to handle inclusion of javascript resources in a specific location of my template (like you would using r:layoutResources if using the resources plugin).
Example layout (grails-app/views/layouts/test.gsp):

      <title><g:layoutTitle/></title>
      <g:layoutHead/>

         <g:layoutBody/>

      <asset:javascript src="application.js"/>

Example gsp (grails-app/views/test.gsp):

      <meta name="layout" content="test"/>
      <title>The Title</title>
      <asset:stylesheet src="thispageonly.css"/>

         Hello World

      <asset:javascript src="thispageonly.js"/>

The resulting decorated page (ignoring asset-pipeline bundling/etc) works for stylesheet (since it's in head) but fails for javascript:

      <meta name="layout" content="test"/>
      <title>The Title</title>
      <link rel="stylesheet" href="/assets/thispageonly.css?compile=false"/>

            Hello World

Currently the only way I can get this to work is to use g:applyLayout and g:pageProperty:

      <title><g:layoutTitle/></title>
      <g:layoutHead/>

         <g:layoutBody/>

      <asset:javascript src="application.js"/>
      <g:pageProperty name="page.javascript"/>

<g:applyLayout name="test2">

      <title>The Title</title>
      <asset:stylesheet src="thispageonly.css"/>

         Hello World

      <content tag="javascript">
         <asset:javascript src="thispageonly.js"/>
      </content>

</g:applyLayout>

But this departure from meta tag seems overly complicated (plus I'm not clear whether the poorly documented g:pageProperty will be supported as-is in future upgrades).  What's the best long-term way of doing this?

A: FYI: This works well for me though it's a little bit ugly.

      <title><g:layoutTitle/></title>
      <g:layoutHead/>

         <g:layoutBody/>

      <asset:javascript src="application.js"/>
      <asset:deferredScripts/>

<g:applyLayout name="test2">

      <title>The Title</title>
      <asset:stylesheet src="thispageonly.css"/>

         Hello World

      <asset:script src="${assetPath(src: 'thispageonly.js')}" type="text/javascript" />

</g:applyLayout>

A: The use of sitemesh to control object placement is totally a valid use case. Sitemesh isn't going anywhere and I actually use this to control sub container and layout inheritance. It didn't make sense to duplicate this built in flow control in the asset-pipeline plugin.
Another trick that is quite useful is to use the <g:layoutHead/> and <g:layoutBody/> tags , which are also quite useful.
If this is proving to be a problem, in the future, we may consider providing a mode that has this behavior. Let me know how things are going with asset-pipeline and if issues like this come up please feel free to open a ticket on github. Apparently, I need to keep an eye on stack overflow as well :)

A: IGNORE THIS ANSWER, see the comment below by the asset-pipeline creator about how this already exists in the asset-pipeline plugin as <asset:script>.
OLD ANSWER:
Sitemesh makes my head hurt, and as far as I can tell, the solution using g:layoutHead and g:layoutBody tags isn't something that'd let you collect a bunch of different javascript snippets and emit them all in a single block.
The application I've recently started working on pretty heavily leveraged the r:script tag, and would use it multiple times within a single gsp page (on various included templates).
How I'm planning to solve this in my app is with a taglib that just does pretty much what the r:script tag did.  Gather up any deferred javascript snippets and emit it where the user asks for it to be emitted.
Here's a sample taglib that can do this:
class DeferTagLib {
    static namespace = 'defer'
    static defaultEncodeAs = [emitScript: 'raw']  // we actually want to inject javascript :)

    private static JAVASCRIPT_DEFER_PROPERTY = "__defer__javascript"

    protected String removeJavascript() {
        try {
            return getJavascript()
        } finally {
            getRequest().removeAttribute(JAVASCRIPT_DEFER_PROPERTY)
        }
    }

    protected String getJavascript() {
        return getRequest().getAttribute(JAVASCRIPT_DEFER_PROPERTY)
    }

    protected void appendJavascript(String javascript) {
        String currentValue = getJavascript() ?: ""
        getRequest().setAttribute(JAVASCRIPT_DEFER_PROPERTY, currentValue + javascript)
    }

    // For gathering script tags in your gsp files and emitting them in the footer of the layout
    // A replacement for the r:script tag that came with Resources, but is not in the asset-pipeline plugin
    def script = { attrs, body ->
        appendJavascript(body())
    }

    // Used in the layout to emit all the script that has been deferred so far in the footer of the page
    // A replacement for the <r:layoutResources/> tag that emitted javascript in the footer
    // (the 2nd time it was called, kind of confusing...)
    def emitScript = { attrs ->
        out << ""
    }
}

Then, in my gsp pages/fragments, I can just replace any previous calls to r:script with defer:script:
<defer:script>
    // this is before
</defer:script>

... maybe another template that's included ...

<defer:script>
    alert("foo!");
</defer:script>

...  later

<defer:script>
    // after
</defer:script>

And in my layout, at the bottom I can just do this

     .... shared head stuff ....
    <g:layoutHead/>

    .... body stuff before layout
    <g:layoutBody/>
    .... other body stuff after layout
    <defer:emitScript/>

That'll end up creating a section after the body that looks like
    ... the actual body from the gsp

A: Not sure about your requirement.
In my project, I needed to move all JavaScript files to Footer.
I moved "layout Resources" tag from Header to Footer and it worked fine.

    <r:layoutResources>


text:
Q: How to setup an environment in anaconda and python 32 bit version on Windows 10 64 bit right now im using Anaconda 64 Bit (latest version) on Windows 10 64 Bit and i need to work with python 64 bit and 32 bit cause I have to work with a 32 bit driver in my python programm.
Maybe somebody can help me cause I dont know how i can change the python bit version.
I also tried the command CONDA_FORCE_32BIT=1 but it doesnt work. Some help would be really great ;).
Thanks in advance
Littlestudent

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como remover essa quebra de linha? tenho uma pagina que usa um editor de texto do tipo 'wysiwyg' que no caso é um elemento textarea, esse gera um codigo html pro texto que o usuario digitar, eu salvo o valor deste campo no onblur do mesmo atraves de um ajax que faz salvar no SESSION via php, o problema está depois, quero fazer com que esse texto que o usuario digitou apareça na tela (mesmo que o usuario atualize a pagina), e estou com problema de setar o texto no editor de texto, pois o codigo gerado é gerado com quebra de linha, e ao colocar esse valor no javascript dá erro devido a essa quebra de linha ja procurei maneiras de remover essas quebras de linha, mas n achei uma que funcionasse.
função que chama ajax:
function SalvaSession(valor){
      $.post( "ajax_salva_session.php",
            {
                'texto' : valor  //valor recebe o html do editor de texto
           },
           function (data) {
           }
      );
 }

arquivo ajax_salva_session.php (que salva o texto recebido do editor):
<?php
    $texto = isset($_POST['texto']) ? $_POST['texto'] : '';
    $texto = str_replace("\n", " ", $texto); //usei essas 3 formas que achei
    $texto = str_replace("\r", " ", $texto); //na net pra tentar eliminar a quebra
    $texto = preg_replace('/\s/',' ',$texto);//de linha, mas até o momento sem sucesso :/
    $_SESSION['capitulo'] = $texto;
?>

linha que seta o texto no editor de texto (a sintaxe está certa, é a sintaxe que consta na documentação: $("#placeHolder").Editor("setText", "Text")):
$('#paragrafo').Editor('setText', "<?php echo ($_SESSION['capitulo']); ?>");

texto gerado no browser (que dá erro):
$('#paragrafo').Editor('setText', "

( ! ) Notice: Undefined variable: _SESSION in C:\wamp\www\index.php on line 10

Call Stack

#	Time	Memory	Function	Location

1	0.0058	241440	{main}(  )	..\index.php:0

");

A: Tente dar um replace assim:
str_replace("> <", "><", $texto);

Caso isso não funcione o problema pode ser com as aspas. Tem um colspan="5", com aspas duplas ao invés de simples. Como você abriu no início as aspas duplas, ele considera essa antes do 5 um fechamento, e a depois do 5 um nova abertura.
Replace no ajax
Tente fazer um replaceno momento do recebimento do texto, substituindo as aspas duplas pelas simples.
function SalvaSession(valor){
      $.post( "ajax_salva_session.php",
            {
                'texto' : valor.replace("\"", "\'")  //valor recebe o html do editor de texto
           },
           function (data) {
           }
      );
 }

A: $logradouro = htmlentities($logradouro, null, 'utf-8');
$logradouro = str_replace(" "," ",$logradouro);
$logradouro = str_replace("\n", "", $logradouro);
$logradouro = str_replace("\r", "", $logradouro);
$logradouro = preg_replace('/\s/',' ',$logradouro);


text:
Q: Task.WhenAll() not working as expected without visual studio debugger attached I have a question about async programming and Task.WhenAll(). I have a code snippet that downloads a folder from google drive and it works as expected when i am debugging my code. However when I run the application without debugger the download function takes atleast 4x the time it takes when it runs with the debugger. I also get crash logs with TaskCancelled  exceptions (System.Threading.Tasks.TaskCanceledException: A task was canceled.) which do not happen with the debugger attached. What needs to be changed for the code to work as expected without debugger attached. NB this snippet downloads +- 1000 files in about 22-25 seconds with debugger and 2min+ without debugger.
public static async Task<bool> DownloadFolder(CloudDataModel.File file, string path, params string[] exclude)
    {
        try
        {
            if (file != null && !string.IsNullOrEmpty(file.id))
            {
                List<string> toExclude = new List<string>();
                if(exclude != null)
                {
                    toExclude = exclude.ToList();
                }

                List<Task> downloadFilesTask = new List<Task>();
                var files = await file.GetFiles();
                foreach (var f in files)
                {
                    var task = f.Download(path);
                    downloadFilesTask.Add(task);
                }

                var folders = await file.GetFoldersAsync();
                foreach (var folder in folders)
                {
                    if (toExclude.Contains(folder.name))
                    {
                        continue;
                    }
                    Task task = null;
                    if (path.Equals(Statics.ProjectFolderName))
                    {
                        task = DownloadFolder(folder, folder.name);
                    }
                    else
                    {
                        task = DownloadFolder(folder, Path.Combine(path, folder.name));
                    }

                    downloadFilesTask.Add(task);
                }
                var array = downloadFilesTask.ToArray();
                await Task.WhenAll(array);
                return true;
            }
        }
        catch (Exception e)
        {
            Crashes.TrackError(e);
        }
        return false;
    }

Edit
after some more trial and error the fault has been identified.
the downloading of the file was the cause of the unexpected behaviour
public static async Task<StorageFile> DownloadFile(CloudDataModel.File file, string destinationFolder)
    {
        try
        {

            if (file != null)
            {
                Debug.WriteLine($"start download {file.name}");
                if (file.mimeType == Statics.GoogleDriveFolderMimeType)
                {
                    Debug.WriteLine($"did not download resource,  resource was folder instead of file. mimeType: {file.mimeType}");
                    return null;
                }

                var endpoint = Path.Combine(DownloadFileEndpoint, $"{file.id}?alt=media");
                // this would cause the unexpected behaviour
                HttpResponseMessage response = await client.GetAsync(endpoint);

                StorageFile downloadedFile;
                using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
                {
                    var memstream = new MemoryStream();
                    StreamReader reader = new StreamReader(streamToReadFrom);
                    streamToReadFrom.Position = 0;
                    await streamToReadFrom.CopyToAsync(memstream);
                    downloadedFile = await fileHandler.SaveDownloadedCloudFile(memstream, file, destinationFolder);
                    Debug.WriteLine($"download finished {file.name}");
                }

                return downloadedFile;
            }

            return null;
        }

        catch (Exception e)
        {
            Crashes.TrackError(e);
            return null;
        }
    }

After setting a timeout to the client (System.Net.Http.HttpClient) the code executed as expected.
client.Timeout = new TimeSpan(0,0,5);

A: So after some trial and error the downloading of the file was identified as the cause of the problem.
var task = f.Download(path);

the Download function implements a System.Net.Http.HttpClient wich was initialized without any kind of timeout. when one of the tasks had a timeout, all other tasks would also not execute as expected. to fix this issue a timeout of 5 seconds was added to the HttpClient object.
       private static void InitializeClient()
       {
            HttpClientHandler handler = new HttpClientHandler { AllowAutoRedirect = true };
            client = new HttpClient(handler);
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AccountManager.LoggedInAccount.Token);
            client.Timeout = new TimeSpan(0,0,5);
        }

After this change the code would execute as expected.

A: My guess is that without the debugger the parallelism increases, and so the remote server is overflowed by requests and can't perform optimally. Your code does not have any provision for limiting the degree of concurrency/parallelism. One possible way to solve this problem is to use a SemaphoreSlim, as shown in this question (among many others).


text:
Q: Creating static resource dictionary I've created a Resource Dictionary that I want to merge with multiple usercontrol xaml files. I want only one instance of this Resource Dictionary to be created. Any idea how to do this?
Note: Merge should happen through xaml only and not through code.
Thanks & Regards,
Vishal

A: How about this?
class DictionaryExtensions
{
    public static ResourceDictionary MyResourceDictionary;

    static DictionaryExtensions()
    {
        MyResourceDictionary = new ResourceDictionary();
        Style buttonStyle = new Style() { TargetType = typeof(Button) };
        buttonStyle.Setters.Add(new Setter(Button.MarginProperty, new Thickness(5)));
        buttonStyle.Setters.Add(new Setter(Button.PaddingProperty, new Thickness(5)));
        buttonStyle.Setters.Add(new Setter(Button.MaxWidthProperty, 100.0d));
        MyResourceDictionary.Add("buttonStyle", buttonStyle);
    }

    public static Type GetMyDictionary(DependencyObject obj)
    {
        return (Type)obj.GetValue(MyDictionaryProperty);
    }

    public static void SetMyDictionary(DependencyObject obj, Type value)
    {
        obj.SetValue(MyDictionaryProperty, value);
    }

    // Using a DependencyProperty as the backing store for MyDictionary.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyDictionaryProperty =
        DependencyProperty.RegisterAttached("MyDictionary", typeof(Type), typeof(UserControl), new UIPropertyMetadata(new PropertyChangedCallback(OnMyDictionaryChanged)));

    public static void OnMyDictionaryChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is UserControl)
        {
            (d as UserControl).Resources.MergedDictionaries.Add(MyResourceDictionary);
        }
    }
}

XAML:
<UserControl x:Class="WpfSOTest.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:WpfSOTest"
         mc:Ignorable="d"
         d:DesignHeight="300"
         d:DesignWidth="300"
         local:DictionaryExtensions.MyDictionary="{x:Type ResourceDictionary}">
<Grid>
    <StackPanel>
        <Button Style="{StaticResource buttonStyle}"
                Content="Button1" />
        <Button Style="{StaticResource buttonStyle}"
                Content="Button2" />
    </StackPanel>
</Grid>

You can use Type object to dynamically choose between multiple dictionaries.

A: If it's truly global, maybe you could merge this dictionary to App.xaml?


text:
Q: How to separate a file per day into hours in Linux I take a file with approximately 30000 lines per day. I take this every hour till end of the day and I want to separate this into hours. For example like below:
Hours    file
00-01     23
01-02     230
02-03     3453

With awk command I count a file and is approximately 30000 lines per day.  Example of a file is like this.
200 | 2003| mandi | 2017-12-27 09:20:21 | end

There are 30000 lines into a file every day in a different hours.This is a reason why i want to separate into hours.
Please help me to separate this into hours, with "for" cycle or "while do".

A: Still not certain what you actually want, but I think this is close. Your sample file is not much use so I extended it as follows:
200 | 2003| mandi | 2017-12-27 09:20:21 | end
190 | 2007| mandi | 2017-12-27 10:20:21 | end
190 | 2007| mandi | 2017-12-27 10:30:21 | end
190 | 2007| mandi | 2017-12-27 10:31:21 | end
190 | 2007| mandi | 2017-12-27 10:31:25 | end
190 | 2007| mandi | 2017-12-27 23:31:25 | end

Then, I use GNU awk as follows:
awk -F'|' '{split($4,a,/[ :]/);hour=a[3]+0; lines[hour]++}
    END{ for(h=0;h<24;h++)printf("%d-%d: %d\n",h,h+1,lines[h]) }' YourFile.csv

Sample Output
0-1: 0
1-2: 0
2-3: 0
3-4: 0
4-5: 0
5-6: 0
6-7: 0
7-8: 0
8-9: 0
9-10: 1
10-11: 4
11-12: 0
12-13: 0
13-14: 0
14-15: 0
15-16: 0
16-17: 0
17-18: 0
18-19: 0
19-20: 0
20-21: 0
21-22: 0
22-23: 0
23-24: 1


text:
Q: IE6 - Elements won't disappear I'm having some major problems trying to get images and paragraphs to disappear in IE6, in my text-only style sheet. I've tested the code in Chrome, FF, Opera, Safari, IE7 & 8, and every thing is working everywhere else... (surprise!) but of course, not in IE6.
You can view a demo with CSS code in the  here http://www.kebo.ca/dev/. I've trimmed the code down to the bare essentials.
There are 2 images (line 59, 70) and 2 paragraphs (line 71, 72) that should not be visible. And they are not in all but ie6. i've also tried -margin, -absolute positioning, NOTHING seems to be working!
Note that I've tried every combination of display:none and visibility:hidden to no avail, including making the parent relative and the containing div absolute. no worky!
all advice greatly appreciated... thanks muchly!

A: The page looks identical to me in Safari 4/Mac and IE6/Win. What is your objective - to hide the image shown on the page?
btw, you have some element nesting issues on your page, run the validator and clear those out before anything else.
--
The simplest solution is to give all elements you want to hide a class 'hide' and create a selector for it:
.hide { display: none; }

or (to be more cautious):
.hide { display: none !important; }


text:
Q: Two simple questions about application manifest and assembly of Visual Studio project I created a simple Win Form project, MyApp, with Visual Studio 2013 & C# .NET.
In order for the app to target Windows 10 and Windows Server 2019, I included an app (executable) manifest for the app's executable. Then, in the  section of the manifest, I added a <supportedOS> element for Windows 10.
Now, my two questions are:

*

*Does the MyApp.exe.manifest file generated after success building have to be deployed to the same folder as the MyApp.exe?

*In the app manifest file, should the 'assemblyIdentity version/name' be the same as the Assembly version/name of my project?
I left the default value, version="1.0.0.0" name="MyApplication.app", for them. To my surprise, it seems to work no problem.
Thanks for your help in advance.


text:
Q: Avoid Mutating JavaScript array Below is my code
let traces = { ref: null, min: null, max: null, avg: null };
let learning = {
    "Application": "b3",
    "t": [
        {
            "d": 2,
            "BinaryType": "Current"
        },
        {
            "d": 3,
            "BinaryType": "Max"
        },
        {
            "d": 4,
            "BinaryType": "Avg"
        },
        {
            "d": 5,
            "BinaryType": "Min"
        }
    ]
};

let traceArr = Object.assign([],learning.t);

traceArr.forEach(trace => {

    if (trace.BinaryType == 'Current') {
        traces.ref = Object.assign({}, learning);
        traces.ref.t = [];
        traces.ref.t.push(trace);
        traces.ref.t[0].BinaryType = 'Refeyrence';
    }

    if (trace.BinaryType == 'Min') {
        traces.min = Object.assign({}, learning);
        traces.min.t = [];
        traces.min.t.push(trace);
    }

    if (trace.BinaryType == 'Max') {
        traces.max = Object.assign({}, learning);
        traces.max.t = []
        traces.max.t.push(trace);
    }

    if (trace.BinaryType == 'Avg') {
        traces.avg = Object.assign({}, learning);
        traces.avg.t = [];
        traces.avg.t.push(trace);
    }
});

console.log("Output",traces);
console.log("Traces- Should be non mutated",traceArr);
console.log("Original",learning.t)

I assume that when I modify the content of the array, the content of the original (learning) object should not getting affected.
Two questions:

*

*I was assuming that traces.ref.t = []; should change the reference in the new created object. Does it not?

*The console.log("Original",learning.t) output is as below which
indicates that the content got changed (text Refeyrence which was
modified during array iteration). Why is this happening? And what
should I be doing to avoid it?
'Original'
[
    {
        d: 2 ,
        BinaryType: "Refeyrence"
    },
    {
        d: 3 ,
        BinaryType: "Max"
    },
    {
        d: 4 ,
        BinaryType: "Avg"
    },
    {
        d: 5 ,
        BinaryType: "Min"
        }
]

A: It looks like you're having two issues, but both with mutateing a shared object.

I was assuming that traces.ref.t = []; should change the reference in the new created object. Does it not?

Doing [] will create a new array instance, but traces.ref is still using the shared traces object at the very start. You likely want to create a copy of the traces object. Since it doesn't have any nested values, using spread syntax is an easy way to achieve that in your case:
const newTrace = { ...traces }

The console.log("Original",learning.t) output is as below which indicates that the content got changed (text Refeyrence which was modified during array iteration). Why is this happening? And what should I be doing to avoid it?

This one is because the trace object is being pushed into the array and then it's being modified. You can work around this by also using an object spread to create a shallow copy:
newTrace.ref.t.push({ ...trace });

With only these changes, you original code may look like this:
let traces = { ref: null, min: null, max: null, avg: null };
let learning = {
  Application: "b3",
  t: [
    {
      d: 2,
      BinaryType: "Current"
    },
    {
      d: 3,
      BinaryType: "Max"
    },
    {
      d: 4,
      BinaryType: "Avg"
    },
    {
      d: 5,
      BinaryType: "Min"
    }
  ]
};

let traceArr = Object.assign([], learning.t);

traceArr.forEach(trace => {
  if (trace.BinaryType == "Current") {
    const newTrace = { ...traces };
    newTrace.ref = Object.assign({}, learning);
    newTrace.ref.t = [];
    newTrace.ref.t.push({ ...trace });
    newTrace.ref.t[0].BinaryType = "Refeyrence";
  }

  if (trace.BinaryType == "Min") {
    const newTrace = { ...traces };
    newTrace.min = Object.assign({}, learning);
    newTrace.min.t = [];
    newTrace.min.t.push({ ...trace });
  }

  if (trace.BinaryType == "Max") {
    const newTrace = { ...traces };
    newTrace.max = Object.assign({}, learning);
    newTrace.max.t = [];
    newTrace.max.t.push({ ...trace });
  }

  if (trace.BinaryType == "Avg") {
    const newTrace = { ...traces };
    newTrace.avg = Object.assign({}, learning);
    newTrace.avg.t = [];
    newTrace.avg.t.push({ ...trace });
  }
});

console.log("Output", traces);
console.log("Traces- Should be non mutated", traceArr);
console.log("Original", learning.t);

Here is this code in the TypeScript playground. It contains a few type errors but this is the minimum number of changes to avoid mutations.

A: I don't think Object.assign() does a deep copy. I'm pretty sure it's creating a new array whose elements point to the original array. The simplest way to do a deep copy is to convert it to json and back.
let traceArr = JSON.parse(JSON.stringify(learning.t));

The big disadvantage there is that if whatever you're copying has circular references, it won't work.
EDIT:
To illustrate what's happening, the learning object starts off as
let learning = {
    "Application": "b3",
    "t": [Object1, Object2, ...]
}

Then this happens,
let traceArr = Object.assign([], learning.t);

Which creates a new array and copies the contents of learning.t into it. At this point, traceArr looks like
traceArr = [Object1, Object2, ...]

Then, it loops over the items in traceArr, which are the same objects from learning.t, just pointed to from a different array.
if (trace.BinaryType == 'Current') {
    // At this point, trace === Object1

    // Shallow copy of learning
    traces.ref = Object.assign({}, learning);
    // traces.ref = { "Application": "b3", "t": [Object1, Object2, ...] }

    // Create a new array for traces.ref.t
    traces.ref.t = [];
    // traces.ref = { "Application": "b3", "t": [] }

    // Adds Object1 (same object from learning.t) to the new array
    traces.ref.t.push(trace);
    // traces.ref = { "Application": "b3", "t": [Object1] }

    // Modify Object1
    traces.ref.t[0].BinaryType = 'Refeyrence';
}

If you don't want traces.ret.t's elements to point to the same objects as learning.t, you need to create new objects, i.e. you need to push a copy of trace instead of trace. Or, as I suggested, make traceArr a deep copy of learning.t so that all the objects are new and nothing is shared.


text:
Q: How to find all the groups the user is a member? (LDAP) I am trying to get all the groups that a certain user is a member of.
I have the following structures in ldap:
o=myOrganization
     ou=unit1
         cn=admin
         cn=guess

and
ou=users
    cn=ann
    cn=bob
    cn=carla

*

*myOrganization is an instance of Organization

*unit1 is an instance of OrganizationUnit

*admin and guess are both GroupOfNames and have everyone as a member

*ann, bob, and carla are instances of Person

Currently, I am using the ldap module on python and this is what I have:
import ldap
l = ldap.initialize("ldap://my_host")
l.simple_bind_s("[my_dn]", "[my_pass]")
ldap_result = l.search("[BASE_DN]", ldap.SCOPE_SUBTREE, "(&(objectClass=Person)(cn=ann))", None)
res_type, data = l.result(ldap_result, 0)
print(data)

And I am able to get the user ann; but, how do I go about getting the groups Ann belongs to?
I tried, the following from this page:
search_filter='(|(&(objectClass=*)(member=cn=ann)))'
results = l.search_s([BASE_DN], ldap.SCOPE_SUBTREE, search_filter, ['cn',])

But I got an empty list. I also tried various combinations of queries, but they all return empty.
PS: I am using OpenLDAP on a linux machine

A: member=cn=ann is not enough.  You have to use ann's full DN, probably something like this:
member=cn=ann,ou=users,dc=company,dc=com


text:
Q: Can I put an AMD APU and an Nvidia GPU in the same computer As the title says, can I put an AMD APU Procesor and an Nvidia GPU in the same PC?
These kinda bugs me because the APU I'll be buying has the power of an AMD R9 240 I think. And I know that Nvidia and AMD GPU's can't mix, so it's a bit complicated for me.

A: Starting since Windows 7 (WDDM 1.1) you can installs 2 different GPU drivers and use a nVIDIA GPU side by side to an AMD APU.


text:
Q: Remove Last Two Characters in a String Is there a quick way to remove the last two characters in a String in Swift?  I see there is a simple way to remove the last character as clearly noted here.  Do you know how to remove the last two characters?  Thanks!

A: var name: String = "Dolphin"
let endIndex = name.index(name.endIndex, offsetBy: -2)
let truncated = name.substring(to: endIndex)
print(name)      // "Dolphin"
print(truncated) // "Dolph"

A: swift 4:
let str = "Hello, playground"
let newSTR1 = str.dropLast(3)
print(newSTR1)

output: "Hello, playgro"

//---------------//

let str = "Hello, playground"
let newSTR2 = str.dropFirst(2)
print(newSTR2)

output: "llo, playground"

A: update: Xcode 9 • Swift 4 or later
String now conforms to RangeReplaceableCollection so you can use collection method dropLast straight in the String and therefore an extension it is not necessary anymore. The only difference is that it returns a Substring. If you need a String you need to initialize a new one from it:
let string = "0123456789"
let substring1 = string.dropLast(2)         // "01234567"
let substring2 = substring1.dropLast()      // "0123456"
let result = String(substring2.dropLast())  // "012345"

We can also extend LosslessStringConvertible to add trailing syntax which I think improves readability:
extension LosslessStringConvertible {
    var string: String { .init(self) }
}

Usage:
let result = substring.dropLast().string

A: Use removeSubrange(Range<String.Index>) just like:
var str = "Hello, playground"
str.removeSubrange(Range(uncheckedBounds: (lower: str.index(str.endIndex, offsetBy: -2), upper: str.endIndex)))

This will crash if the string is less than 2 characters long. Is that a requirement for you?

A: Better to use removeLast()
var myString = "Hello world"
myString.removeLast(2)

output : "Hello wor"


text:
Q: ValueError: Found input variables with inconsistent numbers of samples: [2935848, 2935849] When I run this code:
feature_names = ["date","shop_id", "item_id", "item_price", "item_cnt_day"]
feature_names

X_train = train[feature_names]
print(X_train.shape)
X_train.head()

X_sales = sales[feature_names]
print(X_sales.shape)
X_sales.head()

from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

X_train, X_sales, y_train, y_sales = train_test_split(X_train, X_sales, test_size=0.3)

feature_names = ["date","shop_id", "item_id", "item_price", "item_cnt_day"]
feature_names

X_train = train[feature_names]
print(X_train.shape)
X_train.head()

X_sales = sales[feature_names]
print(X_sales.shape)
X_sales.head()

from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

X_train, X_sales, y_train, y_sales = train_test_split(X_train, X_sales, test_size=0.3)

(2935848, 5)
(2935849, 5)

I get this ValueError:

ValueError                                Traceback (most recent call
last)  in
13 from sklearn.metrics import mean_squared_error
14
---> 15 X_train, X_sales, y_train, y_sales = train_test_split(X_train, X_sales, test_size=0.3)
16
~/anaconda3/envs/aiffel/lib/python3.7/site-packages/sklearn/model_selection/_split.py
in train_test_split(*arrays, **options)    2125         raise
TypeError("Invalid parameters passed: %s" % str(options))    2126
-> 2127     arrays = indexable(*arrays)    2128     2129     n_samples = _num_samples(arrays[0])
~/anaconda3/envs/aiffel/lib/python3.7/site-packages/sklearn/utils/validation.py
in indexable(*iterables)
291     """
292     result = [_make_indexable(X) for X in iterables]
--> 293     check_consistent_length(*result)
294     return result
295
~/anaconda3/envs/aiffel/lib/python3.7/site-packages/sklearn/utils/validation.py
in check_consistent_length(*arrays)
255     if len(uniques) > 1:
256         raise ValueError("Found input variables with inconsistent numbers of"
--> 257                          " samples: %r" % [int(l) for l in lengths])
258
259
ValueError: Found input variables with inconsistent numbers of samples: [2935848, 2935849]

A: Your problem is reached because you two dataframe (train and sales) have different length. Your train dataset has 2935848 samples and the sales dataset has 2935849. Both dataset has to have the same length in order to work properly. Check why this length is not matching and add one row or drop one to match them.
Secondly, but no least, you should understand what are you doing with train_test_split and which is your goal. This function inputs are X and Y, and outputs X_train, X_test, y_train, y_test. Reading your code, you are inputting two X (X_train and X_sales) with same 5 features. I hope you are doing this because some reason, be aware of this.
X are all the samples with their features, and Y are the corresponding outputs value you want to predict. Check that and evaluate is using train_test_split is the function you are looking for.

A: I have this error while I'm trying to do my confusion matrix:
Found input variables with inconsistent numbers of samples: [1527, 1]
This is my code:
x = df[['gender', 'age', 'hypertension', 'ever_married', 'work_type', 'Residence_type', 'avg_glucose_level', 'bmi', 'smoking_status', 'work_type_cat', 'gender_cat', 'Residence_type_cat']]
y = df['stroke']
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=20)
print(x_train.shape, y_train.shape)
print(x_test.shape, y_test.shape)

scaler = StandardScaler()
x_train_scale = scaler.fit_transform(x_train)
x_test_scale = scaler.fit_transform(x_test)

KNN = KNeighborsClassifier()
x = df[['gender', 'age', 'hypertension', 'heart_disease', 'ever_married', 'work_type', 'Residence_type', 'avg_glucose_level', 'bmi', 'smoking_status', 'work_type_cat', 'gender_cat', 'Residence_type_cat']]
y = df['stroke']
print(x.head())
print(y.head())
KNN = KNN.fit(x, y)
test = pd.DataFrame()
test['gender'] = [2]
test['age'] = [3]
test['hypertension'] = [0]
test['heart_disease'] = [0]
test['ever_married'] = [2]
test['work_type'] = [4]
test['Residence_type'] = [2]
test['avg_glucose_level'] = [95.12]
test['bmi'] = [18]
test['smoking_status'] = [2]
test['work_type_cat'] = [4]
test['gender_cat'] = [1]
test['Residence_type_cat'] = [1]
y_predict = KNN.predict(test)

print(y_predict)
from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_test, y_predict))


text:
Q: Build JSON Batches from CSV file with JMeter I need to test an API that accepts bulk JSON requests using records from a CSV file. I'm well versed in sending simple REST requests using data from CSV files (and therefore JMeter variables and all that).
Is it possible for JMeter to batch a CSV file of 10,000 records into JSON payloads of 100 records each?
I've found answers that cover making JSON payloads from CSV files line-by-line, and even how to use pre-made JSON files as payloads, but nothing about dynamically creating JSON payloads from multiple lines in a CSV file before sending the requests.
For example:
The CSV would be something like
col1,col2
a,b
c,d
e,f
...

And I need a JSON payload like
 {
       'Some keys that dont change': null,
       [
          {'RecordNum': 1, 'col1': 'a', 'col2': 'b'},
          {'RecordNum': 2, 'col1': 'c', 'col2': 'd'},
          {'RecordNum': 3, 'col1': 'e', 'col2': 'f'},
          ...
       ]
  }

TIA!

A: Reading multiple lines from CSV is not possible with CSV Data Set Config. So you have to rely on JSR223_PreProcessor.
You can read the CSV file and do the required payload manipulation. Of course, you need to know groovy for that. Not so elegant solution that I can think of :

Output:-


text:
Q: Success Message as a model in ASP.NET MVC I intend to reuse success message in my MVC web application as a model, and this model could be a part of another model to report feedback status during data modification. So far, I can't get this working. Say I have FeedbackMessage object as model below to reflect success message:
public class FeedbackMessage
{
    public string Message { get; private set; }
    public FeedbackType Type { get; private set; } // 'info', 'error', 'warning', 'success'
    public string Image { get; }
}

and I have a user preference page which uses Preference object as the model and this object has FeedbackMessage as folowing
public class Preference
{
    public string DisplayName { get; set;}
    public string BlogUrl { get; set; }
    public FeedbackMessage FeedbackMessage { get; set; }
    public bool IsValid { get; set; }
}

and in my controller, I follow PRG (Post-Redirect-Get) pattern for data modification. The code is briefly as following:
public ActionResult Preference()
{
     var model = new Preference();
     model.DisplayName = Models.Settings.Preference.DisplayName;
     ...
     return this.View(model);
}

[HttpPost]
public Action Preference(Preference model)
{
    if (model.IsValid)
    {
         model.FeedbackMessage = new FeedbackMessage { Type = "success" };
    }
    else
    {
         model.FeedbackMessage = new FeedbackMessage { Type = "failure" };
    }

    ...

    return this.Preference(); // issue Get
}

My problem is that I can't get feedback at all after doing POST, since during GET it again initializes Preference object. At this point, I'm reluctant to use TempData as suggested by other stackoverlow thread since it's more explicit and cleaner done in the model.
Could anyone that has experience around this area show/guide me how to fix this or else show me a better design? Thanks.

A: *

*Use ajax to post the preference model, then use json to return the result(FeedbackMessage) to client,  and use js to display the feedback

*Because Post-Redirect-Get across different request, Normally use TempData to save model and display in the next request, but we can do this at base layout view

*If you don't want to change the code above, you can add a private method whith accept different perfenrence model and return the view action to client. so that reuse the model


text:
Q: Inherit border-radius from child to parent I'm working on a React Component that acts as a clickable wrapper for other components and the issue I have is that some of the other components have a border-radius which makes the wrapper component stick out in the corners. How I've solved this is by giving the wrapper the same border-radius via a prop, the problem with this approach is that I don't know the border-radius of some components. I've been trying to find a way to get the border-radius attribute value from the child component by using useRef() and then wrapperRef.current.props.children[0] but the border-radius value isn't present.

.wrapper {
  border: 1px solid black;
  display: inline-block;
  cursor: pointer;
}

.demo-wrapper {
  border: 1px solid black;
  border-radius: 24px;
  display: inline-block;
  cursor: pointer;
}

.child {
  width: 200px;
  height: 100px;
  border-radius: 24px;
  background-color: teal;

  display: flex;
  justify-content: center;
  align-items: center;
}

What i get

child element

What i want

child element

Is there a way to get the border-radius value from the child element?
Or is there a way to inherit the border-radius from child to parent element?
Or maybe I'm going on about this in the wrong direction entirely and there is a better way to solve this other than setting the same border-radius on parent element?

A: This solution involves:

*

*Setting a ref on the wrapper element

*Using useEffect, which runs after the component's rendered:
2.1. Use element.firstChild on the wrapper ref, to get a reference to the child's outer html element
2.2 Use getComputedStyle() to get the child element's border radius
2.3 Set that border radius on the wrapper element, using our ref.
The wrapper then would be:
import { useEffect, useRef } from "react";

const Wrapper = ({ children }) => {
  const container = useRef();

  useEffect(()=>{
    const borderRadius = getComputedStyle(container.current.firstChild).borderRadius
    container.current.style.borderRadius = borderRadius
  }, [])

  return
{children}
;
};

A working example:


text:
Q: Azure SQL Database Pricing: Standard vs Premium tier I was checking pricing for Standard tier and Premium tier concerning Azure SQL Database and I am a bit confused:
Knowing Standard tier has 1-4 IOPS per DTU and Premium tier has 25 IOPS per DTU (doc), why should I choose a Standard 6 (S6) plan with 400 DTU instead of a Premium 1 (P1) with 125 DTU?
S6 costs 506 euro/month, while P1 costs 392 euro/month and doing calculations:
S6: 506 euro/month | 400 DTU * 4 IOPS = 1600 IOPS
P1: 392 euro/month | 125 DTU * 25 IOPS = 3125 IOPS
Moreover P1 has other interesting features such as Columnstore indexing, In memory OLTP and 2ms IO latency.
Apparently it seems that P1 is way better than S6, even though costing less.

A: In the example you only refer to IO metric and forget about CPU and memory factors which are also a part of the DTU model. In the example you provided database engine with 400 DTU will give you more CPU and memory capabilities than 125 DTU.
The factor which also could be important while choosing between Premium and Standard tier is Max concurrent workers (requests). For S6 it is 800 and for P1 it is 200, so if you have a lot of concurrent queries, you would like to go with Standard which has better worker/EUR ratio.
Just to clarify, Columnstore Indexes are also available in Standard tier starting from S3 (100 DTU).
Generally speaking Premium Tiers are best suited for IO intensive workloads, while Standard tiers could be beneficial in terms of costs perspective for high concurrent systems based on intensive CPU queries.
Materials:

*

*Service tiers in the DTU-based purchase model

*Resource limits for single databases using the DTU purchasing model - Azure SQL Database

*New Azure SQL Database Standard Tier Sizes


text:
Q: kinetic javascript get value on click I have an array of points(pair of x,y) and I draw circles by these points
for (var i = 0; i < points.length;i++){

            var circle = new Kinetic.Circle({
                x: points[i].x,
                y: points[i].y,
                radius: 7,
                fill: "green",
                stroke: "black",
                name:i,
                strokeWidth: 2
            });

            circle.on("click", function() {
                alert(name); //here I want to get name of circle
            });

            layer.add(circle);
        }

I added new attribute name to each circle, like ID and I want to alert name of circle when mouse is clicked at it.
I am not sure that adding new attribute name to circle is correct.
So,how to add new attribute "name" to circle so that when clicking at circle it alerts its value of name?

A: Try this below code
<!DOCTYPE HTML>
<html>
<head>
    <style>
        body
        {
            margin: 0px;
            padding: 0px;
        }
    </style>
</head>
<body onload="displaycircle()">
    <div id="container">
    </div>
    <script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.0.0.js"></script>
    <script>
        function displaycircle() {
            var stage = new Kinetic.Stage({
                container: 'container',
                width: 578,
                height: 200
            });
            var layer = new Kinetic.Layer();
            for (var i = 0; i < 10; i++) {
               var circle = new Kinetic.Circle({
                    x: Math.random() * stage.getWidth(),
                    y: Math.random() * stage.getHeight(),
                    radius: 30,
                    fill: "green",
                    stroke: "black",
                    name: i,
                    strokeWidth: 2,
                    draggable: true
                });
                layer.add(circle);
                stage.add(layer);
                circle.on("click", function() {
                    alert(this.attrs.name); //here you can get name of circle
                });
            }
        }
    </script>

</body>
</html>


text:
Q: Why is there showing a 'None' in the Output? My programm shell show a grid and my programm has a lot of functions which calling each other. My Problem is that there are 3 Nones showing in my output. I can imagine it's because in the bracket after funtionname is written no argument in it instead of do_twice and do_fourth. But i don't need a argument because I have written a function which execute the function do_quater in the end. So I don't know if i should declare in my function a variable to hint the None.
def do_twice(f):
    f()
    f()

def do_fourth(f):
    do_twice(f)
    do_twice(f)

def do_row():
    print '+----',
    print '+'

def do_worms():
    print '|    |'
    print '|    |'
    print '|    |'
    print '|    |'

def do_wormsr():
    print      '|    |'
    print      '|    |'
    print      '|    |'
    print      '|    |'

def do_row():
    print '+----',
    print '+'

def do_worms():
    print '|    |'
    print '|    |'
    print '|    |'
    print '|    |'

def do_wormsr():
    print      '|    |'
    print      '|    |'
    print      '|    |'
    print      '|    |'

def do_row():
    print '+----',
    print '+'

def do_row():
    print '+----',
    print '+'

def do_quarter():
    print do_row()
    print do_worms()
    print do_wormsr()
    print do_row()
    print do_worms()
    print do_wormsr()
    print do_row()

A: Any python function that does not have a return value will return None by default so when you print do_row() etc.. you will get None after the print output
Not sure what you are printing but you would need to do something along the lines of the following to remove the None from your output:
def do_row():
    return '+----+'


text:
Q: Is this approach for establishing regularity of harmonic maps between manifolds valid? $\newcommand{\M}{\mathcal{M}}$
$\newcommand{\N}{\mathcal{N}}$
While trying to understand some regularity results, I thought about the following "naive" approach for establishing regularity of weakly harmonic maps between Riemannian manifolds. I would like to know if my approach makes sense. (can it be made valid under suitable technical adjustments?).
Here is the sketch:

First, we begin with the smooth case: A map $f:\M \to \N$ is harmonic if and only if $df \in \Omega^1(\M,f^*T\N)$ is a harmonic form.

Indeed, let $\nabla$ be the pullback connection of the Levi-Civita  connection of $\N$. Let $d_{\nabla}:\Omega^k(\M,f^*T\N ) \to \Omega^{k+1}(\M,f^*T\N )$ be the associated exterior derivative and $\delta_{\nabla}$ its adjoint. Then $$ d_{\nabla} df=0 \tag{1}$$ follows from the symmetry of the connection on $\N$. (Equation $(1)$ holds for every smooth map).
Harmonicity is $ \delta_{\nabla} df =0$; combining this with equation $(1)$ we obtain the equivalence.
My idea is the following:

*

*Any smooth harmonic map has harmonic differential.

*Thus, any weakly harmonic map should have weakly harmonic differential.

*Since the harmonic equation for forms is linear elliptic, the weak differential of $f$ is smooth.

*This implies $f$ is smooth.

I am trying to use rather standard linear elliptic regularity results; the classical regularity proofs for harmonic maps are more involved.
Somewhere in these steps there is a failure, since there are weakly harmonic maps which are not continuous. Of course, the devil must be somewhere in the details, which I did not really specify yet.
Morally, I am imagining "intrinsice weak formulations" as follows:
The weak version of $(1)$ is
$$ \int_{\M} \langle df , \delta_{\nabla} \sigma \rangle =0, \tag{1'}$$ for all $\sigma \in \Omega^2(\M,f^*T\N )$ which are compactly supported in the interior of $\M$.
Of course, this doesn't make sense as stated, since if $f$ is a Sobolev map, $f^*T\N$ is not a smooth vector bundle. Perhaps we should assume here that $f$ is continuous, and restrict attention to "continuous/weak Sobolev sections" $\sigma$ (which vanish on $\partial \M$ in the trace sense).
Anyway, I think there should be an extrinsic version of $(1')$, by embedding $N$ in a higher dimensional Euclidean space.
(Although this doesn't seem trivial. Any suggestions are welcome).

$\delta(df)=0$ has a well-known extrinsic version, which is "morally equivalent" to
$$ \int_{\M} \langle df , \nabla  \sigma \rangle =0, \tag{2'} $$
for all compactly supported $\sigma \in \Gamma(f^*T\N )$.
(The extrinsic version uses the second fundamental form of $\N$ inside the Euclidean space).

If we assume $ f \in W^{1,p}(\M,\N)$ where $p \ge \dim \M$, then I think this might work. Sobolev maps can then be approximated by smooth maps (If $p<\dim \M$ we need to restrict the topology of the manifolds to get density.)
In that case, $(1')$ should hold for all Sobolev maps, and so $(1'),(2')$ together should hold for all weakly harmonic maps.
So, assuming Sobolev maps can be approximated by smooth maps, does the suggested approach have a chance?

A: Regularity of harmonic map is true in dimension with $f\in W^{1,2}$ but it is subtle see Helein, Harmonic maps, conservation laws and moving frames.
It is false in higher dimension, even if  f\in W^{1,n}$, see Rivière, Everywhere discontinuous harmonic maps into spheres.
Whet you need is to control the morrey norm, see Rivière and Struwe, Partial regularity for harmonic maps and related problems.
You can also look to the survey by Hélein, Frédéric and  Wood, John C. ,Harmonic maps.


text:
Q: Can someone please tell me why I'm not understanding scope in this example? You'll have to forgive me -- I'm a seasoned Java programmer, but still struggling with the semantic differences between the languages!
I have a small JavaScript object constructor. It includes a jQuery function which gets a small piece of Ajax data. When the data gets returned, I want to make use of it in conjunction with a variable (renderMode) defined at the top of the object constructor but, presumably because of function block closure, I am getting 'undefined'.

*

*Can someone give me a corrected piece of code which shows me how to access renderMode inside of function(data)

*Almost as important, can someone explain to me why what I did doesn't work !

Here's the example:
function AsyncRequest() {
    this.renderMode = RenderMode.NONE;
    this.setId = setId;

    function setId(v) {
        this.id = v;
    }
    this.setURL = setURL;

    function setURL(v) {
        this.URL = v;
    }

    this.render = render;

    function render(element) {
        $.get(
            this.URL,
            function (data) {
                // The data comes back just fine ...
                // ... and I know a value was previously assigned to renderMode
                // ... in this instance of AsyncRequest, but how do I get at it ?
                console.log("Render mode: " + this.renderMode); // this.renderMode is undefined
            }
        );
    }
}

A: Unlike in Java, this in JavaScript is determined primarily by how a function is called, not where it's defined. (ES6 will add a way to have this lexically-bound, but for now it's primarily bound by the function call.) So the callback you're passing into $.get is getting called with this not referring to the object you expect.
You can solve this by using the fact you have a closure:
function render(element) {
    var self = this;  // <=== Note
    $.get(
        this.URL,
        function (data) {
            console.log("Render mode: " + self.renderMode);
            // Note ----------------------^
        }
    );
}

There, we're remembering what this was when render was called in a variable called self (the name doesn't matter), and then using the fact that the callback function is a closure over the context of the call to render, and so we have access to the self variable.
You can also solve it with ES5's Function#bind:
function render(element) {
    $.get(
        this.URL,
        function (data) {
            console.log("Render mode: " + this.renderMode); // this.renderMode is undefined
        }.bind(this) // <== Note
    );
}

Function#bind returns a function that, when called, calls the original function with this set to the value you give it.
More (on my blog):

*

*Closures are not complicated

*You must remember this

A: You can create a var for "this" in the main function:
function AsyncRequest() {
    var self = this;
    self.renderMode = RenderMode.NONE;
    self.setId = setId;
    ...

    function render(element) {
        $.get(
            self.URL,
            function (data) {
                console.log("Render mode: ", self.renderMode);
            }
        );
    }
}


text:
Q: How to properly style a phone number label? I want to display a phone number using UILabel in my iOS app.
What are the best font settings to make the numbers look nice? I tried mono spaced but it does not feel right.

A: You can use a UITextView and in the inspector you can make the phone number detectable. It looks nice when it's clickable =]


text:
Q: facebook page tab application - how to check if user is banned from fan page I'm building an iframe application to be installed into a user's fan page.
I'd like to know if there's any way for my application to conclude weather the user has been banned from the page or not.
Thank you

A: If the user has been banned from the page, they shouldn't be able to see the app on the page.

A: I'm not sure if that's possible. The function admin.getBannedUsers returns the banned users for an application on facebook, but may also work for a page.


text:
Q: Web App not getting deployed on startup in Tomcat I'm using tomcat(v7.0.56) in XAMPP(v3.2.2) to deploy my Myapp.WAR file. I'm adding context path in server.xml to deploy Myapp.war file as root webapp from webapps directory. The problem is that when I start the server for the 1st time in xampp the app does not get deployed but when I restart the server the app gets deployed correctly.
Code in server.xmlbelow "Host" tag
 <Context path="/" docBase="Myapp" reloadable="true"></Context>

Can't understand where I'm going wrong...Please help..


text:
Q: handlebars: partial variable inside custom for loop helper I found a very useful for loop from this SO answer
It works well, but my code seems to lose context to the variable being passed to the partial when I use it. Is there a way that I can pass the "assessmentType" variable so that it continues on inside of this helper? I have the exact thing working just fine outside of this loop but it seems to lose context completely inside of it. The context of "this" now belongs to the index number that the for loop is returning so I can't use that.

// for loop helper
hbs.registerHelper('for', (from, to, block) => {
  var accum = '';
  for (var i = from; i < to; i++) {
    accum += block.fn(i);
  }
  return accum;
});

// helper that takes in the assessment type
// and returns a path to a png file that I have
hbs.registerHelper("assessment_path", (assessmentType) => {
  if (assessmentType === "Leadership") return "leadership/Leadership";
  if (assessmentType === "Human") return "human/Human"
})
{{!-- partial --}}
{{> intro assessmentType="Leadership"}}

{{!-- where the variable is being used--}}
{{#for 0 20 }}

{{/for}}

A: I was able to do this by using the "../" to get the previous context, I've previously tried this by using the @ sign as I've done before but that didn't work. Solution code

{{#for 0 20 }}

{{/for}}


text:
Q: Bootstrap alignment issue with table-responsive I'm making a calendar in ASP.NET MVC that dynamically adds anchor links to each day based on whats stored in  a SQL database for that specific day. I'm using a html tables with the table-responsive class to format the widths and such.
Basically, I would like all the columns be responsive in the table, but somewhat fixed.  Depending on the number of anchors added to the col-xs-12, it can look right (Day 5 & 6 in picture below) or add spacing to the right.  The spacing to the right with multiple anchor elements or, events, is my problem.  How do i go about fixing this?  Should I add another row for 2 or more buttons?  I'm not sure how to approach this problem, I'm not an expert ui person.  Any help would be appreciated.  I can provide any other files needed.

html:

 January 2017

7:44:45 pm

Monday, January 16, 2017

                        Sunday

                        Monday

                        Tuesday

                        Wednesday

                        Thursday

                        Friday

                        Saturday

2

 Reminder

 Note

                                    1

                                     1

                                    1

                                    1

3

 Reminder

 Note

                                    1

                                     1

                                    1

4

 Reminder

 Note

5

 Reminder

 Note

                                    1

6

 Reminder

 Note

                                    1

                                     1

7

 Reminder

 Note

mvc calendar.cshtml:

 @Model.MonthData.Name @Model.MonthData.Year

loading...

@DateTime.Now.ToString("D", CultureInfo.CreateSpecificCulture("en-US"))

                    @foreach (var day in Enum.GetValues(typeof(DayOfWeek)).OfType<DayOfWeek>().ToList())
                    {

                            @day.ToString()

                    }

                @foreach (var week in Model.MonthData.WeeksInMonth)
                {

                        @if (Model.PrefixDays.Any() && week.WeekNumber == Model.MonthData.NumberOfWeeks.First())
                        {
                            foreach (var prefixDay in Model.PrefixDays)
                            {

                                    @Html.Partial("_EventData", prefixDay)

                            }
                        }

                        @foreach (var day in week.DaysInWeek)
                        {

                                @Html.Partial("_EventData", day)

                        }

                        @if (Model.SuffixDays.Any() && week.WeekNumber == Model.MonthData.NumberOfWeeks.Last())
                        {
                            foreach (var suffixDay in Model.SuffixDays)
                            {

                                    @Html.Partial("_EventData", suffixDay)

                            }
                        }

                }

mvc _eventdata.cshtml partial view:
@model Common.Calendar.DTODay

        @if (Model.IsCurrentDay)
        {

@Model.DayNumber

        }
        else
        {

@Model.DayNumber

        }

 Reminder

 Note

@if (Model.ReminderCount > 0 || Model.NoteCount > 0 || Model.BirthdayCount > 0 || Model.Holiday != null)
{

            @if (Model.NoteCount > 0)
            {

                    @Model.NoteCount

            }

            @if (Model.ReminderCount > 0)
            {

                     @Model.ReminderCount

            }

            @if (Model.BirthdayCount > 0)
            {

                    @Model.BirthdayCount

            }

            @if (Model.Holiday != null)
                     {

                        1

                }

}

A: The problem has been solved.  I used this SO question to answer it..
table {
    table-layout: fixed;
    word-wrap: break-word;
}

Template:
content

Changed the width to 14px, then i removed bootstrap btn  border-width.
End results and happy camper:

And it also looks proper in mobile:


text:
Q: delete all files in a folder at FTP using ftp batch script Have batch script as follows:
>>ftp.txt open ftp.site.com
>>ftp.txt username
>>ftp.txt password
>>ftp.txt directoryname
>>ftp.txt quit
ftp -s ftp.txt

How can I delete all files in folder 'directoryname'?

A: Put the following commands in ftp.txt and run as follows to accomplish this task:
ftp -i -s:ftp.txt
contents of ftp.txt:
open ftp.site.com
username
password
cd directoryname
mdelete *
quit

A: Here is a complete and safe solution!
One thing is that you have to have a 'y' for every file, and it doesn't matter if you have too many, you can have hundreds it only takes seconds and gives error messages that you'll never are able to see.
The temp file creates in the same folder as your bat file and will be erased by the script.
You can also use mdelete * even if dir * shows all files in the sub-folders.
@echo off
echo.
:MENU
cls
echo.
echo What do you want to do?
echo.
echo 1 - Delete all files in a folder at FTP using ftp batch script
echo 2 - Cancel
echo 3 - Logout

echo.
set /p choice=
if %choice%==1 goto sure
if %choice%==2 goto cancel
if %choice%==3 goto ?
echo Invalid Choice
echo.
pause
goto MENU

:sure
echo.
echo Are you sure to delete all files y/n

echo.
set /p choice=
if %choice%==y goto delete
if %choice%==Y goto delete
if %choice%==n goto cancel
if %choice%==N goto cancel

echo Invalid Choice
echo.
pause
goto sure

:delete
echo open my-domain.com> temp.txt
echo username>> temp.txt
echo password>> temp.txt
echo cd public_html/directoryname>> temp.txt
echo mdelete *.*>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo y>> temp.txt
echo quit>> temp.txt
REM Start FTP and send it to the script
ftp -s:temp.txt
REM delete the temp-file
del temp.txt

cls
echo.
echo All files are deleted!
echo.
pause
goto MENU

:cancel
echo.
echo You have cancelled the erasement!
echo.
Pause
goto MENU


text:
Q: Get Rank by votes and number of same rank PHP MySQL i am trying to get rank and number of same rank by votes but unfortunately no success.
Here my table structure:
| ID| user_id | votes |
| --| ------- | ----- |
| 1 | D10     | 15    |
| 2 | D5      | 9     |
| 3 | D20     | 9     |
| 4 | D23     | 7     |
| 5 | D35     | 3     |
| 6 | D65     | 2     |

I need the rank of user according to votes, referring to above table i need the rank as:
| user_id | Rank|
| ------- | ----|
| D10     | 1   |
| D5      | 2   |
| D20     | 2   |
| D23     | 3   |
| D35     | 4   |
| D65     | 5   |

and also i need the number of rank, referring to above ranks i need:
Rank 1 = 1
Rank 2 = 2
Rank 3 = 1
Rank 4 = 1
rank 5 = 1

i tried to get rank :
SELECT user_id, votes, FIND_IN_SET( votes, (
SELECT GROUP_CONCAT( DISTINCT votes
ORDER BY votes DESC ) FROM table)
) AS rank
FROM votes

the above query i tried referring to this answer to get the ranks but i am getting error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
near '( votes , (SELECT GROUP_CONCAT( DISTINCT votes ORDER BY votes DESC
)

i need the desired result using PHP and MySQL.

A: On MySQL 8+ you could use windows function dense_rank and count over
with votes_rank as (
select *,
      dense_rank() over (order by votes desc) as rnk
from votes
) , count_rank as
  ( select votes_rank.*,
           count(*)over (partition by rnk) as cnt
   from votes_rank
  ) select id,
           user_id,
           votes,
           rnk as votes_rank,
           cnt as count_rank
from  count_rank;

https://dbfiddle.uk/o1DiPyDz
Consider the following data,
CREATE TABLE votes (
  id int,
  user_id varchar(10),
  votes int );

insert into votes values  (1,'D10',15), (2,'D5 ',9), (3,'D20',9), (4,'D23',7), (7,'D50',7), (5,'D35',3), (6,'D65',2);

Result:
id    user_id votes   votes_rank  count_rank
1       D10    15         1         1
2       D5     9          2         2
3       D20    9          2         2
4       D23    7          3         2
7       D50    7          3         2
5       D35    3          4         1
6       D65    2          5         1

Edit,
On MySQL version <8
select tbl.id,tbl.user_id,tbl.votes,tbl.rnk,votes_count
from (SELECT a.id,
             a.user_id,
             a.votes,
             count(b.votes)+1 as rnk
      FROM  votes a
      left join votes b on a.votes<b.votes
      group by  a.id,a.user_id,a.votes
      order by a.votes desc
   ) as tbl
inner join (select rnk,count(rnk) as votes_count
            from ( SELECT a.id,
                         a.user_id,
                         a.votes,
                         count(b.votes)+1 as rnk
                  FROM  votes a
                  left join votes b on a.votes<b.votes
                  group by  a.id,a.user_id,a.votes
                 order by a.votes desc
                 ) a2
            group by rnk
          ) as tbl1 on tbl1.rnk = tbl.rnk;

https://dbfiddle.uk/XlsBjrZO


text:
Q: On the existence of a nontrivial connected subspace of $\mathbb{R}^2$ In the nontrivial sense, does there exist a connected subspace of $\mathbb{R}^2$ which is a union of a non-empty countable collection of closed and pairwise disjoint line segments each of unit length, i.e. length $1$? What are some good examples, if any?

A: I think the following works.
Let $Q_+=\mathbb Q\cap(0,1)$ and $Q_-=\mathbb Q\cap(-1,0)$. Now, define $$X = (Q_+\times[0,1])\cup([-1,0]\times Q_+)\cup(Q_-\times[-1,0])\cup([0,1]\times Q_-).$$
This is a countable disjoint union of closed unit line segments by construction. It is also connected: let $f:X\to\{0,1\}$ be a continuous map. Then $f$ is constant on each of the line segments. Let $\{q_1\}\times[0,1]$ and $\{q_2\}\times[0,1]$ be disjoint line segments. Without loss of generality, $f(q_1,0)=1$. Because $f$ is continuous, there is an open neighborhood $U$ of $(q_1,0)$ such that $f(z)=1$ for $z\in U$. Because of the connectedness of line segments, this means that there is a rational $q<0$ such that for all rationals $0>p>q$ we have $f(z)=1$ for $z\in[0,1]\times\{p\}$. Now, again because of connectedness, there is a neighborhood $V$ of $(q_2,0)$, such that $f$ is constant on $V$. But $V$ intersects at least one interval $[0,1]\times\{p\}$, where $0>p>q$. Therefore $f(q_2,0)=1$. Since $q_1$ and $q_2$ were arbitrary, this means that $f$ must be constant on $Q_+\times[0,1]$. By similar reasoning, it must be constant of the other three members of the union that defines $X$. But because these four sets are not separated, this means that $f$ must be constant on $X$ and since this means every continuous function $f:X\to\{0,1\}$ is constant, $X$ is indeed connected.

A: Consider the union of $[0,1] \times 0$ with $a/b \times [1/b,1/b+1]$ for each $a/b \in \mathbb{Q} \cap (0,1)$, where $a/b$ is written in reduced form.  Let $W$ be this space.  It is obvious that this set satisfies all the properties besides connectedness.
Now, assume $A,B$ are two open sets in $\mathbb{R}^2$ which induce a separation of $W$ in the subspace topology.  That is, $A\cap W$ and $B \cap W$ are disjoint, and $(A \cap W) \cup (B \cap W) = W$.  Clearly the component $[0,1] \times 0$ must lie entirely in either $A$ or $B$, so assume it lies in $A$.  Since $A$ is open and $[0,1] \times 0$ is compact, $A$ contains a "tube" around $[0,1] \times 0$.  That means that there exists some $\epsilon > 0$ such that for all $a/b$ where $0 < 1/b < \epsilon$, we have $(a/b,1/b) \in A$.  But then $A$ must contain the whole connected component $a/b \times [1/b,1/b+1]$.
Now, assume $B$ is nonempty.  Then it contains some component $c/d \times [1/d,1/d+1]$.  In particular, it contains the point $(c/d,1)$.  But then it also contains a point $(a/b,1)$ where $a/b < \epsilon$, because the rationals with denominator greater than $1/\epsilon$ are dense in $[0,1]$.  But then we have $a/b \times [1/b,1/b+1] \subset B$, which is a contradiction because we already observed that this line segment must be in $A$.

A: This should work, and is funny. Use polar coordinates, and identify angles with numbers in $[0,2\pi)$. For every rational $\frac ab\neq0$ in $[0,2\pi)$ with $(a,b)=1$, draw the segment $s(\frac ab)$ pointing at the origin, with angle $\frac ab$ and norm going from $\frac1b$ to $1+\frac1b$. Draw also $s(0)$ starting from the origin and going out with angle 0. Call this set $X$.
Take a clopen set $A\subseteq X$ containing $s(0)$: looking at the origin, we can say that $A$ contains every $s(\frac ab)$ for sufficiently large $b$ (because $A$ is open). But this clearly shows that $A$ is dense, hence, being also closed, $A=X$.


text:
Q: How to add my own custom button in each blog/post of WordPress I want to add my own button in each blog. When will click I separate popup will open and my some calculation will be done here. Similar as Tweet Share is working right know.

A: You can use fancybox to open popup and display your calculations in that popup.
See demo of fancybox popup here
See sample code below:
<input type="button" value="Mybtn">

// your calculations here

A: Thanks Friends for your answer and advise
I solved this problem and added a my own button in each post. Following is the code.
add_action('the_content','customFields');
function customFields($text)
    {
        global $post;
        if($post->post_type=='post')
        {
            return $text."
<image src='".$imgURL."'/>
";
        }
    }


text:
Q: Decompressing single blob in SQLite DB using C# Inside of my .mbtiles SQLite db, there's a column called tile_data holding the information relating to the specific tile that is being queried.
My application is taking a user long/lat as an input and then converting to a tile_row and tile_column equivalent values, then pulling the single blob with the data inside via the SQL query below.
The query (fully functional, just to show the code) is:
string query =
   String.Format("SELECT tile_data from tiles WHERE zoom_level = {0} AND tile_row = {1} AND tile_column = {2}", ZoomLevel, _merc.TileLat, _merc.TileLong);
   SQLiteCommand command = new SQLiteCommand(query, DbConn);
   SQLiteDataReader reader = command.ExecuteReader();

          while (reader.Read())
                {
                    // ...
                }

With the result being a single blob file, querying SELECT * will pull back the single tile with all data.
The blob inside of tile_data is a compressed (gzip) vector file that I need to access and work with, but I can't figure out how to decompress it within my application. Most gzip links that I've read through have been regarding file compression and outputting it to a .txt (or similar), whereas I'm looking to use this data in memory without needing an external file.
How can I decompress the blob and access he data in memory, rather than an external file?

A: Try something like this
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
    using(var file = reader.GetStream(0))
    using(var unzip = new GZipStream(file, CompressionMode.Decompress))
    using(var fileReader = new StreamReader(unzip))
    {
        while(!fileReader.EndOfStream)
        {
            var line = fileReader.ReadLine();
        }
    }
}

Depending on exactly what your file is you might need to substitute a different type of reader.


text:
Q: What is best type for profile image in user class? UserVo,java
public class UserVo extends MemberVo {

    protected String password;
    protected String phoneNumber;
    protected int level;

    // Profile Image
    protected CharSequence profileImagePath;
    protected Bitmap profileImageBitmap;
    protected Drawable profileImageDrawable;
    protected File profileImageFile;
}

I make app. I need to use profile image.
Origin image type is Bitmap. But I think bitmap occur memory leaks... (Right?)
So I save bitmap to File in storage.
What is best type for profile image in UserVo?

A: You can't display a Bitmap directly in an Android App.You must create an ImageView and give it you Bitmap with the setImageBitmap method.


text:
Q: How to Create Toggleable Button using HTML and CSS I know how to create toggleable checkboxes but I need to create a toggleable filter button. For now I only want to know how to structure the HTML and CSS for it to look like this:

When location 4 filter is clicked, it should look like Location 1, should I code this as anchor tags, buttons or input[type="checkbox"]?

A: Here is one way to do it. I simplified and adapted this from https://www.w3schools.com/howto/howto_css_custom_checkbox.asp
<!DOCTYPE html>

        <input type="checkbox" checked="checked">
                Location 1

                <input type="checkbox">
                Location 2

                <input type="checkbox">
                Location 3

                <input type="checkbox">
                Location 4

A: You can use this
See Css Codes

  <input type="checkbox">


text:
Q: What kind of Index should I use? We store records with the following structure:
Ssn, lname, fname
in a data file ordered on lname
If we want an index on lname because lots of queries search based on
last name, what kind of index is needed?

A: From what i can get from your requirements, Try adding B-tree index to that particular column .

A: For people names, I recommend the composite INDEX(lname, fname).  This will help (to some extent) each of these:
WHERE lname = 'James'
WHERE lname = 'James' AND fname LIKE 'R%'
WHERE lname = 'James' AND fname = 'Rick'

Your clustered PRIMARY KEY is probably SSN; this index may as well be a secondary (non-clustered) index.
In MySQL, BTree is essentially the only choice.  Anyway, BTree is at least nearly as good as Hash.
Caution!  Storing SSNs is a serious security problem.  If you lose your machine, or it is hacked into, you will be in deed dodo.  Meanwhile, don't plan on me giving you my SSN.


text:
Q: IBM Worklight - ANT I have installed

*

*Eclipse Kepler Edition

*IBM Worklight Studio plugin version 6.1

And now i want to deploy using ANT script as below :
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="target-name">
<taskdef resource="com/worklight/ant/defaults.properties">
<classpath>
  <pathelement location="WL_INSTALL_DIR/WorklightServer/worklight-ant.jar"/>
</classpath>
</taskdef>
<target name="target-name">
<app-builder
    worklightServerHost="http://server-address:port"
    applicationFolder="adapter-source-files-folder"
    environments="list-of-environments"
    nativeProjectPrefix="project-name"
    outputFolder="output-folder"/>
</target>
</project>

But, I can't find worklight-ant.jar and also worklight-ant-deployer.jar. What software should I install in order to get those file available ?.

A: If you have Worklight enterprise edition you can get the worklight-ant.jar from server.
If you want to start the Ant task from a computer on which Worklight Server is not installed, you must copy the files <WorklightInstallDir>/WorklightServer/worklight-ant.jar and <WorklightInstallDir>/WorklightServer/worklight-jee-library.jar to your computer.
for more info link


text:
Q: error: no suitable constructor found for Builder(no arguments) constructor Builder.Builder(Context) is not applicable I'm working on an app and I managed to get rid of all the bugs except one:

no suitable constructor found for builder

changing to "Intent"
https://file.io/OqhPX8 -> link to the code
private void GameOver()
{
    AlertDialog.Builder alertDialogueBuilder = new  AlertDialog.Builder().Builder(MainActivity.this);
    alertDialogueBuilder
            .setMessage("Ai Pierdut! Scorul tau este:" +mScor + "Puncte/3")
            .setPositiveButton("JOC NOU",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            startActivity(new Intent(getApplicationContext(), MainActivity.class));
                        }
                    });
}

I expect it to work. I am pretty sure everything else is working. The maximum score should be 3/3 if one question would be wrong it the "GameOver" Screen will appear.

A: Can you try to fix the first line, by removing the () ?
AlertDialog.Builder alertDialogueBuilder = new  AlertDialog.Builder.Builder(MainActivity.this);


text:
Q: How to remove all newlines from file within a perl script? I have a file that when viewed with vi with :set list that looks like the following:
one^M$
two$
three$^M
four$

I want to remove all the newlines ($) in the file from within a perl script. So the file should look like this:
one^Mtwothree^Mfour

After that I want to replace the CR (^M) with newlines (\n) but that is another story...
I tried the following code:
#!/usr/bin/perl
use strict;
use warnings;
my $file = "test.txt";
system("sed -i ':a;N;$!ba;s/\n//g' $file");
exit 0;

I know it's ugly to use system but I am punished with this error:
sed: -e expression #1, char 10: unterminated `s' command

Does anyone know an elegant way to achive my goal?

A: If you're already using Perl it's unnecessary to use sed. Perl has an -i switch which makes this sort of thing easy.
perl -pi -e's/\n//' test.txt

Alternatively Path::Tiny provides a functional equivalent to -i.
use strict;
use warnings;
use Path::Tiny;
my $file = shift; # get filename from argument
path($file)->edit_lines(sub { s/\n// });

In both cases the substitution will be performed for each line, which should be fine because the line contains its trailing newline. You can perform it on the whole file at once by passing -0777 to the oneliner, or using ->edit instead of ->edit_lines, then you would want to use s/\n//g to replace multiple occurrences.


text:
Q: How can I mount a partition before the OS has booted? In the instructions for configuring an EFI system partition in Arch Linux, it reads as follows:

mount ESP to /boot. This is the preferred method when directly booting
  a EFISTUB kernel from UEFI.

I don't understand how I can mount a partition when the system hasn't booted yet. It seems like a chicken and egg problem. You need to mount the partition for the UEFI to use it to boot Linux, but I can't mount anything until I have Linux booted. Note that the instructions specifically imply that EFISTUB can boot from the EFI partition without having to copy boot files to the EFI partition:

If you do not use one of the simple methods from #Mount the partition,
  you will need to copy your boot files to ESP

A:
mount ESP to /boot. This is the preferred method when directly booting a EFISTUB kernel from UEFI.

This part of the instructions attempts to say something like this:

"If you choose EFISTUB as your boot method, then you'll should preferably do two things:

*

*at installation time: mount ESP to the location that will be /boot in the Arch-to-be-installed before running the rest of the install procedure, so that the vmlinuz-* (and optionally initramfs) files that normally end up in /boot will automatically go to the ESP without further manual actions.

*when core Arch installation is done: configure /etc/fstab (or any alternative mechanism of your choice) to automatically mount ESP to /boot, so that any kernel updates will also automatically end up on the ESP.

If you choose to do something else, it will be your responsibility to do whatever is required to make the necessary files end up on the ESP."

Apparently, Arch's "recommended procedure" actually violates the UEFI standard of placing any OS-specific files under \EFI\<OS name> within the ESP, and places the EFISTUB-equipped kernel (and optionally the initramfs file) to the root directory of the ESP instead. However, it minimizes the possibly of errors caused by the firmware ESP filesystem driver being unexpectedly case-sensitive, for example. So I can see why they've made that choice.
The chapter "Alternative mount points" then describes a number of techniques you could use if you want to use the UEFI standard paths on the ESP, and/or mount the ESP to some different location, or to keep it unmounted by default. The options are presented as a list including bind mounts and various event systems and/or scripting hooks, without explicitly describing why each solution would be applicable to a particular situation.
Basically, the Arch wiki page on EFI system partition, as it exists at the time of this writing, would be very useful to someone who already understands how UEFI and EFISTUB work, but very confusing for a beginner that doesn't necessarily have a clue what to do and how various things depend on each other. I'm not surprised about that: just listing a number of tricks applicable under a certain topic is much easier than writing a good document that introduces new concepts and dependencies between them.


text:
Q: Create multiple list items using REST I have tried to create multiple list items in sharepoint  online using rest, I am getting the success message but still the items are not created in the list.
Below is the code:-
function CreateIdea(){
      var EmployeesAsJson = [
            {
                __metadata: {
                    type: 'SP.Data.IdeaEngineListItem'
                },
                Title: 'User1'
            },
            {
                __metadata: {
                    type: 'SP.Data.IdeaEngineListItem'
                },
                Title: 'User2'
            },
            {
                 __metadata: {
                     type: 'SP.Data.IdeaEngineListItem'
                 },
                 Title: 'User3'
             }
      ];

// generate a batch boundary
        var batchGuid = generateUUID();

        // creating the body
        var batchContents = new Array();
        var changeSetId = generateUUID();

        // get current host
        var temp = document.createElement('a');
        temp.href = _spPageContextInfo.webAbsoluteUrl;
        var host = temp.hostname;

        // for each employee...
        for (var employeeIndex = 0; employeeIndex < EmployeesAsJson.length; employeeIndex++) {

            var employee = EmployeesAsJson[employeeIndex];

            // create the request endpoint
            var endpoint = _spPageContextInfo.webAbsoluteUrl
                           + '/_api/web/lists/getbytitle(\'IdeaEngine\')'
                           + '/items';

            // create the changeset
            batchContents.push('--changeset_' + changeSetId);
            batchContents.push('Content-Type: application/http');
            batchContents.push('Content-Transfer-Encoding: binary');
            batchContents.push('');
            batchContents.push('POST ' + endpoint + ' HTTP/1.1');
            batchContents.push('Content-Type: application/json;odata=verbose');
            batchContents.push('');
            batchContents.push(JSON.stringify(employee));
            batchContents.push('');
        }
        // END changeset to create data
        batchContents.push('--changeset_' + changeSetId + '--');

        // generate the body of the batch
        var batchBody = batchContents.join('\r\n');

        // create the request endpoint
        var endpoint = _spPageContextInfo.webAbsoluteUrl
                       + '/_api/$batch';

        // batches need a specific header
        var batchRequestHeader = {
            'X-RequestDigest': jQuery("#__REQUESTDIGEST").val(),
            'Content-Type': 'multipart/mixed; boundary="batch_' + batchGuid + '"'
        };

        // create request
        jQuery.ajax({
            url: endpoint,
            type: 'POST',
            headers: batchRequestHeader,
            data: batchBody,
            success: function (response) {
                alert("Successfully saved a batch request");
                SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel);
            },
            fail: function (error) {
                alert('.. create employee FAIL ', error);
                SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel);
            }
        });
}

/*
    * @name generateUUID
    * @description
    * Generates a GUID-like string, used in OData HTTP batches.
    *
    * @returns {string} - A GUID-like string.
    */
function generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
    });
    return uuid;
};

Please help me know where is the issue in the code. I have referred the post [https://www.codeproject.com/Tips/878531/Save-Mutiple-records-to-SharePoint-using-REST-API]

A: First of all you need to specify start and end of batch in body
--batch_someguid
body
--batch_someguid--

Secondly,
a changeset must start with the batch boundary and include some specific lines describing the actual changeset.
For e.g. as below
--batch_someguid
Content-Type: multipart/mixed; boundary="changeset_guid"
Host: [your-sponline-domain]
Content-Length: [size in bytes of the changeset]
Content-Transfer-Encoding: binary

You can follow this post from Andrew Connell to understand batch request properly
Modified code is as below
function CreateIdea(){
  var EmployeesAsJson = [
        {
            __metadata: {
                type: 'SP.Data.IdeaEngineListItem'
            },
            Title: 'User1'
        },
        {
            __metadata: {
                type: 'SP.Data.IdeaEngineListItem'
            },
            Title: 'User2'
        },
        {
             __metadata: {
                 type: 'SP.Data.IdeaEngineListItem'
             },
             Title: 'User3'
         }
  ];

    // generate a batch boundary
    var batchGuid = generateUUID();

    // creating the body
    var batchContents = new Array();
    var changeSetId = generateUUID();

    // get current host
    var temp = document.createElement('a');
    temp.href = _spPageContextInfo.webAbsoluteUrl;
    var host = temp.hostname;

    batchContents.push('--batch_' + batchGuid);
    batchContents.push('Content-Type: multipart/mixed; boundary="changeset_' + changeSetId + '"');
    batchContents.push('Content-Transfer-Encoding: binary');
    batchContents.push(''); //NECESSARY LINE SPACE

    // for each employee...
    for (var employeeIndex = 0; employeeIndex < EmployeesAsJson.length; employeeIndex++) {

        var employee = EmployeesAsJson[employeeIndex];

        // create the request endpoint
        var endpoint = _spPageContextInfo.webAbsoluteUrl
                       + '/_api/web/lists/getbytitle(\'IdeaEngine\')'
                       + '/items';

        // create the changeset
        batchContents.push('--changeset_' + changeSetId);
        batchContents.push('Content-Type: application/http');
        batchContents.push('Content-Transfer-Encoding: binary');
        batchContents.push('');
        batchContents.push('POST ' + endpoint + ' HTTP/1.1');
        batchContents.push('Content-Type: application/json;odata=verbose');
        batchContents.push('');
        batchContents.push(JSON.stringify(employee));
        batchContents.push('');
    }
    // END changeset to create data
    batchContents.push('--changeset_' + changeSetId + '--');
    batchContents.push('--batch_' + batchGuid + '--');  //END OF BATCH

    // generate the body of the batch
    var batchBody = batchContents.join('\r\n');

    // create the request endpoint
    var endpoint = _spPageContextInfo.webAbsoluteUrl
                   + '/_api/$batch';

    // batches need a specific header
    var batchRequestHeader = {
        'X-RequestDigest': jQuery("#__REQUESTDIGEST").val(),
        'Content-Type': 'multipart/mixed; boundary="batch_' + batchGuid + '"'
    };

    // create request
    jQuery.ajax({
        url: endpoint,
        type: 'POST',
        headers: batchRequestHeader,
        data: batchBody,
        success: function (response) {
            alert("Successfully saved a batch request");
            SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel);
        },
        fail: function (error) {
            alert('.. create employee FAIL ', error);
            SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel);
        }
    });
  }

  function generateUUID() {
   var d = new Date().getTime();
   var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
 });
  return uuid;
 };


text:
Q: The pre-application start initialization method Start on type WebMatrix.WebData.PreApplicationStartCode threw an exception Just clicked on new Razor v3 Website in visual studio 2017 v15.4.3 and tried to run it.  It's kicking out the following error: The pre-application start initialization method Start on type WebMatrix.WebData.PreApplicationStartCode threw an exception with the following error message: Could not load file or assembly 'MySql.ConnectorInstaller.  Ive search web.config and every other file in the site and I dont have any references to MySql nor did I add any refs to it.  I do have MySql installed on my dev machine, though.

A: In Package Manager reinstall WebMatrix.WebData
update-package WebMatrix.WebData -reinstall

Restart VS


text:
Q: Bluetooth earphone is connected, but has no sound after shutdown and restart I am currently trying to fix this issue with my friend, but we are now stuck and don't know what to do.
Our teacher uses a Bluetooth earphone (Xiaomi Haylou GT1 PRO TWS) for her everyday tasks. It ran smoothly without problems, but after some time, her hard disk is found to be having a bad sector. It was successfully repaired by her colleagues at school.
After it was repaired, this problem occurs. Her earphone is connected, but it has no sound at all.
We followed some tips and instructions we found here, to fix the issue, and somehow it solved the problem.
But, whenever our teacher shuts down her laptop, the same problem keeps repeating: earphone is connected, but no sound.  We have no idea why the Bluetooth setting is never 'saved' properly on her laptop.
How to keep this Bluetooth setting permanent again? What can we do?
Additional concern: does performing Windows Update have some kind of impact with this issue?


text:
Q: DevServer expecting .WAR when I upload the application of .EAR format This application was built 15 years ago, I guess. The client has sought an upgrade/modification of this app, which I am not aware of.
I have built some POM.xml scripts. When I tried to upload it in development server, it was expecting a .WAR file inside the .EAR that I had uploaded.
Here is my pom.xml script. Please suggest some modifications.
<groupId>itaras</groupId>
<artifactId>itaras</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>ear</packaging>
<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
  <dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>1.0</version>
    <type>war</type>
  </dependency>
</dependencies>
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-war-plugin</artifactId>
      <version>2.2</version>
    </plugin>
    <plugin>
      <artifactId>maven-ear-plugin</artifactId>
      <version>2.3.2</version>
      <configuration>
        <finalName>MyEarFile</finalName>
        <version>5</version>
        <generatedDescriptorLocation>$D:/itaras/ITARAS_Branch_3Aug2017/itaras/WebContent</generatedDescriptorLocation>
        <modules>
          <webModule>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <uri>appITARAS.war</uri>
            <bundleFileName>appITARAS.war</bundleFileName>
            <contextRoot>/ITARAS</contextRoot>
          </webModule>
        </modules>
      </configuration>
    </plugin>
  </plugins>
</build>

A: You need a parent pom like this :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>itaras</groupId>
  <artifactId>itaras</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <modules>
    <module>itaras-ear</module>
    <module>itaras-war</module>
  </modules>

</project>

Then you will have a war project which is a child/module of the parent.  This will be your existing project like:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>itaras</groupId>
    <artifactId>itaras</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>itaras-war</artifactId>
  <packaging>war</packaging>
.....

Then you will have an ear project which will include the war project as a dependency, something like:
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>itaras</groupId>
    <artifactId>itaras</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>itaras-ear</artifactId>
  <packaging>ear</packaging>

  <dependencies>
   <dependency>
     <groupId>itaras</groupId>
     <artifactId>itaras-war</artifactId>
     <version>${project.version}</version>
   </dependency>
  </dependencies>


text:
Q: Scroll to next div issue when the same class isn't continually repeated Having some issues creating a button used to scroll to next element of same class when there is HTML between the divs. The button is a "Next post" button and working nicely when the posts are set up like this.

Content

Content

Content

When there is some HTML between the first post and the rest it stops working.

Content

Content

Content

Content

The button is created successfully with jQuery but stops working when the post div isn't together continually after each other.

Next post

I have tried making the next post button successfully using other jQuery solutions, but also seems stops working when there is something between the post divs.

Any suggestions how to work around this issue?

A: Change next('.new') to nextAll('.new').
next() only returns the next immediate sibling. In this case it checks
Content
 for a new class and and doesn't find it so returns nothing.
nextAll() searches through all following siblings.


text:
Q: Get Python 2.7.14 to use updated OpenSSL on Mac Sierra Python is using old SSL lib and throws an error when trying to connect to newer TLD protocol.
Error from python
ssl.SSLError: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:661)

Python shows old version of OpenSSL even though I've upgraded:
python -c "import ssl; print ssl.OPENSSL_VERSION"
OpenSSL 0.9.8zh 14 Jan 2016

OpenSSL version
openssl version -a                                                             (master✱)
OpenSSL 1.0.2d 9 Jul 2015
built on: reproducible build, date unspecified
platform: darwin64-x86_64-cc
options:  bn(64,64) rc4(ptr,int) des(idx,cisc,16,int) idea(int) blowfish(idx)
compiler: /usr/bin/clang -I. -I.. -I../include  -fPIC -fno-common -DOPENSSL_PIC -DZLIB -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -arch x86_64 -O3 -DL_ENDIAN -Wall -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM -DECP_NISTZ256_ASM
OPENSSLDIR: "/opt/local/etc/openssl"

I've tried all the things on Stackoverflow regarding upgrading python, installing python from python.org, upgrading OpenSSL via brew, relinking OpenSSL via brew (doesn't work, not allowed), symlinking/updating ssl libs and binaries, restarting terminal.
Python path
python -c "import sys; print sys.path"
['', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Users/matt/Library/Python/2.7/lib/python/site-packages', '/usr/local/lib/python2.7/site-packages', '/usr/local/Cellar/numpy/1.13.3/libexec/nose/lib/python2.7/site-packages', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages']