text:
Q: Breaking substitution cipher with language model Frequency analysis is a common tool used to break substitution ciphers, but often relies on intuition and guesswork of a human. Since language models can objectively calculate perplexity (how surprising a piece of language seems), they seem like a good way to formalize this process.
If I could run the calculate the perplexity of the ciphertext under each substitution, I would just pick the one with the lower perplexity. Since this is the least surprising out of the possibilities of the original text, it is likely to be the real original text. However since there are 26^26 different options, doing this with brute force is not possible.
Is there any more efficient way to find the best substitution? In particular, the substitution of letters that minimizes perplexity? This seems to be the same task that gradient descent tries to solve, but the problem here is that I don't think I can calculate the gradient.

A: Your question is a good one—and one that cryptographers have thought about a lot. The answer is yes!
First things first: the number of options isn't quite $26^{26}$, because some of those ciphers wouldn't be invertible. For instance, you could map every letter to Q, but how do you decode that? So the number is only(!) $26!$ possibilities.
That's still astronomically large, but human cryptographers can break these codes from just a few examples. What's the trick? They look at relative frequencies of letters and what makes for natural plaintext.

This seems to be the same task that gradient descent tries to solve…

Well, you've got a point that we'd like to optimize something. We can use some form of local search to improve the goodness of our mapping.
One method proposed for this is described in Hasinoff (2003); I think the paper is pretty approachable compared to a lot of the neural LM based papers coming out for this problem. To optimize, they use a popular technique called hill-climbing. (More specifically, stochastic hill climbing with random restarts—they never mention hill climbing in the paper, though.) The idea is to start with some initial (arbitrary) mapping and measure its perplexity as you suggested. Then loop to improve the perplexity. Pick some pair of letters and swap their mapping. Did this version reduce perplexity? If so, keep it. If not, don't. Now make another swap, and so on, and so on.


text:
Q: noflo browser component have project or graph id? i am creating noflo project and need o get project or graph id inside the component
here is a simple component code
noflo = require 'noflo'

exports.getComponent = ->
  c = new noflo.Component
  c.inPorts.add 'in', (event, payload) ->
    return unless event is 'data'
    # Do something with the packet, then
    c.outPorts.out.send payload
  c.outPorts.add 'out'
c

is any event or any noflo object have project id
or any noflo class having it so i include that one
thanks

A: NoFlo components being executed have no knowledge of the graph or project they are being executed in. This encapsulation is an important part of the component-based approach in FBP. To get access to an identifier, you should send it as an IIP on an inport (like any other piece of data needed by component).

redpajama_set_name: RedPajamaStackExchange


text:
Q: member? function on infinite lists I implemented a member? function in clojure as follows:
(defn member? [item seq]
  (cond (empty? seq) false
        (= item (first seq)) true
        :else (recur item (rest seq))))

Unfortunately this doesn't work with infinite lists. Does anybody know of a way to implement it in order to be able to get:
(member? 3 (range)) -> true

A: Your implementation behaves correctly for an infinite input sequence. It does not terminate until an element has been found because the (empty? seq) case never falls.
Consider searching for something in an infinite space. When is it a good time to say it isn't there? There is no reliable way to tell. Limit the space you are searching in, e. g.:
(member? 3 (take 10 (range)))

A: You can't. I mean, at all.
In order to make sure there is no certain element you need to traverse the entire collection. Then and only then you can guarantee it's not there.
In some cases, such as your example, input sequence is ascending, i. e. every element of your sequence is less than its successive element. You can leverage that and make your sequence finite using take-while:
(member? 3    # is 3 a member of
  (take-while # a sequence of elements
    #(<= % 3) # up to 3 inclusively
    range))   # from range

A: For me, your code already works: (member? 3 (range)) returns true.
But what is the point of checking for the existence of a value in an infinite sequence? It will either return true or it will never return.


text:
Q: WMI Query - 2008 Performace counters alerts I have a set of performance counters alerts on windows 2008 server, which I configured to write in the Event Viewer once the alert is fired.
It does write in this event viewer "Applications and Services Logs/Microsoft/Windows/Diagnosis-PLA/Operational"
I am trying to write a WMI query, in vbscript file, against this event viewer to read the events there.
Here is my query:
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery("select * from Win32_NtLogEvent where Logfile = 'Microsoft-Windows-Bits-Client%4Operational'")

The problem is: when I check colItems.count, it returns zero, however I know that there are events there, I can see them when I navigate to the event viewer.
The same query works fine if I query the 'Application' event viewer:
Set colItems = objWMIService.ExecQuery("select * from Win32_NtLogEvent where Logfile = 'Application'")

It returns the count correctly.
Any idea what the problem is in the first query?

A: WMI doesn't support Event Tracing for Windows event logs. The Application event log (for which your query is working) is a classic event log that does not use the Windows Eventing technology. The Win32_NtLogEvent exposes events logged in classic event logs, however it does not expose events from the more recent event logs (introduced in Vista). You can however read these logs using the PowerShell cmdlet Get-WinEvent.


text:
Q: How to submit parameters by hyperlink-url and retrieve them in php? Carrying values in a while cycle, each value is extracted from a SQL table, and I need to carry em in a  since I'm making a list of items purchased from a specific client. I'm using this line for the href url:
    echo "
";
while($row3 = mysqli_fetch_array($rs3)){
$space = array("");
$text=$row3['description'];
$dash="_";
$url = preg_replace("![^a-z0-9]+!i", "_", $text);
$url= "".$url.".php";

echo "
" . $row3['relid'] . "	" . $row3['invoiceid'] . "	<td width=400 style align=center " . $row3['description'] . "	" . $row3['amount'] . "	Pendiente	" . $row3['duedate'] . "
";
}
mysqli_close($con3);
echo "
";
echo"
";
echo "

";
I'm generating the url from the Description I extract from the database but I need to carry the Order ID, Client ID, etc from the specific row.
Each variable is needs to be carried to a form where the user will fill some fields regarding the product the client bought (Medical Test Results), and I need those variables to mark as "Done" so It won't show up again on the list.

A: Fix these syntax errors, report back if still broken.
<td width=400 style align=center " . $row3['description'] . "

-->
"" . $row3['description'] . "	"

EDIT:
Do you mean how to append a var to an url, so it can be retrived on the called page?
You can append the var to the url by echo ".
On the called page, you can read it by $_GET['id']


text:
Q: What part of C++ creates many "copies" of objects? Although I develop C++ primarily, I don't get the joke about C++ down there. Is this joke about passing by value being default behavior, and hence creating many copies? Or is there some other part of C++ that created this reputation?

A: Compared to other OO languages, C++ heavily uses value semantics. Code like Object B = A; in many languages creates a new reference, but not a new Object. We call this reference semantics. In these languages, you'd have to write something like Object B = new Object(A) to make a copy. But with value semantics, Object B = A; is actually a copy.
A secondary cause was that C++ doesn't use garbage collection. This means you often needed a copy of an object, to guarantee its lifetime. (Today we have std::shared_ptr for that)


text:
Q: css selector works in browser but not in Selenium I am doing test automation with Selenium and usually use css selectors to locate the elements. Recently however, I have encountered a strange issue. I noticed that in some cases the css selector works fine when I test in the browser console. For example, to select a specific button out of many, I do:
(1) $("div.v-app[id^='v-discussions'] .v-button-caption:contains('Add')")

But when I actually use in Selenium it returns an error:
Caused by: org.openqa.selenium.InvalidSelectorException: The given selector div.v-app[id^='v-discussions'] .v-button-caption:contains('Add') is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: An invalid or illegal selector was specified

I also tried that string with querySelector and I get "Illegal string" error:
(2) document.querySelectorAll("div.v-app[id^='v-discussions'] .v-button-caption:contains('Add')")

Why that might happen?
P.S.
This is how each one of the elements looks like:
Add Comment

A: Well go for :
WebElement element = driver.findElement(By.className("v-button-caption"));

I use it in Selenium Webdriver and works fine for me


text:
Q: SceneManager can't recognize LoadSceneAsync I imported a project from an earlier version Unity, I'm currently using 2018.3
I got one Issue, I can't seem to ignore It, commenting it gives me another error

Assets\Scripts\Generals\LoadController.cs(48,22): error CS0117: 'SceneManager' does not contain a definition for 'LoadSceneAsync'

I do not have a defined class named 'SceneManager' that's overriding the unity SceneManager Class
LoadController.cs
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 using UnityEngine.SceneManagement;

 public string nameSceneLoad = "MainGame";
 void NextScene()
{
    CancelInvoke();
    SceneManager.LoadSceneAsync (nameSceneLoad, LoadSceneMode.Single);
}

If I try to ignore It I'll have the following

Assets\Photon Unity Networking\Editor\PhotonNetwork\PhotonViewHandler.cs(188,13): error CS0433: The type 'EditorSceneManager' exists in both 'Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'UnityEditor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'

PhotonViewHandler.cs
//TODO: check if this can be internal protected (as source in editor AND as
dll)
public static void LoadAllScenesToFix()
{
string[] scenes = System.IO.Directory.GetFiles(".", "*.unity",
SearchOption.AllDirectories);

foreach (string scene in scenes)
{
EditorSceneManager.OpenScene(scene);
PhotonViewHandler.HierarchyChange();//NOTE: most likely on load also
triggers a hierarchy change
EditorSceneManager.SaveOpenScenes();
}
Debug.Log("Corrected scene views where needed.");
}

Any ideas ?
I tried Navigating to the defintion F12 leads to
#if !UNITY_MIN_5_3  && ! UNITY_2017
// in Unity 5.3 and up, we have to use a SceneManager. This section re-
implements it for older Unity versions

#if UNITY_EDITOR
namespace UnityEditor.SceneManagement
{
/// Minimal implementation of the EditorSceneManager for older
Unity, up to v5.2.
public class EditorSceneManager
{
    public static int loadedSceneCount
    {
        get { return
  string.IsNullOrEmpty(UnityEditor.EditorApplication.currentScene) ? -1 : 1; }
    }

    public static void OpenScene(string name)
    {
        UnityEditor.EditorApplication.OpenScene(name);
    }

    public static void SaveOpenScenes()
    {
        UnityEditor.EditorApplication.SaveScene();
    }

    public static void SaveCurrentModifiedScenesIfUserWantsTo()
    {
        UnityEditor.EditorApplication.SaveCurrentSceneIfUserWantsTo();
    }
}
}
#endif

 namespace UnityEngine.SceneManagement
{
 /// Minimal implementation of the SceneManager for older Unity, up
to v5.2.
 public class SceneManager
  {
    public static void LoadScene(string name)
    {
        Application.LoadLevel(name);
    }

    public static void LoadScene(int buildIndex)
    {
        Application.LoadLevel(buildIndex);
    }
  }
 }

 #endif

A: Try specifying which one to use to bypass the duplicated EditorSceneManager error like this:
using foo = UnityEditor.EditorSceneManager;
using boo = otherdll.Namespace;

BTW I think this error is because you have a DLL in .NET 4.x and a previous DLL from .NET 3.5, so you can probably just delete the one that is for 3.5.


text:
Q: can not convert value of type 'NSRange!' to expected argument type 'NSRangePointer' Swift Hi I am trying to find a character's CGRect from a Label. I found following How do I locate the CGRect for a substring of text in a UILabel? to be useful but the code is in Objective C. I tried into Swift language. Following in the Swift conversion of the Objective C code
var objLabel:UILabel = UILabel()

func getBoundingRectForCharacterRange(range:NSRange) -> CGRect {

    var objTextStorage = NSTextStorage(attributedString: objLabel.attributedText!)
    var objLayoutManager = NSLayoutManager()
    objTextStorage.addLayoutManager(objLayoutManager)

    var objTextContainer = NSTextContainer(size: CGSizeMake(100,100))
    objTextContainer.lineFragmentPadding = 0
    objLayoutManager.addTextContainer(objTextContainer)

    var objRange:NSRange!

    objLayoutManager.characterRangeForGlyphRange(range, actualGlyphRange: objRange)
    return objLayoutManager.boundingRectForGlyphRange(objRange, inTextContainer: objTextContainer)
}

I am facing following error saying
can not convert value of type 'NSRange!' to expected argument type 'NSRangePointer' (aka 'UnsafeMutablePointer<_NSRange>')

Kindly help me to solve the problem.
Also I tried following from one similar question's answer but its also not working
var range : NSRange?
doSomethingWithRangePointer(&range)

func doSomethingWithRangePointer(range : UnsafeMutablePointer<NSRange?>) {
    // Do stuff
}

A: Change the call to objLayoutManager.characterRangeForGlyphRange() as follows:
objLayoutManager.characterRangeForGlyphRange(range,
  actualGlyphRange: &objRange)


text:
Q: How to display input back to the user on an HTML page? I am new to HTML and I am trying to create a script to display user input in a message box. I have created a textbox and validated it with a regular expression (alphabet only).
Now I need to display the user input in the page itself. How can I do this with JavaScript?
I need to display all the user inputs in the page itself. I need to display the two letter word in one container and three letter word in another container.
This is the code I tried.

form input

        <form name="user"  action="" onsubmit=" "  method="post">

            User<input id="title" type="text" maxlength="4"  onkeyup=" Allow() " >
                <input type="submit" value="Save/Show" onclick=" insert() " />
        </form>

    </form>

A: For a basic client-side validation, start with document.getElementById('foo') and HTML formed like <input id='foo' value='bar' />.  You can validate and repopulate using .value, somthing like this:
var foo = document.getElement('foo');
if (foo.value.match('your regex')) {
   foo.value = foo.value.substr(0, 3);
}

For server-side saving and validation, unfortunately you can't do this with only Javascript.
Javascript is client-side, which means it's trapped inside your browser.
To send values back to the server, you need something like PHP or Ruby to receive POSTed form values and write them to a file.  Javascript can't write to files for security reasons.
To use Ruby or PHP with Javascript, you could do it dynamically with an Ajax request (intermediate skill level) or by submitting a <form> element (beginner skill level).

UPDATE...after you showed some code :)
You need to put the

Your code didn't include the part about the "two letter container" and the "three letter container" so the best I can do there is recommend substr() again.

LAST UPDATE
Here's a basic implementation of two and three letter strings, input delimited using commas like foo,bar,fo,ba:

<input id="title" type="text" >
<input type="submit" value="Save/Show" onclick="clearAndShow()" />

A: You can (temporarily; only on the client side) store user input in javascript variables. Create a container (div) and use Javascript HTML DOM API to update it with the required value.
Here is the JavaScript DOM reference guide from w3schools:
http://www.w3schools.com/jsref/

A: You might want to try looking into JQuery for an easy way to do this..  What you are doing is simple enough where you probably don't need JQuery but would make it a lot simpler for learning.
Here is a quick jsFiddle give a short example of getting values from a text box and appending them to another element.
http://jsfiddle.net/Tvcnx/
HTML:
Enter you name:<input id="name" type ="text"/>

Javascript:
$( document ).ready(function() {
    $('#name').change(function(){
        $('#message').html('Hello ' + $('#name').val());
    });
});

And here is the documentation on getting values easily with jQuery:
http://api.jquery.com/val/
Again jQuery is not required but since you appear new it might be easier.

A: Here is a complete example taken from w3schools which shows how to accomplish what you want. If you want to save the user input to show it to the user later, take a look at a tutorial about cookies.
<!DOCTYPE html>

Click the button to demonstrate the prompt box.

<button onclick="myFunction()">Try it</button>


text:
Q: Edited Typescript Code in Type Towel not reflected in corresponding js file I had Edited the Typescript code of home.ts in Type towel project downloaded from following URL:
https://github.com/Svakinn/TypeTowel/trunk/TypeTowel
I had just added a new variable in view model and tried to display it on my home page it does not reflect on home page. and also no reflected in the corresponding js file.
I am sharing my view model
old viewmodel:
 export class ViewModel {
    title: string = 'Home View';

    public activate() {
        _logger.logger.log('We are home now', null, 'home', true);
        return true;
    }
}
export var vm = new ViewModel();

//The Durandal plugin-interface variables
export var activate = function () { return vm.activate(); };

new View model:
 export class ViewModel {
    title: string = 'Home View';
    titleS: string = "my view";

    public activate() {
        _logger.logger.log('We are home now', null, 'home', true);
        return true;
    }
}
export var vm = new ViewModel();

//The Durandal plugin-interface variables
export var activate = function () { return vm.activate(); };

My Html line that I added to home.html is:

As I am new to type script please let me what is wrong that I am doing?

A: Looks like the TypeScript is not getting compiled in your app.
You should get the latest version of TypeTowel - where the typescript compile is no longer dependent on the Web Essentials plugin.


text:
Q: How to use PowerShell as admin on Hyper.js I'm trying to use PowerShell with Hyper.js. I have this on the hyper config file:
shell: 'powershell.exe',
shellArgs: ['']

This way PowerShell is loaded as non-admin, and I receive an error because I don't have a PowerShell profile file configured, but I have a profile for admin user, I want to configure Hyper.js to use PowerShell as admin.

A: It's not the best solution, but you can run Hyper as admin
https://github.com/zeit/hyper/issues/1752#issuecomment-427086434
There are some other solutions in the linked issue.


text:
Q: How to debug Rust on Android/iOS? I had a hard time finding any useful information about the Rust debugging story on iOS/Android. I guess I can somehow use the same mechanism that allows remote debugging for C++, but I don't know where to start.
My first attempt was to use Android Studio with the Rust plugin by JetBrains, but it seems they see this issue as expected behavior.
My next take will be to try bypass UI and set breakpoints via lldb/gdb directly, but I see it as a crutch.
How can I debug Rust code on Android/iOS? It will be excellent if I could do it with some UI.

A: Say you've built and deployed a Rust library on Android following these steps. In order to debug via rust-gdb or graphically with CLion do the following:

*

*Stop gradle from stripping your Rust .so files of debug symbols by adding packagingOptions.doNotStrip "**/*.so" to app/build.gradle

*Push the gdbserver binary from Android NDK's prebuild directory to the device:
~/Android/Sdk/ndk-bundle/prebuilt/android-x86_64/gdbserver$ ~/Android/Sdk/platform-tools/adb push gdbserver /data/local/tmp
~/Android/Sdk/platform-tools/adb shell "chmod 777 /data/local/tmp/gdbserver"

*

*Restart adbd as root:

~/Android/Sdk/platform-tools/adb root

*

*Forward a port that you will use for gdbserver:

~/Android/Sdk/platform-tools/adb forward tcp:1337 tcp:1337

*

*Attach gdbserver to the process you wish to debug:

~/Android/Sdk/platform-tools/adb shell
generic_x86_64:/ # su
generic_x86_64:/ # set enforce 0
generic_x86_64:/ # /data/local/tmp/gdbserver :1337 --attach $(ps -A | grep your.android.application.id | awk '{print $2}')

*

*Either run rust-gdb or set up CLion's "Remote GDB" configuration with:

target remote tcp:localhost:1337


text:
Q: Plot group averages for each rating on 4 separate plots I have 4 groups (research, sales, manu, hr) and each group has 2 categories (0 & 1). I am trying to plot the average scores for each group in the features in the list ratings. The code that gives me the means looks like this (with depts = ['research', 'sales', 'manu', 'hr']:
ratings = ['JobSatisfaction', 'PerformanceRating', 'EnvironmentSatisfaction', 'RelationshipSatisfaction']

for i in depts:
    for x in ratings:
        print(group_data.groupby([i]).mean()[x])

Which results in this output:
research
0.0    2.700000
1.0    2.773973
Name: JobSatisfaction, dtype: float64
research
0.0    3.100000
1.0    3.167808
Name: PerformanceRating, dtype: float64
research
0.0    2.500000
1.0    2.726027
Name: EnvironmentSatisfaction, dtype: float64
research
0.0    2.687500
1.0    2.705479
Name: RelationshipSatisfaction, dtype: float64
sales
0.0    2.754601
1.0    2.734940
Name: JobSatisfaction, dtype: float64
sales
0.0    3.125767
1.0    3.144578
Name: PerformanceRating, dtype: float64
sales
0.0    2.671779
1.0    2.734940
Name: EnvironmentSatisfaction, dtype: float64
sales
0.0    2.702454
1.0    2.602410
Name: RelationshipSatisfaction, dtype: float64
manu
0.0    2.682759
1.0    2.723077
Name: JobSatisfaction, dtype: float64
manu
0.0    3.186207
1.0    3.158974
Name: PerformanceRating, dtype: float64
manu
0.0    2.917241
1.0    2.735897
Name: EnvironmentSatisfaction, dtype: float64
manu
0.0    2.724138
1.0    2.689744
Name: RelationshipSatisfaction, dtype: float64
hr
0.0    2.705882
1.0    2.557692
Name: JobSatisfaction, dtype: float64
hr
0.0    3.196078
1.0    3.134615
Name: PerformanceRating, dtype: float64
hr
0.0    2.764706
1.0    2.596154
Name: EnvironmentSatisfaction, dtype: float64
hr
0.0    2.813725
1.0    2.961538
Name: RelationshipSatisfaction, dtype: float64

My question is how do I plot these group means (research, sales, manu, hr) for each rating ['JobSatisfaction', 'PerformanceRating', 'EnvironmentSatisfaction', 'RelationshipSatisfaction']onto the 4 different bar graphs so I can visualize and compare the differences between each group?
My data is from the IBM HR dataset: https://www.kaggle.com/pavansubhasht/ibm-hr-analytics-attrition-dataset

A: You can use sns.barplot from seaborn, and since your y variable is comparable, separating by color and same y-axis is ok:
import statsmodels.api as sm
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.read_csv("WA_Fn-UseC_-HR-Employee-Attrition.csv")

ratings = ['JobSatisfaction', 'PerformanceRating', 'EnvironmentSatisfaction', 'RelationshipSatisfaction']

sns.barplot(data = df[['Department'] + ratings].melt(id_vars='Department'),
            x = 'variable',y='value',hue='Department')
plt.xticks(rotation=45)


text:
Q: Mirations in sequelize from existing models in nodejs I am in need of generating migration from existing models, So that don't need to create models again. Is there any way to do this in SequelizeJs with nodejs.

A: It's there in the documentation.
Create a folder migrations, put a skeleton in:
module.exports = {
  up: function(queryInterface, Sequelize) {
    // logic for transforming into the new state
  },

  down: function(queryInterface, Sequelize) {
    // logic for reverting the changes
  }
}

Now you can manipulate tables like so:
queryInterface.createTable(
  'nameOfTheNewTable',
  {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    createdAt: {
      type: Sequelize.DATE
    },
    updatedAt: {
      type: Sequelize.DATE
    },
  },
  {
    engine: 'MYISAM', // default: 'InnoDB'
    charset: 'latin1' // default: null
  }
)

Run sequelize db:migrate to do the migrations.
Full documentation HERE.


text:
Q: flatpickr no funciona en offcanvas bootstrap tengo el siguiente problema, estoy trabajando en un formulario, este incluye el uso de la libreria faltpikr, funciona de maravilla si la vista es normal, el servidor detecta si la llamada espera una respuesta Ajax y de ser asi retorna el codigo html que es inyectado a un elemento offcanvas que a su vez muestra el formulario, es ahi el problema puesto que el campo que usa el faltpickr no funciona
tengo el problema siguiente, estoy usando la libreria de flatpickr pero esta no funciona dentro de un elemento offcanvas, simplemente muestra el input pero este no despliega el selector de la fecha y muestra la leyenda Uncaught TypeError: $(...).flatpickr is not a function, desconozco que estoy haciendo mal, a continuacion el codigo.
    @section('vendor-style')
        <link rel="stylesheet" href="{{ asset(mix('vendors/css/pickers/pickadate/pickadate.css')) }}">
        <link rel="stylesheet" href="{{ asset(mix('vendors/css/pickers/flatpickr/flatpickr.min.css')) }}">
    @endsection

    @section('page-style')
        <link rel="stylesheet" href="{{ asset(mix('css/base/plugins/forms/pickers/form-flat-pickr.css')) }}">
        <link rel="stylesheet" href="{{ asset(mix('css/base/plugins/forms/pickers/form-pickadate.css')) }}">
    @endsection

       <x-form id="save-project-data-form">

               <input type="hidden" name="template_id" value="{{ $projectTemplate->id ?? '' }}">

                       <x-forms.text class="mr-0 mr-lg-2 mr-md-2" :fieldLabel="__('modules.taskShortCode')"
                                     fieldName="project_code" fieldRequired="true" fieldId="project_code"
                                     :fieldPlaceholder="__('placeholders.writeshortcode')" />

                       <x-forms.text class="mr-0 mr-lg-2 mr-md-2" :fieldLabel="__('modules.projects.projectName')"
                                     fieldName="project_name" fieldRequired="true" fieldId="project_name"
                                     :fieldPlaceholder="__('placeholders.project')"
                                     :fieldValue="$projectTemplate->project_name ?? ''" />

                       <x-forms.datepicker fieldId="start_date" fieldRequired="true"
                                           :fieldLabel="__('modules.projects.startDate')" fieldName="start_date"
                                           :fieldPlaceholder="__('placeholders.date')" />

                       <x-forms.datepicker fieldId="deadline" fieldRequired="true"
                                           :fieldLabel="__('modules.projects.deadline')" fieldName="deadline"
                                           :fieldPlaceholder="__('placeholders.date')" />

                           <x-forms.checkbox fieldId="without_deadline"
                                             :fieldLabel="__('modules.projects.withoutDeadline')" fieldName="without_deadline" />

                       Email
                       <input
                           type="email"
                           id="email-id-column"
                           class="form-control"
                           name="email-id-column"
                           placeholder="Email"
                       />

       </x-form>

    @section('vendor-script')

    @endsection
    @section('page-script')

    @endsection

y este es el codigo del componente livewire:
<x-forms.label :fieldId="$fieldId" :fieldLabel="$fieldLabel" :fieldRequired="$fieldRequired"></x-forms.label>
<input
    type="text"
    class="form-control flatpickr-human-friendly  {{ $custom ?? '' }}"
    placeholder="{{ $fieldPlaceholder }}"
    value="{{ $fieldValue }}"
    name="{{ $fieldName }}"
    id="{{ $fieldId }}"
/>
@isset($fieldHelp)

{{ $fieldHelp }}.

@endisset

he usado el mismo codigo en un blade normal y funciona a la perfeccion, el detalle solo es en el elemento offcanvas

lo cual no sucede mientras esta dentro del offcanvas y este muestra el error en consola Uncaught TypeError: $(...).flatpickr is not a function


text:
Q: How to use a lookup table in Jinja? In my Jinja template I have a list of tuples like this one:
{% set typeLabels = [
    ('type1', 'Label for type 1'),
    ('type2', 'Label for type 2'),
    ('type3', 'Label for type 3')
] %}

I use a list and not a dict because the order is important (I also use the list elsewhere to generate a listbox).
Then I need to do lookups like this one:
{{ dict(typeLabels)[someType] }}

which works fine if you do it inside Python, but in Jinja it doesn't work.
How can I do this in Jinja?

A: Well, since there's no answers I'll post my solution based on the suggestions.
First you have to add collections.OrderedDict to the Jinja environment since Jinja doesn't know about it:
JINJA_ENV = jinja2.Environment( . . . )
JINJA_ENV.globals['OrderedDict'] = collections.OrderedDict

And then in the template:
{% set typeLabels = OrderedDict([
    ('type1', 'Label for type 1'),
    ('type2', 'Label for type 2'),
    ('type3', 'Label for type 3')
]) %}

So now you can access the dictionary normally:
{{ typeLabels[someType] }}


text:
Q: ¿Cómo puedo validar una grid para que no se repita al agregarla una vez? Tengo un combobox, donde escojo un ítem, y ese lo agrego a una grid, pero lo que deseo es que no se pueda agregar el mismo al ya ser agregado la primera vez.
onAddClick: function() {
    var me = this,
        combo = me.down('[name=comboboxEventosScoreType]'),
        value = combo.validate();
    if (value === true) {
        var data = combo.valueModels[0].raw,
            grid = me.down('[name=gridEventosScoreType]'),
            rec = new Events.model.grid.ScoreType(data);
        grid.getStore().insert(0, rec);
    }
}

La grid:
xtype: 'grid',
                name: 'gridEventosScoreType',
                flex: 1,
                layout: 'fit',
                autoScroll: true,
                store: new Ext.data.Store({
                    autoDestroy: true,
                    autoLoad: true,
                    model: 'Events.model.grid.ScoreType',
                    proxy: {
                        data: [],
                        type: 'memory',
                        reader: {
                            type: 'json'
                        }
                    }
                }),

Desde ya, gracias por su ayuda!

A: Lo que tienes que hacer es recorrer el store antes de agregar el registro con el comando:
store.each(function(record,id){
});

Y en alli hacer la validacion

A: Puedes recorrer tus datos mientras los agregas y verificar con algun campo, sea Id, nombre o cualquiera que lo diferencia de los demas y preguntar si existe ya en el grid o no. Tambien es otra opcion que tus datos antes de agregarlos los ordenes, no se de que forma los obtienes (base de datos, agregados por el usuario, consulta a un ws, etc) pero puedes hacer cualquiera de las dos.
extend : 'Ext.data.Model',
idProperty:'firstName',
fields: [
    { name: 'Id', type: 'int', defaultValue: 0 },
    { name: 'firstName', type: 'string' },
    { name: 'middleName', type: 'string' },
    { name: 'lastName', type: 'string' },
    { name: 'birthDate', type: 'date' },
    { name: 'address1', type: 'string' },
    { name: 'address2', type: 'string' },
    { name: 'city', type: 'string' },
    { name: 'state', type: 'string' }
],

1) Dejo fuente que puede ayudarte!
Ejemplo
2) Misma pregunta tuya en stack over flow Pregunta


text:
Q: TSQL - Max or Top Date on an unnormalized table I have the following table:
Table: UserName
Userid   User        UserUpdate
1        Dan           1/1/2005
1        Dan           1/1/2007
1        Dan           1/1/2009
2        Pam           1/1/2005
2        Pam           1/1/2006
2        Pam           1/1/2008
3        Sam           1/1/2008
3        Sam           1/1/2009

I need to extract the latest updated for all these users, basically here's what I'm looking for:
Userid   User        UserUpdate
1        Dan           1/1/2009
2        Pam           1/1/2008
3        Sam           1/1/2009

I've tried doing a SELECT TOP or Max but get only the latest result, i.e. 1 result for the WHOLE table, which is not what I want.

A: SELECT Userid, User, Max(UserUpdate) AS MaxDate
FROM myTable
GROUP BY Userid, User

A: group by and max

A: Select Userid, User, MAX(UserUpdate) from myTable GROUP BY Userid, User


text:
Q: R apply a sum on dataset values according to all possible combination of character column I have a dataset that looks like this
data.frame(A = c("a","b","c","d"),B= c(1,2,3,4))
OUTPUT
A  B
a  1
b  2
c  3
d  4

I would like to get a new dataframe with the sum of the element in column B according to the possible combinations of 2 elements in column A, for example
comb_A sum_B
a b    3
b c    5
c d    7
a d    5
excetera...

I'm new to r, is there any way to do this? Thank you in advance

A: A possible solution in base R:
result <- data.frame(
  expand.grid(comb_B = df$A, comb_A = df$A)[2:1],
  sum = c(outer(df$B, df$B, \(x,y) x+y))
)

result <- result[result$comb_A != result$comb_B,]

result

#>    comb_A comb_B sum
#> 2       a      b   3
#> 3       a      c   4
#> 4       a      d   5
#> 5       b      a   3
#> 7       b      c   5
#> 8       b      d   6
#> 9       c      a   4
#> 10      c      b   5
#> 12      c      d   7
#> 13      d      a   5
#> 14      d      b   6
#> 15      d      c   7

A: You may try in base R
df1 <- as.data.frame(t(combn(df$A, 2)))

data.frame(comb_A = paste(df1$V1, df1$V2), comb_B = df$B[match(df1$V1, df$A)] + df$B[match(df1$V2, df$A)])

  comb_A comb_B
1    a b      3
2    a c      4
3    a d      5
4    b c      5
5    b d      6
6    c d      7

A: Here's one (albeit messy) way to do it.
library(tidyverse)

df <- data.frame(A = c("a","b","c","d"),B= c(1,2,3,4))
df %>%
  expand(A, A) %>%
  unite("comb_A", starts_with("A"), sep = " ") %>%
  mutate(sum_B = map_dbl(
    str_split(comb_A, " "),
    ~sum(df$B[match(.x, df$A)])
  ))
#> # A tibble: 16 × 2
#>    comb_A sum_B
#>    <chr>  <dbl>
#>  1 a a        2
#>  2 a b        3
#>  3 a c        4
#>  4 a d        5
#>  5 b a        3
#>  6 b b        4
#>  7 b c        5
#>  8 b d        6
#>  9 c a        4
#> 10 c b        5
#> 11 c c        6
#> 12 c d        7
#> 13 d a        5
#> 14 d b        6
#> 15 d c        7
#> 16 d d        8

A: We can use combn like below
with(
  df,
  data.frame(
    comb_A = combn(A, 2, list),
    sum_B = combn(B, 2, sum)
  )
)

which gives
  comb_A sum_B
1   a, b     3
2   a, c     4
3   a, d     5
4   b, c     5
5   b, d     6
6   c, d     7


text:
Q: Invalid UTF-8 with sys.stdin.read() I have an issue where some of my flow files in NiFi contain invalid UTF-8 encoding. When I attempt to read my flow file into a Python script using the ExecuteStreamCommand it produces an error at sys.stdin.read() because that assumes UTF-8 encoding. I can't figure out how to coerce the encoding to be UTF-8 when I read it in--I figured out that I can use string.encode('utf-8').strip().decode('utf-8') with a string but I'm not quite sure how to apply this to stdin.
I attempted
#!/usr/bin/python3

import json
import re
import sys
import io

try:
    flow_file = sys.stdin.read()
    sys.stdout.write(str(flow_file))
except UnicodeDecodeError as e:
    flow_file = sys.stdin.encode('utf-8').strip().decode('utf-8')
    sys.stdout.write(str(flow_file))

but it failed
  File "/path/to/scripts/test_encoding.py", line 12, in <module>
    flow_file = sys.stdin.encode('utf-8').strip().decode('utf-8')
AttributeError: '_io.TextIOWrapper' object has no attribute 'encode'


text:
Q: Как перебрать строку, отсортировать и построить новую Мне приходит строка вот в таком виде:
2213:0:711.75:0:0:0:0:0:0:0:0:0:0:185.535:397:0:0:0;
5193:0:0:0:0:0:0:0:0:0:0:0:0:464.07:558:0:92.535:0;

Строка построена в таком формате:
(Подстрока1(ИД устройства:значение1:значение2:значениеN);Подстрока2(ИД устройства:значение1:значение2:значениеN);)
Мне нужно, каким то образом просуммировать все значения для устройства 2213, затем просуммировать все значения для устройства 5193, после чего СРАВНИТЬ эти значения, и построить новую строку в порядке возрастания.
Если посчитать вручную, то сумма значений для 2213 будет 1294,285, а для 5193 будет 1114,605
С этого я понятно, что сумма значений для устройства 2213 Больше чем для 5193, значит исходная строка должна быть такой:
5193:0:0:0:0:0:0:0:0:0:0:0:0:464.07:558:0:92.535:0;
2213:0:711.75:0:0:0:0:0:0:0:0:0:0:185.535:397:0:0:0;

Соответственно нужно сравнивать строки не только по 2 оборудованиям но и по N оборудованию, так как входящая строка с которой необходимо работать может включать не 2 устройства а несколько.
Помогите пожалуйста это реализовать

A: Вот допустим ваша строка
$data = "2213:0:711.75:0:0:0:0:0:0:0:0:0:0:185.535:397:0:0:0;5193:0:0:0:0:0:0:0:0:0:0:0:0:464.07:558:0:92.535:0;";

Очевидно, сначала следует ее разделить по ;, для чего используем explode() и выкидываем последний пустой элемент . Теперь у нас есть набор строк.
$lines = explode(";", $data);
array_pop($lines);

Каждую строку следует разделить по :, и, откинув id, посчитать сумму.
$data = [];
foreach($lines as $l){
    $x = explode(":", $l);
    array_shift($x);
    $data[$l] = array_sum($x);
}

при этом нам тут нет смысла хранить детали о строке, как id и т.п. Нужна только сумма и исходный вид строки. Так что сумма становится значением, а строка - ключом.
Далее используем asort() чтобы отсортировать промежуточный массив по сумме, сохраняя ключи:
asort($data); // или arsort в обратном порядке

И осталось склеить в кучу ключи полученного массива. Используем array_keys  и implode:
$result = implode(";", array_keys($data));

останется в конец дописать ;


text:
Q: Symfony Customize Form Validator for a set number of options I have a form with the following widget and validator:
  $this->widgetSchema['num01'] = new sfWidgetFormChoice(array(
  'choices' => Doctrine_Core::getTable('ticket')->getTicketnum(),
  'expanded' => true, 'multiple' => true,
   ));

  $this->validatorSchema['num01'] = new sfValidatorChoice(array(
   'choices' =>
   array_keys(Doctrine_Core::getTable('ticket')->getTicketnum()), 'required' => true, 'multiple' => true,
   ));

The problem that I'm having is that it displays 20 checkboxes and I would like to make them select only 5 of them.   No more and no less.   It has to be exactly 5 boxes checked.   How can I customize my code to make this validate that way?  Thanks

A: I tried this just to see if it would work and it did.   :)
$this->validatorSchema['num01'] = new sfValidatorChoice(array(
   'choices' =>
   array_keys(Doctrine_Core::getTable('ticket')->getTicketnum()), 'required' => true,
   'multiple' => true, 'max' => 5, 'min' => 5,
   ));


text:
Q: select 2 recors in case 2 exists I have 2 rows
code name
1   cake
2   chocolate

This query give me both results
select * from table a  where a.code=2 or a.code =1

If one of these records doesn't show, I don't want to retrieve anything.
select * from table a  where a.code=2 or a.code =1
and exists ( select 1 from table b where a.code=b.code )

A: You can use an analytic function:
SELECT code,
       name
FROM   (
  SELECT a.*,
         COUNT(DISTINCT code) OVER () AS num_codes
  FROM   table_name a
  WHERE  a.code IN (1,2)
)
WHERE  num_codes = 2;

Which, for the sample data:
CREATE TABLE table_name (code, name) AS
SELECT 1, 'cake'      FROM DUAL UNION ALL
SELECT 2, 'chocolate' FROM DUAL;

Outputs:

CODE
NAME

1
cake

2
chocolate

If you:
DELETE FROM table_name WHERE code = 1;

And run the query again, it outputs:

CODE
NAME

db<>fiddle here

A: Simple check the count distict
select * from tab1
where code in (1,2)
and (select count(distinct code) from tab1 where code in (1,2)) = 2;

If you want to discard the case where the table has duplicated rows, e.g. 1,1,2
add an other predicate filter
 and (select count(*) from tab1 where code in (1,2)) = 2


text:
Q: Haskell: how to detect "lazy memory leaks" After few hours of debugging, I realized that a very simple toy example was not efficient due to a missing ! in an expression return $ 1 + x (thanks duplode!... but how come ghc does not optimize that??). I also realized it because I was comparing it with a Python code that was quicker, but I won't always write Python code to benchmark my code...
So here is my question: is there a way to automatically detect these "lazy memory leaks", that slow down a program for no real reason? I'm still pretty bad to optimize Haskell code, and forgetting a ! is quite likely, even when you're experienced I guess.
I'm aware of:

*

*the +RTS -s, but I'm not sure how to interpret it: seeing 79MB of memory for a simple program seems huge to me for example, but maybe it's not as it's what takes my current program... and for bigger programs it's impossible to just detect "lazy leaks" that way I guess as I have no idea of the amount of memory my program should take.

*the cabal v2-run --enable-profiling mysatsolvers -- +RTS -p command, but it seems that enabling the profiler kills some optimisations done by GHC, and therefore it's hard to use these values for a real benchmark. And still, it's not clear to me how to find leaks from that output anyway.

Could you for example explain to me how I could find the "lazy leaks" in a toy program like this one?
{-# LANGUAGE DerivingVia, FlexibleInstances, ScopedTypeVariables #-}
module Main where

--- It depends on the transformers, containers, and base packages.
--- Optimisation seems to be important or the NoLog case will be way to long.
--- $ ghc -O Main.hs

import qualified Data.Map.Strict as MapStrict
import Data.Functor.Identity

import qualified Control.Monad as CM
import qualified Control.Monad.State.Strict as State
import qualified Data.Time as Time

-- Create a class that allows me to use the function "myTell"
-- that adds a number in the writer (either the LogEntry
-- or StupidLogEntry one)
class Monad m => LogFunctionCalls m where
  myTell :: String -> Int -> m ()

---------- Logging disabled ----------
--- (No logging at all gives the same time so I don't put here)
newtype NoLog a = NoLog { unNoLog :: a }
  deriving (Functor, Applicative, Monad) via Identity

instance LogFunctionCalls NoLog where
  myTell _ _ = pure ()

---------- Logging with Map ----------
-- When logging, associate a number to each name.
newtype LogEntryMap = LogEntryMap (MapStrict.Map String Int)
  deriving (Eq, Show)

instance LogFunctionCalls (State.State LogEntryMap) where
  myTell namefunction n = State.modify' $
    \(LogEntryMap m) ->
      LogEntryMap $ MapStrict.insertWith (+) namefunction n m

---------- Logging with Int ----------
-- Don't use any Map to avoid inefficiency of Map
newtype LogEntryInt = LogEntryInt Int
  deriving (Eq, Show)

instance LogFunctionCalls (State.State LogEntryInt) where
  myTell namefunction n = State.modify' $
    \(LogEntryInt m) -> LogEntryInt $! m + n

---------- Function to compute ----------
countNumberCalls :: (LogFunctionCalls m) => Int -> m Int
countNumberCalls 0 = return 0
countNumberCalls n = do
  myTell "countNumberCalls" 1
  x <- countNumberCalls $! n - 1
  return $ 1 + x

main :: IO ()
main = do
  let www = 15000000
  putStrLn $ "Let's start!"
  --- Logging disabled
  t0 <- Time.getCurrentTime
  let n = unNoLog $ countNumberCalls www
  putStrLn $ "Logging disabled: " ++ (show n)
  t1 <- Time.getCurrentTime
  print (Time.diffUTCTime t1 t0)
  -- Logging with Map
  let (n, LogEntryMap log) = State.runState (countNumberCalls www) (LogEntryMap MapStrict.empty)
  putStrLn $ "Logging with Map: " ++ (show n)
  putStrLn $ (show $ log)
  t2 <- Time.getCurrentTime
  print (Time.diffUTCTime t2 t1)
  -- Logging with Int
  let (n, LogEntryInt log) = State.runState (countNumberCalls www) (LogEntryInt 0)
  putStrLn $ "Logging with Int: " ++ (show n)
  putStrLn $ (show $ log)
  t3 <- Time.getCurrentTime
  print (Time.diffUTCTime t3 t2)

A: You ask

return $ 1 + x [...] but how come ghc does not optimize that??

The answer is that strict evaluation and lazy evaluation have subtly different semantics, so having GHC optimise it might break your program.
The difference lies in the treatment of undefined values. Any attempt to evaluate an undefined throws an exception. In GHCi:
Prelude> undefined
*** Exception: Prelude.undefined
CallStack (from HasCallStack):
  error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
  undefined, called at <interactive>:1:1 in interactive:Ghci1

If I have an expression that contains an undefined then the same thing happens:
Prelude> 2 + undefined
*** Exception: Prelude.undefined [...]

However if the evaluation never gets to the undefined then everything is fine:
Prelude> True || undefined
True

Haskell uses "non-strict semantics" and "lazy evaluation". Technically the non-strict semantics are part of the definition of Haskell and lazy evaluation is the implementation mechanism in GHC, but you can think of them as synonyms. When you define a variable the value is not computed immediately, so if you never use the variable then you have no problem:
Prelude> let b = undefined
Prelude> b
*** Exception: Prelude.undefined

The let works fine, but evaluating the variable it defines throws an exception.
Now consider your towering stack of unevaluated 1+ calls. GHC has no way of knowing in advance whether you are ever going to use the result (see below), and it also has no way of knowing whether or not there is an exception lurking in there somewhere. As a programmer you might know that there is an exception and carefully not look at the result, relying on the non-strict semantics of Haskell. If GHC prematurely evaluates and gets an exception your program will fail when it should not have.
Actually the GHC compiler includes a piece of optimisation called the Demand Analyser (it used to be called the Strictness Analyser) which looks for opportunities to optimise in exactly the way you want. However it has limits because it can only optimise computations when it can prove that the result is going to be evaluated.
Another wrinkle here is that you have used the State monad. This actually comes in two variants; Lazy and Strict. The Strict variant forces the state when it gets written, but the Lazy variant (the default) doesn't.

A: The main method for detecting memory leaks is heap profiling.  Specifically, you're looking for unexpected growth in the amount of resident (mostly heap) memory, either the maximum residency in the +RTS -s statistics output, or -- more reliably -- a characteristic "pyramid" shape over time in heap profile output generated with the +RTS -h<x> flags and the hp2ps tool.
If I run your toy program with +RTS -s, I see:
   3,281,896,520 bytes allocated in the heap
   3,383,195,568 bytes copied during GC
     599,346,304 bytes maximum residency (17 sample(s))
       5,706,584 bytes maximum slop
             571 MB total memory in use (0 MB lost due to fragmentation)

The first line can generally be ignored.  Haskell programs typically allocate a roughly constant amount of memory per second of runtime, and this allocation rate is either nearly zero (for certain, unusual programs), or 0.5-2.0 gigabytes per second.  This program ran for 4 seconds and allocated 3.8 gigabytes, and that's not unusual.
The bytes copied during GC and maximum residency are concerning, though.  Assuming you have a program that you expect to run in constant space (i.e., there's no ever-growing data structure whose entire contents are needed), a correctly functioning Haskell program will generally not need to copy much data during garbage collection and will tend to have a maximum residency that's a small fraction of the total bytes allocated (e.g., 100 kilobytes rather than half a gigabyte), and this won't grow substantially with the number of "iterations" of whatever it is you're testing.
You can generate a quick heap profile over time without turning on formal profiling.  If you compile with the GHC flag -rtsopts, you can use:
./Toy +RTS -hT

and then display the result graphically using the hp2ps tool:
hp2ps -c -e8in Toy.hp
evince Toy.ps &

This sort of pyramid pattern is a red flag:

Note that rapid linear increase in heap to the tune of hundreds of megabytes per second followed by a rapid linear collapse.  This is the pattern you see when a huge lazy data structure is being needlessly built up before the entire computation is forced all at once.  You see two pyramids here because both your second and third tests are exhibiting memory leaks.
As an aside, the x-axis is in "MUT seconds" (seconds the "mutator" is running, which excludes garbage collection), so that's why this is less than the actual 4 second runtime.  That's actually another red flag.  A Haskell program that's spending half its time garbage collecting probably isn't running correctly.
To get more detail on what's causing this heap pyramid, you'll need to compile with profiling enabled.  Profiling may cause a program to run somewhat slower but doesn't normally change which optimizations are in place.  However, the flag -fprof-auto (and related flags) which automatically insert cost centers have the potential of causing big performance changes (by interfering with inlining, etc.).  Unfortunately, the cabal --enable-profiling flag turns on profiling (compiler flag -prof) and the flag -fprof-auto-top which automatically generates cost centers for top-level functions, so for your toy example, that substantially changes the behavior of your first test case (increasing the runtime from 0.4 seconds to 5 seconds, even with no +RTS flags).  That may be the problem you're seeing with profiling affecting your results.  You don't need any cost centers for several additional kinds of heap profiles, so you can add the cabal flag --profiling-detail=none to shut that off, and then your profiled program should run with timing a little slower but generally similar performance to the unprofiled version.
I don't use Cabal, but compiling with the following (which should be the equivalent of --enable-profiling --profiling-detail=none):
ghc -O2 -rtsopts -prof Toy.hs    # no -fprof-auto...

I can run your program with profiling by data type:
./Toy +RTS -hy

If I look at the heap profile graph:

this attributes most of the heap to the Int type -- this narrows my problem down to a bunch of unevaluated lazy Int calculations, which might point me in the right direction.
If I'm really having trouble narrowing things down and am feeling like a technical deep-dive, I can also run a heap profile by closure (flag -hd).  This tells me that the culprits are Main.sat_s7mQ and Main.sat_s7kP for the two pyramids respectively.  This looks very mysterious, but they're the names of functions in the "STG", a low-level intermediate representation of my program generated by the compiler.
If I recompile with the same flags but add -fforce-recomp -ddump-stg -dsuppress-all:
ghc -O2 -rtsopts -prof -fforce-recomp -ddump-stg -dsuppress-all Toy.hs

this will dump the STG that contains the definitions of these two functions.  (The generated identifiers can differ with small changes to code and/or compiler flags, so it's best to recompile with the STG dumped and then re-profile that executable, to make sure the identifiers match.)
If I search the STG for the first culprit, I find the definition:
sat_s7mQ =
    CCCS \u []
        case ww2_s7mL of {
          I# y_s7mO ->
              case +# [1# y_s7mO] of sat_s7mP {
                __DEFAULT -> I# [sat_s7mP];
              };
        };

Yes, this is all very technical, but this is STG-speak for the expression 1 + y, which would help me zero in on the culprit.
If you don't speak STG, you can try introducing some cost centers.  For example, I tried profiling only your second test case with -fprof-auto (Cabal flag --profiling-detail=all-functions).  The profile output in Toy.prof isn't that useful for memory leaks because it deals with total allocation instead of active (i.e., resident and not garbage collected) allocations over time, but you can create a heap profile by cost center by running:
./Toy +RTS -hc

In this case, it attributes everything to a single cost center, namely (315)countNumberCalls.  The "315" is the cost center number which you can look up in the Toy.prof input to find the exact source code lines, if it's not clear from the name.  Anyway, this at least helps narrow down the problem to countNumberCalls.
For more complicated functions, you can sometimes narrow down the problem further by manually specifying cost centers, like so:
countNumberCalls :: (LogFunctionCalls m) => Int -> m Int
countNumberCalls 0 = return 0
countNumberCalls n = do
  {-# SCC "mytell_call" #-} myTell "countNumberCalls" 1
  x <- {-# SCC "recursive_call" #-} countNumberCalls $! n - 1
  {-# SCC "return_statment" #-} return $ {-# SCC "one_plus_x" #-} 1 + x

This actually attributes everything to "recursive_call", so it's not that helpful.
It's not wrong, though.  You actually have two memory leaks here -- the x <- countNumberCalls $! n - 1 leaks heap because x isn't forced, and the 1 + x leaks stack.  You could enable the BangPatterns extension and write:
!x <- countNumebrCalls $1 n - 1

and that would actually remove one of the memory leaks, speeding up the second case from 2.5 seconds to 1.0 seconds and dropping the maximum residency from 460 megs to 95 megs (and the bytes copied during GC from 1.5 Gigs to 73 kilobytes!).  However, a heap profile would show linear growing stack accounting for pretty much all of that resident memory.  Because stack isn't as well-tracked as heap, that would be more difficult to track down.
Some additional notes:
Even though the +RTS -h<x> flags are primarily for heap profiling (and are discussed as "heap profiling" options in the GHC documentation), they can technically report on other uses of resident
memory besides heap including per-thread state, which includes thread state objects and stack.  By default, when running a profiled binary (compiled with -prof), the +RTS -h<x> flags do not report on per-thread state including stack, but you can add the -xt flag to add it, as in +RTS -hc -xt.  Due to a probable unintentional oversight, on a non-profiled binary, the +RTS -hT flag (the only -h<x> flag available) includes stack even without the -xt flag.  Due to a compiler bug, the -hT flag doesn't work on profiled binaries for GHC 8.6.x and earlier, but it does work on GHC 8.8.x, and for that version, +RTS -hT includes stack on non-profiled binaries but excludes it on profiled binaries unless you also specify -xt.  That's why in the examples above, "Stack" only shows up when running a heap profile on a non-profiled binary.  You can add the -xt flag to see it for all the other heap profiles.  Note that this "STACK" is actual stack use, rather than objects on the heap that are some how affiliated with the stack.
Black holes are primarily a mechanism for supporting concurrency.  When a thread starts evaluating a thunk, it "blackholes" it (i.e., marks it as a black hole), so that if another thread comes along and wants to evaluate the same thunk, it waits on the evaluation instead of trying to re-evaluate it in parallel (which would duplicate the effort of the running thread).  It's also used in the non-threaded runtime, partly because it can detect infinite loops (if a thread encounters its own black hole), but also for some more important reasons that I can't remember.  For -hT, -hd, and -hy heap profiling, heap objects that have been blackholed like this will be marked as "BLACKHOLE".  The limited sampling rate in the profiles above can make it a little unclear, but what's happening in your program is that a large series of Int thunks are being built in a chain, and when the value is finally forced, they are turned into a long chain of BLACKHOLEs, each of which represents a computation that's been initiated and is waiting on the next computation in the chain.

A: There is a specific class of space leaks that can be detected because they use excessive amounts of stack when they unwind the excessive heap usage. The following website lists the specific approaches, along with lots of case studies, but roughly:

*

*Compile and run with a limited size stack, using +RTS -K10K to limit the stack to 10Kb.

*Examine the code that breaks the stack limit, using +RTS -xc to get stack traces.

It's not a perfect approach since sometimes you have memory leaks without excessive stack usage, and sometimes you have excessive stack usage without memory leaks, but the correspondence is pretty good and the tooling can be deployed on CI to stop introducing new leaks.


text:
Q: Помогите с преобразованием кода из js в python Я написал код на js, необходимо его преобразовать в python-код, но я не знаю как работать с константами в python. Помогите пожалуйста.
js код:
const info = [{
    user: 'Имя_1',
    status: 'Пользователь'
},
{
    user: 'Имя_2',
    status: 'Администратор'
}]

console.log('Пользователь #1: ', info[0].user, '\nСтатус пользователя: ', info[0].status, '\n\nПользователь #2: ', info[1].user, '\nСтатус пользователя: ', info[1].status)

A: info = [{
    'user': 'Имя_1',
    'status': 'Пользователь'
},
{
    'user': 'Имя_2',
    'status': 'Администратор'
}]

print('Пользователь #1: ', info[0]['user'], '\nСтатус пользователя: ', info[0]['status'],
      '\n\nПользователь #2: ', info[1]['user'], '\nСтатус пользователя: ', info[1]['status'])

A: INFO = [
    {
        'user': 'Имя_1',
        'status': 'Пользователь'
    },
    {
        'user': 'Имя_2',
        'status': 'Администратор'
    }
]

print('Пользователь #1: %s\nСтатус пользователя: %s\n\nПользователь #2: %s\nСтатус пользователя: %s' % (
    INFO[0]['user'], INFO[0]['status'],
    INFO[1]['user'], INFO[1]['status']
))


text:
Q: MySQL. Select a value and use in calculating another value in one statement? Is it possible to select a value and use it processing another value in one select statement?
Something like:
SELECT a, b, (value a * 2) as c from table?

Update.
Select concat(a*2+a*4+10) as aa, b, (value (aa) * 2) as c from table?

Is it still possible?

A: Yes, that is possible. In your example column "a" then must be a type int.
SELECT a, b, (a * 2) as c from table


text:
Q: Why Planck scale is so important? I know that Planck scale is the scale where both, gravity and quantum effects are relevant simultaneously. Are there more reasons?

A: The natural diversity of energy levels at which matter organizes itself tends to isolate related phenomena in interesting and often confusing ways.
Consequently, physics has found that phenomena that seemed inexplicable often began to unravel and start to show revealing internal structure when energy levels are raised high enough to overcome those internal bindings. Both chemistry and nuclear chemistry are examples, followed a bit later by particle physics and the Standard Model.
These successes, when combined with mathematical models that describe the various bindings in terms of broken symmetries, has produced what might be called a universal heuristic in physics: the assumption that if you get things hot enough, you will begin to see enough detail to discern what is really going on. You might call it the heat-reveals heuristic.
For quantum phenomena, enabling the resolution of very small details also unavoidably also entails very high momenta, and thus very high energies. That in a nutshell is the reason for building super colliders.
I would suggest that the main reason for focusing so much attention on the Planck scale is that it is simply the logical conclusion of following the heat-reveals heuristic. It becomes an implicit postulate that since at the Planck scale gravity and quantum theory become roughly equal in impact at that level, it is also where the illusion of disparity will begin to unravel, and the deepest insights into the structure of the universe thus are most likely to be found.
Since such energy levels cannot be explored experimentally, they are instead explored mathematically by attempting to build self-consistent models of how physics would operate at that level.


text:
Q: Getting file from FTP with space in filename VB 2010 I'm lookin for a solution for the  problem, that I cannot download a file with a space in its name.
Edit: I found out that the ftp server is running on linux and my connection code need to set to utf-8? can that be true?
I tried to  pass different version of the filename:
Name with Space
Name%20with%20Space
Name/ with/ Space
Name/with/Space
Name"/"with"/"Space
but nothing worked. Here is my code
   Dim ftpRequest As FtpWebRequest = System.Net.FtpWebRequest.Create(myFTPPath & My ftp name with space )

       ftpRequest.Credentials = New System.Net.NetworkCredential(User, Password)

Dim ftpResponse As System.Net.FtpWebResponse = Nothing
            Dim iTries As Integer = 0
            Do While (IsNothing(ftpResponse) And iTries < 10)
                iTries += 1
                ftpResponse = getResponse(ftpRequest)
            loop
 ..........
 ...........
 ...........

Private Shared Function getResponse(ByRef request As FtpWebRequest) As FtpWebResponse
    Dim res As Boolean = False
    Dim response As System.Net.FtpWebResponse = Nothing
    Try
        response = request.GetResponse
    Catch ex As WebException

        If ex.Status = WebExceptionStatus.ConnectFailure Then
            response = Nothing
        End If
    End Try
    Return response
End Function

Anybody knows a working solution?

A: Did you tried cover whole path "" marks?
Dim ftpRequest As FtpWebRequest = System.Net.FtpWebRequest.Create("""ftp://example.com/directory with withespace/file with whitespace.txt""")

As you suppose this will produce
"ftp://example.com/directory with withespace/file with whitespace.txt"

string.


text:
Q: Passing in a function with different arity to lists:map in Erlang Let's say that I want to go over a list of integers using lists:map and I want that map to return a list with the same length with only numbers greater than a certain value. This is how I can achieve it now:
f(Min) ->
    List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    lists:map(fun(N) -> max(N, Min) end, List).

A rough idea of what I wished was possible is:
f(Min) ->
    List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    lists:map(fun erlang:max/2 (Min), List).

Is there a way to pass in a function with arity greater than 1 as the first argument of the lists:map function?

A: You should use list comprehension or lists:filter for this case:
NewList = [N || N <- List, N > Min]

Or
NewList = lists:filter(fun(N) -> N > Min end, List)

However, if you really prefer using lists:map, you will need to take into consideration to return something when N is less than or equal to Min.
f1(N, Min) when N > Min -> N;
f1(N, Min) when N =< Min -> undefined.  % return 'undefined'

myfun(Min, List) -> lists:map(fun(N) -> f1(N, Min) end, List).

As you can see, you can "close over" any function with any number of arity with closure.
You will end up with a list of with all the numbers less than N replaced by undefined followed by those more than N.
> myfun(5, [1, 2, 4, 6, 7]).
> [undefined, undefined, undefined, 6, 7]

lists:map concerns with mapping of values X -> X', not filtering a list's members.

A:
I wish to maintain all elements in the list, but replace invalid
  elements (in this example, below Min) with something I can take as
  input

Using a different syntax than Pie 'Oh' Pah's answer:
my_map(Target, Repl, Nums) ->
    lists:map(
        fun(Num) when Num =< Target  -> Repl;
           (Num)                     -> Num
        end,
        Nums
    ).

In the shell:
15> c(f1).
f1.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,f1}

16> f1:my_map(3, "-", [1, 2, 3, 4, 5]).
["-","-","-",4,5]

17> f1:my_map(
         fun(X) -> 10 end,
         [a, {b,c}],
         [100, a, make_ref(), spawn(fun() -> 2 end),
          {x, 1}, #{a=>1,b=>2}, [1,2,3]
         ]
    ).
[[a,{b,c}],
 [a,{b,c}],
 [a,{b,c}],
 <0.68.0>,
 {x,1},
 #{a => 1,b => 2},
 [1,2,3]]


text:
Q: Integrate WinUI with WPF (Existing as well as new) Currently we trying to improve our existing WPF application UI. For that, we are trying to use the WinAppSDK to use the Winui3 controls.
Steps followed.
Created a new WPF application
Installed the latest version of WinAppSDK from the Nuget package
Refered the winUI controls by including the XAMLControlResources in the APP.Xaml
But i am unable to access the controls from the Microsoft.UI.XAML. It says doesnt exist.
Please advice whether i am trying with the right way of approach .
App.XAML
<Application
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="using:Microsoft.UI.Xaml.Controls"
    xmlns:controls1="clr-namespace:ABI.Microsoft.UI.Xaml.Controls;assembly=Microsoft.WinUI"
    StartupUri="MainWindow.xaml">
    <Application.Resources>
        <controls1:XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls"  x:Key="winAppControl"/>
    </Application.Resources>
</Application>

MainWindow.Xaml

<Window x:Class="WpfApp2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
       xmlns:muxc="using:Microsoft.UI.Xaml.Controls;assembly=Microsoft.WinUI"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800"

        <muxc:TreeView>
    <muxc:TreeView.RootNodes>
        <muxc:TreeViewNode Content="Flavors">
            <muxc:TreeViewNode.Children>
                <muxc:TreeViewNode Content="Vanilla"/>
            </muxc:TreeViewNode.Children>
        </muxc:TreeViewNode>
    </muxc:TreeView.RootNodes>
    </muxc:TreeView>
</Window>

I am getting error as  resource not found

A: As Simon Mourier mentioned already, WinUI 3 and WPF are completely different technologies. You cannot mix them that easily since they use completely different technologies to render controls (e.g. WPF is .NET only while WinUI 3 is written in C++/WinRT).
The only solution would be to use XAML Islands, however they are not available for WinUI 3 as part of the stable releases. As of right now, the only way to do that would be to use experimental releases of WinUI 3 but even then, it's unclear if it will be brought to the stable release channel any time soon (or at all).


text:
Q: Count values based on a condition on another column I am trying to create a dataset where, for each job department, I count the total amount of people in that department and the total amount of people who left (or not) the company.
 Name       Total     Non left    Left
Finance      3000     2500        5000
IT           1500     1000        500
Marketing    1000     750         250
...

My initial datase list, row by row, each perosn in the company. My initial data set is:
ID    Department  Left
1     Finance     0
2     Finance     1
3     Marketing   0
4     Marketing   0
5     IT          1
...

I managed to get the total amount of people per department:
df["department"].value_counts()

Now I need something that does:
df["department"].value_counts(#If element in Left column is 1)
df["department"].value_counts(#If element in Left column is 0)

However I am not sure how to start it.

A: May use crosstab
pd.crosstab(df.Left, df.department ,margins = True)


text:
Q: What dependencies are required for DataNucleus 3.0.0-release? I'm trying to use datanucleus as JPA provider for GAE. This is my pom.xml (part of it):
<dependency>
  <groupId>org.apache.geronimo.specs</groupId>
  <artifactId>geronimo-jpa_2.0_spec</artifactId>
  <version>1.1</version>
</dependency>
<dependency>
  <groupId>org.apache.geronimo.specs</groupId>
  <artifactId>geronimo-jta_1.1_spec</artifactId>
  <version>1.1.1</version>
</dependency>
<dependency>
  <groupId>org.datanucleus</groupId>
  <artifactId>datanucleus-api-jpa</artifactId>
  <version>3.0.0-release</version>
</dependency>
<dependency>
  <groupId>org.datanucleus</groupId>
  <artifactId>datanucleus-core</artifactId>
  <version>3.0.0-release</version>
</dependency>
<dependency>
  <groupId>org.datanucleus</groupId>
  <artifactId>datanucleus-rdbms</artifactId>
  <version>3.0.0-release</version>
</dependency>
<dependency>
  <groupId>com.google.appengine.orm</groupId>
  <artifactId>datanucleus-appengine</artifactId>
  <version>1.0.8</version>
</dependency>

Class finding exception is thrown in runtime:
java.lang.NoClassDefFoundError: org/datanucleus/jpa/exceptions/NoPersistenceXmlException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
at java.lang.Class.getConstructor0(Class.java:2699)
at java.lang.Class.newInstance0(Class.java:326)
at java.lang.Class.newInstance(Class.java:308)
at org.apache.geronimo.osgi.locator.ProviderLocator.getServices(ProviderLocator.java:319)
at javax.persistence.spi.PersistenceProviderResolverHolder$DefaultPersistenceProviderResolver.getPersistenceProviders(PersistenceProviderResolverHolder.java:108)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:91)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:72)
...

Where this org.datanucleus.jpa.exceptions.NoPersistenceXmlException class is located? What JAR did I miss?

A: Official Link For Maven
would provide the required info. If not, do mention here as @DataNucleus can update the website in such an event.

A: Do you need
<dependency>
  <groupId>org.datanucleus</groupId>
  <artifactId>datanucleus-jpa</artifactId>
  <version>2.1.8</version>
</dependency>

Source
Also, note that it has
geronimo-jpa_2.0_spec
datanucleus-core
geronimo-validation_1.0_spec

A: This is how it works (it's datanucleus 1.x, which is the highest version that works with GAE):
    <dependency>
        <groupId>org.apache.geronimo.specs</groupId>
        <artifactId>geronimo-jpa_3.0_spec</artifactId>
        <version>1.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.datanucleus</groupId>
        <artifactId>datanucleus-jpa</artifactId>
        <version>1.1.5</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.datanucleus</groupId>
        <artifactId>datanucleus-core</artifactId>
        <version>1.1.5</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.datanucleus</groupId>
        <artifactId>datanucleus-rdbms</artifactId>
        <version>1.1.5</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>javax.jdo</groupId>
        <artifactId>jdo-api</artifactId>
        <version>3.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.google.appengine.orm</groupId>
        <artifactId>datanucleus-appengine</artifactId>
        <version>1.0.8</version>
        <scope>runtime</scope>
    </dependency>


text:
Q: Prove the following generalization of the Factorization Theorem Prove the following generalization of the Factorization Theorem: Let $f_1$ and $f_2$ be homomorphisms from the ring $R$ onto the rings $R_1$ and $R_2$, respectively.If       $\ker f_1 \subseteq \ker f_2$, then there exists the unique homomorphisms $\bar{f}: R_1 \to R_2$ satisfying $f_2= \bar{f} \circ f_1$. For any element $f_1(a) \in R_1$ , define $\bar{f} (f_1(a))= f_2(a)$.

A: It is a general fact that, given sets $S_1, S_2, S_3$ and functions $f:S_1\rightarrow S_2$, $g_1, g_2:S_2\rightarrow S_3$ and $h:S_1\rightarrow S_3$, such that $h = g_1\circ f = g_2\circ f$, if $f$ is surjective, then $g_1 = g_2$. This fact assures that, if a homomorphism $\overline{f}$ satisfying $f_2 = \overline{f}\circ f_1$ exists, it is unique. It remains to ascertain the existence of such a homomorphism.

*

*The First Ring Isomorphism Theorem assures us that $x\mapsto f_1^{-1}\left(\{x\}\right)$ is an isomorphism from $S_1$ to $R/\mathrm{ker}(f_1)$.

*The Third Ring Isomorphism Theorem assures us that the quotient ring $\frac{R/\mathrm{ker}(f_1)}{R/\mathrm{ker}(f_2)}$ is well-defined, and that the mapping $[x]_{\frac{R/\mathrm{ker}(f_1)}{R/\mathrm{ker}(f_2)}}\mapsto\cup[x]_{\frac{R/\mathrm{ker}(f_1)}{R/\mathrm{ker}(f_2)}}$ constitutes an isomorphism from $\frac{R/\mathrm{ker}(f_1)}{R/\mathrm{ker}(f_2)}$ to $R/\mathrm{ker}(f_2)$. Since the Canonical Map $x\mapsto[x]_{\frac{R/\mathrm{ker}(f_1)}{R/\mathrm{ker}(f_2)}}$ is a homomorphism from $R/\mathrm{ker}(f_1)$ to $\frac{R/\mathrm{ker}(f_1)}{R/\mathrm{ker}(f_2)}$, we obtain that the mapping $x\mapsto \cup [x]_{\frac{R/\mathrm{ker}(f_1)}{R/\mathrm{ker}(f_2)}}$ is a homomorphism from $R/\mathrm{ker}(f_1)$ to $R/\mathrm{ker}(f_2)$.

*The First Ring Isomorphism Theorem assures us that the mapping $[x]_{R/\mathrm{ker}(f_2)}\mapsto f_2(x)$ from $R/\mathrm{ker}(f_2)$ to $R_2$ is well-defined (i.e. independent of the representative $x$), and induces an isomorphism from $R/\mathrm{ker}(f_2)$ to $S_2$.
Stringing the three homomorphisms together, we obtain the homomorphism
$$
\overline{f}:S_1\rightarrow S_2,\hspace{1cm}\overline{f}(a) := f_2\left(\bigcup\left[f^{-1}\left(\{a\}\right)\right]_{\frac{R/\mathrm{ker}(f_1)}{R/\mathrm{ker}(f_2)}}\right),
$$
which satisfies the equation $f_2 = \overline{f}\circ f_1$.


text:
Q: Silverlight TreeGrid/TreeList functionality I have a requirement for a "Tree grid" or "Tree list" control.
This is something that looks like a DataGrid, but the left hand side is a tree that can be expanded and collapsed to show different rows (typically grouped, or perhaps showing data from a heirarchy).
Has anyone tried to build something like this by hand? If so do you recommend that route?
Or am I better of buying the control? If so who sells a good one?
We are targetting Silverlight 4 if that makes a difference
UPDATE: This is the type of control I am looking for (but for SL obviously)

A: This article looks promising.  He uses a DataGrid with a custom data source and cell template.  This is the only example I have found so far that actually ends up looking like a DataGrid (because it is one).
Telerik has a CTP of a TreeListView control, but it definitely looks more like a list than a data grid.
Also see this similar question also on StackOverflow.


text:
Q: Active/passive voice : Let the poor (not be insulted or be not insulted?)
Do not insult the poor.

The above sentence was asked in my exam for voice conversion. I had four options, managed to rule out two of them but confused between these two.
A) Let the poor not be insulted.
B) Let the poor be not insulted.
I tried to find answer to my problem but couldn't find concrete answer. I guess both are same in meaning with just a subtle difference in construction but since its a MCQ question I need to choose one answer, which one should I choose ? Which construction is the better one ? The solution has A as answer but doesn't explain why.

A: What are the other two options? I suspect that the correct answer was actually one of the ones you ruled out.
"Let the poor not be insulted" and "Let the poor be not insulted" seem to me to both have to do with the poor people's own feelings on the matter. This is especially true in the latter case. Thus, if I only had the two answers to choose from, I'd pick A as sounding more like the intention.
However, I suspect the correct answer was actually "Let not the poor be insulted." That is a rather archaic way of saying "Do not insult the poor." Somebody might use it intentionally as an affectation.

A: The first sentence:

*

*Let the poor not be insulted. - is a formal way of saying "Make it that the poor aren't insulted", which means that "the poor mustn't be insulted no matter what". It can be changed to "Do not let the poor be insulted".

"Let" is in the imperative here that means "give permission or make it possible for somebody to do or have something" and may be used in very formal situations such as political documents and speeches, and religious and other ceremonies.
The second sentence:

*

*Let the poor be not insulted. - may either be incomplete and expect a "but' or may be an emphatic way of saying "Let the poor be [not insulted]" stressing the "not insulted" part.

In the first case it can read be an incomplete sentence like "Let the poor be not insulted but exterminated!" for instance.
In the second case it may be something like "Let the poor be not insulted and not offended" which can also be written as "Let the poor not be insulted or offended"

A:
Let not the poor be insulted

OR

let the poor not be insulted

Both are correct. One thing should be kept in mind that MEANING SHOULD NOT BE CHANGED.


text:
Q: Google OAUTH gives 502 error I am successful in authenticating users locally, but on the production server I am receiving 502 errors after timeout..
here is my FLOW:
FLOW = OAuth2WebServerFlow(
        client_id='YOUR_CLIENT_ID',
        client_secret='YOUR_CLIENT_SECRET',
        scope='https://www.googleapis.com/auth/calendar',
        user_agent='Real_Hub/1.0',
        redirect_uri='quickerhub.com',)

locally redirect_uri is simply my localhost ip and it works fine.
here is my error through chrome network panel:
quickerhub.com
GET
502
Bad Gateway
text/html

A: This likely has to do with your redirect_uri. 502 is a very general error. It indicates that Django (probably uWSGI or Passenger) was unable to get a response before timeout. Have you tried that uri directly in your browser? If you have any HTTP authentication or anything on that domain, it will cause this error. For some reason, the OAuth does not seem to be properly creating the redirect response.
Hope this helps!


text:
Q: Outlook 2003 form Macro I have an existing form in outlook that I need to create a macro for.  It is a formed used to submit data to our corporate office.  Every time, I have to fill in my employee number, address, First and Last, etc... can someone help me create a macro to fill in these fields so I do not have to copy and paste or type my information every time?  Thanks!

A:  This HTML email creater.  Insert this into the "Visual Basic Editor in Tools>Macro then run the
 macro "emailpictures".  It will ask for validation.

Sub emailpicture()
    Set objOutlook = CreateObject("Outlook.Application")
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
Set objOutlookRecip = objOutlookMsg.Recipients.Add("companyemail@email.com")
objOutlookRecip.Type = olTo
objOutlookMsg.Subject = "Picture"
' add "C:\picture.png as attachment to Outlook message
Set colAttach = objOutlookMsg.Attachments
Set l_Attach = colAttach.Add("C:\path\image.jpg")
' Dereference the  attachment objects before changing their properties via CDO
Set colAttach = Nothing
Set l_Attach = Nothing
'Set body format to HTML
objOutlookMsg.BodyFormat = olFormatHTML
objOutlookMsg.HTMLBody = "

Title

Body

Hope you will have a worderous day!

From

"
objOutlookMsg.Send
Set objOutlookRecip = Nothing
Set objOutlookMsg = Nothing
Set objOutlook = Nothing

End Sub

A: Sub emailfromexcel()
    Dim OutApp As Object
    Dim OutMail As Object
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    With OutMail
        .To = "person@email.com"
        .BCC = thebcc
        .Subject = "This subject"
        .Body = "This body"
        .Display
        .Send
    End With
    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

A:    Sub emailfromexcel()
    Dim OutApp As Object
    Dim OutMail As Object
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    With OutMail
    .To = "person@email.com"
    .BCC = thebcc
    .Subject = "This subject"
    .Body = "This body"
    .Display
    .Send
    End With
    Set OutMail = Nothing
    Set OutApp = Nothing
  End Sub


text:
Q: how to check in twig if a form field has label when a form field is generated via an iteration:
{% for field in form %}
{{ form_widget(field); }}
{% endform %}

then it will encapsulates a div block surround the field's input type, and a label (if it has a label).
I want to seperate this into label, and widget:

        {% if field.vars.label is not null %}
          {{ form_label(field) }}
        {% endif %}
        {{ form_widget(field) }}

but the field.vars.label is always null. BTW when I generates without the condition, then it's shows labels correctly.
How do I get the label's value for the condition check?
Thank you in advance.

A: Change the label to false and the form_label() twig function will automatically ignore it.
Here's a code snippet from the form_div_layout.html.twig file (see line 2):
{%- block form_label -%}
    {% if label is not same as(false) -%}
        {% if not compound -%}
            {% set label_attr = label_attr|merge({'for': id}) %}
        {%- endif -%}
        {% if required -%}
            {% set label_attr = label_attr|merge({'class': (label_attr.class|default('') ~ ' required')|trim}) %}
        {%- endif -%}
        {% if label is empty -%}
            {%- if label_format is not empty -%}
                {% set label = label_format|replace({
                    '%name%': name,
                    '%id%': id,
                }) %}
            {%- else -%}
                {% set label = name|humanize %}
            {%- endif -%}
        {%- endif -%}
        {{ translation_domain is same as(false) ? label : label|trans({}, translation_domain) }}
    {%- endif -%}
{%- endblock form_label -%}

A: According to the doc of Form Variables Reference,
Try with:
    {% if field.vars.attr.label is not null %}

instead of:
    {% if field.vars.label is not null %}


text:
Q: Radio Buttons not saving correct value in Angular JS After a couple of tries on fixing my code, and searching for any solutions on the net, I finally gave up and would like to ask help on you guys.
I'm working on multiple sets of radio buttons and turn them to star ratings:
imgur link on my ratings section (cause I am not able to post images)
Each star is represented with 1 radio button, and each row has 5 radio buttons. In this image, im creating 3 sets of 5 radio buttons. Using the ng-repeat feature,

            <input type="radio" name="rating" ng-model="temp_called_numbers[$index].rating.value" value="1">
            <input type="radio" name="rating" ng-model="temp_called_numbers[$index].rating.value" value="2">
            <input type="radio" name="rating" ng-model="temp_called_numbers[$index].rating.value" value="3">
            <input type="radio" name="rating" ng-model="temp_called_numbers[$index].rating.value" value="4">

Now this specific page keeps on refreshing so when you click/highlight on a specific star, it refreshes and returns 5 blank stars again. What I did was that, I created an array to temporary store the value of each row.
$scope.temp_called_numbers = [];
$scope.rating_stars = {
        value:0
    };

and setting $scope.temp_called_numbers by:
rate_stars = function(){
        for(i=0; i < $scope.called_numbers.length; i++){
            $scope.temp_called_numbers.push( {rating: $scope.rating_stars});
        }

    }

The issue here now is that, when I select a star/radio button in one row, the other rows get the same value. For example, I select 1 star for row 1 which is temp_called_numbers[0].rating.value indexed 0, all the other rows get 1 star as well.
Any code change, reference or any help is much appreciated. Thanks!

A: $scope.temp_called_numbers = [];
$scope.rating_stars = {
        value:0
    };
rate_stars = function(){
    rating = $scope.rating_stars;
    for(i=0; i < $scope.called_numbers.length; i++){
        angular.extend(temp_called_numbers, rating);
    }
}

A:

            <input type="radio" name="rating" ng-model="number.checked">
            <input type="radio" name="rating" ng-model="number.checked">
            <input type="radio" name="rating" ng-model="number.checked">
            <input type="radio" name="rating" ng-model="number.checked">

// Access selected items
angular.forEach($scope.called_numbers, function(value, index) {
        if (value.checked) {
              $scope.called_numbers[index].checked = isSelectAll;
        }
});

A: For those checking on this thread. I've figure out that the issue here is not on the saving-to-array part, however, the issue is on the HTML side of the code.
Also, this was a visual bug on the stars and the array is fine and it stores the data when clicked. The reason that I was not getting the right data when clicking the radio button from 1 set of radio button group is because I was using  for the wrapper on the radio button.
what happened was that, even though I was getting 2 or more sets of Radio Button through ng-repeat, the page only accepts 1 radio button input.
By changing the wrapper to <form></form>:
<form class="star-rating" ng-init="temp_called_numbers[$index].rating.value ">
        <input type="radio" name="rating" ng-model="number.checked">
        <input type="radio" name="rating" ng-model="number.checked">
        <input type="radio" name="rating" ng-model="number.checked">
        <input type="radio" name="rating" ng-model="number.checked">
    </form>

I can now get 2 or more different inputs from each set of radio button group.


text:
Q: How do I make an API call to viralheat on submit and then parse and save the JSON response? I want to send a request via Viralheat's API in my controller's update method so that when a user hits the submit button, an action is completed and the API call is made. I want to post to http://www.viralheat.com/api/sentiment/review.json?text=i&do&not&like&this&api_key=[* your api key *]
This will return some JSON in the format:
{"mood":"negative","prob":0.773171679917001,"text":"i do not like this"}

Is it possible to make that API call simultaneously while executing the controller method and how would I handle the JSON response? Which controller method would I put it in?
Ultimately I'd like to save the response mood to my sentiment column in a BrandUsers table. Submit is in main.html.erb which then uses the update method.
Controller
def update
  @brand = Brand.find(params[:id])
  current_user.tag(@brand, :with => params[:brand][:tag_list], :on => :tags)
  if @brand.update_attributes(params[:brand])
    redirect_to :root, :notice  => "Brand tagged."
  else
    render :action => 'edit'
  end
end

def main
  @brands = Brand.all
  if current_user
    @brand = current_user.brands.not_tagged_by_user(current_user).order("RANDOM()").first
end

A: With the wrest gem installed, you could do something like
params[:api_key] = "your key"

url = "http://www.viralheat.com/api/sentiment/review.json"

response = url.to_uri.get(params).deserialize

response would contain the json already turned into a hash. So you can access the mood with
response[:mood]


text:
Q: How to trigger a transistor from iphone's audio output jack? I want to trigger a transistor using iPhone's audio output jack. My goal is to turn off an LED(which is fed by an external +5V battery) by sending an audio signal from iphone's output jack. At the beginning i thought it is easy but i encounter many problems. I tried to do it with a transistor but it seems the iphone audio output is too weak even for a transistor.
I am confused every time i find different ideas. Let me be more precise, here are the fatcs:
1-) The output voltage of iphone is very low, something like 300 mV
2-) The output is an audio signal
And here are the problems:
1-) How to amplify this voltage? I found some different ideas after some googling such as:
a-Using transformers. This guys says one needs micro-transformer
http://web.eecs.umich.edu/~prabal/pubs/papers/kuo10hijack-islped.pdf
b- Using capacitor. Here one guy is suggesting using a very simple circuit. I tried it didn't work:
Power LED from headphone jack
c- Using op-amp
Can you assist me a little bit about this?
2-) Do we need to rectify the audio signal?
Here is the circuit i was trying at the beginning. I thought it is simple. But the transistor is not triggering with the audio signal:

A: A transistor will need about 0.65V to start conducting, so the iPhone's output is indeed too low. The lowest part solution to get a higher voltage will be the transformer. You'll need a winding ratio of 1:10 to get a decent output level.
You have to rectify the amplified signal. If you were just to average it using a capacitor you'd get 0V. You don't need full rectification, however. You can do without the negative part of the signal; there will always be enough positive signal to work with. Feed the signal via a diode to a capacitor. This will get you a peak detector: the capacitor will load to the positive peaks in the signal. Of course when the music stops the charge should also disappear. You can discharge the capacitor via the transistor's base resistor (missing in your drawing), and if you want to discharge faster have another resistor parallel to the capacitor.

A: Consider also this different solution: since you have an external supply, if you don't need a lot of current on the LED you can also use an Op-Amp to provide a high-impedance input and a lot of gain. You could even use it in open-loop mode for just on/off switching, just biasing the inverting input with a voltage divider (you can decide the ratios to obtain the right sensitivity).
In that case, just pay attention to pick a rail-to-rail Opamp that works with the 0/+5 V supply and can drive enough current for the LED. If you want to use a more powerful LED, you can still use the Opamp to drive a transistor.


text:
Q: Replacing text with a checkbox using ReplaceWith I'm having trouble replacing text with a div that includes a checkbox.  When I have the following code, the text successfully gets replaced:

Hello</p

Hello

World

When the replacing text includes a checkbox, however, the script stops working. To be specific, the following does not work:

Hello</p

Hello

World

If someone could explain how to fix this, I would appreciate it. Thanks!

A: your problem is that you're using html " inside your javascript "
you must use alternating quotes inside this string
$( ".replaced" ).replaceWith("
<input type="checkbox" id="fractionsandratioscheck1" class="checkappear"/>REPLACING TEXT.
");

it should look something like this
$( ".replaced" ).replaceWith('
<input type="checkbox" id="fractionsandratioscheck1" class="checkappear"/>REPLACING TEXT.
');

A:

$( ".replaced" ).replaceWith("
<input type='checkbox' id='fractionsandratioscheck1' class='checkappear'/>REPLACING TEXT.
");//escape string properly

Hello</p

Hello

World

Only problem with OP is the "" change them to ''


text:
Q: Spring Batch: starting a job from within a Spring MVC contorller WITH A NEW THREAD I have a Spring-Batch job that I launch from a Spring MVC controller. The controller gets an uploaded file from the user and the job is supposed to process the file:
@RequestMapping(value = "/upload")
public ModelAndView uploadInventory(UploadFile uploadFile, BindingResult bindingResult) {

    // code for saving the uploaded file to disk goes here...

    // now I want to launch the job of reading the file line by line and saving it to the database,
    // but I want to launch this job in a new thread, not in the HTTP request thread,
    // since I so not want the user to wait until the job ends.
    jobLauncher.run(
                    jobRegistry.getJob(JOB_NAME),
                    new JobParametersBuilder().addString("targetDirectory", folderPath).addString("targetFile", fileName).toJobParameters()
                    );

    return mav;
}

I've tried the following XML config:
<job id="writeProductsJob" xmlns="http://www.springframework.org/schema/batch">
    <step id="readWrite">
        <tasklet task-executor="taskExecutor">
            <chunk reader="productItemReader" writer="productItemWriter" commit-interval="10" />
        </tasklet>
    </step>
</job>

<bean id="taskExecutor"
    class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="5" />
    <property name="maxPoolSize" value="5" />
</bean>

...but it seems like the multithreading happens only within the job boundaries itself. I.e., the controller thread waits until the job ends, and the job execution is handled by multiple threads (which is good but not the main thing I wanted). The main thing I wanted is that the job will be launched on a separate thread (or threads) while the controller thread will continue its execution without waiting for the job threads to end.
Is there a way to achieve this with Spring-batch?

A: The official documentation describes your exact problem and a solution in 4.5.2. Running Jobs from within a Web Container:

[...] The controller launches a Job using a JobLauncher that has been configured to launch asynchronously, which immediately returns a JobExecution. The Job will likely still be running, however, this nonblocking behaviour allows the controller to return immediately, which is required when handling an HttpRequest.

Spring Batch http://static.springsource.org/spring-batch/reference/html-single/images/launch-from-request.png
So you were pretty close in trying to use TaskExecutor, however it needs to be passed to the JobLauncher instead:
<bean id="jobLauncher"
      class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
    <property name="jobRepository" ref="jobRepository" />
    <property name="taskExecutor" ref="taskExecutor"/>
</bean>

Disclaimer: I have never used Spring Batch...

A: The jobLauncher.run() method can be called in a new Thread like so:
@RequestMapping(value = "/upload")
public ModelAndView uploadInventory(UploadFile uploadFile, BindingResult bindingResult) {
  [...]

  final SomeObject jobLauncher = [...]
  Thread thread = new Thread(){
    @Override
    public void run(){
      jobLauncher.run([...]);
    }
  };
  thread.start();

  return mav;
}

The thread.start() line will spawn a new thread, and then continue to execute the code below it.
Note that, if jobLauncher is a local variable, it must be declared final in order for it to be used inside of the anonymous Thread class.

A: If you don't need to show the processing errors to your client, you can start the spring batch job in a seperate thread.


text:
Q: Cannot convert value of type 'UnsafePointer' to expected argument type 'UnsafePointer<_>' I'm working with an external C library in Swift for OS X. I get a value cda, which is defined in C as a double* (it is a pointer to a double array).
When importing into Swift, it recognizes the type as UnsafeMutablePointer. I'm trying to convert this pointer and the count into a double array. Here's the code that I'm using (assume arrlen is the correct count of the array):
let doublearrptr = UnsafePointer<Double>(cda)
let xptarr = UnsafeBufferPointer<Double>(start: doublearrptr, count:arrlen)

However, when compiling this code fragment, I get the error:
Cannot convert value of type 'UnsafePointer<Double>' to expected argument type 'UnsafePointer<_>'

I'm relatively new to Swift, but I'm fairly certain that I can't convert to UnsafePointer<_>. I tried converting to UnsafePointer<Void>, but that got the same error. Swift does recognize that cda is a UnsafeMutablePointer<Double>.

A: So, I was able to solve it, albeit in a roundabout way.
I created a new function convert and used it:
func convertArr<T>(count: Int, data: UnsafePointer<T>) -> [T] {

    let buffer = UnsafeBufferPointer(start: data, count: count)
    return Array(buffer)
}
...
let doublearrptr = UnsafePointer<Double>(cda)
let arr = convertArr(Int(shobjarrlen), data: doublearrptr)

For some reason this works but not the original syntax...
I'm still open to getting answers from why my original syntax didn't work.


text:
Q: Is it possible to get the number of digits mathematically? I was wondering if it was possible to, say, have function $f$ that would return the number of digits in any given positive integer. I tried using some sort of a summation, but that failed quite miserably.
Using piecewise equations, it might be constructed something like this:
$$f(x)=\begin{cases}1 & \text{ if } x=1 \\2 & \text{ if } x=52 \\3 & \text{ if } x=230 \\4 & \text{ if } x=5023\\\vdots&\text{ }\vdots\end{cases}$$ This is, however, not what I want. Instead, I would like, if possible, some mathematical way of doing this.

A: $$f(x) = 1+\lfloor \log_{10}(x)\rfloor$$
More generally,
$$f(x) = 1+\lfloor \log_{b}(x)\rfloor$$ returns the number of digits of the number in base $b$.

A: Hint: The integer part of the logarithm in base 10 is the function you look for.


text:
Q: scikit-learn tree.DecisionTreeClassifier export to pdf too wide to fit I followed the the instructions in this thread to get my export working Python, PyDot and DecisionTree
but a pdf export truncates the tree after a page width and the png is too small to read. Is there a way of creating a pdf with unlimited width?
My code is
from sklearn import tree

clf = tree.DecisionTreeClassifier().fit(X_train, y_train)

import pydotplus
from IPython.display import Image
from sklearn.externals.six import StringIO
dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data,feature_names=cols_scaled.columns)
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
Image(graph.create_png())
graph.write_pdf("decisiontree.pdf")

Many thanks

A: Try using the following code, PDF requires width and let me know if it worked.
from sklearn.externals.six import StringIO
import pydotplus   #using pydotplus in windows10, python 3.6.X
dot_data = StringIO()

tree.export_graphviz(clf, out_file=dot_data,
                         feature_names=cols_scaled.column,
                         class_names=<replace target column here>,
                         filled=True, rounded=True,
                         special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
graph.write_pdf("iris.pdf")