text:
Q: Error: "app" did not match any elements I'm creating an angular2 clientside app with a node.js server. clientside app seems to work perfectly fine, meaning that:

*

*All of my requests get proper responses.

*Application loads and works as expected.

but I get this error in terminal:
Error: The selector "app" did not match any elements
    at DomRenderer.selectRootElement (/home/mu-user/Projects/my-app/dist/server/index.js:27126:23)
    at selectOrCreateRenderHostElement (/home/mu-user/Projects/my-app/dist/server/index.js:15687:32)
    at AppView._View_AppComponent_Host0.createInternal (/AppModule/AppComponent/host.ngfactory.js:12:16)
    at AppView.create (/home/mu-user/Projects/my-app/dist/server/index.js:50916:21)
    at ComponentFactory.create (/home/mu-user/Projects/my-app/dist/server/index.js:36656:36)
    at ApplicationRef_.bootstrap (/home/mu-user/Projects/my-app/dist/server/index.js:23313:40)
    at /home/mu-user/Projects/my-app/dist/server/index.js:23222:89
    at Array.forEach (native)
    at Object.Call (/home/mu-user/Projects/my-app/node_modules/es6-shim/es6-shim.js:307:14)
    at Array.forEach (/home/mu-user/Projects/my-app/node_modules/es6-shim/es6-shim.js:1313:17)

which doesn't interrupt webpack or http-server .
The question is why I face this and how to resolve it?

A: I'm adding this answer for record as I described in comments too. This bug has been solved by fixing references to modules included in declaration list of ngModule.
It was tricky to figure out the issue from the context of the error message. and also because of the code complexity it wasn't possible to include actual project code, but I figured out the issue while trying to make a simpler version ready to show here.


text:
Q: Failed to read artifact descriptor for com.sun.xml.ws:jaxws-rt:jar:2.2.8: UnresolvableModelException: Failure to transfer com.sun.xml.ws:bundles:pom I am following example from http://memorynotfound.com/deploy-jaxws-application-tomcat-example/. I just imported this project (as Maven) into work-space, but I see following error coming:-
    Description Resource    Path    Location    Type
        ArtifactDescriptorException: Failed to read artifact descriptor for
    com.sun.xml.ws:jaxws-rt:jar:2.2.8: UnresolvableModelException: Failure to transfer com.sun.xml.ws:bundles:pom:2.2.8 from
    http://repo.maven.apache.org/maven2 was cached in the local repository,
resolution will not be reattempted until the update interval of central has
elapsed or updates are forced. Original error: Could not transfer artifact
    com.sun.xml.ws:bundles:pom:2.2.8 from/to central
(http://repo.maven.apache.org/maven2): connection timed out to http://repo.maven.apache.org/maven2/com/sun/xml/ws/bundles/2.2.8/bundles-
    2.2.8.pom   pom.xml /jax-ws-tomcat-example  line 1  Maven Dependency Problem

I am really exhausted with in solving the issue, please help/guide.

A: The error read connection timed out so your maven got problems to connect to the url: http://repo.maven.apache.org/maven2/com/sun/xml/ws/bundles/2.2.8/bundles-2.2.8.pom
Try it in your browser. It may be a network problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: HyperKaehler manifolds are Ricci-flat Hi,
I have the following question: Let $M$ be a Hyperkaehler manifold with complex structures $I,J,K$ and Hyperkaehler metric $g$. Let $\omega_{I} = g(I *, *), \omega_{J} = g(J *, *), \omega_{K} = g(K *, *)$ be the corresponding Kaehler forms. From these we set $\omega_{c} = \omega_{J} + \sqrt{-1}\omega_{K}$, which is a holomorphic symplectic form on $M$ with respect to $I$. Furthermore $(\omega_{c})^{n}$ is a non-vanishing holomorphic $2n$-form. This actually means that the canonical bundle is trivial. How can one show that $M$ is Ricci flat? And wit respect to which form? I would be very thankfull for a lot of answers. Thanks!
Greetings
Mina


text:
Q: Laravel define database in model A chunk of my SQL is held in a different database to the rest of my Laravel installation.
When I use a particular Model, how do I define in that Model, that I'd like to use a particular database and not the one defined in config/database.php?
I am using Laravel 5 so needs to be relevant to that version.
Update: Here is my model;
<?php namespace App\Models;

  use Illuminate\Database\Eloquent\Model;

  class Lookup extends Model {
    protected $connection = 'postcodes';
  }

Here is part of my config/database.php;
'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', $_ENV["DB_HOST"]),
        'database'  => env('DB_DATABASE', $_ENV["DB_DATABASE"]),
        'username'  => env('DB_USERNAME', $_ENV["DB_USERNAME"]),
        'password'  => env('DB_PASSWORD', $_ENV["DB_PASSWORD"]),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

    'postcodes' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', $_ENV["DB_HOST"]),
        'database'  => env('DB_DATABASE', 'postcodes'),
        'username'  => env('DB_USERNAME', $_ENV["DB_USERNAME"]),
        'password'  => env('DB_PASSWORD', $_ENV["DB_PASSWORD"]),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

It's not working - and I can't get Whooops errors to work so all I get is a white screen (but that's a separate issue).
I know my controller code is correct because when I temporarily copy the table in to my main Laravel database, it all works fine. So what's the issue?

A: You can define protected $connection = 'yourohterconnection'; in your model, and add another connection to your database config file.

A: I asked the same question on the Laravel forum and the posted solution worked for me.
Basically the problem is this line;
'database'  => env('DB_DATABASE', $_ENV["DB_DATABASE_TWO"]),

Or in my code above at the time of writing it was actually;
'database'  => env('DB_DATABASE', 'postcodes'),

It needs to be;
'database'  => env('DB_DATABASE_TWO', $_ENV["DB_DATABASE_TWO"]),

And then your .env file needs to have DB_DATABASE_TWO=postcodes (or whatever the name of your second database is).


text:
Q: Solve $ab(a^2+b^2)=2c^4$ over $\mathbb Z$ Find all integer solutions to $ab\left(a^2+b^2\right)=2c^4$.
I have found four classes of solutions: $(n,n,n)$, $(n,n,-n)$, $(n,0,0)$ and $(0,n,0)$, for $n\in\mathbb Z$. I think these are all, but I'm not sure.
It suffices to look for positive integer solutions. Let $g=\gcd(a,b)$. Since $g^4$ divides the LHS, it follows that $g$ must divide $c$. So we can divide out by $g$ and look for solutions where $a,b$ are coprime. In this case, $\gcd(ab,a^2+b^2)=1$.
I am stuck from here though.

A: Multiply by $8$ and rearrange to get
$$(a+b)^4=(2c)^4+(a-b)^4.$$
From here, I have discovered a truly wonderful solution, which math.SE is too small to contain.


text:
Q: Is there a way to initialize a public array based on a condition? I have an array with 3 dimensions. I would like to access this array from several modules in Excel VBA. For that reason I use Public to declare it. Currently I use this code:
Public MyData(1 To 400, 1 To 10, 1 To 3000) As Double

I would like to initialize the first and third variable once at startup of my code at a certain value depending on the sizes of my data.
Since ReDim can only be used for the last variable in an array I am trying to do something like this although this is not possible:
If x < 400 and z < 3000 Then
    Public MyData(1 To 400, 1 To 10, 1 To 3000) As Double
End If

If x < 200 and z < 1000 Then
    Public MyData(1 To 200, 1 To 10, 1 To 1000) As Double
End If

Is there a way to initialize an array based on a condition (the value of x and z below a certain level)?
Thank you!

A: *

*ReDim can be done for any dimension. ReDim Preserve is restricted to modify only the last dimension, keeping the existing loaded items value. But also for ReDim Preserve a workaround exists: You make the last dimension the one you want to redim preserve and finally transpose the array;

*ReDim can be done only for a declared array but, without dimensions setting during its declaration. So, declaring it in the next way:
Public MyData() As Double

will work as you need...

*A Public variable can only be placed on top of your module, in the declarations area. So, no any such code is allowed there. You can only ReDim it as you tried, in a module Sub/Function, only if you declare it as I recommended above

A: Here is a typical ReDim example:
Public multiArray()

Sub initL()
    Dim larry As Long, moe As Long, curley As Long

    larry = 7
    moe = 11
    curley = 13

    ReDim multiArray(1 To larry, 1 To moe, 1 To curley)
End Sub


text:
Q: Pywin32 Outlook Restrict function stopped working I have been using the code snippet below to grab every email in a certain subfolder received within the last 3 hours and extract some business information from them before processing, and it has been working great for a week or so. However, yesterday for some reason I noticed it hasn't been working properly, and when I added a print statement to see what emails are sent to the process function I noticed its sending everything from march to the present date (over a 1000 emails).
        outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
        api_folder = outlook.Folders.Item(1).Folders['Some Folder']

        start = datetime.datetime.now() - datetime.timedelta(hours=3)

        # 05/01/2020 05:23 AM is this the right format?

        start = start.strftime('%m/%d/%Y %H:%M %p')

        messages = api_folder.Items.Restrict("[ReceivedTime] >= '" + start + "'")

        # This prints emails that shouldnt be here after Restrict()
        for msg in messages:
            print(f"{msg.Subject} - {msg.ReceivedTime}")

I'm pretty sure it probably is a very dumb mistake in the way Restrict is called or maybe on the time formatting but since I am new to programming I haven't been able to find the root cause of what is making the function misbehave.
Any help is greatly appreciated.
Thanks

A: Although dates and times are typically stored with a Date format, the Find and Restrict methods require that the date and time be converted to a string representation. To make sure that the date is formatted as Microsoft Outlook expects, use the strftime (or Format in VBA) function. And make sure Outlook understands it:
api_folder.Items.Restrict("urn:schemas:httpmail:datereceived" >= '9/15/2019 12:00 AM')

Note, you may configure the required filter in Outlook manually to get the string representation and use it in the code.

A: The below code in python, is working fine for me, Please don't include the 'seconds' restriction, only restrict to date(mm/dd/yyyy), hour and minute + mention AM/PM for the mail (Ex: 12/22/2021 09:44 AM) and should provide datetime object in string(converted) format to apply restriction.
def read_mails(subject_line: str, start_datetime: datetime, end_datetime: datetime):
    """
    Read the outlook inbox and saves the attachments in the selected destination directory

    """
    print("\nReading messages..")

    # get outlook app
    outlook = win32com.client.Dispatch("outlook.application")

    # getting path for saving attachments
    destination_path = ask_input("select folder to save")

    print("Checking Inbox...")
    inbox = outlook.GetNamespace("MAPI").GetDefaultFolder(6)

    restriction = (
        "[ReceivedTime] >= '"
        + start_datetime.strftime("%m/%d/%Y %H:%M %p")
        + "' And [ReceivedTime] <= '"
        + end_datetime.strftime("%m/%d/%Y %H:%M %p")
        + "'"
    )

    # reading restricted inbox messages
    retriving_messages = inbox.Items.Restrict(restriction)
    print("Restriction: ", restriction)

    for message in list(retriving_messages):
        if subject_line.lower() in message.subject.lower():
            save_attachments(destination_path, message)
        else:
            continue


text:
Q: Prism, Unity - Converting from MEF I recently converted from MEF to Unity - for various reasons.
I previously had a IMenuService object in a module that I exported with MEF and imported in other modules. I believe what I have to do with Unity is take the unity container in as a parameter to the constructor of my module, then use that to register the IMenuService , however, I'm not sure how to do this (what argument type? do I have to first register the container in the bootstrapper to import it into the module?)
Also, in MEF there are ModuleDependency attributes to make sure other modules are loaded first... what would be the equivolent in Unity?
EDIT: figured out the IUnityContainer argument... however, still curious about the seconds part... dependencies

A: as you have figured out, the type you should have your modules depend on to IUnityContainer. You don't really have to register the container with itself in order to be able to work with it in the modules (while you can do it if you wanted, and to make things clearer). And last, module dependencies are independent from the IoC container you're using, so it should work just fine. You can as well configure the ModuleCatalog from xaml using:
protected override IModuleCatalog CreateModuleCatalog()
{
    return ModuleCatalog.CreateFromXaml(new Uri("catalog.xaml", UriKind.Relative));
}

and in the catalog.xaml file, you can specify the dependencies using the DependsOn property of the ModuleInfo.
hope this helps :)


text:
Q: Why can't i pop my fragment after a replace? I have an activity that looks like:
private FragmentA mFragmentA;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fullscreen);

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    mFragmentA = new FragmentA();
    fragmentTransaction.add(R.id.fragment_container, mFragmentA).addToBackStack("fragA").commit();
}

it merely adds fragmentA when it starts. now FragmentA has a button to replace itself with a new fragment, FragmentB like so:
FragmentTransaction ft = getFragmentManager().beginTransaction();
FragmentB fragB = new FragmentB();
ft.replace(R.id.fragment_container, fragB).commit();

So i use the button to replace fragA with fragB. Now, the problem is, no matter what i do (popBackStack, or call remove), nothing seems to ever remove FragmentB. What do i do to get rid of FragmentB?
Clarification:
if i hit the back key, how do i just get rid of FragmentB ? (i dont care if it goes to a blank activity)

A: You need to add fragB to the back stack, just like you did fragA.  Otherwise it just replaces fragA on screen but the FragmentManager doesn't know that it should treat it like something on the back stack.


text:
Q: How to add multiple progress divs to a div based on a List object items I am doing a Polling web application with ASP.NET Webforms and C#. Based on the number of answers stored in an object I want to display the same number of progress divs inside a div preset on the page in this format in C#.

 <asp:RadioButton ID="RadioButton1" runat="server" Text="AnswerOption" />

        Val

I tried the approach below but all I saw was just one div instead of the same number of divs as the numbers of answers in the object. This is what I did:
for (int i = 0; i < lstValues.Count; i++)
{
    var answer = UtilityClass.Utility.SubstringElement(lstValues[i]);
    if (answer.Trim() == new PollAnswersService().GetByPollAnswerId(userResp.PollAnswerId).PollAnswerText)
    {
        ListItem valItem = new ListItem(lstValues[i], lstValues[i]);

        var divResults = ((HtmlGenericControl)e.Item.FindControl("divResults"));
        divResults.Controls.Add(new LiteralControl("
"));

        string percentage = lstValues[i].Substring(lstValues[i].IndexOf("-") + 1);
        var percentVal = percentage.Remove(percentage.Length - 1).Trim();
        RadioButton rb = new RadioButton();
        rb.Text = lstValues[i];
        rb.Checked = true;
        rb.Enabled = false;

        divResults.Controls.Add(rb);

        Panel pnlProgress = new Panel();
        pnlProgress.Attributes["class"] = "progress-bar progress-bar-info";
        pnlProgress.Attributes["role"] = "progressbar";
        pnlProgress.Attributes["aria-valuenow"] = percentVal;
        pnlProgress.Attributes["aria-valuemin"] = "0";
        pnlProgress.Attributes["aria-valuemax"] = "100";
        pnlProgress.Style["width"] = string.Format("{0}%;", percentVal);
        pnlProgress.Controls.Add(new LiteralControl(string.Format("{0}%;", percentVal)));

        divResults.Controls.Add(pnlProgress);
    }
    else
    {
        ListItem valItem = new ListItem(lstValues[i], lstValues[i]);
        ((RadioButtonList)e.Item.FindControl("rblPollResult")).Items.Add(valItem);

        var divResults = ((HtmlGenericControl)e.Item.FindControl("divResults"));
        divResults.Controls.Add(new LiteralControl("
"));

        string percentage = lstValues[i].Substring(lstValues[i].IndexOf("-") + 1);
        var percentVal = percentage.Remove(percentage.Length - 1).Trim();
        RadioButton rb = new RadioButton();
        rb.Text = lstValues[i];
        rb.Checked = true;
        rb.Enabled = false;

        //divResults.Controls.Add(rb);

        Panel pnlProgress = new Panel();
        pnlProgress.Attributes["class"] = "progress-bar progress-bar-info";
        pnlProgress.Attributes["role"] = "progressbar";
        pnlProgress.Attributes["aria-valuenow"] = percentVal;
        pnlProgress.Attributes["aria-valuemin"] = "0";
        pnlProgress.Attributes["aria-valuemax"] = "100";
        pnlProgress.Style["width"] = string.Format("{0}%;", percentVal);
        pnlProgress.Controls.Add(new LiteralControl(string.Format("{0}%;", percentVal)));

        divResults.Controls.Add(pnlProgress);
    }
}

A: I think the answer could be pretty simple, declare this variable outside of the loop :-
var divResults = ((HtmlGenericControl)e.Item.FindControl("divResults"));

for (int i = 0; i < lstValues.Count; i++){

// Your Code Here

}


text:
Q: iOS load dynamic layer mask (i.e. layer mask is provided outside the code) Situation: want to apply interesting photo frame to images, and the photo frame is implemented as layer mask, is it possible to dynamically build the layer mask by load a photo frame template outside of the obj-C code so that I can change the frame layer without ever touching the code?
the end result will be something like this. http://a3.mzstatic.com/us/r1000/106/Purple/9e/b9/9b/mzl.rdrrpcgr.320x480-75.jpg, except the photo edge/frame is dynamically loaded outside of the app, rather than built-into the app.
Ideally, would like to easily create a photo frame in photoshop as png file where the black pixel here will allow full transparency.. and then I can load this photo frame in the iOS app as the frame layer will allow the layer underneath to fully go through wherever the mask layer is black...

A: + (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

CGImageRef maskRef = maskImage.CGImage;

CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                    CGImageGetHeight(maskRef),
                                    CGImageGetBitsPerComponent(maskRef),
                                    CGImageGetBitsPerPixel(maskRef),
                                    CGImageGetBytesPerRow(maskRef),
                                    CGImageGetDataProvider(maskRef), NULL, false);

CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
return [UIImage imageWithCGImage:masked];
}

Then you could use this method with a UIImage you load from a URL.
The URL could serve a different UIImage, or could take a parameter for which UIImageMask to load. Does this answer your question?


text:
Q: Create a floating bar in HighCharts cloud I've had a request form a client to have the following chart replicated in HighCharts cloud, but I'm having difficulty figuring out how to make the first series show as a "floating gray bar" - or whatever it's called. Any suggestions on how I could achieve to this?

A: You can use columnrange series type to add the 'floating bar':
series: [{
    type: 'column',
    data: [...]
}, {
    type: 'columnrange',
    data: [...]
}]

Live demo: https://jsfiddle.net/BlackLabel/ys1x79uk/
API Reference: https://api.highcharts.com/highcharts/series.columnrange.data


text:
Q: setState when fetch data that leads Render in loop The problem is when i create paginaion button, the render is running in loop.
As i call api from external that i can store all data in dataset. I know something went wrong but i am not able to solve it personally, so can any one suggest solutions to help improve? Thanks.
SearchScreen.js
componentDidMount() {
      this.setState({isLoading: true},function(){
        this.fetchData(this.url)
      });
  }

  async fetchData(query, pageNo) {
    try {
      let response = await fetch(query);
      let responseText = await response.json();
      let json = await this.getData(responseText, pageNo);
    } catch(error) {
      console.error(error);
    }
  }

  async getData(responseText, pageNo){
    this.setState({
      data: responseText.response.listings,
      isLoading: false,
      currentPage: pageNo,
      lastPage: responseText.response.total_pages
    });
  }

  PropertyList(arr, navigate) {
    return arr.map(function(property, i){
      return(
      <TouchableHighlight style={styles.button} underlayColor='#99d9f4'
            key={i} onPress={() => navigate('PropertyView', {property: property})} >
        <View key={i} style={styles.rowContainer}>
            <Image style={styles.thumb} source={{ uri: property.img_url }} />
            <View  style={styles.textContainer}>
              <Text style={styles.price}>{property.price_formatted}</Text>
              <Text style={styles.title}
                    numberOfLines={2}>{property.title}</Text>
            </View>
        </View>
      </TouchableHighlight>
      );
    });
  }

  SetPage = (pageNo) =>{
    this.url = this.GetChangedUrl(pageNo);
    this.fetchData(this.url, pageNo);
  }

  GetChangedUrl = (pageNo) =>{
    return this.url.replace(/(page=\d+&)/g, 'page='+pageNo+ '&');
  }

  _formArray = (pageNo) =>{
    if (pageNo == 1){
      return [pageNo, pageNo+1, pageNo+2];
    }else if (pageNo == this.lastPage){
      return [pageNo-2, pageNo-1, pageNo];
    }else{
      return [pageNo-1, pageNo, pageNo+1];
    }
  }

  _createPageButton = (currentPage) =>{
    var array = this._formArray(currentPage);
    var btnBody = array.map( (item, i) => {
      return (
        <TouchableHighlight style={styles.pageButton} key={i} Onpress={this.SetPage(i)}>
          <Text style={styles.text} >{i + 1}</Text>
        </TouchableHighlight>
      )
    });
    return btnBody;
  }

  render() {
    const { navigate } = this.props.navigation;
    const { params } = this.props.navigation.state;
    this.url = params.url;

    let propertyList;
    if (this.state.isLoading){
      propertyList = (
          <ActivityIndicator size={108} style= {styles.indicator}/>
      )
    }else{
      propertyList = (
        <View >
          <View >
            <ScrollView >
              {this.PropertyList(this.state.data, navigate)}
              <View style={styles.separator}/>
              <View style={styles.pageContainer}>
                {this._createPageButton(this.currentPage)}
              </View>
            </ScrollView>
          </View>
        </View>
       )
    }

    return (
      <View>
          {propertyList}
      </View>
    )
  }
}

Whole Code from here

A: I believe this is caused by:
Onpress={this.SetPage(i)}

which should be changed to:
Onpress={() => this.SetPage(i)}

Your code calls setPage when rendering and passes to onPress the result of the call, causing change of page, and therefore a new load, on every render.


text:
Q: SurfaceView overlaps another SurfaceView on Android 8.0 I'm facing some strange issue with my app on Android 8.0. I have my own scrollable widget, code is available on github. It has two childs, which can be scrolled one by one indefinitely.
On the screen, the chess board is a SurfaceView and a scrollable moving child with chess pieces on it is also a SurfaceView. Another child of a scrollable view is simple LinearLayout.
The problem is when child SurfaceView is placed below the chess board, it is showed above it, while another child scrolls normally. Look at the gif below.

The problem appeared on Android 8. On all previous versions it worked fine.

A: You can try this to make SurfaceView to top of the screen:
surfaceView.setZOrderMediaOverlay(true);

The main tip is not to use setZOrderOnTop(true), as it displays SurfaceView above any UI element. setZOrderMediaOverlay displays the SurfaceView below the UI, but above another SurfaceView.

More from here


text:
Q: Flutter: Using Visual Studio Code. Where is the shared preferences file? In Visual Studio Code, how i can find the location and open the  shared preferences file that are used in my Flutter project.
Thanks in Advance.


text:
Q: NPM not working after setting proxy I was trying to set proxy using this command

npm config set proxy "http://domain%5Cusername:password@servername:port/

After setting the proxy, when i use npm or any npm command i get the below error. I think i've messed up the config file. I just want to restore my npm to old state.
Please help!!

URIError: URI malformed
at decodeURIComponent( < anonymous > )
at Url.parse(url.js: 269: 19)
at Object.urlParse[as parse](url.js: 75: 5)
at Object.validateUrl[as validate](C: \node\ node_modules\ npm\ node_modules\ n opt\ lib\ nopt.js: 172: 13)
at validate(C: \node\ node_modules\ npm\ node_modules\ nopt\ lib\ nopt.js: 221: 24)
at validate(C: \node\ node_modules\ npm\ node_modules\ nopt\ lib\ nopt.js: 187: 11)
at C: \node\ node_modules\ npm\ node_modules\ nopt\ lib\ nopt.js: 104: 12
at Array.map(native)
at C: \node\ node_modules\ npm\ node_modules\ nopt\ lib\ nopt.js: 70: 15
at Array.forEach(native)

C: \node\ node_modules\ npm\ lib\ npm.js: 45
throw new Error('npm.load() required') ^


text:
Q: CodeIgniter - order my 'posts' by month? In my website I'd like to create an 'archive' list to categorise my posts.
My posts table is set up like so:
id | post_title | post | pubdate | year | month
Currently this model function pulls the posts:
function getNews(){
     $data = array();
     $this->db->order_by("id", "desc");
     $Q = $this->db->get('posts');
     if ($Q->num_rows() > 0){
       foreach ($Q->result_array() as $row){
         $data[] = $row;
       }
    }
    $Q->free_result();
    return $data;
}

However, is it possible I can create a list like the following?
July (12)

June (5)

May (2)

So it lists the month and the number of posts within that month?
All my attempts thus far have ended in frustration and tears. Any help would be greatly appreciated.

A: Try this one
SELECT  `year`,`month`,(SELECT COUNT(id) FROM `posts` WHERE `month` =p.`month`) AS c
FROM `posts` p  GROUP BY p.`month` ORDER BY `month`

function getNews(){
 $data = array();

 $Q = $this->db->query('SELECT `year`,`month`,(SELECT COUNT(id) FROM `posts` WHERE `month`=p.`month`) AS c FROM `posts` p  GROUP BY p.`month`ORDER BY `month`');
 if ($Q->num_rows() > 0){
   foreach ($Q->result_array() as $row){
     $data[] = $row;
   }
}
$Q->free_result();
return $data;
}

A: This is not codeigniter related but i'll answer you anyway.
use SELECT Count(*) then order by 'month', write a query and run it using this
http://ellislab.com/codeigniter/user-guide/database/queries.html


text:
Q: How to show x,y,count(*) in 2-D by one SQL? For example data in csv is
#row, col, number
y1,x1,1
y2,x2,1
y2,x2,1
y2,x3,1

If I use simple group SQL, it can displayed as one dimension
select y1,x1,count(*) from data group by 1,2 order by 1,2

The 1-D result is
row col count(*)
y1  x1  1
y2  x2  2
y2  x3  3

I want to show like
row x1 x2 x3
y1   1  0 0
y2   0  2 1

If the col is limited in only 'x1','x2','x3', is it possible to use one SQL to display as 2-D?

A: SELECT row,
SUM(CASE WHEN col= 'x1' THEN 1 else 0 END) AS x1,
SUM(CASE WHEN col= 'x2' THEN 1 else 0 END) AS x2,
SUM(CASE WHEN col= 'x3' THEN 1 else 0 END) AS x3
FROM data
GROUP BY row;

A: Try this
sql fiddle
select row,isnull(sum(x2),0) as X2,isnull(sum(x3),0) as X3
from(select row,case when col = 'x1'
then
cnt
end as x1,
case when col = 'x2'
then
cnt
end as x2,
case when col = 'x3'
then
cnt
end as x3
from
(select row,col,count(*) as cnt from test1 group by row,col ) as test)
as total
group by row


text:
Q: Проверить инпут на MIME-type файлов Подскажите, как сделать проверку на файлы которые можно прикрепить для вставки в img?
Нужны только графические форматы

$(document).ready(function() {
    $('input[type="file"]').change(function () {
      var file = this.files;
      if (file[0]) {
        var reader = new FileReader();
        reader.readAsDataURL(file[0], 'UTF-8');
        reader.onload = function (event) {
          var result = event.target.result;
          $('.user-img').attr('src', event.target.result);
        };
      }
    })
  });

<input type="file" id="ec-photo-resource-3" name="photo" multiple accept="image/jpeg,image/png"/>

A: Пища для размышления:
$.each(this.files, function(i, file){
if(file['size']]>1024){
alert('Файл слишком большой');
return false;
}

var reader = new FileReader();

reader.onload = function(e){

$('.combineLoaded').append('

'+ file['name'] +'

');
};
reader.readAsDataURL(file);
});


text:
Q: Spring Cloud Config Server - static buildpack I'm looking for some pointers on putting config files for static HTML app in the PCF config server. Two possible ways on making it happen:

*

*On the cf push, static buildpack would go to config server, fetch latest config and deploy it to the container

*Every time a client (browser) requests config file, there would be a proxied request to config server to get latest config and then send to client.
Did anyone make this work yet? Any pointers to examples or such?

A: Which server is being used as config server?
Option 1: Do you say that your config file would remain same as part of your application life cycle? If so, you may include it as part of your binary distribution. There is no difference if you include it as part of your build or as a step during cf push. You don't need config server.
Option 2: Please note that the default behavior of Spring Config Server is not to serve files. It responds with JSON of the property files specified. You may need a simple customization if you want to serve plain text from Config Server. This works; but Config Servers meant for this.
In any case, have a proper case for Config Server.


text:
Q: Average Visit Duration spikes at midnight Last thursday I implemented a change to our GA script - I added the Enhanced Link Attribution and added the setDomainName attribute. Since then, most of our stats are fine, but the Average Visit Duration has gone completely insane.
We went from averaging around 4mins/visit to massive spikes every morning after midnight of visit times exceeding two hours. I figure it must be something I did wrong, as it started going out of control about the same hour that I deployed the change.
I don't want to flail about making changes on production until I can figure out the cause - any help or suggestions would be greatly appreciated.
Hourly analytics for Average Visit Duration:

The current GA script
var _gaq = _gaq || [];
var pluginUrl = '//www.google-analytics.com/plugins/ga/inpage_linkid.js';

_gaq.push(['_require', 'inpage_linkid', pluginUrl]);
_gaq.push(['_setCustomVar', 1, 'Locale', 'en_CA', 2]);
_gaq.push(['_setAccount', 'REDACTED']);
_gaq.push(['_setSiteSpeedSampleRate', 10 ]);
_gaq.push(['_setDomainName', 'REDACTED']);
_gaq.push(['_trackPageview']);

(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

A: EDIT I solved it. See details below - but summary is that its a symptom of auto-refresh javascript causing sessions that span multiple days. GA resets all session at midnight so it appears as if many long session start at midnight, but they don't, they may start at any hour of the day.

Did you ever figure out what the cause was? We are seeing the same thing, huge spikes in average session length - just started recently. Also at midnight.
We tried what @newUserNameHere suggested - we created an advanced segment for these long sessions (sometimes spanning up to 10 hours, but averaging 1.5 hours) - and we saw that it is made up of about 700 unique users - spanning all browser versions, including multiple dot patch versions of chrome, and spanning the entire world and the entire US. So it doesn't seem like its a single bot...or at least if it is - it is a very distributed and varied bot(s)?
Edit
I solved it!
I turned out the developers have implemented an "automatic" refresh on our site, every 15 minutes. This essentially caused Google Analytics to see any user who kept their browser open as an endlessly long session (as long you hit the site within 30 minutes, it extends the session). Since Google Analytics resets all sessions at midnight, and since the graph above displays sessions based on when they STARTED - we are seeing many many very long sessions starting at midnight. Where in reality, the long sessions just continue all day long, and can start whenever.
This was actually requested by our Product team, but I had no idea.
After drilling down into the data in Google Analytics, I just theorized that something like that must be going on, contiously pinging the site (or at least Google Analytics) to keep the sessions live before 30 minutes are up.
I left a browser open with Charles HTTP Debugger open as well, for a few hours to see what was going on, and I discovered this behavior.
When I brought this back to the developers and to the Product team, they said "of course, we just asked for and implemented this behavior 2 weeks ago."
(Actually seems strangely, gratifyingly scientific. I saw some wierd symptoms. I had a theory as to what could cause it. I set up an experiment to test it (Browser+Charles open), and the experiment proved my theory.)
If you are still seeing this problem, I would suggest trying the above method (leave a browser open for a few hours, along with Charles HTTP debugger). If you don't see the page being refreshed regularly, perhaps its not the homepage - you should use an advanced segment to determine which page this is happening on, and try this on that page.

A: Just a guess but this could be a time zone related bug.
Try to change the time zone for your GA account and see if that changes the report.

A: It's possible that this is related to how Google tracks sessions.  A session is automatically ended at the end of the day, so if someone's been actively  interacting with your site prior to midnight, they will be a new visit at midnight, in addition to the actual new visits that come in during that hour.
How Visits are calculated in Analytics
Another possibility is that its caused by duplicated versions of the __utma and __utmz cookies on users's machine. Changes from the sync to the async GATC can cause it. To solve you may need to delete the extra cookies somehow.


text:
Q: Git clone using ssh I have flux, nginx, gitlab pod running in my kubernetes cluster on AWS. Nginx runs as a load balancer/reverse proxy,while gitlab runs a node port( and only gitlab is behing nginx).Gitlab and flux are in different namespaces.
Now i want to ssh from the flux pod into gitlab.
Flux is installed via helm charts.
Prior to installing flux i run - ssh-keyscan {{ git_host }} > flux_known_hosts and refer to this in the installer command.
since my git_host is a loadbalancer url, ssh-keyscan does not work as it cannot resolve the ELB url.
However on the other hand - git clone ssh://git@gitlab.ethan.svc.cluster.local:222/root/automation.git works when i run this command from the flux pod.
Is there any way to get the below command to work from the flux pod(using the elb url and not the gitlab service name) -
ssh://git@aa82ee1b284b0464bb1353bd2fbccdd2-1957457895.ca-central-1.elb.amazonaws.com:root/automation.git

I have tried opening ports on the Elb but that does not seem to work.


text:
Q: Wrong user name when accessing play project database with h2-browser Unable to access play project embedded H2 database, i followed recommendations, and
 run h2-browser within the same play console as explained here:
Accessing play project database with h2-browser
My Play framework settings ( 2.3.10)
db.default.url="jdbc:h2:mem:play"
db.default.driver=org.h2.Driver
db.default.username=sa
db.default.password=""

But i keep getting this error: Wrong user name or password [28000-180] 28000/28000 (Help)

A: The Play 2.3.x JDBC datasource is managed by BoneCP
Correctly define User name
 db.default.user=sa

So I used settings from more recent version
Play framework 2.5.x is using HikaryCP where this would be correct
 db.default.username=sa

A: Check this link, I tried to describe.
Reason:
When connecting to the H2 database for the first time, the H2 database initializes the user name and password, but properties the database user name and password are defined in the configuration file , causing a conflict.
Solution:

*

*Close the program and close the database connection (if the program is not closed, an error will be reported and cannot be changed)

*Delete the database and delete the xml file in dataSources under .idea

*Recreate the database and start the project


text:
Q: downloading a table from the web I want to extract a table from this website after clicking on "National Data". I know there is an option to download it directly but I'm very interested in web scraping and I want to learn. Previously, I used the Selenium package in Python for automating the process of selecting all the checkboxes containing the years and now I want to extract the table as a dataframe until the last page, in order to have the whole entries in my dataframe. I think the table id I want to scrape is 'DataTables_Table_26'.
I tried to do this for extracting the first table but it doesn't work.
html = driver.page_source
soup = BeautifulSoup(html, "lxml")

table = soup.find_all('table', {'id':'DataTables_Table_26'})

If you need to see the previous lines of my code, just tell me. Thanks in advance.
This is the part of the html code where there is a table object:

A: You can use pandas to read_html() and store into dataframe and then append to each page traverse.
You need to install pandas using pip

pip install pandas

Use infinite loop and traverse the page until next button available else break infinite loop.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
import pandas as pd

driver = webdriver.Chrome()
driver.get("https://dataunodc.un.org/GSH_app")
driver.maximize_window()

#Switch the iframe in order to access the link
WebDriverWait(driver,15).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@src='https://unodc.shinyapps.io/GSH_App/']")))
#Click on National Data link
WebDriverWait(driver,5).until(EC.element_to_be_clickable((By.XPATH,'//ul[@class="nav navbar-nav"]//a[text()="National Data"]'))).click()

#Get all checkbox which are not selected.
allchekbox=WebDriverWait(driver,10).until(EC.visibility_of_all_elements_located((By.XPATH,"//input[@name='YearVar' and not(@checked='checked')]")))

for item in allchekbox:
    item.click()

WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "table.display.dataTable.no-footer")))
time.sleep(2)
html = driver.page_source
df=pd.read_html(str(html))[0]
while True:

    try:
      WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//a[@class='paginate_button next']"))).click()
      time.sleep(1) #slowdown for loop to load data.
      html = driver.page_source
      df1 = pd.read_html(str(html))[0]
      #append data into dataframe
      df=df.append(df1,ignore_index=True)

    except:
      break

#load the data into csv file to verify all data
df.to_csv("testdata.csv")
print(df)

Snapshot of CSV file after loaded.

A: Here is a good table scraper if you can get the link of the data, you just have to pass in which table to scrape:
#Main function
def getContent(link, filename, whichtable=0):
    result1 = requests.get(link)
    src1 = result1.content
    soup = BeautifulSoup(src1,'lxml')
    table = soup.find_all('table')[whichtable]
    with open(filename,'w',newline='') as f:
        writer = csv.writer(f)
        for tr in table('tr'):
            row = [t.get_text(strip=True)for t in tr(['td','th'])]
            writer.writerow(row)

getContent('https://teams.technion.ac.il/residency-placements/', 'what.csv', whichtable=0)
df2= pd.read_csv('what.csv')
or
getContent('https://en.wikipedia.org/wiki/List_of_highest-grossing_films', 'what.csv', whichtable=0)

You can see it's a very good table __scraper__, and you should be able to use it on your site if you can get to the page with the actual table

This table scraper will read any table on a website, as long as you set whichtable, as some sites have more than one table


text:
Q: JS: Why would click event not be bubbling? I have a click event on a child nested within a parent element.  I am logging the target of the event but the click event is only happening when clicking on the #item element, not the parent container.

let item = document.getElementById('item');
item.addEventListener('click', (evt) => {
  console.log(evt.target)
})
.container {
  background: pink;
}

#item {
  width: 90px;
  background: green;
}

    foo

A: The way events (which propagate) work is:

*

*Some element on the page dispatches the event. For example, let's say that an element is clicked.

*The capturing phase of the event starts. Starting from the root element (window), any capturing event listeners for that event fire. For example, listeners on window will fire before listeners on document, and listeners on document will fire before listeners on inner elements. The only elements which will have listeners fire are those that are ancestors of the element that dispatched the element.

*At the end of the capturing phase, listeners on the element that dispatched the event will fire.

*The bubbling phase starts. Listeners for the event will fire in the following order:

*

*The parent element of the element that dispatched the event

*The parent element of that parent
...

*The window
As you can see, if an event is dispatched to an element, the only elements that will have listeners triggered are the element's parents, grandparents, etc. Listeners on child elements will not fire. This is why, if there's a click on your #container, outside the .item, the listener on the .item will not fire.


text:
Q: Inconsistent "LoadError" behavior with 'lib' namespacing/autoloading We have just created a new file in 'lib' that has spawned a series of headaches involving load errors.
/lib/response_set.rb:
module MyCompany
  class ResponseSet < Array
    ...
  end
end

/spec/lib/response_set_spec.rb
require 'spec_helper'

describe MyCompany::ResponseSet do
  describe "..." do
    ...
  end
end

Running this spec in Rspec gives us the following error when it gets to the first 'describe':
/Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:492:in `load_missing_constant': Expected /Users/my_stuff/projects/my_project/lib/response_set.rb to define ResponseSet (LoadError)
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:183:in `block in const_missing'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:181:in `each'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:181:in `const_missing'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/rspec-core-2.5.1/lib/rspec/core/backward_compatibility.rb:20:in `const_missing'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/rspec-expectations-2.5.0/lib/rspec/expectations/backward_compatibility.rb:6:in `const_missing'
    from /Users/my_stuff/projects/my_project/spec/lib/response_set_spec.rb:4:in `<top (required)>'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/rspec-core-2.5.1/lib/rspec/core/configuration.rb:386:in `load'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/rspec-core-2.5.1/lib/rspec/core/configuration.rb:386:in `block in load_spec_files'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/rspec-core-2.5.1/lib/rspec/core/configuration.rb:386:in `map'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/rspec-core-2.5.1/lib/rspec/core/configuration.rb:386:in `load_spec_files'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/rspec-core-2.5.1/lib/rspec/core/command_line.rb:18:in `run'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/rspec-core-2.5.1/lib/rspec/core/runner.rb:55:in `run_in_process'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/rspec-core-2.5.1/lib/rspec/core/runner.rb:46:in `run'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/rspec-core-2.5.1/lib/rspec/core/runner.rb:10:in `block in autorun'

HOWEVER! We have been using many other files for a long long time that have identical structure. For example, here's another one that has been working fine since it was created:
/lib/smart_set.rb
module MyCompany
  class SmartSet < Array
    ...
  end
end

And /spec/lib/smart_set_spec.rb
require 'spec_helper'

describe MyCompany::SmartSet do
  describe "..." do
    ...
  end
end

This file has the identical structure but causes no problems at all.
ResponseSet ( the problem class ) apparently has loading issues for no discernable reason. In the rails console, the first time I try to create one, I get an error, but then I can create one afterwards:
Loading development environment (Rails 3.0.4)
ruby-1.9.2-p136 :001 > rs = MyCompany::ResponseSet.new
LoadError: Expected /Users/my_stuff/projects/my_project/lib/response_set.rb to define ResponseSet
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:492:in `load_missing_constant'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:183:in `block in const_missing'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:181:in `each'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:181:in `const_missing'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:503:in `load_missing_constant'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:183:in `block in const_missing'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:181:in `each'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:181:in `const_missing'
    from (irb):1
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/railties-3.0.4/lib/rails/commands/console.rb:44:in `start'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/railties-3.0.4/lib/rails/commands/console.rb:8:in `start'
    from /Users/my_stuff/.rvm/gems/ruby-1.9.2-p136@my_project/gems/railties-3.0.4/lib/rails/commands.rb:23:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'
ruby-1.9.2-p136 :002 > rs = MyCompany::ResponseSet.new
 => []

Also, adding
require 'response_set'

at the top of response_set_spec.rb allows those tests to run. But no such thing is necessary for smart_set_spec.rb.
The following is in place in application.rb:
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
config.autoload_paths += Dir["#{config.root}/app/models/**/"]

Now, I understand that Rails has some sort of opinion on how file structure should match namespace structure for these types of things, and we have restructured our modules and files towards this end. It SEEMS to have fixed the issue (although we were seeing some other weird load errors for a while when we ran the full test suite - these have mysteriously gone away). Nonetheless everyone here is baffled and not a little annoyed that Rails is being so inconsistent and we would like to know why. As you can see there are two files that are identical as far as namespacing and file structure are concerned, being treated completely differently. In fact we have about a dozen other files in the top level of 'lib' with similar namespacing that have never caused any problems. Can anyone explain what the heck is going on here?

A: I looked into the rails source and there is a
if file_path && ! loaded.include?(File.expand_path(file_path)) # We found a matching file to load
  require_or_load file_path
  raise LoadError, "Expected #{file_path} to define #{qualified_name}" unless local_const_defined?(from_mod, const_name)
  return from_mod.const_get(const_name)
elsif ...

clause in load_missing_constant method. I may guess that as require_or_load is called before raise, this might be a reason that on the second call in your example there is no error...
It would be interesting to see a minimal example where two files with identical structure behave differently.
In your place i would make a copy of the application and would keep removing parts from it while the inconsistent behavior is present to see the minimal inconsistent example.
P.S. I have submitted a similar question here: http://www.ruby-forum.com/topic/2376956

A: Was pointed in the correct direction by Brendan, check your autoload_paths.  I had a similar error and this was the culprit for me in application.rb :
config.autoload_paths += Dir["#{Rails.root}/app/models/[a-z]*"]

My app was not happy once I started using modules for the models along with having sub-directories.  I changed mine to autoload just the non-module directories :
config.autoload_paths += Dir["#{Rails.root}/app/models/aaaaaaaaa"]
config.autoload_paths += Dir["#{Rails.root}/app/models/bbbbbbbbb"]

A: We had a similar issue which, after digging, turned out to be caused by the changes in Rails 3.x and autoload_paths.
Our case appeared only in test (RAILS_ENV=test). When Rails was loading the controllers, it scrambled about looking for each controller's matching model (due to a ActionController::Base.wrap_parameters set in an initializer). Eventually it wound down to the method mentioned above (load_missing_constant). Since our autoload_paths included both lib and lib/**, Rails pulled in all the files from all the subdirectories under lib. Unfortunately, it appears to ignore the implied namespace when loading from subdirectories. It expected foo/base.rb to define Base vs. Foo::Base. That seems to be the core flaw: load_missing_constant invokes search_for_file which returns any file whose name matches (e.g., in my example, foo/base.rb was returned as it matched base.rb).
It's hard to say if this is an error in Rails - in that it violates the namespace-to-directory mapping assumed by Ruby - or a misuse of autoload_paths.
We have worked around this for now by removing lib/** from our autoload_paths and adding the necessary require statements to application.rb.

A: I've suffered from the very same problem with namespaced classes being autoloaded incorrectly. This is the clue to solve it (from Brendan's answer):

Since our autoload_paths included both lib and lib/**, Rails pulled in all the files from all the subdirectories under lib. Unfortunately, it appears to ignore the implied namespace when loading from subdirectories. It expected foo/base.rb to define Base vs. Foo::Base. That seems to be the core flaw: load_missing_constant invokes search_for_file which returns any file whose name matches (e.g., in my example, foo/base.rb was returned as it matched base.rb).

And I've solved it by moving all my namespaced classes, named Events::Something, into app/components/events/* and creating a file app/components/events.rb with the following content:
%w(file1 file2 ...).each do |file|
  require "events/#{file}"
end

And while this is a little bit manual, it works both for application, console and test modes.

A: Another point worth to notice is that whether you have the correct path in services folder.
By correct path, I mean
engine_name/app/services/engine_name/your_service.rb
I have accidentally forgot engine_name folder inside services, and got this strange behaviour.


text:
Q: Codemirror Autocompletion should not hint variables from my javascript code I am using Codemirror with the auto complete addon.
Work very fine, but I have one problem.
For example, when the user enters a text like "ld" and starts the autocomplete, automatically there are all variables from my JS code starting with ld.
What I want: The auto complete should should show just internal javascript keywords, like:function, while, for and so on. Only things that my nashorn scripting engine can handle in Grails.
Background: The user can enter Javascript code that is executed in Nashorn, so only functions that Nashorn can handle should be shown (no window, no console and so on)
How can I achieve this?


text:
Q: Function to re-attempt a failed promise x times - final catch block never gets executed despite promise failing x times I'm writing a function that will take a promise as an argument and if this promise rejects, the function will retry it x times before giving up. The issue I'm having is that after the promise rejects enough times, I get an exception due to not handling a rejected promise, and I haven't been able to figure out why.
My code is included at the bottom, and I've also made a codesandbox with my code. The logic is as follows:

*

*Call retry with the function, the amount of times to re-attempt and the delay in ms between each re-attempt.

*retry function attempts to execute the functionthat is passed to it.

*If it succeeds, resolve with the result of the function. If it fails, go to step 1 and decrease the attempts variable by 1.

*If the attempts variable is 0, retry rejects.

If retry rejects, it's then expected that the catch block in example() (line 61) is execute, but this never happens. Why does it never happen, and how can the code be changed to change this?
Edit: I've just noticed that the rejection isn't really clear in the codesandbox, but this is what happens when retry rejects:
node:internal/process/promises:279
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "rejection".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

The full code, as requested:
const wait = (delay = 5000) =>
  new Promise((resolve) => setTimeout(resolve, delay));

const retry = ({ attempts, delay, fn, maxAttempts = attempts }) => {
  if (maxAttempts !== attempts) {
    /**
     * We want to double the delay on each
     * successive attempt after the first.
     */
    delay = delay * 2;
  }
  return new Promise(async (resolve, reject) => {
    try {
      console.log(1, `attempting ${fn.name}...`);
      const result = await fn();
      resolve(result);
    } catch (e) {
      if (attempts === 0) {
        console.log(2, `${fn.name} failed ${maxAttempts} times, giving up.`);
        reject(e);
        return;
      }
      console.log(
        2,
        `${fn.name} failed, retrying in ${
          delay / 1000
        }s... (${attempts} attempts remaining)`
      );
      await wait(delay);
      console.log(3, "retrying");
      retry({
        attempts: attempts - 1,
        delay: delay,
        fn,
        maxAttempts
      });
    }
  });
};

// An example promise that simply rejects after a second
const fakeReject = () =>
  new Promise((_, reject) => setTimeout(() => reject("rejection"), 1000));

const example = async () => {
  try {
    const result = await retry({
      attempts: 3,
      delay: 2000,
      fn: fakeReject
    });
    /**
     * The following would execute if fakeReject were to resolve instead.
     */
    console.log(result);
  } catch (e) {
    /**
     * I expected this block of code to execute once the fakeReject
     * promise has rejected 3 times, but this is never executed.
     */
    console.log("we tried");
  }
};

example()
  .then((x) => {
    console.log("success", x);
  })
  .catch(console.error);

A: Never pass an async function as the executor to new Promise! In your case you forgot to resolve the returned promise from the catch block of your code, you only made a recursive call - which constructs a new, independent promise that is ignored and whose rejections are never caught. It would have worked if you had written resolve(retry({…})), but really this is not needed:
async function retry({ attempts, delay, fn, maxAttempts = attempts }) { /*
^^^^^ */
  if (maxAttempts !== attempts) {
    delay = delay * 2;
  }
  try {
    console.log(1, `attempting ${fn.name}...`);
    const result = await fn();
    return result;
//  ^^^^^^
  } catch (e) {
    if (attempts === 0) {
      console.log(2, `${fn.name} failed ${maxAttempts} times, giving up.`);
      throw e;
//    ^^^^^
    }
    console.log(2, `${fn.name} failed, retrying in ${delay / 1000}s... (${attempts} attempts remaining)`);
    await wait(delay);
    console.log(3, "retrying");
    return retry({
//  ^^^^^^
      attempts: attempts - 1,
      delay: delay,
      fn,
      maxAttempts
    });
  }
}


text:
Q: What are the url parameters naming convention or standards to follow Are there any naming conventions or standards for Url parameters to be followed. I generally use camel casing like userId or itemNumber. As I am about to start off a new project, I was searching whether there is anything for this, and could not find anything. I am not looking at this from a perspective of language or framework but more as a general web standard.

A: There are no standards that I'm aware of. Just be mindful of IE's URL length limit of 2,083 characters.

A: Standard for URI are defined by RFC2396.
Anything after the standardized portion of the URL is left to you.
You probably only want to follow a particular convention on your parameters based on the framework you use.
Most of the time you wouldn't even really care because these are not under your control, but when they are, you probably want to at least be consistent and try to generate user-friendly bits:

*

*that are short,

*if they are meant to be directly accessible by users, they should be easy to remember,

*case-insensitive (may be hard depending on the server OS).

*follow some SEO guidelines and best practices, they may help you a lot.

I would say that cleanliness and user-friendliness are laudable goals to strive for when presenting URLs.
StackOverflow does a fairly good job of it.

A: I use lowercase. Depending on the technology you use, QS is either threated as case-sensitive (eg. PHP) or not (eg. ASP). Using lowercase avoids possible confusion.

A: Like the other answers I've not heard about any conventions.
The only "standard" I would adhere to is to use the more search engine friendly practice of using a URL rewriter.

A: I recommend reading Cool URI's Don't Change by Tim Berners-Lee for an insight into this question.  If you're using parameters in your URI, it might be better to rewrite them to reflect what the data actually means.
So instead of having the following:
/index.jsp?isbn=1234567890
/author-details.jsp?isbn=1234567890
/related.jsp?isbn=1234567890

You'd have
/isbn/1234567890/index
/isbn/1234567890/author-details
/isbn/1234567890/related

It creates a more obvious data structure, and means that if you change the platform architecture, your URI's don't change.  Without the above structure,
/index.jsp?isbn=1234567890

becomes
/index.aspx?isbn=1234567890

which means all the links on your site are now broken.
In general, you should only use query strings when the user could reasonably expect the data they're retrieving to be generated, e.g. with a search.  If you're using a query string to retrieve an unchanging resource from a database, then use URL-rewriting.

A: There are no standards that I know of, and case shouldn't matter.
However within your application (website), you should stick to your own standards. For your own sanity if nothing else.


text:
Q: D3.js custom ticks on x axis of scatterplot I have three issues:

*

*How can I add ticks on the x axis so that they separate the grouped areas of the scatterplot (grouped columns per year)?

*How can I place the years as text under the corresponding area of the scatterplot?

*Is there a more elegant way to generate the scatterplot than to add the x position for each dot manually into the input data?

More context: I would like to visualize meetings of six organizations grouped by years from 2014 to 2020 with D3.js. Each dot of a scatterplot represents a meeting and the six colors match with the organizations. Currently I've added the x position within the scatterplot for each dot manually into the input data file, so that there are gaps between the years.
Current result:

Desired result:

Current code:

import axios from "axios";

let meetings
let colors = { a: "brown", b: "orange", c: "red", d: "purple", e: "blue", f: "green" };

window.addEventListener("load", () => {
    initUI();
});

function initUI() {
    // parse input data
    axios
        .get("assets/example.txt")
        .then(async (res) => {
            var rawData = res.data
                .split("\n")
                // filter header row
                .filter((row) => (row.indexOf("label") >= 0 ? false : true))
                .map((row) => {
                    var items = row.split(";");
                    return {
                        label: items[0],
                        year: items[1],
                        xPosition: items[2],
                    };
                });

            meetings = addYPositionForAllOrganizations(rawData);
            scatterplot = await showScatterPlot(meetings);
        })
        .then(() => {
            // always executed
        });
}

// Add counter for amount of meetings for one organziation per year for y axis position
function addYPosition(organizationList) {
    organizationList.sort((a, b) => (a.year > b.year) ? 1 : -1)

    var yPosition = 1;
    var year = 2014;

    organizationList.forEach(element => {
        if (year < element.year) {
            // reset counter for next year
            yPosition = 1;
        }
        element.yPosition = 0;
        element.yPosition += yPosition;
        yPosition++;

        year = element.year;
    });
}

function addYPositionForAllOrganizations(data) {
    let a = data.filter(row => row.label == "a");
    addYPosition(a);
    let b = data.filter(row => row.label == "b");
    addYPosition(b);
    let c = data.filter(row => row.label == "c");
    addYPosition(c);
    let d = data.filter(row => row.label == "d");
    addYPosition(d);
    let e = data.filter(row => row.label == "e");
    addYPosition(e);
    let f = data.filter(row => row.label == "f");
    addYPosition(f);

    return a.concat(b).concat(c).concat(d).concat(e).concat(f);
}

async function showScatterPlot(data) {
    let margin = { top: 10, right: 30, bottom: 100, left: 60 },
        width = 1000 - margin.left - margin.right,
        height = 400 - margin.top - margin.bottom;

    // append the svg object to the body of the page
    let svg = d3
        .select("#scatter-plot")
        .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    // Add x axis
    var x = d3.scaleLinear().domain([-2, 75]).range([0, width]);
    //FIXME this destroys ticks so that they are "invisible"
    var xAxis = d3.axisBottom(x).tickValues(2014, 2015, 2016, 2017, 2018, 2019, 2020);
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);
    // Add text label for x axis
    svg.append("text")
        .attr("transform", "translate(" + (width / 2) + "," + (height - (-100 / 3)) + ")")
        .attr("text-anchor", "middle")
        .style("font-family", "sans-serif")
        .text("Years 2014 - 2020");

    // Add y axis
    var y = d3.scaleLinear().domain([0.5, 10]).range([height, 0]);
    svg.append("g").attr("class", "y axis").call(d3.axisLeft(y));
    // Add text label for the y axis
    svg.append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 0 - margin.left)
        .attr("x", 0 - (height / 2))
        .attr("dy", "1em")
        .style("text-anchor", "middle")
        .style("font-family", "sans-serif")
        .text("Amount");

    // Add meetings as dots
    let meetings = svg.append('g')
        .selectAll("dot")
        .data(data)
        .enter()
        .append("circle")
        .attr("cx", function (d) { return x(d.xPosition); })
        .attr("cy", function (d) { return y(d.yPosition); })
        .attr("r", 5.5)
        .style("fill", getColorForMeeting);
    return { svg, x, y };
}

function getColorForMeeting(data) {
    return colors[data.label];
}

Extract of the input data file:

The running project can be investigated here.

A: Here's an example that resolves your three issues.

<!DOCTYPE html>

    <meta charset="UTF-8">


text:
Q: how to create a floating window like truecaller in android
this is an image that I've taken from the popup window of Truecaller
I'm working on an android app in which I want the exact same implementation
I've created a broadcast receiver from where I'll receive a response which will help me to know  which type of a call it is but I don't know that how can I create that floating dialog like Truecaller from onResonse() pls guide me through

A: you can achieve this using dialog fragment in your app and implements as you like
 Class myfragment extends dialogFragment{
    // do your stuff here
  }


text:
Q: jquery simple code not working(id is assigned to the button) This is the sample code that i am learning from w3schools. This time i have given the id too to the button. Please help.
<!DOCTYPE html>

    <title></title>

Try jQuery

<button>Click me</button>

A: $("#hide").click(function () ...

this line of code basically means "when an element with id 'hide' is clicked, do something". So your button is missing that id
<button id="hide">Click me</button>

A: Just copy and paste it. It works. Tested.
<!DOCTYPE html>

    <title></title>

Try jQuery

This will get hide

    <button id="hide">CLick Me</button>

A: You have not set #hide for anything. If you need it on a button, do:
<button id="hide">CLick Me</button>

A: You want to hide p tag elements on onclick of button.
So firstly, you have to provide id for this button because you are making click function on button.
Try this:
<button id='hide'>Click Me</button>

A: As others have mentioned your script is looking for something with the ID attribute 'hide' as indicated in your jQuery $('#hide').
There are many different ways to select everything in your dom.  Have a look at the jquery documentation.  http://api.jquery.com/category/selectors/  The simplicity of selecting dom elements is what makes jQuery so powerful in my opinion.
Select by ID:
$('#id')

You can select every even row in a table.
$('table tr:even')

You can select the 14th div element in the dom.
$('div:eq(14)')

You can select all elements with a given class.
$('.class')

Here is a JSfiddle with the code in a working fashion.
http://jsfiddle.net/5v94cnrr/
It looks like the button is ID 'hide' and it will hide all P elements on click.  Typically you'd use a class called hide and hide all element with class hide on click of the button or some other action.


text:
Q: Grails, Spring Security LDAP Plugin I'm trying to get the LDAP plugin work. I only want a LDAP authentication against an Active Directory but it seems that I'm missing something.
Config
grails {
    plugins {
        springsecurity {

            userLookup.userDomainClassName = 'de.ac.dmf.security.User'
            userLookup.authorityJoinClassName = 'de.ac.dmf.security.UserRole'
            authority.className = 'de.ac.dmf.security.Role'

            ldap {
                context.managerDn = 'CN=dmf Systemuser,CN=Users,DC=dmf,DC=local'
                context.managerPassword = 'Password1'
                context.server = 'ldap://192.168.100.133:389/'
                authorities{
                    groupSearchBase ='OU=Groups'
                    groupSearchFilter = '(member={0})'
                    retrieveGroupRoles = false
                    retrieveDatabaseRoles = false
                    defaultRole = 'USER'
                    ignorePartialResultException = true
                }
                search{
                    base = 'CN=Users,DC=dmf,DC=local'
                    filter = '(sAMAccountName={0})'
                    searchSubtree = true

                }
                // mapper.userDetailsClass = 'user'
                // auth.hideUserNotFoundExceptions = false
                useRememberMe = false
            }
        }
    }
}

On every login I just get this exception
2011-04-29 08:49:09,129 [http-8080-1] DEBUG springsecurity.RequestHolderAuthenticationFilter  - Authentication request failed: org.springframework.security.authentication.AuthenticationServiceException: [LDAP: error code 32 - 0000208D: NameErr: DSID-031001E4, problem 2001 (NO_OBJECT), data 0, best match of:
    'CN=Users,DC=dmf,DC=local'; remaining name 'CN=Users,DC=dmf,DC=local'

It doesn't matter which user from my AD I'm trying to authenticate. Is my configuration wrong?
I'm using

*

*Grails 1.3.7

*spring-security-core 1.1.2

*spring-security-ldap 1.04

A: are you sure about your base configuration? Looks like OU=Users could work instead of CN=Users. Easiest way to figure this out is to use a tool like ad explorer (http://technet.microsoft.com/de-de/sysinternals/bb963907), connect to your AD, browse to a user and take a look at the path to the user...

A: Try using:
filter = '(&(sAMAccountName={0})(objectclass=user))'

That works on our AD.

A: You are missing the provider name list.
grails.plugins.springsecurity.providerNames = ['ldapAuthProvider',
    'anonymousAuthenticationProvider',
    'rememberMeAuthenticationProvider']


text:
Q: jQuery nested DOM selector Let say I have the following HTML elements:

I'm wondering why this doesn't work in jQuery:
$("#id.first.second").click( // do some stuff ...

I usually use something like the following which works fine, but today I just found out that the above example is not working.
// working example
$("#id .second").click( // do some stuff ...

Update: My question is why it is not working without spaces? Thanks!

A: The selector #id.first.second means "an element with the id value "id" which also has the classes first and second".
Your second selector #id .second (with the space before .second) means "an element with the id value "id" which has a descendant element with class second". It's a "descendant selector".
So if you want to specify each of the three levels, you'd do this:
$("#id .first .second").click(...

...which means "an element with the id value "id" which has a descendant element with the class first which, in turn, has a descendant element with class second".
Or alternately, you might do:
$("#id > .first > .second").click(...

...which means "an element with the id value "id" which has a direct child element with the class first which, in turn, has a direct child element with class second. It's a child selector (actually two of them).
Or, of course, some combination of them.

A: This will work:
$("#id .first .second").click( // do some stuff ...

For your first selector it would be searching for:

Explanation
Your first selector is looking for an element with an id id having classes first and second.
But you actually want to look for an element with class second beeing a descendant of an element with class first, which is again a descendant of an element with id id

A: A space between selector means "any descendant of": direct children and children of those children could be selected.
So $('#id .first .second') this means get the DOM inside div with id of id and get descendent DOM with class name of first and its descendent DOM with class name of second.

A: You need to use jQuery descendant  selector here. You need to give a space between the parent selector and the child.
If you specify the sectors without space it will be considered as a and condition. In your case it will look for an element with id id and has the classes first and second. ex:

$("#id.first.second") should be $("#id .first .second")

A: Put spaces between them:
$("#id .first .second").click( // do some stuff ...

See:
$("#id.first.second").click( // do some stuff ...
what this is looking for an id with some classes, something like:

A: Separate the selectors by a space to find descendants.
$("#id .first .second").click(function(){
   alert("Hello");
});

The original selector tried to find an element with and id of id class of first and a class of second.


text:
Q: Specified Text getting converted into icons while posting but doesnt do the same while receiving I tried modifying a chat script.
(The original script is from Eliza Witkowska link.) I mainly tried converting some text into emoticons. So far I can only convert text into emoticons properly.
But, the text gets converted to icons only when I send the message but doesn't get converted when I receive the message on another browser (I'm using sessions so I have to use another browser) unless a refresh or I send a message from that another browser.
To be more clear, suppose I have logged in to an a/c from chrome and another a/c from Firefox; when I send a message from Chrome, the specified characters get converted into icons but only the characters show up on firefox until a page refresh or until a new message is sent from firefox.
db.php
function check_changes(){
    $result = $this->db->query('SELECT counting FROM news WHERE id=1');
    if($result = $result->fetch_object()){
        return $result->counting;
    }
    return 0;
}

function get_news(){
    if($result = $this->db->query('SELECT * FROM news WHERE id<>1 ORDER BY add_date DESC LIMIT 50')){
        $return = '';
        while($r = $result->fetch_object()){
            $timing=explode(" ", $r->add_date);

            $return .= $r->title;
            $return .='
'.$timing[1].' on '.$timing[0].'

 ';
            //$return .= '
';
        }
        return $return;
    }
}

profile.php
function parseSmiley($text){
    //Smiley to image
    $smileys=array('o:)'=>'angel.gif', ':3'=>'colonthree.gif', 'o.O'=>'confused.gif', ":'("=>'cry.gif', '3:)'=>'devil.gif', ':('=>'frown.gif', ':O'=>'gasp.gif', '8)'=>'glasses.gif', ':D'=>'grin.gif', ">:("=>'grumpy.gif', '<3'=>'heart.gif', '^_^'=>'kiki.gif', ':*'=>'kiss.gif', ':v'=>'pacman.gif', ':)'=>'smile.gif', '-_-'=>'squint.gif', '8|'=>'sunglasses.gif', ':p'=>'tongue.gif', ':/'=>'unsure.gif', '>:O'=>'upset.gif', ';)'=>'wink.gif');

    //Now you need to find and replace
    foreach($smileys as $smiley=>$img){
        $smiley = preg_quote($smiley, '/');
        $text = preg_replace( "#(?<=\s|^)(?:$smiley)((?=\s|$))?#i", '', $text);
    }
    //Now only return it
    return $text;
}

$print= parseSmiley($db->get_news());

<div id="message_short" data-counter="<?php echo (int)$db->check_changes();?>">
<?php echo wordwrap($print, 25, "\n", true);?>

<div id="message_long" data-counter="<?php echo (int)$db->check_changes();?>">
<?php echo wordwrap($print, 35, "\n", true);?>

A: Be sure to wrap get_news() everywhere with parseSmiley().
As I can see from the link provided, there is a checker.php in which $db->get_news() should be replaced with parseSmiley($db->get_news())


text:
Q: Training time of Tensorflow Object Detection API on MSCOCO How long does it typically take to train a Faster RCNN  model on MSCOCO on a single GPU card (e.g. K40 or 1080) using the Tensorflow Object Detection API? It would be great if you could provide training times for other models (SSD and R-FCN), too.

A: I have never trained a model on COCO using a single GPU --- we typically train using ~10 k40 GPUs with asynchronous SGD, which takes 3-4 days to converge on COCO.  SSD and R-FCN take about the same amount of time.


text:
Q: How to "transfer" an ongoing gesture from a subview to the superview without interruption? This is what I'm trying to do:
I want to start recognizing a gesture in a subview and then, when the finger leaves the subview, let the superview take over and handle the gesture. Is that possible?

At the moment, the view in which the gesture started "wins". Is there any way to "hand over" a gesture from one view to another "on the fly", without lifting the finger off the screen?
This is the code for a simple demo:
@implementation SPWKViewController {
    UIView *_innerView;
    UIPanGestureRecognizer *_outerGestureRecognizer;
    UIPanGestureRecognizer *_innerGestureRecognizer;

    UILabel *_label;
}

- (void)loadView
{
    [super loadView];

    self.view.backgroundColor = [UIColor yellowColor];

    _innerView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, self.view.frame.size.width - 100, 200)];
    _innerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    _innerView.backgroundColor = [UIColor greenColor];

    _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 300, self.view.frame.size.width, 40)];
    _label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    _label.textAlignment = NSTextAlignmentCenter;
    _label.backgroundColor = [UIColor clearColor];

    [self.view addSubview:_innerView];
    [self.view addSubview:_label];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    _outerGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
    [self.view addGestureRecognizer:_outerGestureRecognizer];

    _innerGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
    [_innerView addGestureRecognizer:_innerGestureRecognizer];
}

- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
        if (gestureRecognizer == _outerGestureRecognizer) {
            _label.text = @"outer";
        } else {
            _label.text = @"inner";
        }
    } else {
        _label.text = @"";
    }
}

@end

Some background information: The actual problem I'd like to solve is this: I'd like to put a UIWebView inside of a UIScrollView. When I scroll to the bottom of the UIWebView, I want the parent UIScrollView to "take over" and keep scrolling without having to lift the finger off the screen first. I figured that in order to achieve that, I'd need to "hand over" the gesture from the UIWebView to the parent UIScrollView.
Thank you!


text:
Q: Set background color based on user's text input I'm trying to make a text box where the user can type in one of the color key words such as blue, lime, or black, click submit, and the page background color will change accordingly.
Here is what I have:
<label for="color">Color: </label><input type="text" name="color" size="20" id="color" />
<button type="button" onClick="javascript:changeBGC(color)">Submit</button>

and then in my script
function changeBGC(color){
    document.bgColor = color;
}

A: Try this:
document.body.style.backgroundColor = document.getElementById('color').value;

document.getElementById('color') is the input element, .value gets it's value.
Here's some more documentation on how to set css styles through JavaScript.
Fiddle example

A: Or you can change markup to following:
<button type="button" onClick="javascript:changeBGC(color.value)">Submit</button>
                                                         ^

Fiddle demo

A: Or you can use a better approach
<label for="color">Color:</label>
<input type="text" name="color" size="20" id="color" value=""/>
<button type="button">Submit</button>

var input = document.getElementById('color');
var button = document.querySelector('button');
button.addEventListener('click', function( event ) {
   event.preventDefault();
   var color = input.value;
   document.body.style.background = color;
});


text:
Q: How to share image and description using social_share_button in rails? I want to share campaign name along with image and description  but it only share name
<%= social_share_button_tag(@campaign.project.project_name, :image => @campaign.campaign_image_url) %>

Is there any way to share image on social media?

A: From the code snippets in the question I'm guessing you're using the social-share-button gem.
Unfortunately, if an attribute you pass in to the social_share_button_tag is used depends on the platform you're trying to share on to, and each of them accept different params than the other. For example, Facebook doesn't allow you to specify images when you try to share that way. You can see the attributes that are passed into each of the platforms in the social-share-button.coffee file.
The best way to get the image to appear is to include meta tags for open graph which includes the title, description, image to use etc for that page. You can see all the relevant Open Graph Markup here. If you render those tags in the header section of your page when its rendered, those images and other information will appear when you share the page. For example:
<meta property="og:title" content="<%= @campaign.project.project_name %>" />
<meta property="og:description" content="<%= @campaign.project.description %>" />
<meta property="og:image" content="<%= @campaign.campaign_image_url %>" />

Additionally, it'll appear even if the user shares the page using the URL straight, rather than going through that plugin. This has become pretty standard now and other platforms such as Slack etc will also use those tags to determine how to display a link on their platform.


text:
Q: java: executing a Object in new JVM instance and getting the results I have a third party jar that connects to a server and executes command and returns result.
But this jar connects to only one server in a single instance of JVM.
So how can i execute a Object of a class in a new JVM instance get the results/ exception  back in invoker JVM instance.

A: Try reflection get to at any non-final state to change the server. Class instances are unique per classloader, so you could load the third-party class in a new custom classloader for each server to connect to.
http://www.google.com/search?q=java%20custom%20classloader

A: You will have to reverse-engineer the protocol between the client lib and the server. tcpmon might help you. A debugger might help you. A profiler might help you as you can see what sort of methods get called.


text:
Q: how to know when shared preference is done writing I have two activities. Activity A has a button which starts activity B. When you hit the back button in activity B it restarts activity A. Also when the back button is hit it goes to the onStop method for activity B and in this point I update shared preferences for the user. Basically I'm storing player data on the shared preferences but the problem is when activity A is restarted I also load the same shared preferences but it doesn't show the updated data that I saved while activity B was stopped. I reload the app and it shows the up to date data. So it seems that while it is being saved while activity B is being stopped there isn't enough time for when it is loaded while activity A is being restarted. So how can I tell whether the shared preferences have finished being written to or not? Basically I want to load the shared preferences once I know for sure the shared preferences has been updated, is that possible?
I am using commit method:
@Override
protected void onStop()
{
    Long dist = (long)treadmill_.Mod.distance_;
    Long newdist = dist + PlayerInfoManager.getInstance().getDistanceTraveled();
    PlayerInfoManager.getInstance().setDistanceTraveled(newdist);

    float fastestSaved = PlayerInfoManager.getInstance().getFastestSpeedAcheived();
    float fastestInSess = treadmill_.Mod.fastestSpeed;
    if(fastestSaved<fastestInSess)
        PlayerInfoManager.getInstance().setFastestSpeedAcheived(fastestInSess);

    Long time = (long)treadmill_.Mod.time_;
    Long newTime = time + PlayerInfoManager.getInstance().getTotalTimeRan();
    PlayerInfoManager.getInstance().setTotalTimeRan(newTime);

    Log.e("OnStop", "at Run, run, run");
    super.onStop();
}

In PlayerInfoManager.getinstance().setDistanceTraveled(newdist):
public void setDistanceTraveled(Long distanceTraveled)
{
    DistanceTraveled = distanceTraveled;
    Editor edit = SP.edit();
    edit.putLong("DistanceTraveled", distanceTraveled);
    edit.commit();
}

SP is the sharedPreference instance:
private SharedPreferences SP;

For activity A when it restarts:
@Override
protected void onRestart() {
    super.onRestart();
    LoadStats();
    Log.e("onrestart", " ");
}

public void LoadStats()
{
    PIM.loadAll();
    Dis.setText(Long.toString(PIM.getDistanceTraveled()));
    FastestSpeed.setText(Float.toString(PIM.getFastestSpeedAcheived()));
    TotalTime.setText(Long.toString(PIM.getTotalTimeRan()));
    KeepItUp.setText(Long.toString(PIM.getLongestTimeInKeepItUp()));
}

    public void loadAll()
{// load all saved player data from sharedpreferences
    DistanceTraveled = SP.getLong("DistanceTraveled", 0L);
    FastestSpeedAcheived = SP.getFloat("FastestSpeed", 0.0f);
    TotalTimeRan = SP.getLong("TotalTime", 0L);
    LongestTimeInKeepItUp = SP.getLong("KeepItUp", 0L);
}

A: using .commit() method will make sure your data has been saved.
see the android doc for sharedPreferences.
see the commit and apply method

A: Use onPause instead since this occurs before onStop
From the documentation

Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.

You might want to see the description of an Activity's lifecycle.


text:
Q: Comparing gson JsonObject value with java String JsonObject json = new JsonObject();
json.addProperty("type", "hello");

System.out.println(json.get("type").toString().equals("hello"));

The above print statement should technically give "true" right?
But am getting "false"...am kind of novice to java..."please bare with this novice question".
Please let me know, whats wrong with the code?

A: Try:
json.get("type").getAsString();

The thing is that GSon JsonObject stores the property inside a Map<String, JsonElement> internally, and when you call a JsonObject.get() method, it returns a JsonElement and not the actual value.


text:
Q: Where is Bootstrap's dashboard.css stylesheet? This is probably a silly question on StackExchange. Please forgive me for asking but where I am trying to follow the example to create a Dashboard theme as shown in the Custom Component example guide of Twitter Bootstrap. So I've downloaded the source code of the bootstrap distribution zip. But there is no file name dashboard.css anywhere. I googled it but it seemed to take me to a third party web site wrapbootstrap.com(Is this where to get it? ) If not, Where is it? Thank you for your help.

A: You can find it on the github repo:
https://github.com/twbs/bootstrap/tree/master/docs/examples/dashboard

A: You can see the styling of the different themes here: https://bootswatch.com


text:
Q: Accessing/Viewing SharePoint 2013 (On-Premise) SSRS reports from Office 365 SharePoint site How do we access/view SSRS reports in SP 2013 (On-premise) from Office 365 SP site. Both SP sites in different domains.

A: You need to create and publish to a Reporting Library.
Here's Microsoft's documentation on the subject.
This is just the beginning stages and if you're unaware of this there's likely a lot more configuration needed on your farm to get this operating. I would strongly suggest bringing a SharePoint Administrator on board.


text:
Q: Variable number of constructor parameters depending on integer template I'm writing a container storage class template that wraps a private std::array in order to add some functionality to it. The template parametrises the number of values, as follows:
template<size_t N> class Vector {
private:
    array<double, N> vals;
public:
    [...]
};

I'd like the constructor for the class to only accept N doubles to fill the array, but I can't find a good way to do this. Variadic arguments don't provide a mechanism to check how many of them there are, so they're right out. Parameter packs don't do floating-point promotion, but I'd be willing to deal with that if I could only figure out how to use them for this.
I've tried following the approach in the answer to Member function template with the number of parameters depending on an integral template parameter but I can't understand the significance enable_if<>::type=0 section. I've tried naïvely copying that code in (though I'd much rather understand how it works. I've seen people use ::value in other places but I can't find any documentation on why) but expanding the resulting parameter pack doesn't seem to work. My other concern with parameter packs is that I'm not sure that they'd ensure the types of all arguments were the same.
I've tried running a static_assert on the size of an initializer list, in the body of the constructor, but of course the size of the list is not constant at compile time, so that doesn't work either.
Is there a standard approach here? Am I just using parameter packs wrong?

Update:
I've got the approach in the answer I linked above partly working:

template<size_t N> class Vector {
private:
    array<double, N> vals;
public:
    template <typename ...T,
          typename enable_if<sizeof...(T) == N, int>::type = 0>
    Vector(T ...args) {
        vals = {args...};
    }
};

The issue is now that the enable_if term in the template means that when I initialise a Vector with, for example,
Vector<3> V {1.0, 2.0, 3.0};

It requests a template specialisation Vector<3>::Vector<double, double, double, 0> rather than <double, double, double>. How do I get rid of this stray term in the template?

A: Don't get what you mean by this:

Variadic arguments don't provide a mechanism to check how many of
  them there are, so they're right out

template <typename ...T>
Vector(T... args) {
    static_assert(sizeof...(args) <= N, "oops");
}

Should work..

A: You could additionally generate a pack of the right size via some template specialization tricks:
template <size_t N, class = std::make_index_sequence<N>>
class Vector;

template <size_t N, size_t... Is>
class Vector<N, std::index_sequence<Is...>>
{
private:
    std::array<double, N> vals;

    template <size_t >
    using double_ = double;
public:
    Vector(double_<Is>... vals)
    {
        ...
    }
};

That is a non-template constructor which takes N doubles.

A: By following Member function template with the number of parameters depending on an integral template parameter and Variadic templates with exactly n parameters, have got it working with the following code.
template<size_t N> class Vector {
private:
    array<double, N> vals;
public:
    template <typename ...T,
          typename enable_if<sizeof...(T) == N, int>::type = 0>
    Vector(T ...args) : vals{args} {}
};


text:
Q: How to convert XML string to JSON using iPhone sdk I am implementing a client based application. In that I have an xml string. I need to convert it to JSON format and send to the server. I have no idea on converting this. Can you  guys please suggest me any documentation or idea to this?

A: Step #1: Read XML into NSDictionary: http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/
Step #2: Convert NSDictionary into JSON: http://code.google.com/p/json-framework/

A: As Steve said the two steps are those, I leave you a bit of code, maybe can help you a bit more:
// Don't forget the imports ;)
#import "XMLReader.h"

// You must have a XML string from somewhere
NSString XMLString = yourXML;
// I remove all returns and tabs from the text, after i would be annoying if you don't remove it
XMLString = [XMLString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
XMLString = [XMLString stringByReplacingOccurrencesOfString:@"\t" withString:@""];

// Parse the XML into a dictionary
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:XMLString error:&parseError];

NSError *error;
self.dataParsed = [NSJSONSerialization dataWithJSONObject:xmlDictionary
                                                   options: NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                     error:&error];

// Print the dictionary
NSLog(@"%@", xmlDictionary);


text:
Q: dbus-monitor is working but problem with Python dbus (Python 3.10) dbus-monitor interface=org.freedesktop.Notifications
is working fine on Fedora 35. it prints all info when receiving a gnome notification.
So, I'm trying to catch dbus notifications with python:
Using this:
from gi.repository import GLib
import dbus
from dbus.mainloop.glib import DBusGMainLoop

def notifications(bus, message):
    print("Test")

DBusGMainLoop(set_as_default=True)

bus = dbus.SessionBus()
bus.add_match_string("interface='org.freedesktop.Notifications'")
bus.add_message_filter(notifications)

mainloop = GLib.MainLoop()

mainloop.run()

When executing this code, I have no error, and the mainloop is working correctly. However, when I send a notification, it does not get caught, and I do not know why.
Please note that:
import dbus

item = "org.freedesktop.Notifications"

notfy_intf = dbus.Interface(
    dbus.SessionBus().get_object(item, "/"+item.replace(".", "/")), item)

notfy_intf.Notify(
    "", 0, "", "Hello world!", "This is the notification body.",
    [], {"urgency": 1}, 3000)

is workikng fine and the notification is shown with Gnome (but still not receive by the previous script).
Is it a bug? Is it related to this version of Python or Dbus.
dbus packages installed:
dbus-broker-29-4.fc35.x86_64
python3-dbus-1.2.18-2.fc35.x86_64
dbus-glib-0.112-2.fc35.x86_64
xdg-dbus-proxy-0.1.2-5.fc35.x86_64
dleyna-connector-dbus-0.3.0-11.fc35.x86_64
abrt-dbus-2.14.6-9.fc35.x86_64
libdbusmenu-16.04.0-18.fc35.x86_64
libdbusmenu-gtk3-16.04.0-18.fc35.x86_64
dbusmenu-qt-0.9.3-0.27.20160218.fc35.x86_64
dbus-libs-1.12.22-1.fc35.x86_64
dbus-tools-1.12.22-1.fc35.x86_64
dbus-common-1.12.22-1.fc35.noarch
dbus-daemon-1.12.22-1.fc35.x86_64
dbus-x11-1.12.22-1.fc35.x86_64
dbus-1.12.22-1.fc35.x86_64


text:
Q: SQL Error: ORA-00905: missing keyword, can someone please tel me whats wrong with the below merge statement MERGE INTO table_a PARTITION (x) A
USING (SELECT distinct col1,col2 FROM table_b)b
ON (A.col1=B.col1(+) AND A.col2=B.col2(+))
WHEN MATCHED THEN
UPDATE SET col3='Y'
WHEN NOT MATCHED THEN
UPDATE SET col3='N';

A: The WHEN NOT MATCHED clause cannot perform an UPDATE - what rows is it supposed to update if it didn't find any?
If you want to update A depending on whether there's an existing row in B, one approach is to pull A into the merge query (this assumes your table A has a primary key PK):
MERGE INTO table_a PARTITION (x) tgt
  USING (
    SELECT A.PK, B.col1, B.col2
      FROM table_a A
      LEFT JOIN table_b b ON A.col1 = B.col1 AND A.col2 = B.col2) src
ON (src.pk = tgt.pk)
WHEN MATCHED THEN
  UPDATE SET col3 = (CASE WHEN src.col1 IS NOT NULL THEN 'Y' ELSE 'N' END);


text:
Q: Re-utilizar método Fiz uma consulta para pesquisar um usuário. Funcionou!
Mas tentei fazer outra consulta, ele deu essa mensagem
Error: Cannot use a pool after calling end on the pool

Porque toda vez que faço conexão, eu fecho depois, e parece que uma vez fechado ele não reabre mais.
Estou usando o nodejs 10 com postgres
Esse é meu método:
       return new Promise( (resolve, reject) => {
                const { pool, errorHandler } = deps
                const query = "SELECT * FROM public.usuario  WHERE cpf = $1"
                const queryData = [ cpf ]
                pool.connect()
                pool.query( query, queryData, (error, results) => {

                    if(error){
                        errorHandler(error, `Não foi possível encontrar usuário com cpf ${cpf}`, reject)
                        return false
                    }
                    if( results.rowCount > 0 ){
                        resolve({ usuario: results.rows })
                    }else{
                        resolve({msg: 'Usuário não encontrado'})
                    }

                })
                pool.end()
            })

Perceba que toda vez que tendo acessar, passo o método connect(), mas não está funcionando
E ainda tem essa mensagem:
Error: Called end on pool more than once

A: Consegui resolver mudando o código para
return new Promise( (resolve, reject) => {
                const { pool, errorHandler } = deps
                pool.connect((err, client, done) => {
                    if( err ){
                        errorHandler(err, `Problema ao conectar ao banco`, reject)
                        return false
                    }
                    const query = "SELECT * FROM public.usuario  WHERE cpf = $1"
                    const queryData = [ cpf ]
                    client.query( query, queryData, (error, results) => {
                        done()
                        if(error){
                            errorHandler(error, `Problema ao encontrar usuário com cpf ${cpf}`, reject)
                            return false
                        }
                        if( results.rowCount > 0 ){
                            resolve({ usuario: results.rows[0], msg: '', status: true })
                        }else{
                            resolve({msg: 'Usuário não encontrado', status: false})
                        }
                    } )
                })

Segundo a documentação