text:
Q: Attempting to verify user roles in dashboard I'm trying to create a login system that checks for user role and redirects to the corresponding dashboard, while also forbidding users from manually entering others' dashboard URLs.
The login is working great, but the check for user role, not so much.
The site has one dashboard for each role, and on top of each is this:
session_start();
if(!$_SESSION['sess_role'] == 'role1') {
    header('location:../../index.php');
}

It seems to work when you haven't logged in, sending you back to the index page correctly because the 'sess_role' attribute does not match, but once I login with ANY user, I'm able to enter EVERY single dashboard by manually entering the URL, despite not having the correct "role" for it.
Here's the login code:
$msg = "";
if(isset($_POST['submitBtnLogin'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    if($username != "" && $password != "") {
        try {
            $query = "select * from `users` where `username`=:username and `password`=:password";
            $stmt = $db->prepare($query);
            $stmt->bindParam('username', $username, PDO::PARAM_STR);
            $stmt->bindValue('password', $password, PDO::PARAM_STR);
            $stmt->execute();
            $count = $stmt->rowCount();
            $row   = $stmt->fetch(PDO::FETCH_ASSOC);
            if($count == 1 && !empty($row)) {

                $_SESSION['sess_user_id']   = $row['id'];
                $_SESSION['sess_username'] = $row['username'];
                $_SESSION['sess_role'] = $row['role'];
            }

                if($row['role'] == "role1") {
                header('location:modules/role1/index.php');
                } else if($row['role'] == "role2") {
                header('location:modules/role2/index.php');
                } else if($row['role'] == "role3") {
                header('location:modules/role3/index.php');
                } else if($row['role'] == "role4") {
                header('location:modules/role4/index.php');

            } else {
                $msg = "Invalid login information.";
            }
        } catch (PDOException $e) {
            echo "Error : ".$e->getMessage();
        }
    } else {
        $msg = "Both fields are required.";
    }
}

I tried doing:
echo($_SESSION['sess_role']);

To see what the output is, and it seems to work as intended, showing "role1" when I'm on a "role1" account, and the same for the other roles.
While accessing "role2" dashboard, for example, the output is still "role1" but I'm still able to enter.
I'd greatly appreciate some help on identifying the issue.

A: The ! operator binds to $_SESSION['sess_role'], not to the whole expression.  You have to either put your expression in brackets if(!($_SESSION['sess_role'] == 'role2')) or better use the not equals operator for better readability if($_SESSION['sess_role'] != 'role2') {

A: As it turns out and as per a comment I left, was cause for failure:

You should add exit; after each header. Your code is probably wanting to continue to execute.

Using a header with an exit is recommended, per the following Q&A here on Stack Overflow:

*

*php - Should I call exit() after calling Location: header?
On an added note; don't store plain text passwords. Store a hashed version of it by using password_hash():

*

*http://php.net/manual/en/function.password-hash.php
And then verifying them with password_verify():

*

*http://php.net/manual/en/function.password-verify.php
Please read through those in its entirety, it's important.
Using just a prepared statement isn't safe enough, not when it comes to passwords.


text:
Q: Spaces in wikimedia templates I'm working on a MediaWiki-generated Wiki, and want to build a template that would link me to a French Wikipedia article. I have this :
[http://fr.wikipedia.org/wiki/{{{1|}}} {{#if:{{{2|}}}|{{{2|}}}|{{{1|}}}}}]

Logic being :
{{Wpfr|article name|alternate name (if needed)}}

Thing is, if the article name has spaces in it, it breaks, keeping the first word as {{{1}}} and putting the rest in {{{2}}}.
I'd like to find a way to be able to use spaces in {{{1}}} without breaking the links. That way :
{{Wpfr|Greg Weisman}}

would automatically link to the article on Greg Weisman and display "Greg Weisman".
I've tried using :
[http://fr.wikipedia.org/wiki/{{{art|}}} {{#if:{{{2|}}}|{{{2|}}}|{{{art|}}}}}]
{{Wpfr|art=article name}}

(even replacing the 2s by 1s) to no avail.
The Wiki admin part hasn't been updated in a while so the Interwiki table can't be updated and I can't use the "replace" function either.
I'm new to Wikicoding, so I'm sorry if the answer is very simple.
Thanks !
Edit : the MediaWiki version is 1.13.5

A: Mediawiki has a magic word for handeling encoding of url:

{{urlencode:data|style}}

{{urlencode:Greg Weisman|PATH}} will return:

Greg%20Weisman

Change your template with:
[http://fr.wikipedia.org/wiki/{{urlencode:{{{1|}}}|PATH}} {{#if:{{{2|}}}|{{{2|}}}|{{{1|}}}}}]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Process Data in Google Storage on an AWS EMR Cluster in Spark How can I process data stored in Google Storage on an AWS EMR cluster in Spark?
Assuming I have some data stored at gs://my-buckey/my-parquet-data, how can I read it in from my EMR cluster without having to copy the data to s3 beforehand or download to local storage?

A: First obtain Google HMAC credentials with access to the GS bucket/objects you want to process
Then use the S3A filesystem (already bundled with AWS hadoop distributions) with the following hadoop configuration values:
val conf = spark.sparkContext.hadoopConfiguration
conf.set("fs.s3a.access.key", "<hmac key>")
conf.set("fs.s3a.secret.key", "<hmac secret>")
conf.setBoolean("fs.s3a.path.style.access", true)
conf.set("fs.s3a.endpoint", "storage.googleapis.com")
conf.setInt("fs.s3a.list.version", 1)

Then you can access google storage with s3a paths as follows:
spark.read.parquet("s3a://<google storage bucket name>/<path>)


text:
Q: Escaping multi-line text with "jq" Suppose, I need to escape a multi-line text:
printf "\"aaa\"\nbbb"
"aaa"
bbb

I'm trying to escape it with jq -aR:
printf "\"aaa\"\nbbb"| jq -aR
"\"aaa\""
"bbb"

Unfortunately it's not what I want. I want to get "\"aaa\"\nbbb" instead.
How can I escape "aaa"\nbbb with jq properly ?

A: Use the --slurp/-s command-line option.
$ printf "\"aaa\"\nbbb"| jq -asR
"\"aaa\"\nbbb"

Of course in this case, the -a option makes no difference.


text:
Q: How can i get a complete list including nested relations? I have a task model related to activities and i want to get a array/hash with all Tasks and their related activities like this:
<% task_group =[
     ['Task1', {'Activity1' => 1, 'Activity2' => 2}],
     ['Task2', {'Activity3' => 3, 'Activity4'=> 4}]
    ] %>

I came up with Task.includes(:activities).all.map(&:name) but this only gives me a list with activities and their name.
How can i get a complete list including nested relations?
My model defintion:
class Task < ActiveRecord::Base
  has_many :activities

class Activity < ActiveRecord::Base
  belongs_to :task

A: you can use:
Task.includes(:activities).all.map{|t| [t.name, t.activities.inject({}){|H, a| H[a.name] = a.id; H}]}

EDIT:
Task.includes(:activities).all.map{|t| [t.name, t.activities.inject({}){|h, a| h[a.name] = a.id; h}]}


text:
Q: Turn off scientific notation visualcode (scipen not working in R profile?) I have downloaded R studios, and R extension in visualcode.
in the R profile file i have typed in
options(scipen=999) and saved.
When i run my code in visualcode it dosent get rid of scientific notation in my output barchart. Why?
Thank you :)

A: Try this:
Set the scientific argument of format function to FALSE in scale_y_continous:
ggplot(mtcars, aes(cyl, mpg))+
  geom_col()+
  scale_y_continuous(labels = function(x) format(x, scientific = FALSE))


text:
Q: reading/writing files to Windows Azure storage using Objective C Does anyone know of any good resources or tutorials on how to write files to Windows Azure and read the files using Objective C? (for an iPhone app)
Thanks!

A: While not an answer to your question, I will share that if you choose to implement your own Objective-C Azure client, beware that NSMutableURLRequest will attempt to be helpful and capitalize the names of any headers you add to the request, i.e: x-ms-date becomes X-Ms-Date. Azure will barf on this and return http code 403 (bad request), even though the HTTP RFC explicitly states that header names are to be treated as case-insensitive.
That's about where I gave up.

A: There is a project on codeproject that would likely answer your questions.
OneNote on iPhone and Palm Pré using Windows Azure
http://www.codeproject.com/KB/aspnet/rinocp.aspx

A: Is the user of the iPhone app also the owner of the storage account?  If so, go for it (though sorry, I have no advice on how to do this in Objective C).
If not, consider the security model.  If you're going to give users access to storage, you'll either need to use blobs with Shared Access Signatures (in which case this should be trivial... you don't need to mess with signing the requests), or you'll need to give users the key to your storage account, which is generally a bad idea.  (This would allow them to read/write/delete anything they find there.)

A: You can now download the Windows Azure Toolkit for iOS. This will provide you with either direct access or proxy access to Windows Azure Storage (with the proxy running in a Role of your deployment).


text:
Q: TSQL To Search For Only Specific Chars In Any Position Have alphanumeric in an nvarchar
Want to search for only
-0-9
(-0123456789)
select top 1000 id, word
from FTSwordDef with (nolock)
where word like '[-0-9]%'

Will return -0-9 in the first position.
Want to apply -0-9 to all positions
So -123c would fail as c is not -0-9

A: WHERE word NOT LIKE '%[^0-9-]%';

You can also say:
WHERE PATINDEX('%[^0-9-]%', word) = 0;

A: do you have the option to install a regex UDF? If so you can do this by regular expression


text:
Q: Setting the value of a combobox with datasource in ListView I have an issue where the combobox does not set to the binding value within a list view.
As you can see from the screenshot below, the other values are populating from the binding correctly. Is it something to do with the fact it is a combobox opposed to a textbox/label?

The admin combo has two options, true or false. The datatable which the listview (code below) is bound to contains the values "True" and "False" for the various records.
<ListView Name="grdUsers" HorizontalAlignment="Left" ItemsSource="{Binding}" Margin="6,27,0,0" VerticalAlignment="Top" Height="225" Width="289"
              ScrollViewer.HorizontalScrollBarVisibility="Disabled">
        <ListView.View>
            <GridView >
                <GridViewColumn DisplayMemberBinding="{Binding Path=PK}" Header="PK" Width="30">
                </GridViewColumn>
                <GridViewColumn Header="Name" Width="115">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox Text="{Binding Path=Name}" Width="115"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Group" Width="50">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox Text="{Binding Path=MemberGroup}" Width="45"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Admin" Width="70">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox Text="{Binding Path=IsAdmin}"  Width="55">
                                <ComboBoxItem>True</ComboBoxItem>
                                <ComboBoxItem>False</ComboBoxItem>
                            </ComboBox>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

It is the last item within here that is the issue, I have tried changing the binding to selectedItem and all sorts.
So, how do I bind the datatable value to the combo and why does it not work for the combo and does for the textboxes?
Thanks

A: It's because your ComboBox has 2 items of ComboBoxItem type and not String and this means that SelectedItem will also be of a ComboBoxItem type. Try something like this:
<ComboBox SelectedItem="{Binding Path=IsAdmin}" Width="55">
   <ComboBox.Items>
      <sys:String>True</sys:String>
      <sys:String>False</sys:String>
   </ComboBox.Items>
</ComboBox>

for this to work you'll nee to define sys: namespace like so:
xmlns:sys="clr-namespace:System;assembly=mscorlib"

A: If IsAdmin is a string containing only True or False, you can simply bind it to a CheckBox using a StringToBoolean converter:
public class StringToBooleanConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (value.ToString() == "True") ? true : false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

Use this converter as a resource
<Window.Resources>
    <local:StringToBooleanConverter x:Key="strToBoolConverter"/>
</Window.Resources>

And use it in the binding
          <GridViewColumn Header="Admin" Width="70">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox IsChecked="{Binding Path=IsAdmin, Converter={StaticResource strToBoolConverter}}"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>

A: There are a number of ways to fix your problem. Personally, I would prefer to use actual bool properties to represent Boolean values. Using this method, you'd need to Bind to a bool collection containing your true and false values in it and then Bind your IsAdmin property (if it were of type bool) to the SelectedItem property of the ComboBox instead.
<ComboBox ItemsSource="{Binding BoolCollection}" SelectedItem="{Binding IsAdmin}" />

Of course, you'll need to add this BoolCollection into whatever object that you have bound to the control, or change your Binding... you could also create bool items like this:
xmlns:System="clr-namespace:System;assembly=mscorlib"
...
<ComboBox.Items>
    <System:Boolean>True</System:Boolean>
    <System:Boolean>False</System:Boolean>
</ComboBox.Items>

An alternative method has been alluded to by @dkozl, although I believe that you still need to Bind from your IsAdmin property to the SelectedItem property of the ComboBox instead of the Text value.


text:
Q: Excel change column format using macro If there is word COST in column name then change the column format to currency using macro for excel.
like if column name is - "Final Cost" or "Total Cost" or "Item Cost"
then change column format to currency.
Thanks

A: Try something like
Public Sub FormatCostColumnsAsCurrency()

  Dim sht As Worksheet
  Set sht = ActiveSheet

  Dim rng As Range
  Dim i As Integer

  For i = 1 To sht.UsedRange.Columns.Count

      Set rng = sht.Cells(1, i)
      If InStr(LCase(rng.Text), "cost") > 0 Then
          sht.Columns(i).NumberFormat = "$#,##0.00"
      End If

  Next

End Sub

A: You can do this with Conditional Formatting, no macro required.

*

*Highlight a cell in the left column of your table.

*On the Home section of the ribbon, click Conditional Formatting, then New Rule.

*Use a formula to determine which cells to format.

*Enter this formula. If your row headings don't start in A1, change accordingly: =SEARCH("cost",A$1,1)

*Click Format and set Number to Currency, then click OK.

*In the Conditional Formatting Rules Manager, set Applies to so that it covers your table.

A: Try below code
Sub CurrFormat()
    Dim colHeader As Range
    Set colHeader = Range("A1:E1")

    Dim currCell As Range
    Set currCell = Cells.Find("COST")

    If Not currCell Is Nothing Then currCell.NumberFormat = "$#,##0.00"

End Sub


text:
Q: Calling Function with ListBoxes I have created a function take two list boxes, take one value from one list box and add that value to another. I placed the function in my Module. Here is the
code.
Here is the function:
Function addtolist(selectionlist As ListBox, listselected As ListBox)

For i = 0 To selectionlist.ListCount - 1
    If selectionlist.selected(i) = True Then
        listselected.AddItem selectionlist.List(i)

    End If

Next i

For i = selectionlist.ListCount - 1 To 0 Step -1
    If selectionlist.selected(i) = True Then
        selectionlist.RemoveItem i

    End If

Next i
End Function

In the private sub, a button click, I am doing the following:
Call addtolist(selectionlist, listselected)

I keep getting Run Time Error '13' Type mismatch.
Please help!

A: from the code and the error you expose, I'd say you have to change the declaration of your function arguments type to MSForms.ListBox:
Function addtolist(selectionlist As MSForms.ListBox, listselected As MSForms.ListBox)


text:
Q: Cowboy server exits on start without errors I'm running a simple cowboy server. Here's my application file:
defmodule MyApp.Application do
  @moduledoc "Application file"

  use Application

  def start(_type, _args) do
    children = [
      Plug.Cowboy.child_spec(
        scheme: :http,
        plug: MyApp.Web.Endpoint,
        options: [port: 8000]
      )
    ]

    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    IO.puts("Starting...")
    Supervisor.start_link(children, opts) |> IO.inspect
  end
end

And here is my endpoint:
defmodule MyApp.Web.Endpoint do
  @moduledoc """
  This is the module responsible for processing incoming requests
  """

  use Plug.Router
  import Plug.Conn, only: [send_resp: 3]

  plug(Plug.Logger)
  plug(:match)
  plug(:dispatch)

  get "/ping" do
    send_resp(conn, 200, "pong")
  end

end

After running mix run, I see the start up log ("Starting..."), but my app exits immediately instead of listening for connections. How do I keep it listening indefinitely?

A: From the mix run docs:

mix run can be used to start the current application dependencies, the
application itself, and optionally run some code in its context. For
long running systems, this is typically done with the --no-halt
option:
mix run --no-halt


text:
Q: firebase add data to database with array I am trying to add a set of data to a database by pushing the data to an array and adding them to the database. I have added my codes here
const com = {

      company: "Com",
      description: "Turn ...",
      pointsNeeded: "500",
      title: "Com",
      PromoCode: Math.floor(Math.random()*1000000000),
      imageLocation: "www...",

  }

  this.afDB.list('rewards/' + se.uid).push(com)
    .then(next => {
      console.log(next);
    });

This is how my database look like

However, I would like the database to be like
 "rewards" : {
"fH7GPHMFupW2JD8fxKnLOvHBZ0w1" : {
    0: {
      "PromoCode" :
      "company" :
      "description" :
      "imageLocation" :
      "pointsNeeded" :
      "title" :
    },
    1" : {
      "PromoCode" :
      "company" :
      "description" :
      "imageLocation" :
      "pointsNeeded" :
      "title" :
    }
  }
}

Can anyone advice? I am not really sure what to do next.
Thanks
UPDATE:
 const getUserReward = firebase.database().ref('rewards/').child(se.uid)
  getUserReward.once('value', data => {

    var rewardArray =[];
    rewardArray.push(comchestReward)
    getUserReward.update({rewards: rewardArray})
  })

So this is the code I have so far but it is now


text:
Q: What does "" do? I can't believe what is happening in my website. When I add this line:

<!DOCTYPE html>

Everything works fine. And when I don't, CSS "messes" up, everything becomes different and layout becomes "ugly".
How can this line solve all the problems?!

A: You're mixing up HTML with XHTML.
Usually a <!DOCTYPE> declaration is used to distinguish between versions of HTMLish languages (in this case, HTML or XHTML).
Different markup languages will behave differently. My favorite example is height:100%. Look at the following in a browser:
XHTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

How tall is this?

... and compare it to the following: (note the conspicuous lack of a <!DOCTYPE> declaration)
HTML (quirks mode)

How tall is this?

You'll notice that the height of the table is drastically different, and the only difference between the 2 documents is the type of markup!
That's nice... now, what does  do?
That doesn't answer your question though. Technically, the xmlns attribute is used by the root element of an XHTML document: (according to Wikipedia)

The root element of an XHTML document must be html, and must contain an xmlns attribute to associate it with the XHTML namespace.

You see, it's important to understand that XHTML isn't HTML but XML - a very different creature. (ok, a kind of different creature) The xmlns attribute is just one of those things the document needs to be valid XML. Why? Because someone working on the standard said so ;) (you can read more about XML namespaces on Wikipedia but I'm omitting that info 'cause it's not actually relevant to your question!)
But then why is  fixing the CSS?
If structuring your document like so... (as you suggest in your comment)

<!DOCTYPE html>

[...]

... is fixing your document, it leads me to believe that you don't know that much about CSS and HTML (no offense!) and that the truth is that without  it's behaving normally and with  it's not - and you just think it is, because you're used to writing invalid HTML and thus working in quirks mode.
The above example I provided is an example of that same problem; most people think height:100% should result in the height of the
 being the whole window, and that the DOCTYPE is actually breaking their CSS... but that's not really the case; rather, they just don't understand that they need to add a html, body { height:100%; } CSS rule to achieve their desired effect.

A: It sounds like your site has CSS or JS that depends on running in quirks mode.  Which is why you need garbage above your doctype to render "correctly".  I suggest removing said garbage and then fixing your CSS+JS to actually work in standards mode; you'll save yourself a lot of pain in the long run.

A: Its an XML namespace. It is required when you use XHTML 1.0 or 1.1 doctypes or application/xhtml+xml mimetypes.
You should be using HTML5 doctype, then you don't need it for text/html.  Better start from template like this :
<!DOCTYPE html>

        <meta charset=utf-8 />
        <title>domcument title</title>
        <link rel="stylesheet" href="/stylesheet.css" type="text/css" />

When you have put your Doctype straight - do and validate you html and your css . That usually will sove you layout issues.

A: The namespace name http://www.w3.org/1999/xhtml
is intended for use in various specifications such as:

Recommendations:

    XHTML™ 1.0: The Extensible HyperText Markup Language
    XHTML Modularization
    XHTML 1.1
    XHTML Basic
    XHTML Print
    XHTML+RDFa

Check here for more detail


text:
Q: need to write a script to change file format from dos to unix I have to make a script using vim which opens a file, set the fileformat=unix, and then save the file and exit. Could you please help? Thanks

A: First, check out whether you have a dos2unix or dos2ux command; it already does this for you.
With Vim, this should do the job:
$ vim -c "wq ++ff=unix" filename

This one in-lines the fileformat change with the :w command; of course, you can also do this separately via -c "set ff=unix".
Notes

*

*You can also do this via a variety of tools, e.g. sed, perl, ...; Vim is a quite heavyweight alternative.

*This still starts up a full, interactive Vim instance. Have a look at this answer which additional command-line arguments can turn Vim into batch mode.


text:
Q: Функция принимает числовую последовательность - 5 целых чисел. swift Не могу понять что не так?
Вот задача:
Функция принимает числовую последовательность - 5 целых чисел. Проверить, упорядочена ли последовательность по неубыванию. Если упорядочена вывести на экран yes, в противном случае вывести no. Задача решается без использования циклов.
Input example:
1 2 3 4 5
Output example:
yes
Naming rule:
func isSorted(a: Int, b: Int, c: Int, d: Int, e: Int)
Решение:
    func isSorted(a: Int, b: Int, c: Int, d: Int, e: Int) {
    if a < b && b < c && c < d && d < e {
        print("yes")
    } else {
      print("no")
    }
}

isSorted(a: 1, b: 2, c: 3, d: 4, e: 5)

A: по неубыванию означает, что сравнение нестрогое
if a <= b и т.д.


text:
Q: How to filter data use select options on button click jQuery I'm working with filtering data on the table.
I have in the view 4 select options, in which I have some data. I want to filter data in the table depending on the options which all ready exist.
The issue is in case I will change only one options, and push button add filter it will works fine, if i will use 2-3 options filter will not work.
HTML:
<select id="option1">
    <option></option>
    <option>Thulasiram.S</option>
    <option>ST Ram</option>
    <option>Ram Kumar.S</option>
    <option>Dinesh Kumar.S  </option>
</select>

<select id="option2">
    <option></option>
    <option>11</option>
    <option>21</option>
    <option>30</option>
</select>

<select id="option3">
    <option></option>
    <option>Chess</option>
    <option>Cricket</option>
</select>
<select id="option4">
    <option></option>
    <option>Day</option>
    <option>Month</option>
    <option>Week</option>
</select>
<button id="test213">Add filter</button>

            Fullname
            Age
            Sport
            Class
            Term

            Thulasiram.S
            11
            Chess
            1
            Day

            ST Ram
            11
            Cricket
            1
            Month

            Ram Kumar.S
            21
            Chess
            2
            Day

            Dinesh Kumar.S
            30
            Chess
            3
            Week

JS:
$('#test213').click(function () {
    getSelectedVal()
});

function getSelectedVal() {
    var startDate = $('#option1 option:selected').text()
    var duetDate = $('#option2 option:selected').text()
    var templateName = $('#option3 option:selected').text()
    var status = $('#option4 option:selected').text()

    filterData(startDate)
    filterData(duetDate)
    filterData(templateName)
    filterData(status)
}

function filterData(data) {
    if (data != '') {
        var rows = $("#shelulerData").find("tr").hide();
        rows.filter(":contains('" + data + "')").show();
    }
}

I create jsfiddle:  here

A: Each time you call filterData you are basically hiding everything.
Suggesting you when applying filter to add that filter to array of applied filters and finally using the array of filter apply the filter.
later you can remove filters referencing and removing items from the array and recalling the filter function. (up to your implementation....)
initiate an empty array at main scope as follows
let filters = []

apply the filters with this function:
function applyFilter(value) {
if(value)
 filters.push(':contains('+value+')')
}

then your filterData function:
function filterData() {
if (filters.length>0) {
    var rows = $("#shelulerData").find("tr").hide();
    var currentFilter = null;
    filters.forEach(filter => {
        if(currentFilter===null) {
        currentFilter = rows.filter(filter)
      } else
      {
      currentFilter = currentFilter.filter(filter)
      }
    })
    currentFilter.show()
  }
}

Basically, you can chain filter functions to get the final filter so this is why i chained the currentFilter var in the loop and finally applied the show() function
here is js fiddle with solution


text:
Q: Find biggest independent subset of a connectivity matrix I have two groups linked by a connectivity matrix like the following:
#
#   X1  X2  X3  X4  X5  X6
#   1   0   0   0   0   0  V1
#   1   1   1   0   0   0  V2
#   0   1   0   0   0   0  V3
#   0   0   1   0   0   0  V4
#   0   0   0   1   0   0  V5
#   0   0   0   1   0   0  V6
#   0   0   0   0   1   0  V7
#   0   0   0   0   1   1  V8
#   0   0   0   0   1   0  V9
#   0   0   0   0   0   1  V10
#

So X1 is linked to V1 and V2 while V2 is linked to X1, X2 and X3 and so on. I need to find a way (algorithm or command) for getting all the biggest independent subsets of the matrix. So, in this case:
#   X1  X2  X3
#   1   0   0  V1
#   1   1   1  V2
#   0   1   0  V3
#   0   0   1  V4

and:
#   X4
#   1  V5
#   1  V6

and:
#   X5  X6
#   1   0   V7
#   1   1   V8
#   1   0   V9
#   0   1   V10

Do you have any hint? I guess there's already some library or function to use either from graph analysis or linear algebra.

A: As you hinted we can do this with igraph:
# dummy data
df1 <- read.table(text = "  X1  X2  X3  X4  X5  X6
V1  1   0   0   0   0   0
                  V2    1   1   1   0   0   0
                  V3    0   1   0   0   0   0
                  V4    0   0   1   0   0   0
                  V5    0   0   0   1   0   0
                  V6    0   0   0   1   0   0
                  V7    0   0   0   0   1   0
                  V8    0   0   0   0   1   1
                  V9    0   0   0   0   1   0
                  V10   0   0   0   0   0   1
                  ")

library(dplyr)
library(tidyr)
library(igraph)

# make graph object
gg <-
  df1 %>%
  add_rownames(var = "V") %>%
  gather(X, value, -V) %>%
  filter(value == 1) %>%
  graph.data.frame

# split based on clusters of graph
lapply(
  sapply(split(clusters(gg)$membership,
               clusters(gg)$membership), names),
  function(i)
  df1[intersect(rownames(df1), i),
      intersect(colnames(df1), i),
      drop = FALSE])

# $`1`
#    X1 X2 X3
# V1  1  0  0
# V2  1  1  1
# V3  0  1  0
# V4  0  0  1
#
# $`2`
#    X4
# V5  1
# V6  1
#
# $`3`
#     X5 X6
# V7   1  0
# V8   1  1
# V9   1  0
# V10  0  1


text:
Q: How to get single clicked word from textarea using JavaScript Is it possible to get clicked word from textarea using jquery or javascript in IE and Firefox. Currently i'm using the below code and it's working perfectly fine in Chrome but it doesn't work at all in IE and Firefox.
<body>
<label for="result" style="display: none">Text</label>
<textarea id="result" rows="30" cols="100"></textarea>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>

    $("#result").click(function() {
        if($(this).val() !== null && $(this).val() !== ''){
            var selection = window.getSelection();
            selection.modify('extend', 'backward', 'word');
            var end = selection.toString();

            selection.modify('extend', 'forward', 'word');
            var start = selection.toString();
            selection.modify('move', 'forward', 'character');
            var wordInput = end+start;

            console.log(wordInput);
        }
    });
</script>
</body>

Expected Working
Let's suppose a textarea with text: 'Hello World'
When i click anywhere in 'Hello' it should print 'Hello' not the whole textarea value. Similarly for 'World' and so on.
Error in IE
SCRIPT438: Object doesn't support property or method 'modify'
Can anyone help me please? Thanks!

A: This code could help you, i guess.

const getTheWord = (selectionStart, value) => {
  let arr = value.split(" ");
  let sum = 0
  for (let i = 0; i < arr.length; i++) {
    sum += arr[i].length + 1
    if (sum > selectionStart) return arr[i]

  }
}

const myArea = document.getElementById("myArea")
myArea.value = "Hello world!"
myArea.onclick = (e) => {
let i = e.currentTarget.selectionStart
console.log(getTheWord(i, myArea.value))
}
<textarea id="myArea"></textarea>

A: No need to split all the text. This may lead to bad performance, because we do not know the length of text.
Give this a try:
function isSpace(character: string) {
  return /\s/.test(character);
}

export function getSelectedWord(
  selectionStart: number,
  value: string
): string | null {
  let start: number = selectionStart;
  let end: number = selectionStart;
  while (start - 1 >= 0 && !isSpace(value[start - 1]!)) {
    --start;
  }
  while (end + 1 < value.length && !isSpace(value[end + 1]!)) {
    ++end;
  }
  const word = value.slice(start, end + 1);
  return word || null;
}


text:
Q: how to save data outside subscribe Angular 5 I am trying to save data received from http get request and save it into another array that belongs to the component
getAlerts(){
 this.ChatAlertsService.getAlerts()
        .subscribe((data) => {
                console.log('ngon Init', data);
                this.useralerts=data['result'];
                 console.log('inside subscribe user_alerts', this.useralerts);

            },
            (error) => console.log(error));
    console.log('outside subscribe user_alerts', this.useralerts);
};

and this is the main call of the function :
ngOnInit() {
        this.getAlerts();

        this.tableData1 = {
            headerRow: ['ID', 'Alert Text', 'Type', 'CreatedAt'],
            dataRows: this.useralerts
                  };
        console.log(this.tableData1.dataRows);
    }

I was passing the data inside the subscribe like this :
this.tabledata1.dataRows=this.useralerts;

this helped me preview the data inside the table component but I am getting the previously visited components in the main page ( like it's the router module stcuk inside subscription )
when I removed that line I am unable to save the data from GET request into the array TableData1.datarows
this a screenshot of the display in my console :

as it shows the data is successfully saved inside subscribe but , outside it is "undefined"
could you please provide me with an explanation to this I am stuck for like 2 days now
this a preview of the pbm I am facing with routing & display :

A: I had a similar trouble, the way i solved i just call a set function outside of the subscribe in your case would be something like this:
getAlerts(){
 this.ChatAlertsService.getAlerts()
        .subscribe((data) => {
                console.log('ngon Init', data);
                this.setUsersArray(data['result']);
                 console.log('inside subscribe user_alerts', this.useralerts);

            },
            (error) => console.log(error));
    console.log('outside subscribe user_alerts', this.useralerts);
};

setUsersArray(data){
   this.useralerts= data;
}


text:
Q: duplicate key is still inserting as an entry in MYSQL It just keeps adding a row even if it already exists and i don't get why?
$submitted = explode("@", $submit['tag']);
foreach ($submitted as $tag => $value) {
    if ($value != "") {
        $attag = "@".$value;
        $sql_insert = dbquery("INSERT INTO dbtags(tag_name, tag_txt) VALUES('$value', '$attag') ON DUPLICATE KEY UPDATE tag_name=tag_name");
    }
}

Can anyone help?

A: You sure you mean UPDATE tag_name=tag_name and not UPDATE tag_name=$value ?
Also, use PDO.

A: It should be Unique other wise duplicate will not work . On DUPLICATE KEY UPDATE tag_name=tag_name")  change to On DUPLICATE KEY  IGNORE

A: change tag_name data type to Binary, you may be facing problem of case-sensitiveness


text:
Q: Why isn't the whole space equal to all the sub partitions? fdisk  -l
Partition table entries are not in disk order.

Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xc3072e18

Device     Boot    Start      End  Sectors  Size Id Type
/dev/sdb1  *       16128 30489407 30473280 14.5G  c W95 FAT32 (LBA)
/dev/sdb4       11580256 13523807  1943552  949M  0 Empty

sdb1+sdb4=14.5g+949M=15.4g
Why is this : Disk /dev/sdb: 14.6, 15610576896 bytes, 30489408 sectors, in the fdisk -l info?
It says that the whole sdb space is 14.6 GiB. Why is it not the 15.4 GiB?
Why is there about 0.8 GiB space lost?

A: You disk size is 14.538 GiB (30489408 sectors * 512 bytes /1024/1024/1024).
Its partition table is seriously broken as sdb4 is overlapping sdb1.
You should remove sdb4 as soon as possible and in any case, you shouldn't use that fourth partition without a very strong risk of corrupting sdb1 content.


text:
Q: Use Object.factory without needing to cast to a specific type I'm trying to create a similar router to Rails ActionDispatch router, which allows you to define a route similar to
map.get "/foo", :controller => "Foo", :action => "index"

which will then route GET /foo to FooController#index. With this structure in place you can use methods like
map.resources :foos

which will call methods like
map.get "/foo", :controller => "Foo", :action => "index"
map.get "/foo/:id", :controller => "Foo", :action => "show"

and so on.
In D, I've been able to figure out a lot of the reflexive code required to make this work, but not all of it.  In Ruby I can do:
class Foo
  def bar
    "FOOO BAR!"
  end
end

f = Object.const_get("Foo")
f.new.__send__(:bar) #=> "FOOO BAR!"

Which I've tried to translate to
module foo;
import std.stdio;

class Foo {
  void bar() {
    writeln("FOO BAR!");
  }
}

void main() {
  auto foo = Object.factory("foo.Foo");
  __traits(getMember, foo, "bar");
}

But that doesn't work because the compiler doesn't know what type foo is, so the call to #bar fails during compile.  Everywhere I've seen Object.factory used they cast it to a specific type, so
module foo;
import std.stdio;

class Foo {
  void bar() {
    writeln("FOO BAR!");
  }
}

void main() {
  auto foo = cast(Foo) Object.factory("foo.Foo");
  __traits(getMember, foo, "bar");
}

would work just fine. But if I know what I want to cast the object to what good is using Object.factory? That doesn't make any sense to me!
UPDATE 2 I've fixed compiler issues, but now it's crashing at runtime, saying it couldn't find the method
module foo;
import std.stdio;

class MyDynamic {
  void call(C, T...)(C instance, string method, T args) {
    foreach(member; __traits(allMembers, C)) {
      writeln(member);
      if (member == method) {
        static if (__traits(compiles, __traits(getMember, instance, member)(args))) {
          __traits(getMember, instance, member)(args);
        }
        return;
      }
    }

    assert(0, "No method found");
  }
}

class Foo : MyDynamic {
  void bar() {
    writeln("FOO BAR!");
  }
}

void main() {
  auto foo = cast(MyDynamic) Object.factory("foo.Foo");
  assert(foo !is null);

  foo.call(foo, "bar");
}

Update For anyone coming to this question now, you can see my final solution here: https://github.com/jaredonline/action-pack

A: The way I do this is to build my own factory function and dynamic dispatches. Using __traits(allMembers), loop through all the supported classes and get a list of methods. Write a wrapper template that takes generic arguments and converts them to the arguments the function needs. Store a reference to the wrapper function in an associative array, or have a dispatch method in your interface to call it.
When it is time to do the work, create the class (with your own wrapper, or you could also use Object.factory and cast it to some generic interface with your dynamic dispatch function), then use the dynamic function. So something like:
// IMPORTANT: Object.factory needs a full name - includes the module and class name!
auto foo = cast(MyDynamic) Object.factory("mymodule.Foo");
assert(foo !is null); // Object.factory can return null if it didn't find the class
// and cast can also return null if it wasn't actually of that interface type, so gotta check

foo.call("my_method", ["arg", "arg2", ...]);

I updated this link with a full example, refresh if you don't see module dynamicstuff; at the top:
http://arsdnet.net/dcode/test46.d
loop allMembers, invoke based on a runtime string. Getting a list of all classes that implement an interface is possible too, by looping over ModuleInfo. See the bottom of the example file for a function to do it.
My web.d does this to do automatic calling of functions from the web. Long, messy code, but it does a lot. Here's the wrapper function:
https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff/blob/master/web.d#L2538
Note the use of ParameterTypeTuple!func from std.traits.
I put a lot of comments in here http://arsdnet.net/dcode/test46.d so hopefully they will answer your questions. That example briefly demonstrates:

*

*compile time reflection with __traits (MyDynamicImplementation)

*run time reflection with ModuleInfo and ClassInfo (getAllDynamicClasses)

*User-defined attributes (isDynamicallyAvailable)

*Calling a method with dynamic data (MyDynamicImplementation, uses ReturnType, to, ParameterTypeTuple, and there's commented code for Variant if you are interested)

*An alternative to multiple inheritance, using an interface and mixin template together.

You don't necessarily have to use all that stuff, but I figured I'd touch upon all of it since these can all be pretty useful for these url routing tasks.


text:
Q: Setting dynamically distinct id attribute using javascript for input element I am facing a problem in setting distinct ids for dynamically added input boxes in a table.
The problem is:
I am inserting new rows when the user clicks on "Add new Row". Now I have to set distinct id for the input box. I have taken a static variable and increasing its value every time user clicks on add new row button. Then I am appending its value to id value lets say temp (i.e. ids will be temp1, temp2 and so on). I have taken a variable xyz as
var xyz = "temp" + i (where i is the counter)
and now I have to assign xyz to the id using setattribute.
But as values in setattribute can only be literals, how can I use a variable in place of the value?
If you have any other methods, please let me know.

A: It can be a variable which holds a string as well.
var fooId = "foo";
for (var i = 0; i <= 2; i++) {
    document.getElementsByTagName('div')[i].setAttribute('id', fooId + (i + 1));
}

Live DEMO

A: setAttribute allows for variables to be used as the value parameter.
eg:
var ele = document.createElement('div')
var id = 'temp1'
ele.setAttribute('id', id)

would result in:

A: element.setAttribute("id", xyz); Where element is your input.

A: First of all setattribute is an undefined property of an element because of case-sensitivity while setAttribute, of course, is available.
Second, you are not absolutely required to use setAttribute at all. You can simply modify the id property to achieve the very same effect:
var el = document.createElement('div'), // your element
    staticPart = 'myUniqId', // your static part of a unique id
    i = 0; // your uniqueness

el.id = staticPart + i; // assign unique id to the element
// el.setAttribute('id', staticPart + i); // does the same, but more verbose

// Let's check if it worked:
el.getAttribute('id'); // "myUniqId0"
el.id; // "myUniqId0"

Third, where did you see that

values in setattribute can only be literals

The spec says that setAttribute accepts two parameters, name and value of type DOMstring. You can pass it any value you want. Mind that it will be converted to String:
el.id = {a: 'b'};
el.id; // "[object Object]"

See http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-F68F082 and https://developer.mozilla.org/en-US/docs/DOM/element.setAttribute

A: for(;i<7;i++)
          {document.getElementById("test").innerHTML +='<form  id="form'+f+++'" method="get"><input type="text" id="in'+i+++'" size="12%"><input type="text" id="in'+i+++'" size="12%" ><input type="text" id="in'+i+++'"size="12%"><input type="text" id="in'+i+++'"size="10%" ><input type="text" id="in'+i+++'"size="10%"><input type="text" id="in'+i+++'" size="10%"><input type="text" id="in'+i+++'"size="12%"></form>'
          }


text:
Q: It is possible to use Tensorflow C++ API in QT project? I trained a Tensorflow model for image classification using the Python API, then i saved the model checkpoint.
Now I want to load this model in a QT(C++) project.
After looking into documentations, I found that to use Tensorflow C++ API you need to create a  project inside a clone of the TensorFlow github repository, then build it with Bazel, who is not possible in my case.
Is there a way to include tensorflow library in my QT project ?

A: You need bazel (or CMake) to build the tensorflow library, but once it is compiled you are free to use whatever tool you like and treat it like an external library.
Believe me, once you have compiled tensorflow, the last thing you want to do is add it to your project and rebuild it accidentally. This baby takes time.

A: Yes, there is. Compile tensorflow project as a library (dll) and include it into qt project.

A: It is also possible to use make instead of bazel to build the TensorFlow library for your target platforms.
You can find more information on building TensorFlow with a Makefile at the TensorFlow GitHub project.
You can also have a look at this guide and open-source example project for Image Classification and Object Recognition with Qt and TensorFlow. It describes how to build TensorFlow using make and integrates it to your Qt project using the QMAKE build system.


text:
Q: how to manage lists in android auto? I can display the information of my phone application but I am restricted to display only six.
I would like to know how to proceed to display the rest of the elements ( i have a list of 17 elements).
For the moment I use the first and last columns of my Template to do an invalidate() and display the previous or next items of my list
    public Template onGetTemplate() {

        ListTemplate.Builder templateBuilder = new ListTemplate.Builder();

        ItemList.Builder sectionABuilder = new ItemList.Builder();

        if(compteur < 4 ) {
            try {
                if (DataMgr.getInstance().getDataListAdress().size() > 0 && compteur < DataMgr.getInstance().getDataListAdress().get(0).length) {
                    for (int i = compteur; i < compteur + 5; i++) {
                        System.out.println("////Test + " + DataMgr.getInstance().getDataListAdress().get(0)[i]);
                        System.out.println("////TestLength + " + DataMgr.getInstance().getDataListAdress().get(0).length);

                        sectionABuilder.addItem(buildRow(DataMgr.getInstance().getDataListAdress().get(0)[i]));
                    }
                }
                sectionABuilder.addItem(buildRowClick("Suivant"));

                templateBuilder.addSectionedList(
                        SectionedItemList.create(sectionABuilder.build(), "Header"));
            } catch (Exception e) {
                CarToast.makeText(getCarContext(), "No more", CarToast.LENGTH_SHORT).show();
            }
        } else {
            sectionABuilder.addItem(buildRowClickPrecedent("Precedent"));
            try {
                if (DataMgr.getInstance().getDataListAdress().size() > 0 && compteur < DataMgr.getInstance().getDataListAdress().get(0).length) {
                    for (int i = compteur; i < compteur + 4; i++) {
                        System.out.println("////Test + " + DataMgr.getInstance().getDataListAdress().get(0)[i]);
                        System.out.println("////Test +" + DataMgr.getInstance().getDataListAdress().get(0).length);

                        sectionABuilder.addItem(buildRow(DataMgr.getInstance().getDataListAdress().get(0)[i]));
                    }
                }
                sectionABuilder.addItem(buildRowClick("Suivant"));

                templateBuilder.addSectionedList(
                        SectionedItemList.create(sectionABuilder.build(), "Header"));
            } catch (Exception e) {
                CarToast.makeText(getCarContext(), "No more", CarToast.LENGTH_SHORT).show();
            }
        }

        return templateBuilder
                .setHeaderAction(Action.PAN)
                .setTitle("ok")
                .build();
    }

@NonNull
    private Row buildRow(String data) {
        return new Row.Builder()
                .setTitle(data)
                .build();
    }

    @NonNull
    private Row buildRowClick(String data) {
        return new Row.Builder()
                .setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick() {
                        compteur += 4;
                        invalidate();
                    }
                })
                .setTitle(data)
                .build();
    }

A: You can't use it like this. Use ConstraintManager.class.
Lists are limited by unit you have in a car. But there is special API to handle this.
Check ConstraintManager:
int listLimit = Math.min(MAX_LIST_ITEMS,
                       getCarContext().getCarService(ConstraintManager.class).getContentLimit(
                                    ConstraintManager.CONTENT_LIMIT_TYPE_LIST));

Docs: https://developer.android.com/reference/androidx/car/app/constraints/ConstraintManager
You can take this limit count and interate your list only based on this number.


text:
Q: ColdFusion: CFID and CFToken change on each page request I have been asked to use J2EE Variables and not store the CFID and CFTOKEN in cookies, as the CFID is reported as non-compliant: Predictable Cookie Session ID's Reported by Compliance Tests

*

*In my Application.cfm, I have added setclientcookies="false".  This stops the CFID and CFToken being written as cookies.

*In the ColdFusion Admin, I have enabled J2EE Session Variables

So I now have a cookie with JESSIONID, and a session variable with URLToken containing CFID and CFTOKEN. However, every time I refresh the page, the CFID and CFTOKEN change. They do not persist as they did before. Which mean our admin login system fails.
I have done my own googling, but have found nothing so far. One suggestion I found was to write code to persist the CFID and CFTOKEN. However, this doesn't feel like a good solution.
Any suggestions?
Barebones Test
I installed CF 10 Developer Edition and enabled J2EE Session Variables
Created an Application.cfm with
<cfapplication name="test" sessionmanagement="Yes" setclientcookies="false">

and an index.cfm with

Cookie

<cfdump var="#cookie#">

Session

<cfdump var="#session#">

The Session.URLToken changes with every refresh

CFID=2212&CFTOKEN=41db974c3d2eb4b6-640C21AE-FD53-499C-71FBEBA35D6B09E8&jsessionid=E28AA17629928FB6F9E17674AC85C7AA.cfusion
CFID=2213&CFTOKEN=bb791a304929d0f5-6425021B-A31B-B9C8-3628AE391B0F48FF&jsessionid=E28AA17629928FB6F9E17674AC85C7AA.cfusion

Further Thoughts
The CFIDand CFTOKEN are used in our login system to verify the user session matches, maybe I should change it to store and verify against the JESSIONID. Maybe it doesn't matter that the CFIDand CFTOKEN change. The session scope is actually maintained, so this could be a completely non-issue.
<cfparam name="session.timestamp" default="#now()#">

A: setClientCookies="false" means that coldfusion server will not create cookies for the current session. CFID and CFToken will still exist and will be non-persistent.
Check in your example that jsessionid value is same in both cases and that is what you should use instead of CFID & CFToken only if need be.
And you are correct, your session state is maintained as you have enabled J2EE session variables.


text:
Q: Chrome remote debugging is not working? when i connect to my phone it shows me error ( i have latest version of chrome on mobile and laptop).
Please guide me, how to remove this error

A: I think the rule is that Chrome on desktop must be newer than Chrome on mobile.


text:
Q: Develop application using Storyboard or xib file I am beginner level ios developer.I want to know which is best practice to develop application using Storyboard or xib file? Why ?
I think xib file is easy to work.Also If I use Storyboard,it will be tough to add dynamic views.

A: Storyboards are now apples recommendation. I have used storyboards to create the current app I'm working on and I love them. The ease of being able to see the entire flow of your app is fantastic, instead of having to open multiple xib files.
There is nothing stopping you from creating dynamic views when using a storyboard, you can add a blank view controller and have it linked to a code file that will create the entire view on viewDidAppear  or viewDidLoad.
You can also use "storyboardID" to create a shortcut so you can jump from one screen to any other screen without having a segue, comes in very handy sometimes.
Over all there is a bit of a learning curve to it, but the benefits especially towards debugging the flow of the app far out weighs the the learning curve, and using storyboards doesn't prevent you from doing anything else, as it can always be done in code later on as it would normally.
Some links to help
I have used this link to start of from scratch:
http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/SecondiOSAppTutorial/Introduction/Introduction.html
This one looks a like it builds a bigger app using them, might be good:
http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1


text:
Q: How to include another cmake project's header files in my cmake project? I'm trying to include another CMake project as a third party library for my project. The problem is that I can't include the headers from the said library.
I tried adding the library using add_subdirectory function but it doesn't seem to work.
This is my CMakeLists.txt:
cmake_minimum_required (VERSION 2.6)
project (Cam2ClientCpp)

set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

include_directories ("${PROJECT_SOURCE_DIR}/restclient-cpp")
add_subdirectory (restclient-cpp)

set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib)

add_executable (Cam2ClientCpp main.cpp)
target_link_libraries (Cam2ClientCpp restclient-cpp)

The other project's CMakeLists.txt is here: https://github.com/mrtazz/restclient-cpp/blob/master/CMakeLists.txt.
When I run make, I get the following error:
/Library/Developer/CommandLineTools/usr/bin/c++   -I/Users/nhendy/Development/cam2clientcpp/restclient-cpp  -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk   -std=gnu++11 -o CMakeFiles/Cam2ClientCpp.dir/main.cpp.o -c /Users/nhendy/Development/cam2clientcpp/main.cpp
/Users/nhendy/Development/cam2clientcpp/main.cpp:1:10: fatal error: 'restclient-cpp/connection.h' file not found
#include "restclient-cpp/connection.h"

A: Usually, to use a library, you have to:

*

*Call add_subdirectory so that the CMakeLists.txt of this project is parsed and interpreted. This makes the project/library known to CMake.

*The library project defines the include paths the user of the library needs to know (PUBLIC), as well as the internal include paths (PRIVATE):

target_include_directories(MyLibrary
  PUBLIC
    include
  PRIVATE
    src
)

*

*The user of the library only needs to reference the library:

target_link_libraries(MyCoolApp
  PRIVATE
    MyLibrary
)

This way the library exports the paths required to use the library, i.e. not the user of the library knows how to use it, but only the library itself.
My suggestion is to create a PR to the library and kindly ask them to use this approach.
In case this is not possible, you can set the include_directories. My CMakeLists.txt looks like this (only change to yours is the include_directories command, using ${CMAKE_SOURCE_DIR}):
cmake_minimum_required (VERSION 2.6)
project (Cam2ClientCpp)

set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

file(WRITE
  ${CMAKE_BINARY_DIR}/restclient-cpp/include/restclient-cpp/version.h
  "#define RESTCLIENT_VERSION \"0.5.0\"\n"
)

include_directories ("${CMAKE_SOURCE_DIR}/restclient-cpp/include")
include_directories ("${CMAKE_BINARY_DIR}/restclient-cpp/include")
#add_subdirectory (restclient-cpp)

set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib)

add_executable (Cam2ClientCpp main.cpp)
target_link_libraries (Cam2ClientCpp restclient-cpp)

I tested with following file structure:
./CMakeLists.txt
./restclient-cpp
./restclient-user
./restclient-user/CMakeLists.txt
./restclient-user/main.cpp

*

*restclient-cpp contains the cloned repo of the client library

*restclient-user the executable code which uses the library

*./CMakeLists.txt only contains:

cmake_minimum_required(VERSION 3.10)
add_subdirectory(restclient-cpp)
add_subdirectory(restclient-user)

A: First, you need to compile the third party library alone. Then link against the output library in your CMake project.
See target_link_libraries


text:
Q: Rails 4: Save Checkbox Results to Serialized Array I have a Campaign model with a channel column. This channel will store a serialized array of chosen results via checkboxes.
Here's the model..
app/models/campaign.rb
class Campaign < ActiveRecord::Base
    serialize :channels, Array
end

app/controllers/compaigns_controller.rb
class CampaignsController < ApplicationController
      def index
        @campaigns = Campaign.all.order("created_at DESC")
      end

      def new
        @campaign = Campaign.new
      end

      def create
        @campaign = Campaign.new(campaign_params)

        if @campaign.save

            zip = Uploadzip.find(params[:uploadzip_id])
            zip.campaign = @campaign
            zip.save

            flash[:success] = "Campaign Successfully Launched!"
            redirect_to @campaign
        else
            flash[:error] = "There was a problem launching your Campaign."
            redirect_to new_campaign_path
        end
      end

      def show
        @campaign = Campaign.includes(:program, :uploadzip, :channel, :plan, :uploadpdfs).find(params[:id])
      end

  private

      def campaign_params
        params.require(:campaign).permit(:name, :comment, :channel, :plan_id, :program_id, :campaign_id, uploadpdf_ids: [])
      end
end

The part of the form with checkboxes..
views/campaigns/_target.rb
<%= form_for @campaign, url: {action: "create"} do |f| %>

   ...

   <%= f.label :channel, "Distribution Channel", class: "right-label" %>

    <% ["Folder", "Fax", "Email"].each do |channel| %>

<%= check_box_tag :channel, channel %> <%= channel %>
        <% end %>

...

<% end %>

I'm having problems saving these results inside the Campaign object.
Any help is highly appreciated.

A: First of all, you mentioned that the column name is channel, but you have used its plural version in Campaign model. Since you are planning to save array of channels in this column, I would suggest you change the name of the column in the database to channels. All the code below assumes that you will change the database column to channels.
Since you are serializing the channels attribute to an Array and your form will send that parameter as an array to the controller, you will need to update your campaign_params method accordingly.
def campaign_params
  params.require(:campaign).permit(:name, :comment, :plan_id, :program_id, :campaign_id, uploadpdf_ids: [], channels: [])
end

Now, the relevant part of your @campaign form should look like this:

  <% ["Folder", "Fax", "Email"].each do |channel| %>

<%= check_box_tag "campaign[channels][]", channel, @campaign.channels.include?(channel), id: "campaign_channels_#{channel}" %> <%= channel %>

  <% end %>

Explanation
First argument in check_box_tag is name attribute of the tag. Second is value attribute. Third is boolean value to tell whether the checkbox will be checked or not when rendered initially. This will be helpful in edit form to show current selections.
Note that I am providing id attribute explicitly. If we don't do that, all three checkboxes will have the same id (derived from their names), which would not be valid HTML because id should not be repeated.
Generated HTML should look like this:

<input type="checkbox" name="campaign[channels][]" id="campaign_channels_Folder" value="Folder" /> Folder

<input type="checkbox" name="campaign[channels][]" id="campaign_channels_Fax" value="Fax" /> Fax

<input type="checkbox" name="campaign[channels][]" id="campaign_channels_Email" value="Email" /> Email

The controller will see channels param as an array of selected values.
This should work both for New and Edit forms.


text:
Q: Autocorrelation function $\rho(s)$ of AR(p), when s goes infinity Let $\{X_t\}_{t\in\mathbb{Z}}$ is the stacionary autoregressive process of degree p (AR(p)), and autocorrelation function of AR(p) is $$\rho(s)=\phi_1\rho(s-1)+\phi_2\rho(s-2)+\dots+\phi_p\rho(s-p), \text{ for $s=1,2,\dots, p$}.$$
I should show that when $s\rightarrow \infty$ then $\rho(s)\rightarrow0$. I am trying to solve difference equation and then $s\rightarrow \infty$. But I have no idea how to make it in general, because I think that when $s$ goes to the infinity ($s\rightarrow \infty$), it means also that p goes to the infinity ($p\rightarrow \infty$). Any help will be appreciated, thank you very much.

A: This can be seen by solving for $\{\rho(s)\}_{s \geq 0}$ directly.
The system of linear homogeneous difference equation (of degree $p$) is
$$
\underbrace{ \rho(s)- \phi_1\rho(s-1)+\phi_2\rho(s-2)+\dots+\phi_p\rho(s-p) }_{ \Phi(L)\rho(s)} =  0, \;\; s \geq {0}.
$$
with initial conditions $\rho(0), \cdots \rho(p-1)$ given by the Yule-Walker equations
$$
\begin{bmatrix}
1           &\rho(1)      & \rho(2) &\cdots& \rho(p-1) \\
\rho(1)     & 1 & \rho(1) &\cdots   & \rho(p-2) \\
\rho(2)     & \rho(1)     & 1       &\cdots   & \rho(p-3) \\
\vdots      & \vdots      & \vdots  &\ddots   & \vdots \\
\rho(p-1)   & \rho(p-2)   &\rho(p-3)&\cdots   & 1 \\
\end{bmatrix}
\begin{bmatrix}
\phi_1           \\
\phi_2           \\
\phi_3           \\
\vdots           \\
\phi_p           \\
\end{bmatrix}
=
\begin{bmatrix}
\rho(1)           \\
\rho(2)           \\
\rho(3)           \\
\vdots           \\
\rho(p)           \\
\end{bmatrix}.
$$
The general solution is a linear combination of terms corresponding to the AR polynomial $\Phi(z)$.
For example, if $\Phi$ have $p$ distinct real roots $r_1, \cdots, r_{p}$,
the general solution is
$$
\rho(s) = c_1 r_1^{-s} + \cdots c_{p} r_{p}^{-s}.
$$
The coefficients $c_1, \cdots, c_{p}$ are given by the initial conditions.
By assumption (covariance stationarity), $|r_1|, \cdots, |r_{p+1}| > 1$,
$$
\lim_{s \rightarrow \infty} r_l^{-s} = 0, \; l = 1, \cdots, p.
$$
This implies
$$
\lim_{s \rightarrow \infty} \rho(s) = 0.
$$
The case of repeated or complex roots is similar. Same result holds.
The key condition is that all roots of $\Phi$ lies outside the unit circle.
If there is a root on or inside the unit circle, e.g. if $r =1$ is a root, then the term $1^{-s}$ in $\rho(s)$ clearly does not approach $0$.


text:
Q: Datatables library not working in CodeIgniter 3 I'm trying the Datatables Library on CodeIgniter 3, but it doesn't work in CI3. I've tried this example in CodeIgniter 2 and it works perfectly but I want this library on CodeIgniter 3.
What do I need to change in order for it to work with CodeIgniter 3?

A: create Person_model.php in model directory
<?php defined('BASEPATH') OR exit('No direct script access allowed');
     class Person_model extends CI_Model {
           var $table = 'persons';
           var $column = array('firstname','lastname','gender','address','dob');
          var $order = array('id' => 'desc');

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

     private function _get_datatables_query()
    {
        $this->db->from($this->table);
        $i = 0;
        foreach ($this->column as $item)
        {
            if($_POST['search']['value'])
                ($i===0) ? $this->db->like($item, $_POST['search']['value']) : $this->db->or_like($item, $_POST['search']['value']);
            $column[$i] = $item;
            $i++;
        }

        if(isset($_POST['order']))
        {
            $this->db->order_by($column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
        }
        else if(isset($this->order))
        {
            $order = $this->order;
            $this->db->order_by(key($order), $order[key($order)]);
        }
    }

    function get_datatables()
    {
        $this->_get_datatables_query();
        if($_POST['length'] != -1)
        $this->db->limit($_POST['length'], $_POST['start']);
        $query = $this->db->get();
        return $query->result();
    }

    function count_filtered()
    {
        $this->_get_datatables_query();
        $query = $this->db->get();
        return $query->num_rows();
    }

    public function count_all()
    {
        $this->db->from($this->table);
        return $this->db->count_all_results();
    }

create controller file Person.php
    <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Person extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('person_model','person');
    }

     public function index()
    {
        $this->load->helper('url');
        $this->load->view('person_view');
    }

    public function ajax_list()
    {
        $list = $this->person->get_datatables();
        $data = array();
        $no = $_POST['start'];
        foreach ($list as $person) {
            $no++;
            $row = array();
            $row[] = $person->firstName;
            $row[] = $person->lastName;
            $row[] = $person->gender;
            $row[] = $person->address;
            $row[] = $person->dob;
            $data[] = $row;
        }

        $output = array(
                        "draw" => $_POST['draw'],
                        "recordsTotal" => $this->person->count_all(),
                        "recordsFiltered" => $this->person->count_filtered(),
                        "data" => $data,
                );
        //output to json format
        echo json_encode($output);
    }

and the last create for view. person_view.php at views directory
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Ajax CRUD with Bootstrap modals and Datatables</title>
    <link href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css')?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/datatables/css/dataTables.bootstrap.css')?>" rel="stylesheet">

          First Name
          Last Name
          Gender
          Address
          Date of Birth
          Action

          First Name
          Last Name
          Gender
          Address
          Date of Birth
          Action

the SQL to create table :
create database crud;
   use crud;
   CREATE TABLE persons (
   id int(11) unsigned NOT NULL AUTO_INCREMENT,
   firstName varchar(100) DEFAULT NULL,
   lastName varchar(100) DEFAULT NULL,
    gender enum('male','female') DEFAULT NULL,
    address varchar(200) DEFAULT NULL,
   dob date DEFAULT NULL,
     PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;


text:
Q: Sequential importance sampling for multi way contingency table Full disclosure: this is a homework problem. I'm having a really hard time understanding the algorithm for applying SIS to contingency tables or what it even means to do sequential importance sampling in this case.

So first thing. What is this saying? $\mu = \sum_{T \in \Omega}1_{\{p(T)\le p(T_o)\}}p(T)$
As best as I can make out, it means the sum of the probabilities of all tables $\in \Omega$ with probability $\le p(T_o)$.
So then... I need to simulate all possible tables $\in \Omega$ and determine their respective probabilities. I can determine the probability using $p(T)$ provided.
In that case, how does this come into play?

If someone could just really dumb this down for me that'd be awesome.

A: As another student in Stat 428, I know that this question required a lot of thinking to figure out. Yuguo also went over the basic idea in lecture about a week ago. Basically,

*

*The expression given below is the p-value for the (fisher) exact test.
$$
p = \sum_{T \in \Omega}\mathbb{1}_{p(T)\leq p(T_0)}P(T)
$$
where $$\mathbb{1}_{p(T)\leq p(T_0)}$$ is an indicator function that equals 1 if $p(T) \leq p(T_0)$ and $0$ otherwise. Thus, this is the sum of probabilities that any table $T$ in the total set of possible tables that could exist given the row and column totals (which are considered fixed for these problems) is less likely than $T_0$, the observed table. Thus, using the importance sampling mindset, the target distribution $p(T)$ (which is difficult to sample directly) is weighted by a proposal distribution $g(T)$. For question, we have multinomial sampling for the table, meaning $$
p(T) \propto \frac{1}{\prod_{i}\prod_{j}n_{ij}!}
$$.

The exact test requires the use of the multinomial distribution, therefore, we can choose that as a proposal distribution. In Yuguo's notes (and in his paper he cites at the end of the section), he gives a schematic of how to iterate through the cells of a contingency table, starting at the $t_{11}$ position. You start off by sampling the first value randomly on the proposal distribution (hypergeometric), then calculating the importance weight, then calculating the next position $t_{21}$, then calculating the importance weight ... so on and so forth, for each column. The T.A. actually gives code for the second question in the lab notes section on compass, so it's pretty easy to re-tool it to calculate the p-value. I suggest running the example given in the lab, and looking over the R-Code carefully to get a better idea of what is being asked.
Good luck!


text:
Q: How can I use YouTube API with JS to successfully carry out a search on my web page? I'm trying to carry out a YouTube search on a user-entered keyword in JS. Here is my code:

function onClientLoad() {
    gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}

function onYouTubeApiLoad() {
    gapi.client.setApiKey('AIzaSyCzpZZP564ykVqpun38mS0AbtR0cHoEYE0');
}

function search() {
    var query = document.getElementById('query').value;
    var request = gapi.client.youtube.search.list({
        part: 'snippet',
        q:query
    });
    request.execute(onSearchResponse);
}

function onSearchResponse(response) {
    var responseString = JSON.stringify(response, '', 2);
    document.getElementById('response').innerHTML = responseString;
}
<!DOCTYPE html>

        <input id="query" value='cats' type="text"/>
        <button onclick="search()">Search</button>

I'm getting the error "TypeError: gapi.client is undefined". I haven't used YouTube API before so I would really appreciate any help. What am I doing wrong?


text:
Q: Hierarchical URLs in Django Is there a way to implement hierarchical query pattern in Django? As far as I know, the framework only allows to route to views by parsing URLs of a specific format, like:
/customers/{order} -> customer.views.show_orders(order)

But what if I need something like this:
/book1/chapter1/section1/paragraph1/note5 -> notes.view.show(note_id)

where note_id is the id of the last part of the URL, but the URL could have different number of components:
/book1/chapter1
/book1/chapter1/section1
etc.

Each time, it would point to the relevant part of the book depth depending on the depth. Is this doable?
I know there is this: https://github.com/MrKesn/django-mptt-urls, but I am wondering if there is another solution. This isn't ideal for me.

A: Django URLs are just regular expressions, so the simplest way would be to just ignore everything prior to the "note" section of the URL. For example:
url(r'^.*/note(?P<note_id>[0-9]+)$', 'notes.view.show'),

However, this would ignore the book, chapter, paragraph components. Which would mean your notes would need unique ids across the system, not just within the book. If you needed to capture any number of the interim parts it would be more complicated.
I can't confirm this will work right now, but using non-capture groups in regular expressions, you should be able to capture an optional book and chapter like so:
url(r'^(?:book(?P<book_id>[0-9]+)/)?(?:chapter(?P<chapter_id>[0-9]+)/)?note(?P<note_id>[0-9]+)$', 'notes.view.show'),

A: Use named groups to accomplish this: https://docs.djangoproject.com/en/dev/topics/http/urls/#named-groups
url(r'^book(?P<book_id>\d+)/chapter(?P<chapter_id>\d+)/section(?P<section_id>\d+)/paragraph(?P<paragraph_id>\d+)/note(?P<note_id>\d+)$', notes.view.show(book_id, chapter_id, section_id, paragraph_id, note_id)

A: For those who really need a variable-depth URL structure and need the URL to consist strictly of slugs, not IDs, knowing all the components of the URL is critical to retrieve the correct record from the database. Then, the only solution I can think of is using:
 url(r'^.*/$', notes.views.show, name='show')

and then parsing the content of the URL to get the individual components after retrieving the URL in the view using the request.path call. This doesn't sound ideal, but it is a way to accomplish it.


text:
Q: iOS Apps sharing documents directories Is it possible for two applications to access documents in each other applications given that they have the same bundle seed id. I know that it is possible to share items in the keychain with applications that share a bundle seed id (see here).
For example, let's say you had an application that had a free version and a paid version. Is it possible that after someone has upgraded from the free to the paid version you could migrate their data over to the paid version?

A: You cannot share document directories between applications. But there are other communication channels open.
The keychain is one possibility, as you mentioned.
Another could be custom URL schemes. Maybe a bit like this:

*

*The free app registers the ability to open URLs with the freeapp:// scheme. Similarly the pro app registers the ability to open URLs with the proapp:// scheme. Use the "URL Types" entry in the info plist.

*Pro app checks if [UIApplication canOpenURL:@"freeapp://goPro"] == YES

*If true the pro app calls [UIApplication openURL:@"freeapp://goPro"]

*This launches the free app which must implement handleOpenURL from UIApplication.

*The free app packages the necessary data together in a URL. You can use HTTP-like parameters if you like. You can also build a dictionary and serialize it to a long hex-string using NSCoding.

*The free app passes the data back to the pro app using [UIApplication openURL:@"proapp://YOUR_DATA_IN_WHATEVER_FORMAT"]

*The pro app receives the URL in its overridden implementation of handleOpenURL from UIApplication and performs the necessary data migration.

Obviously you want to use more unique URL schemes than the above.
Consider the security implications of being able to inject this type of data into your app using URLs, though. It's probably OK for many purposes, but I'm sure that if the Facebook app provided a way to nuke your account settings via a URL some people would find it hilarious to post facebookapp://reset_my_account links everywhere.
Bonus tip: URL schemes are also very handy for bridging the gap between native code and web views. I have had a few apps with an embedded web view showing a page on a server under my control. The web page can talk to the app by setting the document location from JS. The app can intercept the request in the web view delegate and talk back to the web view using stringByEvaluatingJavaScriptFromString.


text:
Q: Django fields assign to html fields How to assign Django fields to html fields. Without adding {{form}} in html?
The actual problem that I want my fields to look like this:

But if I use this {{form}}, what I can get is

I've created a custom form, can I assign my input fields from HTML to form class fields in Django?

A: simple answer You can have your own form not use {{ form }} just give the input tag.
<input type="text" name="<your name">

Please note given name must match the your database field.
yes of course you can create the custom form
class YourForm(forms.ModelForm):
    class Meta:
        model = YourModel
        widgets = {
            'your_field': forms.TextInput(attrs={'class': 'yourFieldClass'}),
        }

A: How I solved this problem (it was very simple)

*

*I installed django-widget-tweaks 1.4.1
pip install django-widget-tweaks

*My code started to look like this

{% load widget_tweaks %}
{% csrf_token %}

  {{ form.username | add_class:'form-control' | attr:"placeholder:Username"}}

Note: form.username - username is name of your field in forms.py


text:
Q: DocuSign API: Is it possible to filter envelopes by the value a document field? Assuming I have a field with label FOO in all the envelopes sent, how do I filter the envelopes where the value of FOO is 123456?
I tried setting the search_text parameter with 123456 but it doesn't work.
This is the request I tried to use:
https://demo.docusign.net/restapi/v2.1/accounts/reste_idreste/envelopes?from_date=2021-02-01&search_text=123456

A: Unfortunately, there's not currently a way to search Tabs/Form Data via the API. We do have long term plans in this area, but nothing firm yet. I would pass this request along to your account team to let them know you are interested in learning more about that functionality as it develops.
The ListStatusChanges call doesn't allow you to pull form data in bulk. You'd need to make one GetEnvelope call per envelope with include=recipients,tabs to pull form data and parse through it yourself.
If this is something you are looking at building out, you could use populate a local database using the GetEnvelope results, and then use DocuSign Connect to automatically pass information about new envelopes moving forward.
It is possible to search for values of Envelope Custom Fields. Moving forward, if your application can populate an ECF, you can then search for that to find specific envelopes.


text:
Q: BHO Plugin not working properly I have implement BHO Plugin to detect NUmber from webpage using C#.Every time page loaded append javascript in webpage and that javascript detect number and replaced it with hyperlink number.
Code
 public void  WebBrowser_DownloadComplete()
{
HTMLDocument document = (HTMLDocument)webBrowser.Document;

    IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)
                           document.all.tags("head")).item(null, 0);
    IHTMLScriptElement scriptObject =
      (IHTMLScriptElement)document.createElement("script");
    scriptObject.type = @"text/javascript";
    scriptObject.src = @"myscript.js";
((HTMLHeadElement)head).appendChild((IHTMLDOMNode)scriptObject);

}

Problems
When I test Plugin with offline web pages it is working Fine. But with online pages it is not working. DownloadComplete event triggers multiple time.
Questions
Which event is triggered by IE when page is refresh and loaded?

A: You have to add condition in DocumentLoaded event like below,
if (rootDocLoaded && (HTMLDocument != null) && url != "about:blank"){
  //Your code here
}

Using above condition its called only one after full page loaded. And you can also use beforeNavigate and Navigate method also.


text:
Q: ehCache : Delete keys with prefix I have added the following keys in my ehCache.
cache.put(new Element("MyKey1", List1));
cache.put(new Element("MyKey2", List1));
cache.put(new Element("MyKey3", List1));
cache.put(new Element("MyKey4", List1));

Now I want to remove them all at a time. But I want to do that with the help of key prefix - "MyKey".
Update:
I have managed to do that by the following way -
public static void clearStartWith(String key){
      Ehcache cache = getCache(AC.CACHE_NAME);
      Query query;
      Results results;
      query = cache.createQuery();
      query.includeKeys();
      query.addCriteria(Query.KEY.ilike(key+"*")).end();
      results = query.execute();
      for (Result result : results.all()) {
          cache.remove(result.getKey());
      }
}

But the problem is persistence strategy - localTempSwap does not support this feature. Again for using 'localRestartable'  I need an enterprise version. So I need to use 'none' persistence strategy.


text:
Q: Port range in the argument to PORT command Suppose I want to connect to FTP server, then list root directory in active mode (via PORT command). For this I'm going to use cURL library.
Seems, like cURL provides such capability. There's CURLOPT_FTPPORT option and the official reference says, that the port may be optionally followed by a '-' to specify a port range.
    if (CURL* curl = ::curl_easy_init())
    {
        guard.reset(curl, ::curl_easy_cleanup);

        ::curl_easy_setopt(curl, CURLOPT_URL, "ftp://10.0.0.162:21");
        ::curl_easy_setopt(curl, CURLOPT_FTPPORT, "localhost:37000-38000");

        CURLcode retval = ::curl_easy_perform(curl);
        if (retval != CURLE_OK)
        {
            throw NetworkError(retval, ::curl_easy_strerror(retval));
        }
    }

    ...

But here's a problem.
If the first port in the range is not available, curl_easy_perform fails with CURLE_FTP_PORT_FAILED.
EDIT
Output in verbose mode:
* Rebuilt URL to: ftp://10.0.0.162:21/
* timeout on name lookup is not supported
*   Trying 10.0.0.162...
* Connected to 10.0.0.162 (10.0.0.162) port 21 (#0)
< 220 eugee-server / banner
> USER anonymous
< 331 Anonymous access allowed, send identity (e-mail name) as password.
> PASS ftp@example.com
< 230-Welcome to ftp.eugeeserver
< 230 User logged in.
> PWD
< 257 "/" is current directory.
* Entry path is '/'
* socket failure: Bad access
* Remembering we are in dir ""
* Connection #0 to host 10.0.0.162 left intact


text:
Q: Decodable conformance with property of enum type I have this enum:
enum DealStatus:String {
    case PENDING = "Pending"
    case ACTIVE = "Active"
    case STOP = "Stop"
    case DECLINED = "Declined"
    case PAUSED = "Paused"
}

and struct:
struct ActiveDeals: Decodable {
    let keyword:            String
    let bookingType:        String
    let expiryDate:         Int
    let createdAt:          Int?
    let shopLocation:       String?
    let dealImages:         [DealImages]?
    let dealStatus:         String?
    let startingDate:       Int?
}

In struct I am trying to assign enum as type for dealStatus like this:
struct ActiveDeals: Decodable {
        let keyword:            String
        let bookingType:        String
        let expiryDate:         Int
        let createdAt:          Int?
        let shopLocation:       String?
        let dealImages:         [DealImages]?
        let dealStatus:         DealStatus
        let startingDate:       Int?
    }

But I am getting some compiler error:

Type 'ActiveDeals' does not conform to protocol 'Decodable'
Protocol requires initializer 'init(from:)' with type 'Decodable'
(Swift.Decodable)
Cannot automatically synthesize 'Decodable'
because 'DealStatus' does not conform to 'Decodable'

A: The error says mean that some of the properties of class do not conform to Decodable protocol.
Add Decodable conformance to your enum and it should be fine.
extension DealStatus: Decodable { }

A: According to Federico Zanetello on his post Swift 4 Decodable: Beyond The Basics, Codable and Decobable protocols will works fine if you need to parse a subset of primitives (strings, numbers, bools, etc).
On your case, just making DealStatus conform to Decodable (as suggested by
JeremyP) should solve your problem. You can check on Playgrounds creating your own JSON data and trying to parse it:
import UIKit

enum DealStatus: String, Decodable {
    case PENDING = "Pending"
    case ACTIVE = "Active"
    case STOP = "Stop"
    case DECLINED = "Declined"
    case PAUSED = "Paused"
}

struct ActiveDeals: Decodable {
    let keyword:            String
    let bookingType:        String
    let expiryDate:         Int
    let createdAt:          Int?
    let shopLocation:       String?
    let dealStatus:         DealStatus
    let startingDate:       Int?
}

let json = """
{
    "keyword": "Some keyword",
    "bookingType": "A type",
    "expiryDate": 123456,
    "createdAt": null,
    "shopLocation": null,
    "dealStatus": "Declined",
    "startingDate": 789456
}
""".data(using: .utf8)!

do {
    let deal = try JSONDecoder().decode(ActiveDeals.self, from: json)
    print(deal)
    print(deal.dealStatus)
} catch {
    print("error info: \(error)")
}

And the output will be:
ActiveDeals(keyword: "Some keyword", bookingType: "A type", expiryDate: 123456, createdAt: nil, shopLocation: nil, dealStatus: __lldb_expr_61.DealStatus.DECLINED, startingDate: Optional(789456))
DECLINED

However, to become a better programmer you should always be curious and try to learn how things, so if you are interested on how you could conform to Decodable protocol (let's say you need custom keys, custom errors or some more complex data structure), this is how you can do it:
import UIKit

enum DealStatus: String {
    case PENDING = "Pending"
    case ACTIVE = "Active"
    case STOP = "Stop"
    case DECLINED = "Declined"
    case PAUSED = "Paused"
}

struct ActiveDeals {
    let keyword:            String
    let bookingType:        String
    let expiryDate:         Int
    let createdAt:          Int?
    let shopLocation:       String?
    let dealStatus:         DealStatus
    let startingDate:       Int?
}

extension ActiveDeals: Decodable {
    enum StructKeys: String, CodingKey {
        case keyword = "keyword"
        case bookingType = "booking_type"
        case expiryDate = "expiry_date"
        case createdAt = "created_at"
        case shopLocation = "shop_location"
        case dealStatus = "deal_status"
        case startingDate = "starting_date"
    }

    enum DecodingError: Error {
        case dealStatus
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: StructKeys.self)

        let keyword = try container.decode(String.self, forKey: .keyword)
        let bookingType = try container.decode(String.self, forKey: .bookingType)
        let expiryDate = try container.decode(Int.self, forKey: .expiryDate)
        let createdAt = try container.decode(Int?.self, forKey: .createdAt)
        let shopLocation = try container.decode(String?.self, forKey: .shopLocation)

        //Get deal status as a raw string and then convert to your custom enum
        let dealStatusRaw = try container.decode(String.self, forKey: .dealStatus)
        guard let dealStatus = DealStatus(rawValue: dealStatusRaw) else {
            throw DecodingError.dealStatus
        }

        let startingDate = try container.decode(Int?.self, forKey: .startingDate)

        self.init(keyword: keyword, bookingType: bookingType, expiryDate: expiryDate, createdAt: createdAt, shopLocation: shopLocation, dealStatus: dealStatus, startingDate: startingDate)
    }
}

let json = """
{
    "keyword": "Some keyword",
    "booking_type": "A type",
    "expiry_date": 123456,
    "created_at": null,
    "shop_location": null,
    "deal_status": "Declined",
    "starting_date": 789456
}
""".data(using: .utf8)!

do {
    let deal = try JSONDecoder().decode(ActiveDeals.self, from: json)
    print(deal)
    print(deal.dealStatus)
} catch {
    print("error info: \(error)")
}

In this case the output is still the same:
ActiveDeals(keyword: "Some keyword", bookingType: "A type", expiryDate: 123456, createdAt: nil, shopLocation: nil, dealStatus: __lldb_expr_67.DealStatus.DECLINED, startingDate: Optional(789456))
DECLINED

A: The problem is that Swift can automatically synthesize the methods needed for Decodable only if all the properties of a struct are also Decodable and your enum is not Decodable.
Having just had a go in a playground, it seems you can make your enum Decodable just by declaring that it is and Swift will automatically synthesize the methods for you. i.e.
enum DealStatus:String, Decodable
//                      ^^^^^^^^^ This is all you need
{
    case PENDING = "Pending"
    case ACTIVE = "Active"
    case STOP = "Stop"
    case DECLINED = "Declined"
    case PAUSED = "Paused"
}


text:
Q: How to use elasticsearch.helpers.streaming_bulk Can someone advice how to use function elasticsearch.helpers.streaming_bulk instead elasticsearch.helpers.bulk for indexing data into elasticsearch.
If I simply change streaming_bulk instead of bulk, nothing gets indexed, so I guess it needs to be used in different form.
Code below creates index, type and index data from CSV file in chunks of 500 elemens into elasticsearch. It is working properly but I am wandering is it possible to increse prerformance. That's why I want to try out streaming_bulk function.
Currently I need 10 minutes to index 1 million rows for CSV document of 200MB. I use two machines, Centos 6.6 with 8 CPU-s, x86_64, CPU MHz: 2499.902, Mem: 15.574G total.
Not sure can it go any faster.
es = elasticsearch.Elasticsearch([{'host': 'uxmachine-test', 'port': 9200}])
index_name = 'new_index'
type_name = 'new_type'
mapping = json.loads(open(config["index_mapping"]).read()) #read mapping from json file

es.indices.create(index_name)
es.indices.put_mapping(index=index_name, doc_type=type_name, body=mapping)

with open(file_to_index, 'rb') as csvfile:
    reader = csv.reader(csvfile)        #read documents for indexing from CSV file, more than million rows
    content = {"_index": index_name, "_type": type_name}
    batch_chunks = []
    iterator = 0

    for row in reader:
        var = transform_row_for_indexing(row,fields, index_name, type_name,id_name,id_increment)
        id_increment = id_increment + 1
        #var = transform_row_for_indexing(row,fields, index_name, type_name)
        batch_chunks.append(var)
        if iterator % 500 == 0:
            helpers.bulk(es,batch_chunks)
            del batch_chunks[:]
            print "ispucalo batch"
        iterator = iterator + 1
    # indexing of last batch_chunk
    if len(batch_chunks) != 0:
        helpers.bulk(es,batch_chunks)

A: streaming_bulk consumes an iterator of actions and yields a response for every action.
So you would first need to write a simple iterator over your documents like this:
def document_stream(file_to_index):
    with open(file_to_index, "rb") as csvfile:
        for row in csv.reader(csvfile):
            yield {"_index": index_name,
                   "_type": type_name,
                   "_source": transform_row(row)
                   }

And then to do the streaming bulk insert
stream = document_stream(file_to_index)
for ok, response in streaming_bulk(es, actions = stream):
    if not ok:
        # failure inserting
        print response

A: So streaming bulk returns an interator.  Which means nothing will happen until you start iterating over it.  The code for the 'bulk' function looks like this:
success, failed = 0, 0

# list of errors to be collected is not stats_only
errors = []

for ok, item in streaming_bulk(client, actions, **kwargs):
    # go through request-reponse pairs and detect failures
    if not ok:
        if not stats_only:
            errors.append(item)
        failed += 1
    else:
        success += 1

return success, failed if stats_only else errors

So basically calling just streaming_bulk(client, actions, **kwargs) won't actually do anything.  It's not until you iterate over it as is done in this for loop that the indexing actually starts to happen.
So in your code.  You are welcome to change 'bulk' to 'streaming_bulk' however you need to iterate over the results of streaming bulk in order actually have anything indexed.


text:
Q: Inserting Data into text file in C++ I inserted data into the text file text file used in C++ programme
The data is like this, but it should be in readable form.
Here is the programme
#include<iostream>
#include <fstream>
#include <Windows.h>
#include <string>

using namespace std;

class Record {
    private:
        int id;
        char name[50];
    public:

        void insert_data();
        void show_data();
};

void Record::insert_data() {
    cout << "\n\tName: ";
    cin.ignore();
    cin.getline(name, 50);

    cout << "\n\tID: ";
    cin >> id;
}

void Record::show_data() {
    cout << "\n\tName: ";
    cout << name;
    cout << "\n\tID: ";
    cout << id;
}

void write_info();
void show_info();

int main() {

    //write_info();
    show_info();

    cout << endl;
    system("pause");
}

void write_info() {
    Record info;
    ofstream data("data.txt", ios::app);
    info.insert_data();
    data.write((char *)(&info), sizeof(Record));
    data.close();
} // Function Ends here

void show_info() {
    Record info;
    ifstream data("data.txt", ios::app);
    data.read((char *)(&info), sizeof(Record));
    info.show_data();
    data.close();
}

Why such type of data (which is not readable) been entered into text file?
Please check my programme, if there is an error due to that this unreadable data
is in text file.

A: ifstream data("data.txt", ios::app);

ios::app is the append flag. Don't use it with ifstream. Since you are reading binary data then use ios::binary flag for both ofstream and ifstream.
Evidently, you want to save data in text form (wise choice). Use data >> info.name and data >> info.id to write the data instead.
You can also use std::string name instead of char name[50]. Use std::getline if you want to read the whole line.
class Record {
public:
    int id;
    std::string name;
    void Record::insert_data() {
        cout << "Name: ";
        getline(cin, name); //reads the whole line
        cout << "ID: ";
        cin >> id;
    }

    void Record::show_data() {
        cout << "Name: " << name << ", ID: " << id << "\n";
    }
};

void write_info() {
    Record info;
    info.insert_data();
    ofstream data("data.txt", ios::app);
    data << info.name << "\n" << info.id << "\n";
}

void show_info() {
    Record info;
    ifstream data("data.txt");
    while(true) {
        if(!data.good()) break;
        data >> info.name;
        if(!data.good()) break;
        data >> info.id;
        info.show_data();
    }
}


text:
Q: How to suppress clutter parentheses in output? Dozens of unnecessary parentheses are making my output hard to read.
For example, this:
expr = D[f[x], {x, 2}]^2;

returns this:
(* f"[x]^2  *)
But when I try to tidy up my output:
expr = D[f[x], {x, 2}]^2 /. Derivative[m_][f][x] -> Derivative[m][f]

it adds ()'s I didn't ask for:
(* (f")^2  *)
How do I make those not appear?

A: edit
This form might be better at catching just the desired parentheses
ToBoxes[expr] /. RowBox[{"(", a_SuperscriptBox, ")"}] :> RowBox[{a}]

previous
Not terribly clean, but this works
DisplayForm[ToBoxes[expr] /. {"(" -> "", ")" -> ""}]


text:
Q: App worked on VSCode but didn't after deployed to Lambda, no error in CloudWatch I have this piece of code that runs perfectly fine locally.
But after I deployed it to AWS Lambda, it didn't execute as expected, plus, it did not print any errors to CloudWatch for me to see what had happened.
I assume that it was because of the async/await that caused it but it seems to be correct.
Did anyone witness it before?
module.exports.fetch = async event => {
  const getParametersResponse = await ssm.getParameters({
    Names: [
      "TOKEN",
      "ACCESS_KEY"
    ]
  })

  await axios
    .get(url)
    .then(async (res) => {
      return downloadFile(res.data, project)
    })
    .then(async () => {
      const readStream = await zipFile.openReadStream(entry)
      return sendToDrive(readStream, project, gdriveKey)
    })
    .catch((error) => {
      console.log("error")
    })
};

CloudWatch details:

A: It looks like your function has a timeout set to a too-small value. By default, the timeout is set to 3 seconds, and if I'm not mistaken that's what can be seen in the logs you've pasted. Increase the timeout and the function should be able to execute.


text:
Q: Any finite set of points in in the projective plane can be defined by two polynomials According to an exercise in Shafarevich's Basic Algebraic Geometry I

[Prove that] any finite set of points $S\subset\mathbb{P}^2$ can be defined by two equations.

I need to prove this, but I'm struggling to even work out some examples, e.g.

*

*$\{[1:0:0]\}=\mathbb{V}(y,z)$

*$\{[1:0:0],[0:1:0]\}=\mathbb{V}(xy,z)$

*$\{[1:0:0],[0:1:0],[0:0:1]\}=\mathbb{V}(?,?)$

Any hints for proving the statement, or ideas for coming up with an algorithm for finding the two polynomials? (I would assume that a constructive proof is relatively easy to find, but this question is in the section about dimension in the book, so I'm guessing there might also be some sort of dimensional argument that is not necessarily constructive.)

A: Here is a possible theme. If there is only one  point, there is not much to do, so assume that there are at least two points. So, we may assume that one of the points is $[0:1:0]$ and all other points lie in the affine plane $z\neq 0$. After linear change of variables, you can also assume that the $x$-coordinates of all the points in finite distance are distinct, say $a_1,\ldots, a_n$. Then choose a sufficiently large degree polynomial say of degree $d\geq 2$, $f(x)$ so that $f(a_i)=b_i$, where $(a_i,b_i)$ are the points of interest. Then, let $F(x,z$ be the homogenization of $f$. I claim that the set in question is defined by $yz^{d-1}-F(x,z)$ and $\prod (x-a_iz)$.


text:
Q: Disabled dropdown option didn't work in semantic UI This is my Cshtml

    @Html.LabelFor(modelItem => modelItem.plateNumber)
    @Html.DropDownListFor(m => m.plateNumber, new SelectList(ViewBag.PlateNoList, "Value", "Text"),
    "", new { Class = "ui selection dropdown document-type" })

    @Html.LabelFor(modelItem => modelItem.FuelType)
    @Html.DropDownListFor(m => m.FuelType, new SelectList(ViewBag.FuelType,"Value","Text"),
    "", new { Class = "ui selection dropdown fuel-type",@id="FuelType"/*, @disabled = "true"*/ })

This is my JavaScript
document.getElementById("FuelType").disabled = true;

$('#plateNumber').change(function() {
    $('.ui.dropdown').dropdown();
    document.getElementById("FuelType").disabled = false;
});

When the plateNumber dropdown is selected, the bottom FuelType dropdown should be available, but it cannot be used even though the plateNumber dropdown is selected, any idea?

A: Try removing the disabled class from the dropdown as well. This is checked (and added) internally by SUI.
document.getElementById("FuelType").disabled = true;

$('#plateNumber').change(function() {
    document.getElementById("FuelType").disabled = false;
    $('.ui.dropdown').dropdown();
    $('.ui.dropdown').removeClass('disabled');

});