text:
Q: Why put things in a tuple only to immediately get them out? I have seen this in many places in the .NET framework. Unfortunately, I can't remember the others but they are all in the Katana source code assemblies.
Stuff is put into a tuple and immediately removed / read back out in the same method. This doesn't make any sense to me.
I understand (and also from reading the Wikipedia entry on the subject and having learnt the meaning when studying relational data many years ago) its uses. Just that this particular behavior does not make much sense to me.
public AuthenticationResponseChallenge AuthenticationResponseChallenge
{
    get
    {
        Tuple<string[], IDictionary<string, string>> challengeEntry = this.ChallengeEntry;
        if (challengeEntry == null)
        {
            return null;
        }
        return new AuthenticationResponseChallenge(challengeEntry.Item1, new AuthenticationProperties(challengeEntry.Item2));
    }
    set
    {
        if (value == null)
        {
            this.ChallengeEntry = null;
            return;
        }
        this.ChallengeEntry = Tuple.Create<string[], IDictionary<string, string>>(value.AuthenticationTypes, value.Properties.Dictionary);
    }
}

UPDATE
Okay, sorry, bad example. I've been working too long. I need to an example that illustrates my point. Unfortunately, I've rummaged through so much since morning that I can't remember and will get back to this when I can.

A: In that way, the original tuple this.ChallengeEntry, isn't changed when the set / returned tuple changes.
Along the way, it keeps references to the original items in the tuple, but not the tuple itself.

A: In the example you provided, you have two properties that work together: AuthenticationResponseChallenge and ChallengeEntry.  They can both be accessed at any time, but the values need to be analogous.
The AuthenticationResponseChallenge is calculated from the ChallengeEntry.
I can't answer for why the authors of any library make the design decisions that they do.  I can say that the built in Tuple is convenient for temporary storage when you need any number of values associated together and you don't need the semantics of a dictionary.
In this particular instance, I personally would have done one of two things:

*

*Create my own struct/object with meaningful names for the member elements and a ToAuthenticationResponseChallenge() conversion method and a constructor that accepts an AuthenticationResponseChallenge object.

*Create an extension method or function that does the conversion.


text:
Q: How could a boost::asio::io_service running on 1 thread wake up awaiting condition Thanks for you reply Sam Miller, but i need to implement it on windows.
Look at this example o wrote:
boost::mutex mut;
boost::condition_variable cond;

boost::asio::io_service io_service;

boost::asio::deadline_timer t(io_service);

void test_func()
{
    boost::mutex::scoped_lock lk(mut);
    cond.notify_all();
}

void cancel_test_func()
{
    boost::unique_lock< boost::mutex > lk(mut);
    auto canceled_timers = t.cancel();
    cond.wait(lk);
    printf("Canceled...%u.", canceled_timers);
}

int main(int argc, char* argv[])
{
  try
  {
    t.expires_from_now(boost::posix_time::seconds(5));
    t.async_wait(boost::bind(&test_func));

    io_service.post(boost::bind(cancel_test_func));

    boost::thread_group tg;
    tg.create_thread( boost::bind(&boost::asio::io_service::run, &io_service) );
    //tg.create_thread( boost::bind(&boost::asio::io_service::run, &io_service) );

    getchar();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

To make this example works(cancel the timer) i need to uncomment the second thread creation. With only one thread, i never receive notification.
The question is: is this behavior normal?

A: A condition variable is a synchronous concept, it doesn't integrate well with an event loop like an io_service. If you want asynchronous events on Linux, look at eventfd(2) with with EFD_SEMAPHORE flag for semaphore semantics. I'm not sure if there's an analogous interface on other platforms

redpajama_set_name: RedPajamaStackExchange


text:
Q: VBA - Copy and paste into multiple workbooks if cell = "Y" I'm trying to write some code to do the following:
If a cell says "Y", then open workbooks x, a, b, c, and copy data from workbook x and paste into workbooks a, b, and c.
This will then check to see if another cell says "Y" and repeat the process with another set of workbooks.
I'm having difficulty with two things.  First, I would like to open workbooks based on a filepath name that is in a cell.  For instance, I can get the workbooks to open if I use set x = workbooks.open ("file path name here") but, if I instead put the filepath name in cell "A1" and try set x = workbooks.open ("A1") the macro won't work.  Second, I have no idea how to get the code to skip over the operation if a certain cell isn't labeled "Y".  You can see my attempt in the code but I tried several other things and keep running into issues.
The code I'm linking is just a sample, as my goal is to have this cycle through about 6 primary workbooks, each of the primary will then be copy and pasted into 3-5 sub workbooks.
Thanks in advance for any help on this!!
Sub Foo()
    Dim x As Workbook
    Dim y As Workbook
    Dim z As Workbook

    Dim a As Workbook
    Dim b As Workbook
    Dim c As Workbook
    Dim d As Workbook
    Dim e As Workbook
    Dim f As Workbook
    Dim g As Workbook

    Dim vals As Variant

    'skip these workbooks if N14 is "N"
    If wSheet.Range("N14") = "Y" Then

    '## Open workbooks:
    Set x = Workbooks.Open("A1")
    Set a = Workbooks.Open("A2")
    Set b = Workbooks.Open("A3")
    Set c = Workbooks.Open("A4")

    'Store the value in a variable:
    vals = x.Sheets("Processed Summary").Range("M5:M63").Value

    'Use the variable to assign a value to the other file/sheet:
    a.Sheets("Processed Summary").Range("L5:L63").Value = vals
    b.Sheets("Processed Summary").Range("L5:L63").Value = vals
    c.Sheets("Processed Summary").Range("L5:L63").Value = vals

    If wSheet.Range("N15") = "Y" Then
    Set y = Workbooks.Open("B1")
    Set d = Workbooks.Open("B2")
    Set e = Workbooks.Open("B3")
    Set f = Workbooks.Open("B4")

    'Store the value in a variable:
    vals = y.Sheets("Processed Summary").Range("M5:M63").Value

    'Use the variable to assign a value to the other file/sheet:
    d.Sheets("Processed Summary").Range("L5:L63").Value = vals
    e.Sheets("Processed Summary").Range("L5:L63").Value = vals
    f.Sheets("Processed Summary").Range("L5:L63").Value = vals

    'Close x:
    'x.Close
    'y.Close
    'z.Close
    'a.Close
    'b.Close
    'c.Close
    'd.Close
    'e.Close
    'f.Close
    'g.Close

End Sub

A: You need to specify from where Range is originating. When code is trying to open second workbook Set a = Workbooks.Open(Range("J6").Value), it pulls Range out of cell J6 in workbook x as it is currently active workbook.
Try changing to:
Set a = Workbooks.Open(Workbooks("name.xls").Worksheets("Sheet1").Range("J6").Value)


text:
Q: Get index of an item within mongodb query I have a query which looks like:
function getPage(page) {
  return db.messages.aggregate(
    {
      '$group': {
        _id: "$subjectID"
      }
    },
    { '$skip': page * 20 },
    { '$limit' : 20 });
}

Say I have a subjectID that I know appears somewhere in that collection.  What I want to do is write something like:
function pageOf(subjectID) {
  return Math.floor(db.messages.aggregate(
    {
      '$group': {
        _id: "$subjectID"
      }
    }).indexOf({__id: subjectID}) / 20);
}

Except I have no idea how to write the indexOf part of that query.  I was wondering if mongodb might have some sort of "take while" or "take until" query, then you could do that followed by a count of the number of items.

A: Ordering by subjectID
If your subjectID is (or can be changed to) a monotonically increasing value (for example, a MongoDB default ObjectID), you have a straightforward option using a normal find() with appropriate sort, skip, and limit. In this case you can look for documents with subjectIDs $gte (greater than or equal to) your subjectID:
var page = 1;
var subjectID = ObjectId("515535a0760fe8735f5f6897");
db.users.find(
    { _id: { $gte : subjectID } }
).sort({'_id':1}).skip(page*20).limit(20)

Aggregation Framework
As at MongoDb 2.4, there is no such feature in the Aggregation Framework to match based on the document position in the result pipeline.  You could file a new feature suggestion the MongoDB Jira project's SERVER queue.
It sounds like you would want a new pipeline operator such as a $matchfrom which would ignore any documents until the first occurrence of the $matchfrom criteria.  You could then add a $limit to take the next n items.  You would also want to have sorted output before the $matchfrom so there is a predictable outcome.
This seems overcomplicated compared to having an increasing subjectID, but there may be a use case for doing paging based on more advanced search criteria or results calculated in the aggregation pipeline.
Alternative approaches
Aside from future support for such a feature in the Aggregation Framework, you have a few options to implement the same matching approach in code:

*

*use the older group() aggregation command with a finalize() function.  NOTE: group() does not work with sharded clusters.

*use MapReduce and a finalize() function

*fetch the whole result set from the Aggregation Framework, and implement the matching/reduction of results in your application code (though this somewhat defeats the "paging" notion if you are fetching all pages for every request).
Performance considerations
Queries with skip still have to read through the intervening index entries, so skipping a large number of documents will not be very efficient.
Instead of paging with a skip offset, you could consider doing successive page queries by starting from the last entry of the previous page (i.e. the first page would be $gte the starting subjectID and subsequent pages would be $gt the last subjectID included on the previous page).  This will depend on how you present the paging in your user interface - it would be easiest to use this approach if your UI only has the option to show "next" page of messages rather than jumping to a specific page.


text:
Q: Can RTP payload type be changed in ffmpeg I'm using ffmpeg to generate an RTP stream for testing purposes, but I need to change the RTP payload type to 107. Currently, it's 96.
This is the command I use to generate the stream:
ffmpeg -re -i video.h264 -an -c:v copy -f rtp -sdp_file localhost.sdp "rtp://127.0.0.1:1234"

Is it possible to change the payload type?
Thanks.

A: Use -payload_type 107 before the output url, like: ... -payload_type 107 "rtp://..."


text:
Q: How can Nautilus dropdown and popup notifications be disabled? I recently upgraded to Ubuntu 16.10 and am using Nautilus 3.20.3. I find that Nautilus has changed such that actions like deletions and moves result in dropdown and popup notifications that obscure the current directory view. An example is shown below:

How can these notifications be disabled or otherwise changed so that they do not obscure things?


text:
Q: React filter large dataset without re-render (Too many re-renders error) I have a really large array of objects, parsed (PapaParse) from a CSV:
import { readRemoteFile } from 'react-papaparse'

const [studentData, setStudentData] = useState(null)
const [filteredStudents, setFilteredStudents] = useState([])
const [loading, setLoading] = useState(true)

useEffect(() => {
  grabData()
}, [])

const grabData = () => {
  readRemoteFile('my-data.csv', {
    complete: (results) => { // this method gets called once file is finished parsing
      setStudentData(results.data)
      setLoading(false)
    }
  }
}

I want to filter the student data and only show students with the name 'Amber' for example:
const getFilteredStudents = (name) => {
  let updatedStudents = studentData.filter((student) => {
    return student.name === name
  }
  setFilteredStudents(updatedStudents)
  // Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
}

if (!loading) {
  getFilteredStudents('Amber')
}

In the above codeblock, called setFilteredStudents(updatedStudents) causes a react error.
Finally I just want to render only the filtered students in the component:
render (

  { filteredStudents ?
    filteredStudents.map((student, index) => {

        student.name

    } : null
  }

)

A: This is happening because your are calling
if (!loading) {
  getFilteredStudents('Amber')
}

everytime the component renders, which triggers a new => getFilteredStudents which does => setFilteredStudents resulting into a new re-render and an infinite loop
you should instead do
const grabData = () => {
  readRemoteFile('my-data.csv', {
    complete: (results) => { // this method gets called once file is finished parsing
      setStudentData(results.data);
    }
  }
}

and just call getFilteredStudents('Amber') with a button..

A: The problem was the conditional:
if (!loading) {
  getFilteredStudents('Amber')
}

Removed it and it seems to be working. Now I just need a much better way of rendering the data, because there are about 5000 Amber objects


text:
Q: Convert web form content to PDF using c# in asp.net web forms I'm calling ExportToPDF2 method in a for loop to produce pdf documents.
The problem is the loop stops after the Respons.End().
How can I get this resolved, and is there a better way than using this technique?
private int ExportToPDF2()
{
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
            Page.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
            pdfDoc.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(pdfDoc);
            Response.End();
        }
    }
    return 0;
}

A: It strange to me that you are saving the output of same page (Page.RenderControl(hw);) multiple times!
Anyway, It's not possible to send multiple outputStream from Server, you can try
Response.Write(somefile);
Response.End();
textBox1.Text = "1111"; // it wont work because you can't have multiple outputstream

The best workaround you can have is to make a zip file then do Response.Write(zipFile)
But if you still insist on having them separately(multiple downloads) better you save each file on the server first by:
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
  Page.RenderControl(hw);
  StringReader sr = new StringReader(sw.ToString());
  Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
  PdfWriter.GetInstance(pdfDoc, new FileStream(Server.MapPath("~") + pdfName + ".pdf");
}

then use this trick https://stackoverflow.com/a/30682695/336511 to support multiple download. note that this will work on modern browsers.
var links = [
  'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.exe',
  'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.dmg',
  'https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.jar'
];

function downloadAll(urls) {
  var link = document.createElement('a');

  link.setAttribute('download', null);
  link.style.display = 'none';

  document.body.appendChild(link);

  for (var i = 0; i < urls.length; i++) {
    link.setAttribute('href', urls[i]);
    link.click();
  }

  document.body.removeChild(link);
}
<button onclick="downloadAll(window.links)">Test me!</button>


text:
Q: Printing task names when running ansible adhoc commands I need to run some roles from command line for testing and sometimes I have some adhoc tasks to apply. So I use ansible to run the role. For example:
$ ansible all -i 192.168.1.123,  -m include_role -a"name=myrole" -e '@role.json'

This works fine and prints out a lot of information but it does not print task -name: text. What I mean is the text which is normally printed by ansible-playbook like this:
TASK [Do this and that...]

But ansible does not print this. Without this information, sometimes it is difficult to tell where ansible is exactly. If a task fails, it is difficult to figure out which task failed...
Is there a way to run roles in adhoc fashion and also have more information about exactly which task is running?

A: No, the adhoc ansible script can't print that. Workaround is creating a simple playbook:
---

- hosts: "{{ myhost }}"
  tasks:

  - import_role:
      name: "{{ myrole }}"

Run with:
ansible-playbook /path/roletest.yml -e 'myrole=coolrole myhost=awesomehost' -e '@role.json'


text:
Q: Spring boot Auto Restart Self After JAR Update I have a Spring Boot JAR on a linux server located at some directory /dev/ExampleApplication.jar.
Is it possible for the Spring Boot application to monitor that specific JAR for an update (maybe a change in the checksum), and if there is an update, shut itself down, and start the updated JAR?
I want something like this in pseudo code:
@Scheduled(fixedDelay = 1000)
public void checkForUpdates() {
  long fileChecksum = getJarChecksum();
  if (checksum != fileChecksum) {
    command("java -jar /dev/ExampleApplication.jar");
    context.shutdown();
  }
}

A: You could use inotify-tools to re-launch the jar file any time it is deleted or altered.
You'll need to install inotify-tools on your Linux distro if it is not already.
while inotifywait -e close_write /dev/ExampleApplication.jar; do java -jar /dev/ExampleApplication.jar; done

The -e parameter takes an event type.  You can also watch a directory to see if anything is deleted or created in that directory.  See here for more on the inotifywait event types: https://linux.die.net/man/1/inotifywait


text:
Q: .finally is not a function when using async redux actions with promises I'm writing a redux application using thunk middleware and experienced an issue regarding promises inside the async actions.
db.getLoggedInUser() returns a promise (Bluebird) that is fulfilled with a user object or a null (corresponding to the current logged in user).
If the user is logged in, I would like for fetch some relevant data, where userActions.fetchUserInfo is another async action (like initializeApp).
In the beginning of the process I'm dispatching a 'start_loading' action and after the all process is done - I'm dispatching a 'stop_loading' action.
export const initializeApp = () => dispatch => {
  dispatch(loadingActions.startLoading());

  return db.getLoggedInUser()
    .then((user) => {
      if (user) {
        return dispatch(userActions.fetchUserInfo(user.id));
      }
    })
    .catch(dbError => dispatch(errorActions.reportError(dbError.message)))
    .finally(() => dispatch(loadingActions.stopLoading()));
};

When dispatching initializeApp() I'm getting the following error:

db.getLoggedInUser(...).then(...).catch(...).finally is not a function

I'm getting this error regardless the resolved value of getLoggedInUser().
Anyone has an idea?


text:
Q: Populating Select List including OptGroup I'm populating a select list with an array of data. Like this:
$(somedata).each(function() {
    $(document.createElement('option'))
        .attr('value', this.Value)
        .text(this.Text)
        .appendTo(SelectList);
});

How do I append optgroups in the same way? the array of data is a list with the properties Text, Value, OptGroup (boolean) and ordered so the OptGroup comes first followed by it's options. Like this:
[
    ['OptGroup1', 'OptGroup1', true]
    ['Value1', 'Value1', false]
    ['Value2','Value2',false]
    ['OptGroup2', 'OptGroup2', true]
    // ...
]

A: The answer is pretty straightforward - check if 3rd value is true or false and create the proper element accordingly.
a few points though:

*

*optgroups are appended to the select, while options need to be appended to the last optgroup that you have added. an optgroup is a container of options, and not a title that comes before them.

*the text on the optgroup is set by the label="" attribute, and not value/text.

$(function () {
    var somedata = [
        ['OptGroup1', 'OptGroup1', true],
        ['Value1', 'Value1', false],
        ['Value2', 'Value2', false],
        ['OptGroup2', 'OptGroup2', true],
        ['Value3', 'Value3', false],
        ['Value4', 'Value4', false]
    ];
    console.log(somedata);
    var SelectList = $("#SelectList");
    $(somedata).each(function () {
        var $newElem;
        if ($(this)[2] == false) {
            $newElem = $(document.createElement('option')).attr('value', this[1])
            .attr('label', this[0])
            .appendTo(SelectList.find("optgroup").last());
        } else {
            $newElem = $(document.createElement('optgroup')).attr('value', this[1])
            .attr('label', this[0])
            .appendTo(SelectList);;
        }

    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="SelectList"></select>


text:
Q: Laravel error after [composer update=>commit=>push=>pull] Well, I added a package, "guzzlehttp/guzzle": "~5.3|~6.0" to be specific, inside my laravel app, and updated(for sending email). Then I committed the changes to the local repo (git), and pushed to the remote repo on Bitbucket. And finally I pulled the changes on my VPS server. It's worth mentioning that I have done this same process a hundred times without any problems whatsoever and I don't have any clue why it's being such a jerk this time :-|
OK, here's the problem: Blank white screen screen and when I do error_reporting(E_ALL); ini_set.... I get this error message:
Warning: require(/home/.../vendor/guzzlehttp/promises/src/functions_include.php): failed to open stream: No such file or directory in /home/.../vendor/composer/autoload_real.php on line 54

Fatal error: require(): Failed opening required '/home/.../vendor/guzzlehttp/promises/src/functions_include.php' (include_path='.:/usr/share/php:/usr/share/pear') in /home/.../vendor/composer/autoload_real.php on line 54

Oh, and by the way, the project is totally working fine on my local machine without any problems.
Thanks a lot, appreciate it :-)
EDIT:
I also tried running these:

*

*running composer update

*deleting vender/ and composer.lock and
then running the above command

and they didn't work because I saw the same error during the execution of composer update because it was calling artisan.

A: Thanks to aldrin27 I solved the error by dumping the autoloads using:
composer dump-autoload

But then there was this error:
Trait 'Illuminate\Database\DetectsLostConnections' not found

For some odd reason that file was missing and I had to create it manually to fix the problem.


text:
Q: .txt file is acting weird under readlines() The contents of the file look like this:
1/15/13,930,1441.5
1/15/13,1000,1442.75
1/15/13,1030,1444

I run:
the_txt_file = open('/txt_file')

Then I run:
the_txt_file_as_a_list =  the_txt_file.readlines()

Then I run:
print the_txt_file_as_a_list

And I get this:
['1/15/13,930,1441.5\r1/15/13,1000,1442.75\r1/15/13,1030,1444\r1/']

But I was expecting something like:
['1/15/13,930,1441.5\n','15/13,1000,1442.75\n','15/13,1030,1444\n']

This happens to me pretty frequently, what is going on?

A: So it seems that the problem had something to do with the way my mac interacted with the .txt file
The problem was fixed by swapping:
the_txt_file = open('/txt_file')

with:
the_txt_file = open('/txt_file', 'rU')

The 'rU' is called 'universal-readline'. Opening a file in 'rU' mode is opening a file in Universal readline mode. Upon running:
the_txt_file_as_a_list =  the_txt_file.readlines()

and then:
print the_txt_file_as_a_list

my output went from:
['1/15/13,930,1441.5\r1/15/13,1000,1442.75\r1/15/13,1030,1444\r1/']

to:
['1/15/13,930,1441.5\n', '1/15/13,1000,1442.75\n', '1/15/13,1030,1444\n']

Later, I was able to print each item seperatly by:
for item in the_txt_file_as_a_list:
    print item

The output looked like:
1/15/13,930,1441.5

1/15/13,1000,1442.75

1/15/13,1030,1444

A: I would assume that you, or the original creator of this data file were on a Mac. Seems you are expecting it to be a simple '\n' line ending, but suffer from the originating editors system default line ending (most likely).
An easy fix, is to call open(...) with the rU option like so:
the_txt_file = open('/txt_file', 'rU')
This ensures that the file is opened read only, and uses Universal newline support when reading the particular file.
Good luck!


text:
Q: Imagick php not printing hindi utf8 characters correctly I have user imagick to printsome names from my mysql db to an image
    $data = Common::getCandidatesForIdCard();
    mkdir($data[0]['ulbRegion'], 0777, true);
    for($i=0; $i<1; $i++) {
        $image = new Imagick("image/img.jpeg");
        $draw = new ImagickDraw();

        /* Font properties */
        $draw->setFont('fonts/MANGAL.TTF');
        $draw->setFontSize(30);
        $draw->setTextEncoding('UTF-8');

        /* Create text */
        $address = Common::getFormattedAddress($data[$i]['permanentAddress']);
        $line1 = $address[0]." ".$address[1]." ".$address[2]." ".$address[3]." ".$address[4];
        $line2 = $address[5]." ".$address[6]." ".$address[7]." ".$address[8]." ".$address[9];
        $image->annotateImage($draw, 320, 740, 0, $data[$i]['name']);
        $image->annotateImage($draw, 320, 840, 0, $data[$i]['guardian']);
        $image->annotateImage($draw, 320, 940, 0, $line1);
        $image->annotateImage($draw, 60, 1040, 0, $line2);
        $image->annotateImage($draw, 320, 1140, 0, $data[$i]['ulbRegion']);

        /* Give image a format */
        $image->setImageFormat('png');
        $image->minifyImage();

        header('Content-type: image/png');
        file_put_contents($data[0]['ulbRegion']."/imagick_ouput_".$i.".png" , $image);
    }

But the issue is the text on the image is not printing correctly ....
i.e instead of अमित it is printing अमति


text:
Q: ssh tunnel to remote dockerized mongo server I have a mongo docker instance  running on a remote server, what is the correct way to access the command line from my local machine?
If i login to the remote host, i can access this by:
$ docker exec -it mongo-dev mongo ccc-mongo
but i am unsure how to do this from my local machine.
I tried this:
$ ssh -L 4321:localhost:27017 khine@ccc1 -f -N

Are you sure you want to continue connecting (yes/no)? yes
khine@ccc1's password:
khine@dhegdheer:~/Sandboxes/$ mongo --port 4321
MongoDB shell version: 2.4.9
connecting to: 127.0.0.1:4321/test
channel 2: open failed: connect failed: Connection refused
Wed Sep  9 15:36:44.386 DBClientCursor::init call() failed
Wed Sep  9 15:36:44.388 Error: DBClientBase::findN: transport error: 127.0.0.1:4321 ns: admin.$cmd query: { whatsmyuri: 1 } at src/mongo/shell/mongo.js:147
exception: connect failed

on my remote machine i have 3 mongo instances running
khine@ccc1 /ccc $ docker ps
CONTAINER ID        IMAGE                        COMMAND                CREATED             STATUS              PORTS                                      NAMES

22a32b4f6a1d        redis:2.8                    "/entrypoint.sh redi   7 days ago          Up 7 days           6379/tcp                                   redis-web
167b022ab793        mongo:2.4                    "/entrypoint.sh mong   7 days ago          Up 7 days           27017/tcp                                  mongo-web
ab84ea6cb44a        redis:2.8                    "/entrypoint.sh redi   2 weeks ago         Up 2 weeks          6379/tcp                                   redis-www
04dcc306af04        redis:2.8                    "/entrypoint.sh redi   2 weeks ago         Up 2 weeks          6379/tcp                                   redis-dev
02c0c18307dc        mongo:2.4                    "/entrypoint.sh mong   2 weeks ago         Up 2 weeks          27017/tcp                                  mongo-www
61df69ec7edb        mongo:2.4                    "/entrypoint.sh mong   2 weeks ago         Up 2 weeks          27017/tcp                                  mongo-dev

running docker inspect, i get this:
khine@ccc1 /ccc $ docker inspect 61df69ec7edb
[{
    "AppArmorProfile": "",
    "Args": [
        "mongod"
    ],
    "Config": {
        "AttachStderr": false,
        "AttachStdin": false,
        "AttachStdout": false,
        "Cmd": [
            "mongod"
        ],
        "CpuShares": 0,
        "Cpuset": "",
        "Domainname": "",
        "Entrypoint": [
            "/entrypoint.sh"
        ],
        "Env": [
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
            "MONGO_VERSION=2.4.14"
        ],
        "ExposedPorts": {
            "27017/tcp": {}
        },
        "Hostname": "61df69ec7edb",
        "Image": "mongo:2.4",

    "HostConfig": {
        "Binds": [
            "/ccc/mongo-data/dev:/data/db"
        ],
        "CapAdd": null,
        "CapDrop": null,
        "CgroupParent": "",

    "Name": "/mongo-dev",
    "NetworkSettings": {
        "Bridge": "docker0",
        "Gateway": "172.17.42.1",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "IPAddress": "172.17.0.34",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "LinkLocalIPv6Address": "fe80::42:acff:fe11:22",
        "LinkLocalIPv6PrefixLen": 64,
        "MacAddress": "02:42:ac:11:00:22",
        "PortMapping": null,
        "Ports": {
            "27017/tcp": null
        }
    },
    "Path": "/entrypoint.sh",
    "ProcessLabel": "",
    "ResolvConfPath": "/var/lib/docker/containers/61df69ec7edb6995f06d797f5b2eed420d0c4daa4cd089c3b9174900d72d0b13/resolv.conf",
    "RestartCount": 0,
    "State": {
        "Dead": false,
        "Error": "",
        "ExitCode": 0,
        "FinishedAt": "0001-01-01T00:00:00Z",
        "OOMKilled": false,
        "Paused": false,
        "Pid": 15346,
        "Restarting": false,
        "Running": true,
        "StartedAt": "2015-08-26T06:01:55.361817334Z"
    },
    "Volumes": {
        "/data/db": "/ccc/mongo-data/dev"
    },
    "VolumesRW": {
        "/data/db": true
    }
}
]

if i add the IP address for the instance, i get this warning
$ Warning: remote port forwarding failed for listen port 4321
any advice much appreciated.


text:
Q: Solr commands not returning json output I was going through the php documentation for solr and wanted to try out the basic example. But the expected output isn't received and a blank page is returned when i try the following code with my existing project.
<?php
include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login'    => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('ID', 334455);
//$doc->addField('cat', 'Software');
//$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

print_r($updateResponse->getResponse());

?>

The bootstrap.php goes something like this:

/* Domain name of the Solr server */
define('SOLR_SERVER_HOSTNAME', 'localhost');

/* Whether or not to run in secure mode */
define('SOLR_SECURE', false);

/* HTTP Port to connection */
define('SOLR_SERVER_PORT', ((SOLR_SECURE) ? 8443 : 8080));

/* HTTP Basic Authentication Username */
define('SOLR_SERVER_USERNAME', 'admin');

/* HTTP Basic Authentication password */
define('SOLR_SERVER_PASSWORD', 'changeit');

/* HTTP connection timeout */
/* This is maximum time in seconds allowed for the http data transfer operation.Default value is 30 seconds */
define('SOLR_SERVER_TIMEOUT', 10);

/* File name to a PEM-formatted private key + private certificate (concatenated in that    order) */
define('SOLR_SSL_CERT', 'certs/combo.pem');

/* File name to a PEM-formatted private certificate only */
define('SOLR_SSL_CERT_ONLY', 'certs/solr.crt');

/* File name to a PEM-formatted private key */
define('SOLR_SSL_KEY', 'certs/solr.key');

/* Password for PEM-formatted private key file */
define('SOLR_SSL_KEYPASSWORD', 'StrongAndSecurePassword');

/* Name of file holding one or more CA certificates to verify peer with*/
define('SOLR_SSL_CAINFO', 'certs/cacert.crt');

/* Name of directory holding multiple CA certificates to verify peer with */
define('SOLR_SSL_CAPATH', 'certs/');

?>

I'm using the tomcat username and password for solr_server_username/password. and solr is working fine otherwise on the UI. I am using solr 4.6.1 with php solrclient 1.0.2
    <?php

// make sure browsers see this page as utf-8 encoded HTML
header('Content-Type: text/html; charset=utf-8');

$limit = 10;
$query = isset($_REQUEST['q']) ? $_REQUEST['q'] : false;
$results = false;

if ($query)
{
  // The Apache Solr Client library should be on the include path
  // which is usually most easily accomplished by placing in the
  // same directory as this script ( . or current directory is a default
  // php include path entry in the php.ini)
  require_once('/usr/local/apache-tomcat-7.0.50/SolrPhpClient/Apache/Solr/Service.php');

  // create a new solr service instance - host, port, and webapp
  // path (all defaults in this example)
  $solr = new Apache_Solr_Service('localhost', 8080, '/solr/collection1');

  // if magic quotes is enabled then stripslashes will be needed
  if (get_magic_quotes_gpc() == 1)
  {
    $query = stripslashes($query);
  }

  // in production code you'll always want to use a try /catch for any
  // possible exceptions emitted  by searching (i.e. connection
  // problems or a query parsing error)
  try
  {
    $results = $solr->search($query, 0, $limit);
  }
  catch (Exception $e)
  {
    // in production you'd probably log or email this error to an admin
        // and then show a special message to the user but for this example
        // we're going to show the full exception

        die("<title>SEARCH EXCEPTION</title>
{$e->__toString()}
");
  }
}

?>

    <title>PHP Solr Client Example</title>

ABCD

    <form  accept-charset="utf-8" method="get">
      Search:
      <input id="q" name="q" type="text" value="<?php echo htmlspecialchars($query, ENT_QUOTES, 'utf-8'); ?>"/>
      <input type="submit"/>
    </form>
<?php

// display results
if ($results)
{
  $total = (int) $results->response->numFound;
  $start = min(1, $total);
  $end = min($limit, $total);
?>

Results <?php echo $start; ?> - <?php echo $end;?> of <?php echo $total; ?>:

<?php
  // iterate result documents
  foreach ($results->response->docs as $doc)
  {
?>

<?php
    // iterate document fields / values
    foreach ($doc as $field => $value)
    {
?>

            <?php echo htmlspecialchars($field, ENT_NOQUOTES, 'utf-8'); ?>
            <?php echo htmlspecialchars($value, ENT_NOQUOTES, 'utf-8'); ?>

    <?php
    }
    ?>

    <?php
  }
?>

    <?php
    }?>

While trying the above alternative code, the following error is encountered:

exception 'Apache_Solr_HttpTransportException' with message ''0'
  Status: Communication Error' in
  /usr/local/apache-tomcat-7.0.50/SolrPhpClient/Apache/Solr/Service.php:338
  Stack trace:
0 /usr/local/apache-tomcat-7.0.50/SolrPhpClient/Apache/Solr/Service.php(1170):
Apache_Solr_Service->_sendRawGet - ('http://localhos...')
1 /var/www/html/testproject/tryout.php(33): Apache_Solr_Service->search('abhilash', 0, 10)
2 {main}

A: Solr's default response writer is XML.
If you want to get back your results in JSON, you should specify it by defining the URL parameter wt=json
Example
http://localhost:8983/solr/customers/select?q=customerSearchName&wt=json

Make sure that you do so.

A: You need to add
'wt' => 'json'

to the array you pass into SolrClient()
See http://php.net/manual/en/solrclient.construct.php


text:
Q: Thread local RefCell as replacement to local variable in Rust I'm new to Rust.
I'm trying to implement alternative to private variable inside classes to keep Postgres connection inside Struct. Currently I have:
    thread_local! {

        static CONNECTION: RefCell<Option<Connection>> = RefCell::new(None);
    }

Than I initialize it like this:
        PostgresDb::CONNECTION.with(|pg_connection| {
            *pg_connection.borrow_mut() = Some(connection)
        });

It works fine.
But when I try to execute some query on it like this:
PostgresDb::CONNECTION.with(|pg_connection| {
            *pg_connection.borrow_mut().map(|conn| conn.execute("Select * from test", &[]));
}

I'm getting:
type `std::option::Option<Result<u64, psql::Error>>` cannot be dereferenced

If I change it to:
PostgresDb::CONNECTION.with(|pg_connection| {
            pg_connection.borrow_mut().map(|conn| conn.execute("Select * from test", &[]));

I'm getting:
cannot move out of dereference of `RefMut<'_, std::option::Option<psql::Connection>>`
move occurs because value has type `std::option::Option<psql::Connection>`, which does not implement the `Copy` trait

What should I change to make it work?

A: The problem is that Option::map() consumes the option in order to pass the closure it receives the content of the option. Since conn.execute only needs a (mutable) reference to the option contents, you can create a new Option whose content references the contents of the original one, and pass that to map(). This is easiest to accomplish with the Option::as_mut() convenience method:
pg_connection.borrow_mut().as_mut().map(|conn| conn.execute(...));

In most cases the error "cannot move out of ... Option" can be resolved with the use of Option::as_ref or Option::as_mut.


text:
Q: How to display loading spinner during image load with Url.Action Method in Razor/C#? I'm currently loading an image through an API call in my Index.cshtml with this code:
<img src="@Url.Action("ImageFromAPI")" width="500px" />

This calls my HomeController.cs:
public ActionResult ImageFromAPI()
{
    var client = new RestClient("http://IP-ADDRESS/snapshot.cgi?channel=0");
    var request = new RestRequest(Method.GET);
    request.AddHeader("cache-control", "no-cache");
    request.AddHeader("authorization", "Basic Xwjk15j5oi1gsdg");
    IRestResponse response = client.Execute(request);

    if (response == null)
    {
        var ms = new MemoryStream();
        using (Bitmap bitmap = new Bitmap("~/img/404.jpg"))
        {
            bitmap.Save(ms, ImageFormat.Jpeg);
        }

        ms.Position = 0;
        return File(ms, "image/jpg");
    }
    else
    {
        return File(response.RawBytes, "image/png");
    }
}

To explain what's going on - I'm calling my API through the RestClient and seeing if it returns something. If so, I output the image to the page, if not, I output the 404 jpg to the page.
The problem is, during the Url.Action call (sometimes it takes more than just a second or two), there's no "Image is loading.." substitute.
Is there a proper way to do this? Any/or is there a better way?

A: I would not load the image directly from a call to the server side.  I would set all images being loaded to some "loading" image on page load and create some functionality with your client side framework to make a call to this action on your server side and replace the loading image with the fully loaded image once it has been received by the client side.


text:
Q: Auto-correct case spelling of a word database I am stuck on a seemingly simple Python problem since 2 days.
It involves updating a 'database' of mixed string/tuple sequences (with always the same structure) but with case-sensitive mistake correction.
For instance the database is:
[['Abc',  ('Def',  'Ghi'),  'Jkl'],
 ['Abc',  ('Def',  'Mno'),  'Pqr'],
 ['123',  ('456',  '789'),  '012'],
 ['ToTo', ('TiTi', 'TaTa'), 'TeTe']]

Now if I input another sequence with same words but different case, I would like it to be corrected automatically:
['abc',  ('def',  'ghi'),  'jkl']  ->  ['Abc', ('Def',  'Ghi'),  'Jkl']
['abc',  ('def',  'XYZ'),  'jkl']  ->  ['Abc', ('Def',  'XYZ'),  'jkl']
['abc',  ('titi', 'tata'), 'tete'] ->  ['Abc', ('titi', 'tata'), 'tete']

So the items should be corrected as long as we don't meet a different word.
The real problem is that each item can be a string or a tuple, otherwise it won't be so difficult.
I've tried using a 'flatten' function and check items per items, and then rebuild the original structure but the processing is too heavy (database can grow to more 50 000 sequences).
Do someone know some magic trick in Python which would help my current problem ?
Thanks a lot !

A: Try NLTK using Brown and PorterStemmer. Brown have a very wide word list and a pre-learned stemmer.
Example:
from nltk import PorterStemmer
from nltk.corpus import brown

import sys
from collections import defaultdict
import operator

def sortby(nlist ,n, reverse=0):
    nlist.sort(key=operator.itemgetter(n), reverse=reverse)

class mydict(dict):
    def __missing__(self, key):
        return 0

class DidYouMean:
    def __init__(self):
        self.stemmer = PorterStemmer()

    def specialhash(self, s):
        s = s.lower()
        s = s.replace("z", "s")
        s = s.replace("h", "")
        for i in [chr(ord("a") + i) for i in range(26)]:
            s = s.replace(i+i, i)
        s = self.stemmer.stem(s)
        return s

    def test(self, token):
        hashed = self.specialhash(token)
        if hashed in self.learned:
            words = self.learned[hashed].items()
            sortby(words, 1, reverse=1)
            if token in [i[0] for i in words]:
                return 'This word seems OK'
            else:
                if len(words) == 1:
                    return 'Did you mean "%s" ?' % words[0][0]
                else:
                    return 'Did you mean "%s" ? (or %s)' \
                           % (words[0][0], ", ".join(['"'+i[0]+'"' \
                                                      for i in words[1:]]))
        return "I can't found similar word in my learned db"

    def learn(self, listofsentences=[], n=2000):
        self.learned = defaultdict(mydict)
        if listofsentences == []:
            listofsentences = brown.sents()
        for i, sent in enumerate(listofsentences):
            if i >= n: # Limit to the first nth sentences of the corpus
                break
            for word in sent:
                self.learned[self.specialhash(word)][word.lower()] += 1

def demo():
    d = DidYouMean()
    d.learn()
    # choice of words to be relevant related to the brown corpus
    for i in "birdd, oklaoma, emphasise, bird, carot".split(", "):
        print i, "-", d.test(i)

if __name__ == "__main__":
    demo()

Install:
http://www.nltk.org/install.html
You will need the data as well to get this working:
http://www.nltk.org/data.html
Good luck!

A: You should define a function like this:
def capitalize(structure):
    return [structure[0].capitalize(), (structure[1][0].capitalize(), structure[1][0].capitalize()), structure[2].capitalize()]

However this is a very ugly solution. You should probably think at another way to represent data in a more clever way.

A: I'd suggest using a dictionary to convert your words from some generic form (perhaps all lowercase) to the "correct" form that you want to have all items use in the database. Since the path to a word matters, I suggest using a tuple including all the previous normalized paths as the key into the dictionary:
_corrections = {}

def autocorrect(sequence):
    normalized = () # used as keys into _autocorrection_dict
    corrected = []  # values from _autocorrection_dict
    for item in sequence:
        if isinstance(item, str):
            normalized += (item.lower(),)
            corrected = _corrections.setdefault(normalized, corrected + [item])

        elif isinstance(item, tuple):
            sub_norm = tuple(subitem.lower() for subitem in item)
            if normalized + (sub_norm,) not in _corrections:
                sub_corrected = ()
                for subitem in item:
                    sub_result = _corrections.setdefault(normalized + (subitem.lower(),),
                                                         corrected + [subitem])
                    sub_corrected += (sub_result[-1],)
                _corrections[normalized + (sub_norm,)] = corrected + [sub_corrected]
            normalized += (sub_norm,)
            corrected = _corrections[normalized]

        else:
            raise TypeError("Unexpected item type: {}".format(type(item).__name__))

    return corrected

The first part of this code (the if block) handles simple string values. It should be fairly easy to understand. It builds up a tuple of "normalized" values, which is just the strings seen so far in all lowercase. The normalized tuple is used as a key into the _corrections dictionary, where we store the "correct" result. The magic happens in the setdefault call, which creates a new entry if one doesn't already exist.
The second part of the code (the elif block) is the much more complicated bit for dealing with tuple values. First we normalize all the strings in the tuple, and check if we already have a result for it (this lets us avoid the rest if we've already seen this exact tuple). If not, we have to check if there are previously saved results for each of the subitems in the tuple (so ["foo", ("BAR", "BAZ")] will have "BAR" and "BAZ" corrected if there were already entries for ["foo", "bar"] and ["foo", "baz"]). Once we've found correct values for each of the subitems in the tuple, we can put them all together and then add the combined result to the dictionary. Making the short circuiting part work is a bit awkward, but I think it's worth it.
Here's an example session using the code:
>>> autocorrect(['Abc',  ('Def',  'Ghi'),  'Jkl'])
['Abc', ('Def', 'Ghi'), 'Jkl']
>>> autocorrect(['ABC', ("DEF", "GGGG"), "JKL"])
['Abc', ('Def', 'GGGG'), 'JKL']
>>> autocorrect(['abC', 'gggg', 'jkL'])
['Abc', 'GGGG', 'jkL']

"Abc" is always put into the same form, and "Def" and "GGGG" are too, when they are used. the different forms of "Jkl" however don't ever get modified, since they're each following a different earlier value.
While this is perhaps the best solution if your database can't be changed, a much easier approach would be to simply force all of your data into the same normalization scheme. You could probably write some fairly simple code to go through your existing data to make it all consistent, then just normalize each new item you get without there being any need to worry about what the previous entries were.


text:
Q: How can I resolve Digital Envelope Errors on a Windows OpenSSL configuration? I've read all of the same documents, questions online, Stack overflow "answers", and not a single, useful solution has ever been posted for a WINDOWS OPENSSL Configuration.
NodeJS 16.16 installed, with all of the chocolatey add ons and such. Tried this on two separate Windows machines with the exact same results
How do you solve this on Windows?  This is such a simple task, there's absolutely nothing on any website that I've been able to find to resolve it.  Most sites have been telling me to modify the "package.json" file... The question is, which one?  There are quite literally hundreds of them in the nodejs installation directory...
C:\temp>openssl pkcs12 -in certname.pfx -out file.nokey.pem -nokeys
Enter Import Password:
Error outputting keys and certificates
F4480000:error:0308010C:digital envelope routines:inner_evp_generic_fetch:unsupported:crypto\evp\evp_fetch.c:349:Global default library context, Algorithm (RC2-40-CBC : 0), Properties ()

Any help is appreciated, my head is spinning


text:
Q: How would I convert this into laravel query builder format? I have a query that works using regular sql notation but having a hard time converting it to laravel builder notation.
Query:
SELECT Course.CourseName
     , SUM(CASE WHEN StudentID <> 0 THEN 1 ELSE 0 END) As InClass
     , Instructor.InstructorFirstName
     , ProgramName
     , SemesterTaught
 FROM program
      JOIN course
        ON program.ProgramID = course.ProgramID
      JOIN (SELECT CourseID
                 , SemesterTaught
              FROM classtime
            GROUP BY CourseID, SemesterTaught) AS classtime
        ON course.CourseID = classtime.CourseID
      LEFT JOIN (SELECT InstructorID
                      , CourseID
                      , StudentID
                   FROM enrolled) AS enrolled
             ON classtime.CourseID = enrolled.CourseID
      LEFT JOIN instructor
             ON enrolled.InstructorID = instructor.InstructorID
GROUP BY CourseName, InstructorFirstName, SemesterTaught, ProgramName

What I've tried:
DB::table('programs')
->select('courses.CourseName', 'SUM(CASE WHEN StudentID <> 0 THEN 1 ELSE 0 END AS StudentsInClass', 'instructors.InstructorFirstName', 'ProgramName', 'SemesterTaught')
->join('courses', 'programs.ProgramID', '=', 'course.ProgramID')
->join(DB::raw('(SELECT CourseID, SemesterTaught FROM classtimes GROUP BY CourseID, SemesterTaught) AS classtimes'), 'courses.CourseID', '=', 'classtimes.CourseID')
->leftJoin(DB::raw('(SELECT InstructorID, CourseID, StudentID FROM enrolleds) AS enrolled'), 'classtimes.CourseID', '=', 'enrolled.CourseID')
->leftJoin('instructors', 'enrolled.InstructorID', '=', 'instructors.InstructorID')
->groupBy('courses.CourseName', 'instructors.InstructorFirstName', 'SemesterTaught', 'ProgramName')->get();

I would like to achieve this query using laravel query builder syntax and try to avoid using DB::raw if possible. I also am trying to figure out how to use the aggregate function in my select cause without getting the "column doesn't exists error."

A: Figured out the answer to getting the query to work if anyone in the future see's this:
DB::table('programs')
->select('courses.CourseName', DB::raw('SUM(CASE WHEN StudentID <> 0 THEN 1 ELSE 0 END) AS StudentsInClass'), 'instructors.InstructorFirstName', 'ProgramName', 'SemesterTaught')
->join('courses', 'programs.ProgramID', '=', 'courses.Program')
->leftJoin(DB::raw('(SELECT CourseID, SemesterTaught FROM class_times GROUP BY CourseID, SemesterTaught) AS classtimes'), 'courses.CourseID', '=', 'classtimes.CourseID')
->leftJoin(DB::raw('(SELECT InstructorID, CourseID, StudentID FROM enrolleds) AS enrolled'), 'classtimes.CourseID', '=', 'enrolled.CourseID')
->leftJoin('instructors', 'enrolled.InstructorID', '=', 'instructors.InstructorID')
->groupBy('courses.CourseName', 'instructors.InstructorFirstName', 'SemesterTaught', 'ProgramName')->get();


text:
Q: After shuffling the positions of an array traversing it becomes a lot slower, why is that? I have a big array with teams (1M). Each of those teams has 10 elements.
The pool of elements is stored in a map (id -> { id, points }).
If I calculate the points for each team it's pretty fast (as expected).
But if then I alter the array the calculation of the points performance decreases for around 5x.
Does someone has an idea what could be the issue? Here's the code if you want to have a look: https://playcode.io/656462/

A: When you create an array for the first time, most of the memory is alloted consecutively.
Each element points towards the immediate next which is probably consecutively stored in memory. Once you shuffle the array, the values stay at the same addresses. Only the corresponding pointers change. So now your memory is not sequential. It's randomly spread.
Now when you try to traverse it, computer hardware takes more time to find those randomly spread memory locations than it would in a sequential memory. You wouldn't notice this with small arrays but this will be a factor when you're working on huge data like in your case.
I didn't really find a source on the internet to back my answer, I would have commented this rather than answering but I don't have enough reputation. This answer is based on my understanding of CS


text:
Q: How to use OR in the PHP language <?php
$con = mysqli_connect('localhost', 'root', '');
if(!$con)
{
    die("not ok");
}

mysqli_select_db($con,"uoh");
$q = "SELECT * FROM courses
LEFT JOIN degree_plan ON degree_plan.course_number= courses.course_number
LEFT JOIN student_record ON courses.course_number= student_record.course_number
LEFT JOIN equal ON equal.sn= student_record.sn
AND student_record.id= 201102887
WHERE degree_plan.major='COE';";

$result = mysqli_query($con , $q ) ;
if($result){
   echo "
";
   echo "
";
   echo "
";
   echo "id	";
   echo "
";

while($row = mysqli_fetch_array($result))
{
   if($row["id"]==201102887 || null)
   {
   echo "
";
   echo "" . $row["id"]. "	";
   echo "
";
   }
    else
  {}
}
echo "
";
   }

?>

I have some code in my program and it works, but I have problem with if($row["id"]==201102887 || null) because it does not accept null, despite null being present in my database.
I want to make it so that if id is equal to 201102887 or null (no value) then the statements execute.

A: You will have to use variables on both sides of the OR ||
The code should be if($row["id"]==201102887 || $row["id"]== null)
This should work.

A: use like that
if($row["id"]==201102887 || $row["id"]== null){

}

A: If you want to use Logical operators you should write two statements in if condition
Statement 1 : $row["id"] == 201102887
Statement 2 : $row["id"] == null
In if condition putt || between two statements
 if($row["id"]==201102887 || $row["id"]== null){
      // do something
    }

Another method of using if
     if($row["id"]==201102887 || $row["id"]== null):
      // do something
     endif;


text:
Q: Zurb foundation accordion in dynamic html and javascript I'm using handlebars/hamlbars to create dynamic html, and the dynamic html uses zurb to style an accordion but unfortunately the javascript part (show/hide contents) of the accordion doesn't work. Can anyone suggest a solution for this? Thanks.

A: Have you included modernizr.js in your application?  Most of the JavaScript Foundation uses relies on it.
The easiest way to install it is to use the modernizr-rails gem
https://github.com/russfrisch/modernizr-rails


text:
Q: Dropdown menu item links not working in rails and bootstrap4 I have a navbar with a couple dropdowns. The toggle works fine, the navbar collapses at smaller screens, everything works except the links in the dropdowns. Can anyone see what's wrong with this? Also, any of the extra classes I have are just for coloration. I have not included the css here because I think it is irrelevant to the issue.

    <%= link_to root_path do %>
            <%= image_tag 'yarnn-text-logo.png', width: 120, alt: 'Yarnn icon', id: "logo" %>
        <% end %>
    <button class="navbar-toggler bg-dark" type="button" data-toggle="collapse" data-target="#myNavbar">

    </button>

          <% if user_signed_in? %>

                <%= current_user.username %>

                <%= link_to "Dashboard", dashboard_path, :class => "dropdown-item navdrop-link" %>
                <%= link_to "Profile", user_path(current_user), :class => "dropdown-item navdrop-link" %>
                <%= link_to "Edit Account", edit_registration_path(current_user), :class => "dropdown-item navdrop-link" %>

                    <%= link_to "My Station", station_path(current_user), :class => "dropdown-item navdrop-link" %>
                    <%= link_to "My Downloads", purchases_path, :class => "dropdown-item navdrop-link" %>

                    <%= link_to "Upload Track", new_track_path, :class => "dropdown-item navdrop-link" %>
                <%= link_to "Create Album", new_album_path, :class => "dropdown-item navdrop-link" %>
                <%= link_to "Create Blog Post", new_blog_path, :class => "dropdown-item navdrop-link" %>

                <% if current_user.uid? %>
                    <%= link_to "Sell Something", new_listing_path, :class => "dropdown-item navdrop-link" %>
                    <%= link_to "Sales", sales_path, :class => "dropdown-item navdrop-link" %>
                    <%= link_to "Payout", payout_method_path, :class => "dropdown-item navdrop-link" %>
                <% else %>
                    <%= link_to "Become a Seller", payout_method_path, :class => "dropdown-item navdrop-link" %>
                <% end %>

                    <%= link_to  destroy_user_session_path, method: :delete, :class => "dropdown-item navdrop-link current" do %>
                     Log Out
              <% end %>

                <%= link_to notifications_path(current_user), :class => "nav-link text-light m-2" do %>

                    <% if @notifications.count > 0 %>
                        <%= @notifications.count %>
                    <% end %>
                <% end %>

                 Explore

                    <%= link_to "Albums", albums_path, :class => "dropdown-item navdrop-link" %>
                  <%= link_to "Tracks", tracks_path, :class => "dropdown-item navdrop-link" %>
                  <%= link_to "Genres", genres_path, :class => "dropdown-item navdrop-link" %>
                  <%= link_to "Blog Posts", blogs_path, :class => "dropdown-item navdrop-link" %>

                <%= link_to listings_path, :class => "nav-link text-light m-2 menu-item" do %>
                     Marketplace
                <% end %>

            <%= link_to  destroy_user_session_path, method: :delete, :class => "nav-link text-light m-2 menu-item" do %>

            <% end %>
          <% end %>

A: I got this to work, but I had to rebuild the functionality completely, this time using buttons from the Bootstrap documentation. I figure the functionality is the important part, I can style it to my liking later. This is also my full navbar, I left some extraneous elements out earlier to make it less dense.

    <%= link_to root_path do %>
            <%= image_tag 'yarnn-text-logo.png', width: 120, alt: 'Yarnn icon', id: "logo" %>
        <% end %>
    <button class="navbar-toggler bg-dark" type="button" data-toggle="collapse" data-target="#myNavbar">

    </button>

        <% unless user_signed_in? %>

                      <button class="btn btn-default dropdown-toggle m-2" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                        EXPLORE

                      </button>

<%= link_to "Albums", albums_path %>

<%= link_to "Tracks", tracks_path %>

<%= link_to "Genres", genres_path %>

<%= link_to "Blog Posts", blogs_path %>

                <%= link_to listings_path, :class => "nav-link text-light m-2 menu-item" do %>
                           Marketplace
                        <% end %>

              <%= link_to "Login", new_user_session_path, :class => "nav-link text-light m-2 menu-item" %>

              <%= link_to "Register", new_user_registration_path, :class => "nav-link text-light m-2 menu-item" %>

          <% else %>

                          <button class="btn btn-default dropdown-toggle m-2" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                            <%= current_user.username %>

                          </button>

<%= link_to "Dashboard", dashboard_path %>

<%= link_to "Profile", user_path(current_user) %>

<%= link_to "Edit Account", edit_registration_path(current_user) %>

<%= link_to "My Station", station_path(current_user) %>

<%= link_to "My Downloads", purchases_path %>

<%= link_to "Upload Track", new_track_path %>

<%= link_to "Create Album", new_album_path %>

<%= link_to "Create Blog Post", new_blog_path %>

                                <% if current_user.uid? %>

<%= link_to "Sell Something", new_listing_path %>

<%= link_to "Sales", sales_path %>

<%= link_to "Payout", payout_method_path %>

                    <% else %>

<%= link_to "Become a Seller", payout_method_path %>

                    <% end %>

<%= link_to destroy_user_session_path, method: :delete do %>
                             Log Out
                      <% end %>

                <%= link_to notifications_path(current_user), :class => "nav-link text-light m-2" do %>

                            <% if @notifications.count > 0 %>
                                <%= @notifications.count %>
                            <% end %>
                        <% end %>

                      <button class="btn btn-default dropdown-toggle m-2" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                        EXPLORE

                      </button>

<%= link_to "Albums", albums_path %>

<%= link_to "Tracks", tracks_path %>

<%= link_to "Genres", genres_path %>

<%= link_to "Blog Posts", blogs_path %>

                <%= link_to listings_path, :class => "nav-link text-light m-2 menu-item" do %>
                           Marketplace
                        <% end %>

            <%= link_to  destroy_user_session_path, method: :delete, :class => "nav-link text-light m-2 menu-item" do %>

          <% end %>

          <% end %>


text:
Q: vectorizing a check of minimum index in MATLAB I have a vector named 'r' of 201 real values, and another vector named 'knots' of 21 real values.
I want to find for each of the 'r' values the index i of the smallest 'knot' value which is greater than the 'r' value. Do I have to do it in a 'for' loop over the 'r' vector, or is there a way I can vectorize the code so I can avoid the for loop?

A: Nope you can avoid loops.  You can use bsxfun combined with max.  I don't know what shape r and knots is in ... if they're row or column vectors, so I'm going to make the code independent of this fact.  Take note that what I'm going to write assumes that there is at least one element in r where a value in knots is larger than r.  If it isn't, then this code won't work.
Something like this is what I have in mind:
rs = r(:).'; %// Make sure r a row vector '
[knotss,indk] = sort(knots(:)); %// Make sure knots a column vector

%// Make sure that the values are sorted
%// For each value in knots, find all values that are greater than r
check = bsxfun(@gt, knotss, rs);

%// Determine the right indices for each value of knots in sorted array
[~,indc] = max(check, [], 1);

%// Get the original indices
indices = indk(indc);

The first two lines of code make sure that r is a row vector and knots is a column vector.  We also sort the values in knots because you want to find the smallest value of knots that is greater than a value in r.  It allows us to make things more efficient.  I also return the actual ordering of knots because when we find the locations of the smallest value in knots that is greater than some value r, we have to refer back to the original order.
Next, the call to bsxfun creates a 2D Boolean matrix check.  Each column in check is for each value in knots.  Specifically, each column tells you which values of knots are greater than a value in r.  For each column, false means that the corresponding value in r is not greater than the value in knots you're looking at and true is otherwise.  Once you find this matrix, you call max and check over each column independently.  When calling max, only the first time the maximum value is encountered gets returned.  Because the Boolean matrix only consists of zeroes and ones, this effectively gives you the first time a true value is encountered per row, which denotes the smallest possible index that r can be that is greater than each value in knots.
You don't need to look at the actual maximum values, but you want the indices of where this maximum occurred, hence the variable indices is created and is the second output from max.

Here's a quick example with some test data:
r = [-1 0];
knots = [3 -1 1 0 -3];

Running through the above code, I get this for my indices:
indices =

     4
     3

This makes sense.  The first value of r is -1, and the value in knots that is the smallest possible value where knots is greater than -1 is the value 0, which is in location 4.  The second value of r is 0, and the value in knots that is the smallest possible value where knots is greater than 1 is 1, and is in location 3.


text:
Q: Attach debugger in C# to another process I'd like to be able to automatically attach a debugger, something like:  System.Diagnostics.Debugger.Launch(), except rather than the current process to another named process. I've got a process name and PID to identify the other process.
Is this possible?

A: Simpler way of doing it.
public static void Attach(DTE2 dte)
        {
            var processes = dte.Debugger.LocalProcesses;
            foreach (var proc in processes.Cast<EnvDTE.Process>().Where(proc => proc.Name.IndexOf("YourProcess.exe") != -1))
                proc.Attach();
        }

        internal static DTE2 GetCurrent()
        {
            var dte2 = (DTE2)Marshal.GetActiveObject("VisualStudio.DTE.12.0"); // For VisualStudio 2013

            return dte2;
        }

Usage:
Attach(GetCurrent());

A: An option is to run; vsjitdebugger.exe -p ProcessId
It may be possible to use Process.Start to do this within a c# app.

A: Edit:
GSerjo offered the correct solution. I'd like to share a few thoughts on how to improve it (and an explanation). I hope my improved answer will be useful to to others who experience the same problem.

Attaching the VS Debugger to a Process
Manually

*

*Open the Windows Task Manager (Ctrl + Shift + Esc).

*Go to the Tab Processes.

*Right click the process.

*Select Debug.

Or, within Visual Studio, select Debug > Attach to Process....
Results will vary depending on whether you have access to the source code.
Automatically with C#

A note of caution: The following code is brittle in the sense that certain values,
  such as the Visual Studio Version number, are hard-coded. Keep this in mind going forward
  if you are planning to distribute your program.

First of all, add a reference to EnvDTE to your project (right click on the references folder in the solution explorer, add reference). In the following code, I'll only show the unusual using directives; the normal ones such as using System are omitted.
Because you are interacting with COM you need to make sure to decorate your Main method (the entry point of your application) with the STAThreadAttribute.
Then, you need to define the IOleMessageFilter Interface that will allow you to interact with the defined COM methods (note the ComImportAttribute). We need to access the message filter so we can retry if the Visual Studio COM component blocks one of our calls.
using System.Runtime.InteropServices;

[ComImport, Guid("00000016-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleMessageFilter
{
    [PreserveSig]
    int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);

    [PreserveSig]
    int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);

    [PreserveSig]
    int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
}

Now, we need to implement this interface in order to handle incoming messages:
public class MessageFilter : IOleMessageFilter
{
    private const int Handled = 0, RetryAllowed = 2, Retry = 99, Cancel = -1, WaitAndDispatch = 2;

    int IOleMessageFilter.HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo)
    {
        return Handled;
    }

    int IOleMessageFilter.RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType)
    {
        return dwRejectType == RetryAllowed ? Retry : Cancel;
    }

    int IOleMessageFilter.MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType)
    {
        return WaitAndDispatch;
    }

    public static void Register()
    {
        CoRegisterMessageFilter(new MessageFilter());
    }

    public static void Revoke()
    {
        CoRegisterMessageFilter(null);
    }

    private static void CoRegisterMessageFilter(IOleMessageFilter newFilter)
    {
        IOleMessageFilter oldFilter;
        CoRegisterMessageFilter(newFilter, out oldFilter);
    }

    [DllImport("Ole32.dll")]
    private static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, out IOleMessageFilter oldFilter);
}

I defined the return values as constants for better readability and refactored the whole thing a bit to get rid of some of the duplication from the MSDN example, so I hope you'll find it self-explanatory. extern int CoRegisterMessageFilter is our connection to the unmanaged message filter code - you can read up on the extern keyword at MSDN.
Now all that's left is some code illustrating the usage:
using System.Runtime.InteropServices;
using EnvDTE;

[STAThread]
public static void Main()
{
    MessageFilter.Register();
    var process = GetProcess(7532);
    if (process != null)
    {
        process.Attach();
        Console.WriteLine("Attached to {0}", process.Name);
    }
    MessageFilter.Revoke();
    Console.ReadLine();
}

private static Process GetProcess(int processID)
{
    var dte = (DTE)Marshal.GetActiveObject("VisualStudio.DTE.10.0");
    var processes = dte.Debugger.LocalProcesses.OfType<Process>();
    return processes.SingleOrDefault(x => x.ProcessID == processID);
}

A: Check this out
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using EnvDTE;
using NUnit.Framework;

namespace UnitTests
{
    [TestFixture]
    public class ForTest
    {
        [STAThread]
        [Test]
        public void Test()
        {
            var dte = (DTE) Marshal.GetActiveObject("VisualStudio.DTE.10.0");
            MessageFilter.Register();

            IEnumerable<Process> processes = dte.Debugger.LocalProcesses.OfType<Process>();
            var process = processes.SingleOrDefault(x => x.ProcessID == 6152);
            if (process != null)
            {
                process.Attach();
            }
        }
    }

    public class MessageFilter : IOleMessageFilter
    {
        //
        // Class containing the IOleMessageFilter
        // thread error-handling functions.

        // Start the filter.

        //
        // IOleMessageFilter functions.
        // Handle incoming thread requests.

        #region IOleMessageFilter Members

        int IOleMessageFilter.HandleInComingCall(int dwCallType,
                                                 IntPtr hTaskCaller, int dwTickCount, IntPtr
                                                                                lpInterfaceInfo)
        {
            //Return the flag SERVERCALL_ISHANDLED.
            return 0;
        }

        // Thread call was rejected, so try again.
        int IOleMessageFilter.RetryRejectedCall(IntPtr
                                                    hTaskCallee, int dwTickCount, int dwRejectType)
        {
            if (dwRejectType == 2)
            // flag = SERVERCALL_RETRYLATER.
            {
                // Retry the thread call immediately if return >=0 &
                // <100.
                return 99;
            }
            // Too busy; cancel call.
            return -1;
        }

        int IOleMessageFilter.MessagePending(IntPtr hTaskCallee,
                                             int dwTickCount, int dwPendingType)
        {
            //Return the flag PENDINGMSG_WAITDEFPROCESS.
            return 2;
        }

        #endregion

        public static void Register()
        {
            IOleMessageFilter newFilter = new MessageFilter();
            IOleMessageFilter oldFilter = null;
            CoRegisterMessageFilter(newFilter, out oldFilter);
        }

        // Done with the filter, close it.
        public static void Revoke()
        {
            IOleMessageFilter oldFilter = null;
            CoRegisterMessageFilter(null, out oldFilter);
        }

        // Implement the IOleMessageFilter interface.
        [DllImport("Ole32.dll")]
        private static extern int
            CoRegisterMessageFilter(IOleMessageFilter newFilter, out
                                                                     IOleMessageFilter oldFilter);
    }

    [ComImport, Guid("00000016-0000-0000-C000-000000000046"),
     InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IOleMessageFilter
    {
        [PreserveSig]
        int HandleInComingCall(
            int dwCallType,
            IntPtr hTaskCaller,
            int dwTickCount,
            IntPtr lpInterfaceInfo);

        [PreserveSig]
        int RetryRejectedCall(
            IntPtr hTaskCallee,
            int dwTickCount,
            int dwRejectType);

        [PreserveSig]
        int MessagePending(
            IntPtr hTaskCallee,
            int dwTickCount,
            int dwPendingType);
    }
}

*

*How to: Create and Attach to Another Instance of Visual Studio

*How to: Fix 'Application is Busy' and 'Call was Rejected By Callee'
Errors

A: If you have troubles with attaching debugger to process that is too quick to attach manually, don't forget you can sometimes add Console.ReadKey(); to a first line of your code and then you have all the time you need to attach it manually. Surprisingly it took me a while to figure that one out :D


text:
Q: Rails 4: metainspector gem slowing app down In my Rails 4 app, I am using the metainspector gem to allow users to display meta data from a URL they post to a form.
Since I installed this gem, each time I try to visit the page of my own app where metadata is pulled from another website, load time increases significantly.
The load time increase goes from an imperceptible delay for small and local websites, to almost freezing the app for larger and foreign websites.
To give you an idea, a regular page usually loads under 400 ms: when we pull data with metainspector, it can go beyond a 30,000 ms (I measured these load times with rack-mini-profiler).
I did not find much about similar issues online.
Here is what I am trying to figure out:

*

*Does this sound normal or did I setup something in the wrong way?

*Is there a way to speed up load time with metainspector? For instance by caching responses?

*If there is no way to speed up load time, should I implement a timeout limit and display an error message?

A: That is perfectly normal, to be exact it's not metainspector what is slowing your app down, it's the fact that you're requesting external URLs.
You should try to cache the responses using the built-in caching mechanism in metainspector, but also if possible move this to an asynchronous job using a background queue, and save or cache the result.


text:
Q: Grpc Authentication Flow I implemented Google Sign-In in an Android App and in a C# backend I was able to implement this flow. However I'm doing this within a special sign-in call.
I'm wondering what the expected flow on the server-side is (in C#). Do I better use an interceptor? Finally I need to be able to access authentication data in any subsequent calls of the same client. How do I put it into the ServerCallContext? I haven't found any good C# examples on how to do this.
BR,
Daniel


text:
Q: Cppcheck generate xml dump file I'm trying use xml dump file in cppcheck to create my rule. And when I'm look dump file generate when run cppcheck i see tag rawtokens have list file relate and raw data in file.
<rawtokens>
<file index="0" name="qtProject/untitled1/teststatistic.cpp"/>
<file index="1" name="qtProject/untitled1/teststatistic.h"/>

But I just see raw data fileIndex = 0
<tok fileIndex="0" linenr="1" column="1" str="#"/>
<tok fileIndex="0" linenr="1" column="2" str="include"/>
<tok fileIndex="0" linenr="1" column="10" str=""teststatistic.h""/>
<tok fileIndex="0" linenr="4" column="1" str="TestStatistic"/>
<tok fileIndex="0" linenr="4" column="14" str="::"/>
<tok fileIndex="0" linenr="4" column="16" str="TestStatistic"/>
<tok fileIndex="0" linenr="4" column="29" str="("/>
<tok fileIndex="0" linenr="4" column="30" str=")"/>
<tok fileIndex="0" linenr="5" column="1" str="{"/>
<tok fileIndex="0" linenr="7" column="1" str="}"/>
</rawtokens>

Is there any option in cppcheck to show raw data from all file list in rawtokens ?
Command I generate file dump:
cppcheck --dump teststatistic.cpp

A: cppcheck produces a .dump file for each input file listed on the command line. So, when you do cppcheck --dump teststatistic.cpp, you get teststatistic.cpp.dump as output.
You can do cppcheck --language=c++ --dump teststatistic.cpp teststatistic.h to get dump files for both the .cpp and .h file. Or you can invoke cppcheck twice, once for the .cpp file and once for the .h file. Either way, you can then get the raw data for each input file from the corresponding .dump file.
Note that cppcheck knows that a .cpp file is c++, but does not know that a .h file is c++. So, when processing the .h file, you must specify the language on the command line.


text:
Q: Modsecurity V3.0: OpenLiteSpped how to block cookie I am using mod-security V3 on a centos machine with Openlitespeed.
My php file access.php create cookie: honey_bot_trap with value : 16 character [0-9a-zA-z]. - dynamic: ex: au4abbgjk190Bl
in modsecurity create rules:
SecRule REQUEST_HEADERS:Cookie "@contains honey_bot_trap" "chain,id:'990014',phase:1,t=none,block,msg:'fake cookie'"
i want create rules :

*

*All request to my domain will redirect to access.php (the cookie create by file: honey_bot_trap: au4abbgjk190Bl)

*Modsecurity check if no cookie honey_bot_trap: au4abbgjk190Bl is block.

*if request has honey_bot_trap: au4abbgjk190Bl add to check rate.

*if rate of IP over 2 click /s is block (or redirect to https://m ydomain.com/verify.php)

Please help me. Thank for all.

A: OpenLiteSpeed is not a creator of rules, but a consumer of them.  We generally recommend the use of pre-created rules like OWASP or Comodo.  If you wish to create rules you should check out the rules guide: https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual-(v3.x)https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual-(v3.x)

A: The rule you are attempting to create is very, very complicated. It may sound simple, but I've written the 2nd edition of the ModSecurity Handbook and trust me, I would take me 2-3 hours to get this working.
With that being said, ModSec is probably not the best tool for what you have in mind. If you want to push through, try to put your hands on a copy of the ModSecurity Handbook (instead of the reference linked above) and use mod_qos or something along those lines for rate limiting and not ModSec.
#CRSDevOnDuty
P.S. Hat tip to Robert Perper.


text:
Q: Send Whatsapp image to specific contact in ios How to send image to specific contact on whatsapp through my application on iOS?
Android provide Intent to share image to specific contact like:
Intent sendIntent = new Intent("android.intent.action.SEND");
File f=new File("path to the file");
Uri uri = Uri.fromFile(f);
sendIntent.setComponent(new ComponentName("com.whatsapp","com.whatsapp.ContactPicker"));
sendIntent.setType("image");
sendIntent.putExtra(Intent.EXTRA_STREAM,uri);
sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators("919xxxxxxxxx")+"@s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT,"sample text you want to send along with the image");
startActivity(sendIntent);

A: You can use Apple's default method UIActivityViewController to share image
UIImage *img = [UIImage imageNamed:@"image.png"];

NSArray *arrImg = @[img];

UIActivityViewController *activity = [[UIActivityViewController alloc]
initWithActivityItems:arrImg applicationActivities:nil];

[self presentViewController:activity animated:YES completion:nil]


text:
Q: Get variable within function and assign it to another variable out of its scope I am using Chartist and VueJS and I am trying to access data within my chart. When I click my chart, I should be able to get the information about the index of my click. I get this data, but I am having trouble passing that data to Vue itself.
Here is my current code:
  data() {
    return {
      monthIndex: 0,
      chartData: {
        labels: [],
        series: [[], []]
      },

      /* other chart options that I omitted */

      chartEventHandlers: [
        {
          event: "draw",
          fn(data) {
            if (data.type === "bar") {
              data.element.animate({
                y2: {
                  begin: data.index * 40,
                  dur: "0.3s",
                  from: data.y1,
                  to: data.y2,
                  easing: "easeOutQuad"
                },
                opacity: {
                  begin: data.index * 40,
                  dur: "0.3",
                  from: 0,
                  to: 1,
                  easing: "easeOutQuad"
                }
              });

              data.element._node.onclick = evt => {
                console.log(data.axisX.ticks[data.index]);
               // How do I assign this to monthIndex??

              };
              //
            }
          }
        }
      ]
    };
  }

As you can see here:
data.element._node.onclick = evt => {
                console.log(data.axisX.ticks[data.index]);
              };

I can get it to display the correct value in the console, I just am trying to figure out a way to make
monthIndex = data.axisX.ticks[data.index]

However, monthIndex does not exist in the scope of the function, so I can't simply assign it to that variable. How do I go about doing this? I am trying to get monthIndex to show up on the html View so that it changes everytime I click on another part of the chart.

A: What @Chris Li is saying is that you can bind the Vue scope to a function by doing this:
function(data) {

}.bind(this)

Which allows you to access the Vue scope, or this inside of the function so to be able to assign the index value to the appropriate variable.


text:
Q: Show given metric is equivalent Let $(X,d)$ be a metric space. Prove that the function
 $$\rho(x,y) = \frac{d(x,y)}{ 1 + d(x,y)}$$
 defines an equivalent metric on $X$.  (Metrics $d_1$ and $d_2$ are called equivalent,  if every convergent sequence in the metric $d_1$ converges also to the same point in the metric $d_2$ and vice-versa).
Attempt: Assume there is a convergent sequence $x_n$ that converges to $x$ in metric $d(x,y)$. Thus, given $\epsilon>0$ $\exists N$ such that $\forall n > N$ we have $0 \leq d(x_n,x)< \epsilon$. Then,
\begin{align*}
1 \leq 1+ d(x_n,x) < 1+ \epsilon \\
\implies \frac{1}{1+ d(x_n,x)} \leq 1 \\
\implies 0 \leq \frac{d(x_n,x)}{1+ d(x_n,x)} < \frac{\epsilon}{1+ d(x_n,x)} < \epsilon \\
\implies \rho(x_n,x) < \epsilon\\
\end{align*}
Thus $x_n$ that converges to $x$ in metric $\rho(x,y)$.
Now, assume $x_n$ that converges to $x$ in metric $\rho(x,y)$. Thus, given $\epsilon>0$ $\exists N$ such that $\forall n > N$ we have $0 \leq \rho(x_n,x)< \epsilon$.
\begin{align*}
\frac{d(x_n,x)}{1+ d(x_n,x)}  < \epsilon \\
d(x_n,x) < \epsilon + \epsilon d(x_n,x)\\
 d(x_n,x) < \frac{\epsilon}{1-\epsilon} \\
\end{align*}
Is the procedure correct? Also I am stuck at the end. I cannot show $d(x_n,x) < \epsilon$
Please note: There are solutions in this website that show equivalence but use a different definition for the equivalent metric.
Edit: (Based on Arthur's suggestion)
assume $x_n$ that converges to $x$ in metric $\rho(x,y)$. Thus, there $\exists N$ such that $\forall n > N$ we have $0 \leq \rho(x_n,x)< \frac{\epsilon}{1+\epsilon}$.
\begin{align*}
\frac{d(x_n,x)}{1+ d(x_n,x)} (1+ \epsilon) < \epsilon \\
d(x_n,x) (1+\epsilon)< \epsilon + \epsilon d(x_n,x)\\
d(x_n,x) < \epsilon \\
\end{align*}
Thus $x_n$ converges to $x$ in metric $d(x,y)$.

A: Let $$ \rho = \frac {d}{1+d}$$
Note that for $$0\le \rho \le 2/3$$ we have $$ \rho \le d \le 3\rho $$
Thus  $$ d\to 0 \iff \rho \to 0$$
The convergence in one metric is equivalent to the convergence to the other metric.
Thus the metrics are equivalent.


text:
Q: What is difference between filtering: Where and takeWhile in Dart I see both of them (where and takeWhile) has the same function .. or I might miss something here!

A: The documentation for Iterable.where says:

Returns a new lazy Iterable with all elements that satisfy the predicate test.

The documentation Iterable.takeWhile says:

Returns a lazy iterable of the leading elements satisfying test.

(emphasis added).
In other words, Iterable.takeWhile will stop iterating once it reaches the first item that does not satisfy the test callback.
A concrete example:
var list = [1, 1, 2, 3, 5, 8];
print(list.where((x) => x.isOdd).toList()); // Prints: [1, 1, 3, 5]
print(list.takeWhile((x) => x.isOdd).toList()); // Prints: [1, 1]


text:
Q: Inferring r2 and pvalues in a scatterplot between observed and modelled values I have a dataframe, consisting of modelled and MODIS observed data. The values represent mean GPP for the year 2000,2001,2002,2003 .. till 2010.
A tibble: 11 x 2
   MODIS  Modelled
   <dbl> <dbl>
 1  0.39  0.4
 2  0.39  0.4
 3  0.4   0.39
 4  0.38  0.43
 5  0.38  0.41
 6  0.39  0.45
 7  0.42  0.42
 8  0.41  0.44
 9  0.41  0.45
10  0.4   0.44
11  0.41  0.48

I calulcate the r2 and p value in R by following code:
summary(lm(modelled~observed, data=df1))$r.squared
cor.test(df1$MODIS,df1$Modelled)

The r2 is 0.14 and p value is 0.25
What can be inferred from this pvalue and r2 value? Does the p value indicate that there is a weak agreement between the modis and modelled values? Kindly help me to understand how pvalue can help to infer r2.
Detailed lm output
Call:
lm(formula = modelled ~ observed, data = df1)

Residuals:
     Min       1Q   Median       3Q      Max
-0.03959 -0.02186  0.00268  0.01428  0.04268

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   0.1203     0.2512   0.479    0.643
observed      0.7732     0.6305   1.226    0.251

Residual standard error: 0.02648 on 9 degrees of freedom
Multiple R-squared:  0.1432,    Adjusted R-squared:  0.04798
F-statistic: 1.504 on 1 and 9 DF,  p-value: 0.2512


text:
Q: Compatibility of named colors below iOS 11 I need to implement the dark mode in my iOS app which runs on iOS 8+. Also I have custom colors defined in color assets with RGB codes for both light and dark appearance.
The problem is named colors are not supported proir to iOS 11, but I can use only named colors to support both appearances - dark and light.
Is there any way to implement a backward compatibility?

A: You can't do it while using color assets. However you can create your own ThemeManger to handle the app's theme.
First create a ThemeManager. It's main purpose is to hold the style of the app.
class ThemeManager {

    static let shared: ThemeManager = ThemeManager()

    var style: ThemeStyle = .light
}

Here ThemeStyle should be an enum containing your themes(light, dark etc.).
Create a ThemeColor class to handle your colors
class ThemeColor {
    var dark: UIColor = UIColor.clear
    var light: UIColor = UIColor.clear
    var asset: String = ""

    func getColor(for theme: ThemeStyle = ThemeManager.shared.style) -> UIColor {
        if #available(iOS 13.0, *) {
            if asset != "", let assetColor = UIColor(named: asset) {
                return assetColor
            }
        }
        if theme == .dark {
            return dark
        }

        return light
    }
}

You can use the getColor function to get required color. Notice that ThemeColor returns the asset color value for iOS 13. This is for changing the app's theme when user changes his/her preference from settings.
Example:

extension UIColor {
    class var backgroundColor: ThemeColor {
        let themeColor = ThemeColor()
        themeColor.light = UIColor.white
        themeColor.dark = UIColor.black
        themeColor.asset = "backgroundColor"

        return themeColor
    }
}

// Somewhere in your code set the backgroundColor of your view
myView.backgroundColor = UIColor.backgroundColor.getColor()

*

*To make this work you need to update your style variable in ThemeManger based on user's preference for iOS 13 devices. You can do this by traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) implementing this method in your UIViewController class.

*Just like the backgroundColor example you need to define all your colors which are effected by the theme change.

*Set the style value of your ThemeManger to your preferred style so that your app opens in it's default theme when not running on iOS 13.

Edit: If your users won't be able to change the app's theme on their own from within the app itself then you don't need the light and dark UIColor values in ThemeColor. Just define a defaultColor value and return it at the end of getColor function. This will allow your app to appear in it's default theme for devices running iOS 12 or lower.


text:
Q: when i connect to the server using telnet protocol ,I receive the error "could not open connection to the host,connection failed" when i connect to the specific server using telnet protocol ,I receive the error "could not open connection to the host,on port 23,connection failed" ..only I am unable to access specific three servers from telnet protocol..I am able to access some other servers without issues.

A: This mean on those three servers telnet server is not started. You can check it by connecting to the host and execute command like:
netstat -an|grep 23


text:
Q: How to translate a HRESULT to a string? The answer found here is not the one I want: when fed with 0x80131500, the _com_error class says "Unknown error 0x80131500"
If you read that other answer, you'll find that what I really need is being able to call that Marshal.GetExceptionForHR(hr).Message piece of code from C/C++
Question: HOW to achieve same result as Marshal.GetExceptionForHR(hr).Message from C/C++?
I will accept any answer which ultimately allows me to have something other that "Unknown error" for 0x80131500, which is not "unknown", it's COR_E_EXCEPTION.


text:
Q: HTML code to send SMS message through a form I am trying to create an HTML code in order to send SMS messages through a form.
My provider give to me the Http address that i could send these SMS and it looks like bello (of course i have hide passwords, etc)
http://sms.services/send-sms?app-id=108744&password=1111111&to={1}&from=TestSender&message={0}
When i call this address with a phone number instead of {1} and a text insted of {0} it works fine.
But when i try to create the bellow page it says that the attributes are wrong.
Can you please help?
<form action="http://sms.services/send-sms?app-id=108744&password=1111111&to=telnumber&from=TestSender&message=textsms" method="post">
<input type="number" name="telnumber" />
<input type="text" name="textsms" />
<input type="submit" value="Submit" />

A: Change your method to GET
Make other parameters input type hidden so user will not see those but internally it will be passed.
<form action="http://sms.services/send-sms" method="get">
    <input type="number" name="to" />
    <input type="text" name="message" />

    <input type="hidden" name="app-id" value="108744" />
    <input type="hidden" name="password" value="1111111" />
    <input type="hidden" name="from" value="TestSender" />

    <input type="submit" value="Submit" />
</form>

Note: It is not recommended to do like it because it will expose your app-id and password. You should send it to a php or any backend framework and then from there call this.

A: Try to use input type="text" instead of number.
Probably, input type="number" tries to convert string to demical, but your provider use string


text:
Q: How to calculate the operability ratio per month on Python? I have the following dataframe containing start & end dates of available slots (called 'operability_df_x' in the code):

I'm trying to calculate how many hours are available per month, let's call it the operability ratio. The output is the following (called 'g' in the code):

The current code I wrote is the following, however since I'm new to pandas & python I get the impression there is a lot of redundancy. Is there an easier way to achieve my goal directly without writing 30 lines of code ? Thanks in advance for any piece of advice
for i in operability_df_x.index :
        a = operability_df_x['Start Date'].loc[i].month
        b = operability_df_x['Start Date'].loc[i].year
        c = datetime.datetime(b,a+1,1,0,0,0)
        #  The following condition is in case there is an interval that stretches in two months :
        window = chain_seq_glob[(chain_seq_glob['Start Date'] < c) & (chain_seq_glob['End Date'] > c)].reset_index(drop=True)
        if not window.empty :
            if (operability_df_x.iloc[i].equals(window.iloc[0])):
                operability_df_x['End Date'].loc[i] = c
                window['Start Date'].loc[0] = c
                operability_df_x = operability_df_x.append(window)

    operability_df_x['Duration [Hours]'] = (operability_df_x['End Date'] - operability_df_x['Start Date'] ) / pd.to_timedelta(1, unit ='h')
    operability_df_x = operability_df_x[['Start Date','End Date', 'Duration [Hours]']]
    operability_df_x = operability_df_x.sort_values(by="Start Date").reset_index(drop=True)
    operability_df_x.to_csv('Operab.csv')
    ### Final operability table:
    g = operability_df_x.set_index('Start Date').groupby(pd.Grouper(freq="M")).sum().reset_index(drop=False)
    g['Year/Month'] = g['Start Date'].apply(lambda x: x.strftime('%Y-%m'))
    g = g.reindex(columns=['Year/Month','Duration [Hours]','Start Date'])
    g.columns = ['Year/Month','Total Available Hours','End month']

    g['Total Monthly Hours'] = (g['End month'].apply(lambda x: int(x.strftime('%d'))))*24
    g['Operability ratio'] = g['Total Available Hours'] / g['Total Monthly Hours']
    g = g.drop(['End month','Total Monthly Hours'], 1)

A: Let's consider an example dataframe:
df = pd.DataFrame({
    'start': pd.to_datetime(['20200103', '20200104', '20200123', '20200205']),
    'end': pd.to_datetime(['20200105', '20200107', '20200203', '20200209']),
})

Let's also define a utility function:
def intervals(row):
    if row.start.month == row.end.month:
        return [(row.start, row.end)]
    middle = row.end.replace(day=1, hour=0, minute=0, second=0)
    return [(row.start, middle), (middle, row.end)]

Now, let's use it to get a list of intervals (either one or two) for each row depending on how many months the row spans:
df['intervals'] = df.apply(intervals, axis=1)

Now, let's explode this list so that each interval has a row of its own:
df = df.explode('intervals')['intervals']
df = pd.DataFrame(df.tolist(), columns=['start', 'end'])

Let's add a column we'll use later for grouping:
df['month'] = df['start'].dt.strftime('%Y-%m')

And one for the number of hours between start and end:
df['hours'] = (df['end'] - df['start']).astype('timedelta64[h]')

I'm sure there is a better way to get the total number of hours for a given month. I'm doing it by adding two separate columns for the beginning of the current month and the beginning of the next month. Then, I add yet another column to store the difference between the two:
df['month_start'] = df['start'].apply(
  lambda d: d.replace(day=1, hour=0, second=0))
df['month_end'] = df['month_start'].apply(
  lambda d: d.replace(month=(d.month+1) % 12, year=d.year + int(d.month==12)))
df['total_hours'] = (df['month_end'] - df['month_start']).astype('timedelta64[h]')

Finally, perform the group-by and aggregate:
df = df.groupby('month').agg({'hours': 'sum', 'total_hours': 'first'})
df['ratio'] = df['hours'] / df['total_hours']

There are lots of built-in utility functions for dates I am not familiar with so I'm sure some of the stages could be substituted for an idiomatic expression but this works and is quite readable.


text:
Q: Audio Interface is not showing up in System Preferences Output Input Running Catalina OS. Unfortunately when plugging in my Focusrite Saffire 6 interface it is not recognized in System Preferences > Sound > Output Input. Very frustrating. I am using the correct high speed USB cable and the interface is showing up in my USB tree (About this mac > System Report > Hardware > USB) but only 'Internal Speakers' shows up in System Preference Output and Input. I can't find anything online about how to get the mac to recognize the interface. Only an article about deleting temp files which I did to no success. Also downloaded drivers for the USB 1.1 driver even though I am pretty sure I am running 2.0.

A: Unfortunately, Focusrite doesn't support Saffire 6 any longer with MAC Catalina 10.15.x. They stopped after the 10.15 update. It's useless to me now.


text:
Q: PyLint does not see installed modules since upgrading to Python 3.8 I am using the coc.nvim IntelliSense engine in neovim together with the Python linter Pylint. Since upgrading from Python 3.7 to 3.8,
pylint doesn't see my installed modules.
I installed pylint with pip3 install pylint and linked it to coc using the vim command :CocInstall coc-python. This worked flawlessly before upgrading to Python 3.8.
If I now try to import e.g. numpy
import numpy as np

coc displays the error message
[pylint E0401] [E] Unable to import 'numpy' (import-error)

Running the code does not lead to any errors, so the problem should not be with Python or numpy. Also, coc works without problems in other filetypes (e.g. JS or LaTeX), so it has to do something with Pylint not being configured for Python 3.8.
Does anyone know how to fix this?