text:
Q: HTML embed PDF , Set Content from Buffer I have an html embed tag and want to show a pdf inside. This works with src, from a file. But rather from a File I want to load the content from the memory. So I get back the pdf data from a rest api in buffer and want to feed this into the embed tags. Is this possible?
this is some example code
<div id ="pdfView">
    <embed class="form-control" src="some/path/file.pdf" id="pdf"/>
</div>

A: A clunky way would be to download a temporary file on the server then update the file name used in the src. I haven't tested but it seems like it should work.
Another way is with a data tag. You need to Base64 encode the PDF contents and then produce a src tag using the data URL scheme.
Example:
<embed class="form-control" src="data:application/pdf;base64,JVBERi0xLjEKJcKlwrHDqwoKMSAwIG9iagogIDw8IC9UeXBlIC9DYXRhbG9nCiAgICAgL1BhZ2VzIDIgMCBSCiAgPj4KZW5kb2JqCgoyIDAgb2JqCiAgPDwgL1R5cGUgL1BhZ2VzCiAgICAgL0tpZHMgWzMgMCBSXQogICAgIC9Db3VudCAxCiAgICAgL01lZGlhQm94IFswIDAgMzAwIDE0NF0KICA+PgplbmRvYmoKCjMgMCBvYmoKICA8PCAgL1R5cGUgL1BhZ2UKICAgICAgL1BhcmVudCAyIDAgUgogICAgICAvUmVzb3VyY2VzCiAgICAgICA8PCAvRm9udAogICAgICAgICAgIDw8IC9GMQogICAgICAgICAgICAgICA8PCAvVHlwZSAvRm9udAogICAgICAgICAgICAgICAgICAvU3VidHlwZSAvVHlwZTEKICAgICAgICAgICAgICAgICAgL0Jhc2VGb250IC9UaW1lcy1Sb21hbgogICAgICAgICAgICAgICA+PgogICAgICAgICAgID4+CiAgICAgICA+PgogICAgICAvQ29udGVudHMgNCAwIFIKICA+PgplbmRvYmoKCjQgMCBvYmoKICA8PCAvTGVuZ3RoIDU1ID4+CnN0cmVhbQogIEJUCiAgICAvRjEgMTggVGYKICAgIDAgMCBUZAogICAgKEhlbGxvIFdvcmxkKSBUagogIEVUCmVuZHN0cmVhbQplbmRvYmoKCnhyZWYKMCA1CjAwMDAwMDAwMDAgNjU1MzUgZiAKMDAwMDAwMDAxOCAwMDAwMCBuIAowMDAwMDAwMDc3IDAwMDAwIG4gCjAwMDAwMDAxNzggMDAwMDAgbiAKMDAwMDAwMDQ1NyAwMDAwMCBuIAp0cmFpbGVyCiAgPDwgIC9Sb290IDEgMCBSCiAgICAgIC9TaXplIDUKICA+PgpzdGFydHhyZWYKNTY1CiUlRU9GCg==" id="pdf"/>

The above is the Base64 encoded data of this minimal PDF example. You can't give it a filename like this, though, and might see something weird in its place.
If you need a guide on Base64 encoding that's possibly out of scope but plenty of solutions on here, like this one.


text:
Q: Bind javascript events to MVC controls What is the best way to bind Javascript events to my custom MVC controls? My initial thought is to create the controls using Html Helpers which give them a CSS class that signifies what kind of control they are.  Then, on document.ready, I'll use jQuery to select all such controls by their class name and bind their events.
However, I'm concerned about the speed of selecting from the entire dom by class name.  I've read (and experienced) how slow this can be, especially in IE8 which we need to target for this project.
I could select by IDs by creating a js file for each page, but I'd rather not do this, as it's a complicated web app with lots of pages.  I'd rather have one js file for each type of control that gets included in a view if the view contains at least one of that type of control.
Are CSS classes my best option?  Any other ideas?  I'm using MVC3.

A: My advice would be to try it out with classes and test the performance. If you are not satisfied, switch to IDs. I use class selectors all the time and don't find them terribly slow  in any browser. When you give jquery a context to search in, things are quite fast. For example:
$('#controls .control').whatever();

Or
$('.control', '#controls').whatever();

Sizzle is great at optimizing these things to be fast.
Edit: Here is a good reference for jQuery performance tips in general (notice #5):
http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to increase progressBar when i running havey query in sql server or oracle? i have query that thakes some time until i see the result.
how i can increase progressBar until i get the result ?
(working in C#)
thank's in advance

A: Do you have any indication of when it's going to complete, e.g. getting "results so far"? If not, you want to use a ProgressBar with the Style set to ProgressBarStyle.Marquee - that will automatically animate, and you just need to stop it afterwards. Note that you'll need to enable visual styles.
Obviously you should perform the query in a background thread (e.g. via BackgroundWorker) to avoid blocking the UI thread.
If your overall query actually consists of multiple steps, you could make your progress bar more useful by indicating how far it's really gone... but I quite understand that often this isn't the case.
Here's an example of using the marquee style:
using System;
using System.Drawing;
using System.Windows.Forms;

public class Test
{
    public static void Main(String[] args)
    {
        Application.EnableVisualStyles();
        Button start = new Button {
            Text = "Start",
            Location = new Point(10, 30)
        };
        Button stop = new Button {
            Text = "Stop",
            Location = new Point(10, 60)
        };

        ProgressBar bar = new ProgressBar {
            Style = ProgressBarStyle.Marquee,
            Location = new Point(10, 90),
            MarqueeAnimationSpeed = 20,
            Visible = false
        };
        Form form = new Form {
            Size = new Size(100, 200),
            Controls = { start, stop, bar }
        };
        start.Click += (s, a) => bar.Visible = true;
        stop.Click += (s, a) => bar.Visible = false;
        Application.Run(form);
    }
}

A: You can use a thread or, if the problem is that you get a lot of data, use a DataReader and update your progressBar while reading.


text:
Q: Checksum calculation for ROM memory I am using controller STM32Lxx. During the calculation of ROM memory checksum missing interrupts(In LIN bus is not responding properly.)
How to avoid this scenario?
I thought to calculate a checksum for a small portion of ROM then----> finally add all these checksum values.
is there any other method to overcome this issue?


text:
Q: Capture error message with status 400 Bad Request VB.Net When the response is a 400 Bad Request status, I don't know how to capture the message that generates the error.
In postman you can see the error message in the following image:

My code in vb.net is the following:
Dim resp As HttpWebResponse
Dim request As HttpWebRequest = HttpWebRequest.Create("MyUrl")
request.Method = "POST"
request.ContentType = "application/json"
request.Headers.Add("authorization", "Bearer " + TokenAPI)
Dim PostString As String = JSON
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(PostString)
request.ContentLength = byteArray.Length
Dim dataStream1 As Stream = request.GetRequestStream()
dataStream1.Write(byteArray, 0, byteArray.Length)
dataStream1.Close() 'sends request
Try
  resp = DirectCast(request.GetResponse(), HttpWebResponse)
  If resp.StatusCode = 201 Then
      MsgBox("OK")
  End If
  Return "ok"
Catch ex As WebException
    Dim rep As HttpWebResponse = ex.Response
    Return "error"
End Try

When the exception is executed in VB.net, the 400 error is detected but I cannot capture the message. View image:

Capture the message when the response is status 400 Bad Request

A: It's in the response stream
Catch ex As WebException
    Dim rep As HttpWebResponse = ex.Response
    Using rdr As New StreamReader(rep.GetResponseStream())
        Return rdr.ReadToEnd()
    End Using
End Try


text:
Q: Why is this boolean parameter for Jenkins / Gradle (defined in groovy) not working? I have this Jenkins job defined in groovy and I would like to tick the "Make gradlew executable" box.
steps {
    gradle {
        executable(true)
        tasks("""forbiddenApisMain
jar""")
    }
}

According to https://readthedocs.org/projects/jenkins-job-builder/downloads/pdf/stable/ (page 102), I need to set executable to true
However I get this error:
ERROR: (Build.groovy, line 576) No signature of method: javaposse.jobdsl.dsl.helpers.step.GradleContext.executable() is applicable for argument types: (java.lang.Boolean) values: [true]. I don't get the error if I remove executable(true)). Any idea? I checked and I have the latest plugin


text:
Q: Fermi energy, occupation factor and number of particles Using the grand canonical ensemble, we can show that the occupation factor of an energy level (when the temperature $T$ and chemical potential $\mu$ are fixed) is given by $$ f_E(T,\mu) =  \frac{1}{\exp \frac{E-\mu}{kT} \pm 1} \quad  (1)$$. The total number of particles and energy in the system are thus given by
$$ N(T,\mu) = \int dE \, DoS (E) f_E(T,\mu) \quad (2)$$
$$ U(T,\mu) = \int dE \, E\, DoS (E) f_E(T,\mu) \quad (3)$$
On the other hand, the chemical potential is related to the internal, free or Gibbs energy of the system as $$\mu = \left( \frac{\partial U}{\partial N} \right)_{S,V}= \left( \frac{\partial F}{\partial N} \right)_{T,V}= \left( \frac{\partial G}{\partial N} \right)_{T,p} \quad (4)$$
Is there a way to recover these relations from (1) - ie to check that the $\mu$ which appears in eq.(1) is indeed a chemical potential is the sense of (4) ?

A: Solved it.
The grand potential is
$$
A =kT\int dE\,D(E)\log\left(1-\frac{1}{\exp\left(\frac{E-\mu}{kT}\right)+1}\right)
 =-kT\int dE\,D(E)\log\left(1+\exp\left(\frac{\mu-E}{kT}\right)\right)$$
from where we calculate
$$ S=-\left.\frac{\partial A}{\partial T}\right|_{\mu,V}=-\frac{A}{T}-\frac{1}{T}\int dE\,D(E)\frac{(\mu-E)}{\exp\left(\frac{E-\mu}{kT}\right)+1}$$
and $$ p=-\left.\frac{\partial A}{\partial V}\right|_{T,V}=-\frac{A}{V}$$
and it is then straightforward to calculate
$$G=U-TS+pV  =\mu\int dE\,\frac{D(E)}{\exp\left(\frac{E-\mu}{kT}\right)+1} = \mu N$$
CQFD.


text:
Q: Attaching click to anchor tag in angular I am trying to attach click event to anchor tags (coming from ajax) and block the default redirection. How can I do it in angular ?

abc

abc1

abc2

abc3

In ts file:
constructor(elementRef: ElementRef, renderer: Renderer) {
    this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
        event.preventDefault();
        let target = event.target || event.srcElement || event.currentTarget;
        console.log(target);
    });
}

This will attach event to all elements, how can I limit this to anchor tag only ?
All helps appreciated.

A: Go to Page 2

A: I have encountered this issue in Angular 5 which still followed the link. The solution was to have the function return false in order to prevent the page being refreshed:
html
Change expired password

ts
openChangePasswordForm(): boolean {
  console.log("openChangePasswordForm called!");
  return false;
}

A: I think you are not letting Angular work for you.
In angular 2:

*

*Remove the href tag from  to prevent a page forwarding.

*Then just add your usual Angular click attribute and function.

*Add to style: "cursor: pointer" to make it act like a button

A: I was able to implement this successfully
abc

A: I had to combine several of the answers to get a working solution.
This solution will:

*

*Style the link with the appropriate 'a' styles.

*Call the desired function.

*Not navigate to http://mySite/#
Link

A: I've been able to get this to work by simply using [routerLink]="[]". The square brackets inside the quotes is important. No need to prevent default actions in the method or anything. This seems to be similar to the "!!" method but without needing to add that unclear syntax to the start of your method.
So your full anchor tag would look like this:
Your Link

Just make sure your method works correctly or else you might end up refreshing the page instead and it gets very confusing on what is actually wrong!

A: You can use routerLink which is an alternative of href for angular 2.**
Use routerLink as below in html
My Link

and make sure you register your routerLink in modules.ts or router.ts like this
const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent }
]

A: You just need to add !! before your click method handler call: (click)="!!onGoToPage2()". The !! will prevent the default action from happening by converting the return of your method to a boolean. If it's a void method, then this will become false.

A: You can use routerLink (which is an alternative of href for angular 2+) with click event as below to prevent from page reloading
Go to page

A: I had issues with the page reloading but was able to avoid that with routerlink=".":
My Function

I received inspiration from the Angular Material docs on buttons:
https://material.angular.io/components/button/examples
UPDATE I've started using routerLink="" since Angular 12.  I was finding that routerLink="." was routing me to a parent page.

A: Go to page 2

A: You can try something like this:

OR

A: While the question is technically already answered I think all answers here forget something important: Just adding a click-handler is not enough. You also want the link to be usable for people who only use the keyboard for Accessibility reasons. Usually this means that hitting Enter while focussing the element should have the same effect as clicking on it. While we're at it we could also set the role. If the link is actually used as a button we should set role="button" - this way screenreaders will announce it as a button and not a navigation-link.
For the original problem: Almost all answers here seem to work for me, but i chose the one with the empty routerLink - I think it makes it semantically clear that no navigation is wanted. Other solutions could lead to confusions later (lets say someone reads your code in a year).
your link

A: Clean way to handle anchor tags and href and keeping your anchor styling:
html:
Pass in the $event on click
Do something

Typescript:
Get the event as MouseEvent and call e.preventDefault()
doSomething(e: MouseEvent): void {
    e.preventDefault();

    //Do something
}

Your styling will stay in tact and no default browser anchor handling will take place.

A: I have examined all the above answer's, We just need to implement two things to work it as expected.
Step - 1: Add the (click) event in the anchor tag in the HTML page and remove the href=" " as its explicitly for navigating to external links, Instead use routerLink = " " which helps in navigating views.

Click One

Click Two

Step - 2: Call the above function to attach the click event to anchor tags (coming from ajax) in the .ts file,
  hitAnchor1(e){
      console.log("Events", e);
      alert("You have clicked the anchor-1 tag");
   }
  hitAnchor2(e){
      console.log("Events", e);
      alert("You have clicked the anchor-2 tag");
   }

That's all. It work's as expected. I created the example below, You can have a look:-
https://stackblitz.com/edit/angular-yn6q6t

A: This worked for me:
Click me


text:
Q: Messaging between web app and chrome extension I'm building chrome extension that is going to interact with web applications and send data to it. I have 2 features - connect to web app and generate hash message (Metamask like functionality). But I faced with issue that to interact with extension http web app needs to have permissions (externally_connectable) and write permissions for every http site is a bad idea I guess (as I know it works good for https web apps). As patterns for externally_connectable like <all_urls> is prohibited I ask for help, maybe I chose wrong solution for this features. Help please.
manifest.json
{
  "manifest_version": 3,
  "name": "extension",
  "description": "extension",
  "version": "1.0.0",
  "icons": {
    "16": "16x16.png",
    "48": "48x48.png",
    "128": "128x128.png"
  },
  "host_permissions": ["https://google.com/", "http://localhost:3000/"],
  "permissions": ["cookies", "storage", "tabs"],
  "action": {
    "default_popup": "popup.html",
    "default_title": "Open popup",
    "default_icon": "16x16.png"
  },
  "background": {
    "service_worker": "background.js"
  },
  "externally_connectable": {
    "matches": [
      "http://my-http-test-web-app/",
      "http://localhost:3000/",
      "http://localhost:3001/"
    ]
  }

webapp script
const message = { id: ExtensionID, method: 'requestAccounts' }

chrome?.runtime?.sendMessage(ExtensionID, JSON.stringify(message),  (response) => console.log(response)}

background.js

chrome.runtime.onMessageExternal.addListener(async (request, sender, sendResponse) => {
  const parsedRequest: IExternalRequest = JSON.parse(request)

  const { connectedSites, activeAccount, userBalances } = await chrome.storage.local.get()

  if (connectedSites && connectedSites.includes(sender.origin)) {
    sendResponse({
      id: EXTENSION_ID,
      success: true,
      method: 'responseRequestAccounts',
      data: {
        address: activeAccount.address,
        guildName: activeAccount.username,
        balance: userBalances,
      },
    })
    return
  }

  await chrome.storage.local.set(prepareRequestData(method, sender.tab, sender.origin))
  await openNewNotificationsPage()

  chrome.runtime.onMessage.addListener((request) => {
    sendResponse(JSON.parse(request))
  })

}

const openNewNotificationsPage = async () => {
  const { top, left, width } = await chrome.windows.getCurrent()
  const topPosition = Math.max(top, 0)
  const leftPosition = Math.max(left + (width - 340), 0)
  const options = {
    url: 'notification.html',
    type: 'popup',
    width: 340,
    height: 516,
    left: leftPosition,
    top: topPosition,
  }
  openWindow(options)
}

function openWindow(options) {
  chrome.windows.create(options)
}

On new opened window there is a extension script that gets account data and sends it
chrome.runtime.sendMessage(
        EXTENSION_ID,
        JSON.stringify(buildConnectWalletResponseData(response, true)),
        handleClose

A: In your web application, you need to put window.chrome.runtime instead of chrome.runtime in order for your script to have access to the chrome runtime. Keep in mind this will cause errors if you run this JS outside of Chrome.


text:
Q: Can't look around in Minecraft I am playing Minecraft, but the left stick no longer makes me look around. I can still sneak/crouch with the left stick though. It has been happening ever since I tried to download a map.
I have tried restarting the game as well as the console, I have ejected the disk, played a new game, and came back on.  Does anyone know how I can fix this?

A: That should be your sensitivity for the game.  Go to settings and look for the 'reset to default'  buton. Click it.  That should make you be able to look around again, it fixed it for me.

A: Pause the game and go to options then setting , and then on the bottom press a on reset defaults.


text:
Q: How to bypass itms-services://?action=download-manifest UIAlertView in iOS? We are using below lines to install new app to device.
NSURL *url = [NSURL URLWithString:@"itms-services://?action=download-manifest&url=https://xxxxxx.com/rest/images/apps/ipa/dev/xyz.plist"]];
[[UIApplication sharedApplication] openURL:url];

It displays an UIAlertView with message "xxxxxx would like to install "xyz"".
Is there anyway either to bypass this alert view and forcefully install the ipa or any method callback sothat i can recognise that user pressed cancel button?

A: No, There is no way to bypass that popup and just install the app on users phone. This behavior prevents any app to install app on your device without the users permission.


text:
Q: Sending data to header.ejs using Nodejs I send data to my Nodejs pages doing something like:
res.render("mainPage.ejs",{myArray})

However, I have a situation where I want to change set the navbar dropdown values using some values form my database.
I wanted to know if is possibile to send data to every header.ejs file using Nodejs.

A: Like Handlebars, ejs also has the concept of partials.
Check out the official doc. here:
https://www.includehelp.com/node-js/ejs-partials.aspx
You can pass the data to the views by doing something like this:
router.get('/routeHere', (req,res)=>{

res.render('pages/blog',
{
 key1: value1,
key2: value2

 });

});

You will then be able to access the object under 'res.render()' in the view.

A: You don't "send data to a partial". You pass data into your temaplate res.render('mytemplate', { user }) and user is available to each partial you included in mytemplate.ejs. Included partials see their parent template data.


text:
Q: The Univere's mass-energy and uncertainty A virtual creation with total mass-energy = $E$ is allowed as long as that virtual creation doesn't last longer than $E/h$. Can the uncertainty principle also be used to estimate the mass-energy in the spontaneous creation of a universe - a spontaneous creation that has now lasted $13.6$ billion years?  If so, the principle would require that universe to have a mass-energy less than $1.54\times 10^{-51}$ Joules. Is there a flaw in this?

A: Well , the mass of the visible universe 6e51 kg contradicts this simplification  .
The HUP is an inequality. It tells you that the mass must be at least this small number you give, it does not put bounds from above, that is why it is immaterial for our classical existence.
In addition the existing universe is not in a quantum mechanical virtual state, since it has undergone decoherence billions of years ago.
Edit in response to comments:
At the time of the Big Bang General Relativity holds. Unification of GR with the other three forces in a consistent with all data quantum mechanical theory is under research. We can only hand wave extrapolating our laboratory and observational knowledge to the first seconds of the creation of the universe.
The assumption is that the system will be following quantum mechanical laws and therefore a form of the  HUP should apply.
The problem is  in assuming the HUP for the virtual states of the first instants of the creation of the universe as an equality, assuming energy conservation, i.e. that the total observed energy existed at that instant. This is not valid, as conservation of energy is not well defined in General Relativity.  Therefore at that small interval where the whole universe was coherent it is the inequality bounds that could have a meaning, and those are not violated. As time starts flowing  decoherence appears and matter as we know it.
Conclusion: The current universe is not in a coherent quantum mechanical state where one could apply the HUP, so taking current time numbers and applying HUP for energy  has little meaning except as a lower bound, if at that.
Applying the HUP at the first instants of the creation has little meaning because energy is not conserved where GR is dominant.


text:
Q: How can I translate text in a predefined google sign-in button? Quite new to this and couldn't find a clear answer. I've added the predefined button from the top of this page:
https://developers.google.com/identity/sign-in/web/build-button?hl=no
As you can see the rest of the text is in norwegian, but I can't change the text in the google button
Is it possible at all or do I need another button/code?

  <meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">


text:
Q: Two docker containers attached to same network but can't reference each other by name, only IP I have 2 docker containers running attached to same network.  From within container 1 I can ping container 2 by IP (and vice versa).  But from within container 1 I can't ping container 2 by name (nor vice versa).
According to this I should be able to ping by container name: https://docs.docker.com/network/network-tutorial-standalone/#use-user-defined-bridge-networks
What am I doing wrong?
//START MYSQL IN CONTAINER ONE CONNECTING TO TESTNET
PS C:\Users\Administrator> docker run -e MYSQL_ROOT_PASSWORD=my-secret-pw -e MYSQL_DATABASE=MyDb -p 3306:3306 --network testnet -d mysql:latest
7ba710ca9ed0ffd346416eae31553460799cc1bedf3f7cfa9d7ef3b369e41f7e

//START MYEXECUTABLE IN CONTAINER TWO CONNECTING TO TESTNET
PS C:\Users\Administrator> docker run -p 8948:8948 --network testnet -d myexecutable:ubuntu
399c19d4adaf9cb6679ed062cf92455d1dd2d83087d51966e6a4d499dc312909

//BOTH CONTAINERS RUNNING
PS C:\Users\Administrator> docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS              PORTS                               NAMES
399c19d4adaf        myexecutable:ubuntu    "dotnet myexecut…"   About a minute ago   Up About a minute   0.0.0.0:8948->8948/tcp              optimistic_lamport
7ba710ca9ed0        mysql:latest        "docker-entrypoint.s…"   About a minute ago   Up About a minute   0.0.0.0:3306->3306/tcp, 33060/tcp   charming_gates

//INSPECT TESTNET, SEE THAT BOTH CONTAINERS CONNECTED
PS C:\Users\Administrator> docker network inspect testnet
[
    {
        "Name": "testnet",
        "Id": "8db5e107100350f594d405890f94a8f0770aae37ae71a102cbbdb24baa27e117",
        "Created": "2020-03-11T11:24:45.060816989Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "172.18.0.0/16",
                    "Gateway": "172.18.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "399c19d4adaf9cb6679ed062cf92455d1dd2d83087d51966e6a4d499dc312909": {
                "Name": "optimistic_lamport",
                "EndpointID": "a99566e018a295f28ffc6758e3e78dfa0b1f5292dedfef0546e8ceaed11b2b3d",
                "MacAddress": "02:42:ac:12:00:03",
                "IPv4Address": "172.18.0.3/16",
                "IPv6Address": ""
            },
            "7ba710ca9ed0ffd346416eae31553460799cc1bedf3f7cfa9d7ef3b369e41f7e": {
                "Name": "charming_gates",
                "EndpointID": "78729185c317d096a637d637929d3bd3d32dec9f5587327bc5703ac708225d37",
                "MacAddress": "02:42:ac:12:00:02",
                "IPv4Address": "172.18.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]

//ATTACH TO CONTAINER ONE SHELL
PS C:\Users\Administrator> docker exec -it optimistic_lamport bash

//PING CONTAINER TWO BY IP - WORKS FINE
    root@399c19d4adaf:/app# ping -c 2 172.18.0.2
    PING 172.18.0.2 (172.18.0.2) 56(84) bytes of data.
    64 bytes from 172.18.0.2: icmp_seq=1 ttl=64 time=0.100 ms
    64 bytes from 172.18.0.2: icmp_seq=2 ttl=64 time=0.047 ms

//PING CONTAINER TWO BY NAME - FAIL
    root@399c19d4adaf:/app# ping -c 2 charming_gates
    ping: charming_gates: Name or service not known

//CAT /ETC/HOSTS
    root@399c19d4adaf:/app# cat /etc/hosts
    127.0.0.1       localhost
    ::1     localhost ip6-localhost ip6-loopback
    fe00::0 ip6-localnet
    ff00::0 ip6-mcastprefix
    ff02::1 ip6-allnodes
    ff02::2 ip6-allrouters
    172.18.0.3      399c19d4adaf

What am I doing wrong?
I've reviewed these, that seem to have similar issues but no definitive result.  Except one solution to specifically allocate an IP to the container, which I don't like the idea of.
How to get Docker containers to talk to each other while running on my local host?
Can't access Docker container by name in same network
How to configure containers in one network to connect to each other (server -> mysql)?

A: Wow after all that it was really simple.  I just needed to assign my own name, not accept the docker issued name.
//NOTE THE ADDITION OF --NAME SWITCH
PS C:\Users\johng\source\repos\Ontic5\etrade-rtd\RtdActorSystemOutOfProc> docker run --name mysqlcontainer -e MYSQL_ROOT_PASSWORD=my-secret-pw -e MYSQL_DATABASE=mydatabase -p 3306:3306 --network testnet -d mysql:latest
0bfd4b7ff990ca2ffba8d8a200e33b7c6cee7cc422dad84f50311bfe46cdd468

//NOW CAN PING JUST FINE
PS C:\Users\johng\source\repos\Ontic5\etrade-rtd\RtdActorSystemOutOfProc> docker exec -it myexecontainer bash

root@a932138635fd:/app# ping mysqlcontainer
PING mysqlcontainer (172.18.0.3) 56(84) bytes of data.
64 bytes from mysqlcontainer.testnet (172.18.0.3): icmp_seq=1 ttl=64 time=0.049 ms
64 bytes from mysqlcontainer.testnet (172.18.0.3): icmp_seq=2 ttl=64 time=0.050 ms


text:
Q: Reading only one "message" from a pipe each time? I have two processes connected with a pipe.
One process has several threads writing messages on the pipe.
The other process reads the pipe and process the messages.
The problem is that, when the process reads the pipe, it gets all the messages one after another. ¿Is there any way of reading just one message at a time?
At first I used the write and read functions, using the file descriptors directly.
Then I tried treating them as files, using fdopen, fread and fwrite, but it still reads all the data at the same time.
The message's size can change each time, so I can't fix it by reading a fixed amount of characters.

A: Once upon a long time ago, in a time before POSIX was a known concept anywhere in the world, at least one version of Unix maintained things such that writes less than the size of the space left in the pipe buffer were read in atomic chunks corresponding to the size of the packets written to the pipe, subject to the constraint that you tried to read enough data.  Unfortunately (or maybe I mean 'obviously'), I can no longer prove that this was the case — I've not had access to the relevant hardware and O/S for over a quarter of a century.
However, proof by counter-example demonstrates that Mac OS X no longer handles the reading side like that (though POSIX does guarantee that write() calls are atomic if the requested sizes written are small enough).  This was something of a surprise to me.
Counter-example — code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

static void childish(int fd)
{
    char buffer[1024];
    int  nbytes;
    int  pid = getpid();
    while ((nbytes = read(fd, buffer, sizeof(buffer))) > 0)
    {
        printf("%.5d: %.4d <<%.*s>>\n", pid, nbytes, nbytes, buffer);
        fflush(stdout);
    }
    printf("%.5d: exiting\n", pid);
    exit(0);
}

static void parental(int fd)
{
    char message[] = "The Quick Brown Fox Jumped Over The Lazy Dog";
    int  pid = getpid();
    for (int i = 0; i < 20; i++)
    {
        int  nbytes = rand() % (sizeof(message) - 1);
        while (nbytes == 0)
            nbytes = rand() % (sizeof(message) - 1);
        if (write(fd, message, nbytes) != nbytes)
            break;
        printf("%.5d: %.4d <<%.*s>>\n", pid, nbytes, nbytes, message);
        fflush(stdout);
    }
    printf("%.5d: exiting\n", pid);
    exit(0);
}

int main(void)
{
    int fd[2];
    pipe(fd);
    pid_t pid = fork();
    if (pid < 0)
        fprintf(stderr, "failed to fork\n");
    else if (pid == 0)
    {
        close(fd[1]);
        childish(fd[0]);
    }
    else
    {
        close(fd[0]);
        parental(fd[1]);
    }
    return EXIT_FAILURE;  // Failed to fork
}

Counter-example — data
Tested on Mac OS X 10.8.3.
86504: 0043 <<The Quick Brown Fox Jumped Over The Lazy Do>>
86504: 0001 <<T>>
86504: 0033 <<The Quick Brown Fox Jumped Over T>>
86504: 0006 <<The Qu>>
86504: 0030 <<The Quick Brown Fox Jumped Ove>>
86504: 0036 <<The Quick Brown Fox Jumped Over The >>
86504: 0024 <<The Quick Brown Fox Jump>>
86504: 0022 <<The Quick Brown Fox Ju>>
86504: 0031 <<The Quick Brown Fox Jumped Over>>
86504: 0037 <<The Quick Brown Fox Jumped Over The L>>
86504: 0028 <<The Quick Brown Fox Jumped O>>
86504: 0017 <<The Quick Brown F>>
86504: 0032 <<The Quick Brown Fox Jumped Over >>
86504: 0038 <<The Quick Brown Fox Jumped Over The La>>
86504: 0019 <<The Quick Brown Fox>>
86504: 0007 <<The Qui>>
86504: 0023 <<The Quick Brown Fox Jum>>
86504: 0005 <<The Q>>
86504: 0020 <<The Quick Brown Fox >>
86504: 0004 <<The >>
86504: exiting
86505: 0456 <<The Quick Brown Fox Jumped Over The Lazy DoTThe Quick Brown Fox Jumped Over TThe QuThe Quick Brown Fox Jumped OveThe Quick Brown Fox Jumped Over The The Quick Brown Fox JumpThe Quick Brown Fox JuThe Quick Brown Fox Jumped OverThe Quick Brown Fox Jumped Over The LThe Quick Brown Fox Jumped OThe Quick Brown FThe Quick Brown Fox Jumped Over The Quick Brown Fox Jumped Over The LaThe Quick Brown FoxThe QuiThe Quick Brown Fox JumThe QThe Quick Brown Fox The >>
86505: exiting

Atomic Writing — Non-Atomic Reading
This code uses writev() to write both a message length and the message to the pipe.  Of necessity, it uses two reads to get the data, fetching the length and then the message.  This works with a single reader; with multiple readers, you'd have to coordinate between the readers so that the file descriptor was not accessed by one reader while another had read the length but not read the data.  The code uses the writev() system call to write the length and the data in a single system call.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/uio.h>
#include <unistd.h>

static void childish(int fd)
{
    int  nbytes;
    int  pid = getpid();
    while (read(fd, &nbytes, sizeof(nbytes)) == sizeof(nbytes))
    {
        char buffer[1024];
        int  actual;
        if ((actual = read(fd, buffer, nbytes)) != nbytes)
        {
            fprintf(stderr, "%.5d: short read (wanted %d, actual %d)\n", pid, nbytes, actual);
            break;
        }
        printf("%.5d: %.4d <<%.*s>>\n", pid, nbytes, nbytes, buffer);
        fflush(stdout);
    }
    printf("%.5d: exiting\n", pid);
    exit(0);
}

static void parental(int fd)
{
    char message[] = "The Quick Brown Fox Jumped Over The Lazy Dog";
    int nbytes = 0;
    struct iovec req[2];
    req[0].iov_base = &nbytes;
    req[0].iov_len  = sizeof(nbytes);
    req[1].iov_base = message;
    req[1].iov_len  = 0;
    int  pid = getpid();
    for (int i = 0; i < 20; i++)
    {
        do
        {
            nbytes = rand() % (sizeof(message) - 1);
        } while (nbytes == 0);
        req[1].iov_len = nbytes;
        if (writev(fd, req, 2) != (int)(nbytes + sizeof(nbytes)))
            break;
        printf("%.5d: %.4d <<%.*s>>\n", pid, nbytes, nbytes, message);
        fflush(stdout);
    }
    printf("%.5d: exiting\n", pid);
    exit(0);
}

int main(void)
{
    int fd[2];
    pipe(fd);
    pid_t pid = fork();
    if (pid < 0)
        fprintf(stderr, "failed to fork\n");
    else if (pid == 0)
    {
        close(fd[1]);
        childish(fd[0]);
    }
    else
    {
        close(fd[0]);
        parental(fd[1]);
    }
    return EXIT_FAILURE;  // Failed to fork
}

Example Output
86798: 0043 <<The Quick Brown Fox Jumped Over The Lazy Do>>
86798: 0001 <<T>>
86798: 0033 <<The Quick Brown Fox Jumped Over T>>
86798: 0006 <<The Qu>>
86798: 0030 <<The Quick Brown Fox Jumped Ove>>
86798: 0036 <<The Quick Brown Fox Jumped Over The >>
86798: 0024 <<The Quick Brown Fox Jump>>
86798: 0022 <<The Quick Brown Fox Ju>>
86798: 0031 <<The Quick Brown Fox Jumped Over>>
86798: 0037 <<The Quick Brown Fox Jumped Over The L>>
86798: 0028 <<The Quick Brown Fox Jumped O>>
86798: 0017 <<The Quick Brown F>>
86798: 0032 <<The Quick Brown Fox Jumped Over >>
86798: 0038 <<The Quick Brown Fox Jumped Over The La>>
86798: 0019 <<The Quick Brown Fox>>
86798: 0007 <<The Qui>>
86798: 0023 <<The Quick Brown Fox Jum>>
86798: 0005 <<The Q>>
86798: 0020 <<The Quick Brown Fox >>
86798: 0004 <<The >>
86798: exiting
86799: 0043 <<The Quick Brown Fox Jumped Over The Lazy Do>>
86799: 0001 <<T>>
86799: 0033 <<The Quick Brown Fox Jumped Over T>>
86799: 0006 <<The Qu>>
86799: 0030 <<The Quick Brown Fox Jumped Ove>>
86799: 0036 <<The Quick Brown Fox Jumped Over The >>
86799: 0024 <<The Quick Brown Fox Jump>>
86799: 0022 <<The Quick Brown Fox Ju>>
86799: 0031 <<The Quick Brown Fox Jumped Over>>
86799: 0037 <<The Quick Brown Fox Jumped Over The L>>
86799: 0028 <<The Quick Brown Fox Jumped O>>
86799: 0017 <<The Quick Brown F>>
86799: 0032 <<The Quick Brown Fox Jumped Over >>
86799: 0038 <<The Quick Brown Fox Jumped Over The La>>
86799: 0019 <<The Quick Brown Fox>>
86799: 0007 <<The Qui>>
86799: 0023 <<The Quick Brown Fox Jum>>
86799: 0005 <<The Q>>
86799: 0020 <<The Quick Brown Fox >>
86799: 0004 <<The >>
86799: exiting

I'm disappointed that the processes run strictly consecutively in this example; since this is multi-core machine, it was not what I expected.  When I changed the loop limit from 20 to 2000, then I got interleaved execution and the data stayed in synchrony on send and receive side.
I used 4-byte int values for the length.  Clearly, for the data on hand, it would have been sufficient to use a 1-byte unsigned char (heck, it could even be a signed char since the string is only 44 characters long).
Note that I've not seeded the rand() generator, so the output is deterministic apart from the process IDs each time it is run.
Note, too, that I'm not absolutely certain from reading the POSIX specification that the writev() segments are guaranteed to be treated as a single unit on the pipe.  If that's not the case, then you'll need to manufacture a buffer in the parental() code that contains the length followed by the relevant amount of data, and fall back on the plain write() call.  This is not at all hard to do:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static void childish(int fd)
{
    char nbytes;
    int  pid = getpid();
    while (read(fd, &nbytes, sizeof(nbytes)) == sizeof(nbytes))
    {
        char buffer[1024];
        int  actual;
        if ((actual = read(fd, buffer, nbytes)) != nbytes)
        {
            fprintf(stderr, "%.5d: short read (wanted %d, actual %d)\n", pid, nbytes, actual);
            break;
        }
        printf("%.5d: %.4d <<%.*s>>\n", pid, nbytes, nbytes, buffer);
        fflush(stdout);
    }
    printf("%.5d: exiting\n", pid);
    exit(0);
}

static void parental(int fd)
{
    char message[] = "\000The Quick Brown Fox Jumped Over The Lazy Dog";
    int  pid = getpid();
    for (int i = 0; i < 20; i++)
    {
        int nbytes;
        do
        {
            nbytes = rand() % (sizeof(message) - 1);
        } while (nbytes == 0);
        message[0] = nbytes;
        if (write(fd, message, nbytes + 1) != (nbytes + 1))
            break;
        printf("%.5d: %.4d <<%.*s>>\n", pid, nbytes, nbytes, message+1);
        fflush(stdout);
    }
    printf("%.5d: exiting\n", pid);
    exit(0);
}

int main(void)
{
    int fd[2];
    pipe(fd);
    pid_t pid = fork();
    if (pid < 0)
        fprintf(stderr, "failed to fork\n");
    else if (pid == 0)
    {
        close(fd[1]);
        childish(fd[0]);
    }
    else
    {
        close(fd[0]);
        parental(fd[1]);
    }
    return EXIT_FAILURE;  // Failed to fork
}

Adding threading to the writing code
Creating threads to do the writing is not all that hard.  The code still uses rand(), but rand() is not guaranteed to be thread-safe, so it may not be as good as you'd like.  On the other hand, this code is simply using rand() to generate variable sized messages; it is not critical that it perform perfectly.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static void childish(int fd)
{
    char nbytes;
    int  pid = getpid();
    while (read(fd, &nbytes, sizeof(nbytes)) == sizeof(nbytes))
    {
        char buffer[1024];
        int  actual;
        if ((actual = read(fd, buffer, nbytes)) != nbytes)
        {
            fprintf(stderr, "%.5d: short read (wanted %d, actual %d)\n", pid, nbytes, actual);
            break;
        }
        printf("%.5d: %.4d R <<%.*s>>\n", pid, nbytes, nbytes, buffer);
        fflush(stdout);
    }
    printf("%.5d: exiting\n", pid);
    exit(0);
}

static void *p_thread(void *data)
{
    int fd = *(int *)data;
    char message[] = "\000The Quick Brown Fox Jumped Over The Lazy Dog";
    int  pid = getpid();
    for (int i = 0; i < 20; i++)
    {
        int nbytes;
        do
        {
            nbytes = rand() % (sizeof(message) - 1);
        } while (nbytes == 0);
        message[0] = nbytes;
        if (write(fd, message, nbytes + 1) != (nbytes + 1))
            break;
        printf("%.5d: %.4d W <<%.*s>>\n", pid, nbytes, nbytes, message+1);
        fflush(stdout);
    }
    printf("%.5d: thread exiting\n", pid);
    return(0);
}

static void parental(int fd)
{
    enum { NUM_THREADS = 3 };
    pthread_t thr[NUM_THREADS];
    int  pid = getpid();
    for (int i = 0; i < NUM_THREADS; i++)
    {
        if (pthread_create(&thr[i], 0, p_thread, (void *)&fd) != 0)
        {
            fprintf(stderr, "%.5d: failed to create thread number %d\n", pid, i);
            exit(EXIT_FAILURE);
        }
    }
    for (int i = 0; i < NUM_THREADS; i++)
    {
        if (pthread_join(thr[i], 0) != 0)
        {
            fprintf(stderr, "%.5d: failed to join thread number %d\n", pid, i);
            exit(EXIT_FAILURE);
        }
    }
    printf("%.5d: master thread exiting\n", pid);
    exit(EXIT_SUCCESS);
}

int main(void)
{
    int fd[2];
    pipe(fd);
    pid_t pid = fork();
    if (pid < 0)
        fprintf(stderr, "failed to fork\n");
    else if (pid == 0)
    {
        close(fd[1]);
        childish(fd[0]);
    }
    else
    {
        close(fd[0]);
        parental(fd[1]);
    }
    return EXIT_FAILURE;  // Failed to fork
}

Note that p_thread(), the thread function, is almost a copy of the previous parental function, but the new parental() function coordinates the creation and termination of three threads.  The code in childish() and main() did not need changing at all (though I added the R to the print in childish() to match the W in the code in p_thread()).


text:
Q: backbone.js/marionette.js global region: body inside body In my index.html I've got empty  tag. I've got a view that loads content for the view (through icanhaz). I would like to have a global region (bound to body tag) and to put some contents inside it through a view. The problem I have is that it puts entire new body tag into existing body tag.
This is application:
var Application = new Marionette.Application();

Application.addRegions({
  bodyRegion: new Marionette.Region({el: "body"})
});

Application.addInitializer(function(options) {
    Application.bodyRegion.show(new RootView());
});

This is my rootView:
Backbone.View.extend({
    tagName: 'body',

    initialize: function(options) {
        logger.init('root');
        loader.loadTemplate(template);
        this.headerView = new HeaderView();
        this.usersView = new UsersView();
    },

    render: function() {
        logger.render('root');
        this.$el.html(ich.rootTemplate);
        this.headerView.setElement(this.$el.find('#header')).render();
        this.usersView.setElement(this.$el.find('#main')).render();
        return this;
    }
});

This is my root.ich:

The problem I've got is that after rendering I've got a  tag inside another  tag. If I don't use Marionette and use plain backbone views instead, with following lines:
var rootView = new RootView();
rootView.setElement('body').render();

everything works fine. What am I doing wrong?

A: tagName: 'body', creates a new body element (your second one). Use el: 'body' if your element has to be the body, tagName is used to create a new element for the views which don't have one.

A: just remove the tagname declaration and you should be fine.
your view root view will inset itseft into the body ( your region el) creating a div for itself that will be its on el.
if a div is not acceptable and you need the region el to be the body then
change your region declaration
Application.addRegions({
    bodyRegion:"body" // this will create your new region just fine with body as its el
});

and your view should look like this...
Backbone.View.extend({
el: 'body',  // with this line your view will be atached to an existing element in this case the body.

initialize: function(options) {
    logger.init('root');
    loader.loadTemplate(template);
    this.headerView = new HeaderView();
    this.usersView = new UsersView();
},

render: function() {
    logger.render('root');
    this.$el.html(ich.rootTemplate);
    this.headerView.setElement(this.$el.find('#header')).render();
    this.usersView.setElement(this.$el.find('#main')).render();
    return this;
}

});


text:
Q: React native error when get data firebase firestore I can add data to firestore on firebase. But I can't get data from.
Does anyone can give me example and good configuration for?
Error:

Could not invoke RNFirebaseFirestore.collectionGet null

Image for error when try to get data

Build.gradle on Project

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.3'
        classpath 'com.google.gms:google-services:4.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }

        maven {
            url 'https://maven.google.com'
        }
    }
}

Build.gradle on App

dependencies {
    implementation(project(':react-native-firebase')){
        transitive = false
    }
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:23.0.1"
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'com.google.firebase:firebase-core:16.0.1'
    implementation "com.google.android.gms:play-services-base:15.0.1"
    implementation "com.google.firebase:firebase-firestore:15.0.0"
}

apply plugin: 'com.google.gms.google-services'

Version i used :

"dependencies": {
    "firebase": "^5.3.0",
    "react-native": "0.55.4",
    "react-native-firebase": "^4.3.8",

This is my code to get data

firebase.firestore().collection("Product").get().then(function(querySnapshot) {
   querySnapshot.forEach(function(doc) {
    console.log(doc.id, " => ", doc.data());
   });
  });

Thanks in advance


text:
Q: Streaming Twitter Error : Error parsing twitter reply: `Exceeded connection limit for user` I'm trying to stream twitter status in Node.js, but keep getting that error. What is Twitter limitation for such connection ? Or what that error means ?
Btw, it's still in development, so I might try to restart app frequently. I thought that was the problem. Is it true ?

A: Twitter generally don't allow you to establish too many connections to the streaming API at the same time with the same set of credentials.
In my case, work finally done by unifying all the wanted changing "Track" as one string, and seperating by "," which means OR between each. Then you filter the results as your wish.


text:
Q: Typescript: literal type with restrictions I have come across the following situation a few times already and have never really found an optimal solution yet. The problem is I want to construct an object with certain restrictions, but also keep the literal type info. The idea is to create a simple object with string keys and restrict the value type.
Literal type
const pets = {
  dog: {
    sound: "Bark",
    name: "Canis familiaris"
  },
  cat: {
    sound: "Meow",
    name: "Felis catus"
  }
} as const;

This preserves all literal information, so you can get a union type of the keys or sounds, e.g.
type PetKey = keyof typeof pets; // 'cat' | 'dog'
type PetSound = typeof pets[PetKey]['sound']; // 'Bark' | 'Meow'

However it does not enforce any type in the declaration itself - I would like to enforce that sound and name are strings. You could use some sort of assertion like this:
type Pet = {
  sound: string,
  name: string
}

pets as Record<string, Pet>;

Now you'll get a Typescript error if a pet has the wrong type; however the error will be at the line of the assertion, and there's no autocomplete when editing pets.
Record type
type Pet = {
  sound: string,
  name: string
}

const pets: Record<string, Pet> = {
  dog: {
    sound: "Bark",
    name: "Canis familiaris"
  },
  cat: {
    sound: "Meow",
    name: "Felis catus"
  }
}

This gives you type checking in place and autocomplete, but loss of literal type information, so now:
type PetKey = keyof typeof pets; // string
type PetSound = typeof pets[PetKey]['sound']; // string

Function helper
This is perhaps the best I was able to find/come up with:
type Pet = {
  sound: string,
  name: string
}

export const assertPets = <T>(_pets: {
    [K in keyof T]: Pet;
}) => _pets;

const pets = assertPets({
  dog: {
    sound: "Bark",
    name: "Canis familiaris"
  },
  cat: {
    sound: "Meow",
    name: "Felis catus"
  }
});

type PetKey = keyof typeof pets; // 'dog' | 'cat'
type PetSound = typeof pets[PetKey]['sound']; // string

You'll get autocomplete and type-checking in place. The keys are reserved, but there is still some loss of information, so PetSound is still just string.
It also feel a bit dirty, because it adds an actual runtime function call.
Ideal solution
This is where you come in, is there a way to get the best of both worlds? So restricting the type while also preserving the fully literal type?


text:
Q: How create Dropdown list only using ViewBag in ASP.NET MVC 4? Here I have a model class..
public class MyDrop
{
    public int id { get; set; }
    public string value { get; set; }
}

In my controller I use this code....
public ActionResult Index(){

    var GenreLst = new List<MyDrop>();

    MyDrop a = new MyDrop();
    a.id = 1;
    a.value = "hello";

    MyDrop b = new MyDrop();
    b.id = 2;
    b.value = "hello2";

    GenreLst.Add(a);
    GenreLst.Add(b);
    ViewBag.ShowDropDown = new SelectList(GenreLst);

}

Then in my view I add this code...
@Html.DropDownList("ShowDropDown", "All")

After run the project.It show a dropdown list.
But not showing correct values.
In the page source it likes this....
<select id="ShowDropDown " name="ShowDropDown "><option value="">All</option>
<option>DropDown.Models.MyDrop</option>
<option>DropDown.Models.MyDrop</option>
</select>

How do I solve this???
I was Expected like this.....
<select id="ShowDropDown " name="ShowDropDown "><option value="0">All</option>
<option value="1">hello</option>
<option value="2">hello2</option>
</select>

Please Help......

A: public ActionResult Index(){

    var GenreLst = new List<MyDrop>();

    MyDrop a = new MyDrop();
    a.id = 1;
    a.value = "hello";

    MyDrop b = new MyDrop();
    b.id = 2;
    b.value = "hello2";

    GenreLst.Add(a);
    GenreLst.Add(b);
    ViewBag.ShowDropDown = new SelectList(GenreLst, "id", "value");

}

In your View:
@{
SelectList list = ViewBag.ShowDropDown;
}

@Html.DropDownList("DROPDOWNID", list, "All")


text:
Q: Dynamic programming: find possible sums of given digits to reach given sum Maybe anyone has idea how to solve this problem using dynamic programming: I have a natural number. Let's name it n. Then, have digits: 1, 3, 4. I have to find all possible sums (with repetitives) of n using digits above. For example.
n=3. Then solution:
1+1+1=3
3=3

I know how to solve this problem using recursion or loops, but I really have no idea how to solve it with dynamic programming. And how to write relation for subproblems.

A: Hint: condition on the first element in the sum.


text:
Q: c free of two dimensional array gives segmentation fault Can somebody please explain me way the free(test[0]) is giving me a segmentation fault (core dumped)? I've tried to comment out the free and then the program terminates correctly (except from the lost memory). Also if I comment out test[0] = "abcd" and insert the free(...) again it terminates correctly too!?
char **test = (char**) (malloc(sizeof(char*) * 5));
for (int i=0; i<5; i++) {
  test[i] = (char*) (malloc(sizeof(char*) * 5));
}

test[0] = "abcd";
free(test[0]);

A: Use strcpy instead of == , because here, you just gives test[0] the adresse of a static chain "abcd", that cannot be disallocated like that.

A: Please see @Fvirtman's answer to fix your crash.
Then to prevent leaks :
test is a two dimentional array so you need to free each one of it's sub-arrays first then free test like this :
for (int i=0; i<5; i++) {
  free(test[i]);
}
free(test);

A: You overwrite your pointer test[0] with address of "abcd",which is statically allocated array that resides in read-only area. Add this printf("%p",test[0]); before and after test[0] = "abcd"; for visualisation of what happens.


text:
Q: How unique are the adventures of the Enterprise within Starfleet? Throughout the Star Trek franchise, we are shown that the Enterprise is held in especially high esteem within Starfleet.  For example, Riker refused his own ship to pursue a tour on the Enterprise, and it seems that not many (if any) other ships have been recommissioned again and again so many times (Enterprise-D, Enterprise-E, etc).  It is often the flagship of Starfleet, and many crew members are unusual or highly respected (such as the unique Data or Captain/Admiral/Captain Kirk).  And of course, the adventures and exploits of the Enterprise are legendary, with entire wars and even threats to reality itself being thwarted regularly, and many revolutionary discoveries being credited to the ship and her crew.
However, we've also seen enough of the larger universe to know that other ships get into similar situations.  The Voyager crew, for example, got into quite a few hijinks, and the crew of Deep Space 9 didn't have an easy time of it either.  It's probably safe to say that Sulu's Excelsior had an interesting service history, from what we see of it, and every once in a while we encounter a Starfleet officer who isn't terribly impressed by the Enterprise, implying that it's not objectively unique, or at least not indisputably so.
Are we therefore to assume that most, if not all, Starfleet ships have similar adventures?  That encounters with extra-dimensional beings, ancient planetary disputes, accidental time travel, and threats to the fabric of reality are the norm, or at least not unheard of, for all major space-faring vessels?  To put it another way, is that just how things work for a galactic civilization, just as jet lag, juggling time zones, and international law disputes become commonplace for a planet-spanning society?
Or do the adventures shown in the various Star Trek shows and movies constitute the "best and weirdest" of the things that happen in the Star Trek universe, and the Enterprise (and Voyager and DS9, etc) are unique in the quantity (or sheer existence) of unusual "adventures" among the ships of Starfleet?

A: Well, not wholly unique - each starship has its own voyages and adventures, but the ships we see specifically in each Star Trek series are under exceptional circumstances.
We have:

*

*ToS: A capital-class starship on an exploratory mission at the edge of space, during a time when conflict with violent Klingons and other newly-discovered species was frequent.

*TNG: The flagship of the federation.  You'll notice that a lot of the conflicts that Enterprise D encounters are more diplomatic in nature, but as a Flagship and the height of Starfleet's advances in technology, this Galaxy-Class ship is used often in the most dangerous of situations, and is also being used to explore unknown problems (At the time of the first episode, 'Farpoint' was the edge of Federation space).

*DS9: A starbase that, at the start of the series is next to a remote little-known planet (albiet having just overcome an enemy occupation), but quickly gains importance for being located right next to a worm hole, through which races and dangers never seen before are emerging.

*Voyager: Flung to the very farthest reaches of space, to lands uncharted, with no help from anyone in Starfleet.

*Enterprise: The first real exploratory starship in Starfleet, of course it's going to encounter a lot of interesting and unknown things.

But, it should be noted that the episodes we see of their encounters are the exceptional events that occur aboard these starships (and one starbase), not the norm.  We're expected to assume a period of normalcy between episodes unless otherwise stated (like episodes that are part of a series or running plotline).  Simply put - the events we seen in each episode are the things 'worth writing home about'.

A: In The Next Generation series, it is implied that Galaxy class vessels such as the Enterprise did have unique missions of exploration compared with more routine missions for other ships in Star Fleet.
We hear the following exchange in "Tin Man" (TNG 3x20) between Captain DeSoto of the USS Hood (Excelsior class) and Captain Picard:

Captain Picard: "So, old friend, how are you?"
Captain DeSoto: "Ah,
well... you know they send you Galaxy-class boys out here to the far
reaches. Me, I just haul my butt between starbases."

A: No. The Enterprise was not unique in its exploration of space no matter what era it was in. The Original Series Star Trek Enterprise was one of twelve Constitution-class starships.

*

*Each of those ships was involved in the same kinds of missions the Enterprise had. We learned in The Original Series, it was dangerous to be on a Constitution class vessel.

*As viewers we are privy to the destruction of or loss of at least four of those ships or their crews. (Constellation, Exeter, Intrepid and Excaliber)

*The Enterprise had a distinction of having a crew that had a great deal of experience considering by the time Captain Kirk takes command of the ship, it had already been on three five year missions, one with its first captain, Robert April in 2245, two with its second captain, Christopher Pike and its most famous period with Captain James T. Kirk in 2265.

In 2267, there were around twelve Constitution-class starships in the fleet. (TOS: "Tomorrow is Yesterday") These included:

*

*Enterprise - Survived five year missions

*Exeter - Crew infected and ship abandoned - (TOS: "The Omega Glory")

*Excalibur - Damaged by M-5. Crew killed. (TOS: "The Ultimate Computer")

*Lexington - Damaged in exercise with M-5 computer (TOS: "The Ultimate Computer")

*Hood - Damaged in exercise with M-5 computer. (TOS: "The Ultimate Computer")

*Potemkin - Damaged in exercise with M-5 computer. (TOS: "The Ultimate Computer")

*Constellation - Destroyed by the Doomsday Machine (TOS: "The Doomsday Machine")

*Farragut - Heavy crew casualties after attack from dikironium cloud creature

*Intrepid - Destroyed by a macrocellular organism (TOS: "The Immunity Syndrome")

*Yorktown - Survived five-year missions, later disabled by Whale Probe in 2286

*Republic - Survived five year missions, patrolled Neutral Zone, a training vessel

*Valiant - Destroyed as a casualty in a war simulation (TOS: A Taste of Armageddon)

*Constitution - Fate unknown

*Kongo - Never seen on screen, fate unknown

Despite the successes of the class, exemplified by the performance of Kirk's ship, the mission parameters for the Constitution-class also meant that the vessels of the class operated under highly dangerous circumstances, resulting in a relatively high loss rate, and that being assigned to one was hazardous at best.

*

*While we see the Enterprise and other ships which were on TV as having special adventures, other Federation crews were having potentially similar and dangerous interactions with alien life, discovering new technologies and experiencing unknown phenomena. It was part of the job description:

"These are the voyages of the starship (your ship name here). It's continuing mission, to explore strange new worlds, seek out new life and new civilizations. To Boldly go where where no one has gone before."
Unspoken but fervently hoped by every crewmember: "And hopefully we get to come back home when we're done."

A: There's an episode of Voyager where something unbelievably weird and mind-blowing happens to Harry Kim, and towards the end of the episode he tries to talk to Janeway about it.  She simply shrugs, and says "That's just another day in the life of a Star Fleet officer".

A: Not only are differing classes of starship given differing roles, long or short range, investigative or martial, but they have different crews.
What could end badly for a Miranda-class with an average captain, could end heroically for a captain of greater ability or bravery, or just a better vessel, like a Nebula-class. Reading a situation one way could lead to great discovery, reading it another way could mean a missed chance.
As a flagship, the Enterprise has a top-line captain and crew who obviously see things in a particular way, take a braver or more direct course, read different things into it and have more spectacular ideas of how to deal with it.
Two identical ships have differing crews, its the spectacular crews we want to watch, not the shy careful ones.

A: Even in real life, the name Enterprise for a ship has a special signification to Americans: not only the first Enterprise airplanes carrier has escaped the attack on Pearl Harbour without any damage but it's also the only carrier to have fought through all the second world war without beeing sunk.  All the other carriers have either been sunk or have been built after the start of WWII and therefore, this name has a special place in the heart of many Americans (and especially more for those in the Navy and the Army).
Even today, you don't name a small boat Enterprise without the risk of seeing Americans taking this as a personal insult and even when Gene R. decided to chose this name for the main ship of his new Star Trek serie, that decision nearly got reversed by the network because many of its administrators feared a backlash.


text:
Q: Mathematical models in psychology Do you know examples of application of mathematics in psychology besides statistical data processing?
For example, do there exist mathematical models of addiction to Internet sites?

A: The mathematician Ulf Grenander wrote a book where he applied his General Pattern Theory to propose a mathematical model of generation of train of thoughts.
This is an example of application of mathematics to higher cognition.
The model can be tuned to model abnormal psychological disorders characterized for example by obsessional thoughts.
The book is a good read and you have Matlab code to play with.
References :
Grenander, U. (2012). A calculus of ideas: a mathematical study of human thought. World Scientific.
Grenander, Ulf. General pattern theory: A mathematical study of regular structures Oxford mathematical monographs. Oxford University Press: Clarendon, 1993.
Code of the model :
http://www.dam.brown.edu/ptg/REPORTS/mind07.zip

A: Actually there are a few models using a different approach.
Have a look at Abelson 1967 and more recently
Agent-Based Modeling: A New Approach for Theory Building in Social Psychology
Eliot R. Smith and Frederica R. Conrey
Pers Soc Psychol Rev 2007; 11; 87
DOI: 10.1177/1088868306294789
I published also some models, see e.g.
Dal Forno A., & Merlone, U., (2013). Nonlinear dynamics in work groups with Bion's basic assumptions. Nonlinear Dynamics, Psychology, and Life Sciences, Vol.17, No.2, April, pp.295-315.


text:
Q: Поиск определенных значений в тексте Прошу подсказать удобный метод для  поиска слов/значений в тексте.
Есть  hashMap c ключом и значением это код страны RU и значение Россия <String,String>
Мне нужно проверить большой текст на наличие в нем Кодов стран , которые содержатся  в  hashMap.
Например , если в тексте есть RU DE ZB , то нужно вывести их и отобразит.
Идея такая , что нужно брать каждый элемент (код) из hashMap и искать его в тексте , если он есть , добавляем его значение (полное название страны) в коллекцию и так до конца и  так до конца , пока не
не закончится текст.
После того, когда я заполнил мапу значениями:
 @Test
    Map<String,String> contextLoads() {

        String[] countries = Locale.getISOCountries();

         var arr = new ArrayList<Countries>(countries.length);

        var hm = new HashMap<String, String>();

        for(Countries o : arr) {

            hm.put(o.getCode(), o.getName());

        }

        return hm;
        }

Далее , создал метод , который посоветовали в комментариях, чтобы найти в тексте
коды стран и вывести их:
@Test
    void contextShow(String text, Map m) {

        String t = "if(panContry=='DE')";
    m=contextLoads();

        String reg =String.format("^|[ (])(%s)($|[\\s.!?,)])", String.join("|", m.keySet()));
        Pattern p = Pattern.compile(reg);
        Matcher mat = p.matcher(t);

        Set<String> countries =new HashSet<>();

        while (mat.find()) {
            countries.add((String) m.get(mat.group(2)));
        }

       for(String c : countries) {
           System.out.println(c);
       }

Ошибка при выполнении:
  org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [java.lang.String text] in method [void com.statusinfonew.springboot.SpringBootStatusinfoApplicationTests.contextShow(java.lang.String,java.util.Map)].
    at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameter(ExecutableInvoker.java:200)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:183)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:144)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:96)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:84)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

Уточите , в чем может быть проблема ?

A: Ну, если немного поупарываться, то так:
    public static void main(String[] args) {
    String text = "lalala RU bla bla RU. DE la al UK";

    Map<String, String> codes = new HashMap<>();
    codes.put("RU", "Russia");
    codes.put("DE", "Germany");
    codes.put("UK", "United Kingdom");

    String reg = String.format("(^|[ (])(%s)($|[\s.!?,)])", String.join("|", codes.keySet()));
    Pattern p = Pattern.compile(reg);
    Matcher m = p.matcher(text);

    Set<String> countries = new HashSet<>();

    while (m.find()) {
        countries.add(codes.get(m.group(2)));
    }

    countries.forEach(System.out::println);
}

В такой задаче регулярные выражения жизненно необходимы, чтобы не учитывать случаи, когда нужная последовательность символов является частью какого-то слова, но учитывать её в начале/конце текста, вместе с запятой, в скобочках и тд.
String.format() тут нужен, чтобы подставить страны из мапы в выражение.
Что по поводу принципа работы... По моей логике, перед кодом страны может находиться начало строки, открывающая скобка или пробел. За это отвечает (^|[ (]) данная часть выражения. Обычно для выбора одного любого символа из какого-то списка используют [] квадратные скобки, но с таким методом у меня возникли проблемы с символом начала строки ^ и с открывающей скобкой, которые либо автоматически экранировались, где не надо, либо не экранировались там, где надо. Поэтому я использовал конструкцию (элемент|элемент|элемент), она сработала, как запланировано.
Потом после выполнения подстановки у меня идет такая часть: (RU|DE|UK). Здесь я использую |, так как мне требует именно сочетание двух букв, а не любой из символов.
После кода страны по логике должен следовать знак препинания, пробел, закрывающая скобка или конец строки, за что и отвечает эта ($|[\s.!?,)]) часть выражения. Опять использую |, потому что возникали проблемы с экранированием символа $.


text:
Q: Hashing algorithm support in firebase real-time database security rules I would like to compute hash functions inside security rules.
md5hash(auth.token.email) === $hashedvalue

Is there a way for me to do that in bolt? or natively in firebase real-time database?
Use Case:
Basically I would like to store the email as the key in the firebase real-time database and use it in the firebase security rules for authentication and authorization. Since few special characters like dots (.) are not supported in keys I was thinking of using some hashing algorithm which is available in firebase real-time database.
auth.id doesn't work in my case as I'm not giving any sign up option as I have a pre defined set of users with pre-defined profile details accessing my application through their Google login (which I know the email ID of) to start with and since they haven't yet logged into my application I don't have a corresponding ID to authenticate or authorize them on their first attempt.

A: This page of documentation shows all the functions available in Realtime Database security rules.  There are no hashing functions there.  You could file a feature request to explain you use case.

A: For the sake of posterity, I got this working with a small workaround (Yay!).
From the fire firebase real-time database documentation I found out that firebase security rules supports an amazing string function called "replace" xD.
So now I pre process the email Ids by replacing all the characters not supported as database key with their url encoding equivalent before creating the key and use the same set of replacements in my firebase security rules.


text:
Q: Issue creating Laravel Nova tool I'm trying to create a Laravel Nova tool but when I do via the command line, after the first prompt (see below), I get this error
 Would you like to install the tool's NPM dependencies? (yes/no) [yes]:
 >

npm WARN deprecated browserslist@2.11.3: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm WARN deprecated browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm WARN deprecated gulp-util@3.0.8: gulp-util is deprecated - replace it, following the guidelines at https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5

I've run npm i -g npm but that doesn't seem to have fixed the problem. I can't seem to solve this, any ideas of how I can get this working?


text:
Q:  using mechanize of Python I'm trying to use mechanize submit a picture's URL to a website's image search engine. This is my code bit. The image I choose is randomly selected from internet.
r = br.open('http://stu.baidu.com/')
for f in br.forms():
    print f
br.select_form(nr=1)

br.form['objurl']='http://images2.fanpop.com/image/photos/13900000/Pretty-Dogs-in-Garden-dogs-13905929-1920-1200.jpg'
br.submit()
print br.submit

However, this is what I get from the terminal response. I don't know where am I wrong....
face2.py:13: UserWarning: gzip transfer encoding is experimental!
  br.set_handle_gzip(True)
<form2 POST http://stu.baidu.com/i?rt=0&rn=10&stt=0&ct=0&tn=baiduimage multipart/form-data
  <FileControl(image=<No files added>)>>
<form1 GET http://stu.baidu.com/i multipart/form-data
  <TextControl(objurl=)>
  <SubmitControl(<None>=识图一下) (readonly)>
  <HiddenControl(filename=) (readonly)>
  <HiddenControl(rt=0) (readonly)>
  <HiddenControl(rn=10) (readonly)>
  <HiddenControl(ftn=indexstu) (readonly)>
  <HiddenControl(ct=1) (readonly)>
  <HiddenControl(stt=0) (readonly)>
  <HiddenControl(tn=shituresult) (readonly)>>
Traceback (most recent call last):
  File "face2.py", line 42, in <module>
    br.submit()
  File "/Library/Python/2.7/site-packages/mechanize-0.2.5-py2.7.egg/mechanize/_mechanize.py", line 541, in submit
    return self.open(self.click(*args, **kwds))
  File "/Library/Python/2.7/site-packages/mechanize-0.2.5-py2.7.egg/mechanize/_mechanize.py", line 530, in click
    request = self.form.click(*args, **kwds)
  File "/Library/Python/2.7/site-packages/mechanize-0.2.5-py2.7.egg/mechanize/_form.py", line 2999, in click
    self._request_class)
  File "/Library/Python/2.7/site-packages/mechanize-0.2.5-py2.7.egg/mechanize/_form.py", line 3201, in _click
    return control._click(self, coord, return_type, request_class)
  File "/Library/Python/2.7/site-packages/mechanize-0.2.5-py2.7.egg/mechanize/_form.py", line 2350, in _click
    r = form._switch_click(return_type, request_class)
  File "/Library/Python/2.7/site-packages/mechanize-0.2.5-py2.7.egg/mechanize/_form.py", line 3269, in _switch_click
    req_data = self._request_data()
  File "/Library/Python/2.7/site-packages/mechanize-0.2.5-py2.7.egg/mechanize/_form.py", line 3235, in _request_data
    "unknown GET form encoding type '%s'" % self.enctype)
ValueError: unknown GET form encoding type 'multipart/form-data'

A: I can't seem to load Baidu, however it might have something to do with "UserWarning: gzip transfer encoding is experimental". Alternatively, you may need to urllib.urlencode your GET data.
Some examples:
http://pymotw.com/2/urllib/
http://kentsjohnson.com/kk/00010.html


text:
Q: How to set tableview height according to its content-size in SwiftUI? I need to disable scroll in tableView and increase the height according to its content. below is my code for table view in swiftUI please draw me guidance
var body: some View {
        List{

         ForEach(testData){ data in
                    VStack(alignment: .leading){
                                   HStack{
                                    Image(data.name)
                                       .resizable()
                                       .frame(width: 50, height: 50, alignment: .leading)

                                    VStack(alignment: .leading){
                                        Text(data.name)
                                               .bold()
                                        Text(data.bio)
                                               .font(.subheadline)
                                       }
                                   }
                               }
            }
        }
        .offset(y:-60)
        .padding(8)
    }

A: You could do this by removing the List and swapping it for a VStack. Then you would use a divider at the end of each VStack of elements and you would add  horizontal padding and this gives the same effect as a list, but makes it not scrollable and it would adjust height depending on the elements.
VStack{
ForEach(testData){ data in
 VStack(alignment: .leading){
        HStack{
        Image(data.name)
            .resizable()
            .frame(width: 50, height: 50, alignment: .leading)

         VStack(alignment: .leading){
             Text(data.name)
                    .bold()
             Text(data.bio)
                    .font(.subheadline)
            }
        }
    }
 }
Divider()
.padding(.horizontal)
}
.offset(y:-60)
.padding(8)

}


text:
Q: Python: Matching multiple patterns in File I'm trying to extract some information from a File.
File:
ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34  CONTENT ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34  CONTENT

CONTENT
CONTENT
CONTENTCONTENTCONTENT CONTENTCONTENT
CONTENTCONTENTCONTENTCONTENTCONTENT
CONTENTCONTENTCONTENTCONTENTCONTENT

I wanna execute multiple pattern in this file but when I extract the first information the rest of them (File) comes empty.
import re
import pdb

w = open("extractfile.txt","r")

print w.read()
print re.findall(r'CONTENT', w.read())
print re.findall(r'\w{3} \d{2}-\d{2}-\d{2}', w.read())

Output:
ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34  CONTENT ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34 ASD 23-02-34  CONTENT

CONTENT
CONTENT
CONTENTCONTENTCONTENT CONTENTCONTENT
CONTENTCONTENTCONTENTCONTENTCONTENT
CONTENTCONTENTCONTENTCONTENTCONTENT

[]
[]

If I change the print order, it always shows the first print, the rest of them comes empty... Another thing that I thought was Multiple Pattern in one line, by using groups, but I don't know if it would work

A: >>>> import re
>>>> with open('extractfile.txt', 'r') as txt:
....     file = txt.read()

>>>> match = re.findall(r'CONTENT', file)
>>>> content
['CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT', 'CONTENT']

>>>> pattern = re.findall(r'(?P<asd>[\w]+ )(?P<dgt>[\d-]+)', file)
>>>> pattern
[('ASD ', '23-02-34'), ('ASD ', '23-02-34'), ('ASD ', '23-02-34'), ('ASD ', '23-02-34'), ('ASD ', '23-02-34'), ('ASD ', '23-02-34'), ('ASD ', '23-02-34'), ('ASD ', '23-02-34'), ('ASD ', '23-02-34'), ('ASD ', '23-02-34'), ('ASD ', '23-02-34'), ('ASD ', '23-02-34'), ('ASD ', '23-02-34'), ('ASD ', '23-02-34'), ('ASD ', '23-02-34')]

the  whitespace after [\w]+ can also excluded from the <asd> group by  moving it out, but it's slower since regex ends up doing more steps.
re.findall(r'(?P<asd>[\w]+) (?P<dgt>[\d-]+)', file)


text:
Q: Remove IIS server details in Angular application I am trying to hide server details when angular application after loading. help me to hide this details. I attached the screen shot for reference

A: You need to remove the server response header from IIS. Following is a question answer that might help you.
Remove Server Response Header IIS 8.0 / 8.5
First, you need to install the plugin and write the code like below in web.config file.

Basically you need to add rewrite module and overwrite that value with your value.


text:
Q: How do I type the pipe character on a MacBook Pro (Lion) with a Turkish-Q keyboard layout? I can't find the keyboard combination to make the | symbol. On snow leopard "shift+ı" worked. I've tried shift+\. Any suggestions?

A: Under Ubuntu 12.04 LTS running on PowerBook G4, I selected Macintosh layout. Then, I mapped the third level key binding to the right Apple key (Alt right). Once done, typing Shift+Alt,→+L gives the pipe character.

A: I was on a turkish-q keyboard. The correct combination is strange, but  alt + < worked for me.


text:
Q: How to forward to one of two overloads, without duplicating code? I have a C++ class with two overloads of a private method, and those should be connected to two overloads of a public method.
The public method is the same in both overloads, it differs only in which overload of the private method it calls. The two private method overloads, on the other hand, are entirely different, which is why I chose to overload them in the first place.
To avoid duplicating code in the public method, this seems like a good use case for perfect forwarding. But on the other hand, then if you want to call the public method and are not familiar with the API, it's difficult to see which arguments you have to provide; you would have to examine the body of the public method, and then consult the private interface to see which overloads of the private method exist.
I've tried to make a toy class that illustrates my problem:
class Foo {
public:
    struct DontCopyTheBaz {};

private:
    bool init_from_baz(Baz& a_baz);
    bool init_from_baz(Baz& a_baz, DontCopyTheBaz);

public:
    // ...should I use perfect forwarding, making the API not easily readable?
    template<typename... Args>
    static Foo* new_for_baz(Baz& a_baz, Args&&... args) {
        Foo* the_foo = new Foo();
        if (!the_foo->init_from_baz(a_baz, std::forward<Args>(args)...)) {
            delete the_foo;
            return nullptr;
        }
        return the_foo;
    }

    // ...or should I write duplicated code?
    static Foo* new_for_baz(Baz& a_baz) {
        Foo* the_foo = new Foo();
        if (!the_foo->init_from_baz(a_baz)) {
            delete the_foo;
            return nullptr;
        }
        return the_foo;
    }
    static Foo* new_for_baz(Baz& a_baz, DontCopyTheBaz no_copy) {
        Foo* the_foo = new Foo();
        if (!the_foo->init_from_baz(a_baz, no_copy)) {
            delete the_foo;
            return nullptr;
        }
        return the_foo;
    }
};

(In reality both the private and public methods are longer and more complicated.)
Is there a way to avoid the code duplication, while still making the API easy to understand?

A: You can add extra indirection to factorize the code and have clean interface:
class Foo {
public:
    struct DontCopyTheBaz {};

private:
    bool init_from_baz(Baz& a_baz);
    bool init_from_baz(Baz& a_baz, DontCopyTheBaz);

    template<typename... Args>
    static std::unique_ptr<Foo> new_for_baz_impl(Baz& a_baz, Args&&... args) {
        auto the_foo = std::make_unique<Foo>();
        if (!the_foo->init_from_baz(a_baz, std::forward<Args>(args)...)) {
            return nullptr;
        }
        return the_foo;
    }

public:
    static std::unique_ptr<Foo> new_for_baz(Baz& a_baz) {
        return new_for_baz_impl(a_baz);
    }
    static std::unique_ptr<Foo> new_for_baz(Baz& a_baz, DontCopyTheBaz no_copy) {
        return new_for_baz_impl(a_baz, no_copy);
    }
};


text:
Q: Bidirectional infinite scrolling with FlatList? Has anyone had experience doing bidirectional infinite scrolling with FlatList (or any other component)?
My use case is I have a calendar month view that I want to be able to swipe left and right to get the next and previous month.
FlatList with onEndReached and onEndReachedThreshold works great for one direction, but there is no similar thing for the start.  Any suggestions?

A: You can use the onScroll props on the Flatlist for that: https://reactnative.dev/docs/scrollview#onscroll
        onScroll={({
                nativeEvent: {
                    contentInset: { bottom, left, right, top },
                    contentOffset: { x, y },
                    contentSize: { height: contentHeight, width: contentWidth },
                    layoutMeasurement: { height, width },
                    zoomScale,
                },
            }) => {
                if ( y <= your_start_threshold) {
                     // Do what you need to do on start reached
                }
            }}

Only problem is that React native doesn't support bidirectional FlatList on Android. This means that when you add items to the start of your list, it will jump to the top instead of keeping the current items in view (https://github.com/facebook/react-native/issues/25239).
(iOs does have a maintainVisibleContentPosition props)


text:
Q: How to populate a TableView using AFNetworking, CocoaPods and ObjectiveGumbo? I have this code from a web site:

                        Titolo
                        Data
                        Data scadenza

                        Linee bus 40-72: dal 29/7 spostamento di fermata
                        29/07/2014
                        19/08/2014

                        Linea 162: dal 29/07 modifica di percorso
                        29/07/2014
                        29/07/2015

                        Linea tram 12: modifica di percorso del 01/08
                        29/07/2014
                        01/08/2014

                        Linea M2: dal 26/7 chiusa Gessate. Bus tra Gorgonzola e Gessate
                        28/07/2014
                        31/08/2014

                        Linea 566: dall'1/8 modifica di percorso
                        28/07/2014
                        19/08/2014

..and so on with other data.
I want to take the data of Titolo, Data and DataScandenza and put them in a table view.
How can I do that using AFNetworking, CocoaPods and ObjectiveGumbo?
I've already made this method, but I think there's something wrong:
    -(id)responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing *)error
{
    OGDocument * document = [super responseObjectForResponse:response data:data error:error];

    NSArray * panels = [document select:@".AspNet-GridView"];

    NSMutableArray * articles = [NSMutableArray new];

    //The list of most read articles is in the second panel
    OGElement * list = (OGElement*)[panels[0] first:@"tr"];

    for (OGElement * listItem in [list select:@"td"])
    {
        OGElement * link = (OGElement*)[listItem first:@"a"];
        NSString * href = link.attributes[@"href"];
        NSString * title = [link.children[2] text];
        Article * article = [Article new];
        article.title = title;
        article.link = [NSURL URLWithString:href];
        [articles addObject:article];
    }

    return articles;
}

Please, someone helps me! :-) Thanks!
EDIT:
I solved it!
Here's how I did it. I modified the method in this way:
-(id)responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing *)error

{
    OGDocument * document = [super responseObjectForResponse:response data:data error:error];
 NSMutableArray * articles = [[NSMutableArray alloc]init];

NSMutableArray * panels = [document select:@".Infomobilita-Titolo"];

// OGElement * list = (OGElement*)[panels[1] first:@"a"];
    [panels removeObjectAtIndex:0];
for (OGElement *file in panels) {

    OGElement *li = (OGElement*) [file first:@"a"];
    NSString * href = li.attributes [@"href"];
    NSLog(@"%@",href);
    NSString * title = [file.children[0] text];
    Article * article = [Article new];
    article.title = title;
    article.link = [NSURL URLWithString:href];
    [articles addObject:article];
    NSLog(@"%@",[file.children[0] text]);
}

return articles;

}


text:
Q: select skip and limit item array user {
        [
            _id: xyz...,
            Statuss["id1", "id2", "id3", "id4", "id5", "id6", "id7", "id8", "id9", "id10"]
        ]
    }

I want to select Statuss skip(0).limit(5)
Tried:
collection.findOne({_id: id}, {Statuss: {$slice: [0, 5]}

but the result is:
Statuss["id1", "id2", "id3", "id4", "id5"]

want this result:
Statuss["id10", "id9", "id8", "id7", "id6"]

A: Tried this:
collection.findOne({_id: id}, {Statuss: {$slice: [5, 5]}


text:
Q: Changelog computation broken when using both shallow and non-shallow checkouts in Jenkins multibranch pipeline I am working on a Jenkins multibranch pipeline project that builds code on multiple platforms. Our code uses the GitSCM plugin to checkout. There is one initial shallow checkout that just fetches some bootstrap scripts:
    checkout scm: [
        $class: 'GitSCM',
        extensions: [
            [$class: 'CloneOption', depth: 1, noTags: false, reference: '', shallow: true],
            ...
        ],
        ...
    ]

After this initial checkout, there is one extra full (i.e. deep) checkout for each platform that we build on.
The problem I am seeing is that Jenkins computes only one changelog that contains only the most recent commit on the branch. This makes sense for the initial shallow checkout as commit history is not fetched. However, I am not seeing additional changelogs for the other checkouts. I wouldn't mind the commit in the branch tip to get duplicated in additional changelogs.
Here's what I've tried so far to fix the problem:

*

*I tried disabling the changelog computation for the initial checkout by passing changelog: false in addition to the scm parameter. However, this stopped changelogs being generated altogether, even for the other checkouts (I even tried explicitly setting changelog: true for the per-platform checkouts without success).

*I tried adding the ExcludeFromChangeSet extension to the initial checkout. This extension is mentioned (but not fully documented) here (see under $class GitSCM >> extensions): https://www.jenkins.io/doc/pipeline/steps/workflow-scm-step/. This failed because no known implementation of class hudson.plugins.git.extensions.GitSCMExtension is named ExcludeFromChangeSet.

*I had the idea that doing a deep but blobless clone (using Git's --filter=blob:none) might be a good compromise, but I cannot seem to find a way to specify that option. I'm also not sure whether this would actually fix the problem.

I'd rather not have to revert to a full checkout for the initial fetch. Interestingly, if there are any additional commits to the branch between the initial checkout and one of the per-platform checkouts, then an additional changelog for those new commits is generated.
Any help would really be appreciated here!
EDIT: Forgot to say that I also considered running the fetch command manually instead of using the checkout step, but I'd rather avoid that because GitSCM is currently doing all the heavy lifting for us (e.g. credentials management and cross-platform portability).


text:
Q: How to get min/max value indices in a Ruby array arr = [4, 9, 0, -3, 16, 7]
Is there any simple way to find the indicies of the lowest x elements?  Something like this?
arr.min_index(4)

A: arr.each_index.min_by(x) { |i| arr[i] }

or
arr.each_with_index.min(x).map(&:last)

Demo:
> arr, x = [4, 9, 0, -3, 16, 7], 4
=> [[4, 9, 0, -3, 16, 7], 4]
> arr.each_index.min_by(x) { |i| arr[i] }
=> [3, 2, 0, 5]
> arr.each_with_index.min(x).map(&:last)
=> [3, 2, 0, 5]

A: Here's one simple way to do it:
class Array
  def min_index(n)
    each_with_index.sort.map(&:last).first(n)
  end
end

>> arr = [4, 9, 0, -3, 16, 7]
>> arr.min_index(4)
#> [3, 2, 0, 5]
>> [4, 2, 2].min_by(2)
#> [1, 2]


text:
Q: WP Sql query - this has to be correct :-( i am trying to do actually very easy SQL query in Wordpress. I do not know why, but this does not work :-(
$my_query = ("SELECT DISTINCT meta_value FROM wp_usermeta WHERE meta_key = 'schoolcountry'");
    $vysledek = $wpdb->get_results($my_query);
    foreach ($vysledek as $value){
       echo $value->schoolcountry . ", ";
    }

I am in table called wp_usermeta, where are two columns - "meta_key" and "meta_value". And I need to echo the meta_value according to its "meta_key".
So my meta_key is called "schoolcountry" and value should be "CZ"... But this code returns empty nothing ", , , , , ," :-(
Anony knows, what is wrong?
Picture of table structure:
And Picure of var_dump:

A: The query itself is fine. The issue is with the way you're trying to display the result.
You're attempting to access the value by its meta_key (schoolcountry). The property you're trying to access doesn't exist. You need to use the column name (meta_value) instead.
Example:
foreach ( $vysledek as $value ) {
    echo $value->meta_value . ", ";
}

Another point worth raising is that by appending commas for each value in the loop, you'll have an extra comma on the end.
value1, value2, value3,

I'd be tempted to use implode() to fix that.
echo implode( ', ', array_map( function( $v ) {
    return $v->meta_value;
}, $vysledek );

Here we're using array_map to return a new array containing all of the meta values. Implode will then join them together without the extra comma on the end.