问:
Serve mp4 file through coldfusion and play with jwplayer
I have an web application in coldfusion which record videos and serve videos to user.

The video is working fine on android and desktop browsers but it is giving me error "Error loading media: File could not be played" in IOS.

Here is my JWPlayer code which is currently working.

```<code>jwplayer("element").setup({
  file: "/video.cfm?token=4514_129_9B2F727D-5056-A85D-6EBE3E48FC2AB9C6",
  image: "path/to/image",
  width: 450,
  height: 360,
  type: "mp4",
  logo: {
     file: 'path/to/logo',
     link: 'example.com',
     hide : true
  }
});
</code>```

Here is my video.cfm to server mp4 after verification.

```<code><cfset videoFile = 'path\to\file'>
<cfset fileInfo = GetFileInfo(videoFile)>
<cfset length = fileInfo.size>
<cfset start = 0>
<cfset end = fileInfo.size - 1>
<cfheader name="Content-type" value="video/mp4">
<cfheader name="Accept-Ranges" value="0-#length#">
<cfheader name="Content-Range" value="bytes #start#-#end#/#fileInfo.size#">
<cfheader name="Content-Length" value="#length#">
<cfcontent file="#videoFile#" type="video/mp4">
</code>```

I have tried some solution by adding some header. But that doesn't work. Can anyone help me to sort out the problem.

答:
I am able to resolve my problem. iOS uses a partial content header to run videos. Thanks to rickward for this lovely solution: Media Delivery to iPhones and iPads. I have made some little changes and it started working for me.

Here is the final video.cfm file.

```<code><cfset videoPath = 'path\to\mp4\file'>
<cfif FileExists(videoPath)>
    <cfset fileInfoVar = GetFileInfo(videoPath)>
    <cfheader name="Last-Modified" value="#fileInfoVar.Lastmodified#">
    <cfheader name="ETag" value="#hash(videoPath, 'MD5')#">
    <cfheader name="Content-Location" value="http://example.com/video.cfm">

    <cfif structKeyExists(GetHttpRequestData().headers, 'Range')>
        <cfset rangeDownload(videoPath)>
    <cfelse>
        <cffile action="readbinary" file="#videoPath#" variable="theData">
        <cfscript>
            context = getPageContext();
            context.setFlushOutput(false);
            response = context.getResponse().getResponse();
            response.setContentType("video/mp4");
            response.setContentLength(arrayLen(theData));

            out = response.getOutputStream();
            out.write(theData);
            out.flush();
            out.close();
        </cfscript>
    </cfif>
</cfif>

<cffunction name="rangeDownload" returnType="void" output="yes">
    <cfargument name="file" type="string" required="true" hint="path to file">

    <cfset var l = {}>
    <cfset l.request = GetHttpRequestData()>

    <cffile action="readbinary" file="#ARGUMENTS.file#" variable="l.theData">

    <cfset l.size = arrayLen(l.theData)>
    <cfset l.length = l.size>
    <cfset l.start  = 0>
    <cfset l.end = l.size - 1>

    <!--- Now that we've gotten so far without errors we send the accept range header
    /* At the moment we only support single ranges.
     * Multiple ranges requires some more work to ensure it works correctly
     * and comply with the spesifications: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
     *
     * Multirange support annouces itself with:
     * header('Accept-Ranges: bytes');
     *
     * Multirange content must be sent with multipart/byteranges mediatype,
     * (mediatype = mimetype)
     * as well as a boundry header to indicate the various chunks of data.
     */
    --->
    <cfheader name="Accept-Ranges" value="0-#l.length#">
    <!---<cfheader name="Accept-Ranges" value="bytes"> --->
    <!---
      multipart/byteranges
      http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2 --->
    <cfif structKeyExists(l.request.headers, 'Range')>

        <cfset l.c_start = l.start>
        <cfset l.c_end = l.end>

        <!--- Extract the range string --->
        <cfset l.range = ListGetAt(l.request.headers.range, 2, '=')>
        <!--- Make sure the client hasn't sent us a multibyte range --->
        <cflog file="rangeDownload" text="#l.range#" />
        <cfif l.range contains ','>
            <!--- (?) Should this be issued here, or should the first
             range be used? Or should the header be ignored and
             we output the whole content?
            --->
            <cfheader statusCode = "416" statusText = "Requested Range Not Satisfiable">
            <cfheader name="Content-Range" value="bytes #l.start#-#l.end#/#l.size#">
            <!--- (?) Echo some info to the client? --->
            <cfabort>
        </cfif>
        <!--- If the range starts with an '-' we start from the beginning
            If not, we forward the file pointer
            And make sure to get the end byte if specified --->
        <cfif Left(l.range, 1) eq '-'>
        <!--- The n-number of the last bytes is requested --->
            <cfset l.c_start = l.size - Mid(l.range, 2, Len(l.range))>
        <cfelse>
            <cfset l.rangeArray = ListToArray(l.range, '-')>
            <cfset l.c_start = l.rangeArray[1]>
            <cfif ArrayLen(l.rangeArray) eq 2 and val(l.rangeArray[2]) gt 0>
                <cfset l.c_end = l.rangeArray[2]>
            <cfelse>
                <cfset l.c_end = l.size>
            </cfif>
        </cfif>
        <!---
        /* Check the range and make sure it's treated according to the specs.
         * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
         */
        // End bytes can not be larger than l.end. --->
        <cfif l.c_end gt l.end>
            <cfset l.c_end = l.end>
        </cfif>

        <!--- Validate the requested range and return an error if it's not correct. --->
        <cfif l.c_start gt l.c_end || l.c_start gt (l.size - 1) || l.c_end gte l.size>
            <cfheader statusCode = "416" statusText = "Requested Range Not Satisfiable">
            <cfheader name="Content-Range" value="bytes #l.start#-#l.end#/#l.size#">
            <!--- (?) Echo some info to the client? --->
            <cfabort>
        </cfif>

        <cfset l.start = l.c_start>
        <cfset l.end = l.c_end>
        <cfset l.length = l.end - l.start + 1><!--- Calculate new content length --->

        <cfscript>
            context = getPageContext();
            context.setFlushOutput(false);
            response = context.getResponse().getResponse();
            response.setContentType("video/mp4");
            response.setContentLength(l.length);
        </cfscript>
        <cfheader statusCode = "206" statusText = "Partial Content">

    </cfif>

    <!--- Notify the client the byte range we'll be outputting --->
    <cfheader name="Content-Range" value="bytes #l.start#-#l.end#/#l.size#">
    <cfheader name="Content-Length" value="#l.length#">

    <cfscript>
        // Start buffered download
        out = response.getOutputStream();
        // write the portion requested
        out.write(l.theData, javacast('int', l.start), javacast('int', l.length));
        out.flush();
        out.close();
    </cfscript>
</cffunction>
</code>```

Body:
I have an web application in coldfusion which record videos and serve videos to user.

The video is working fine on android and desktop browsers but it is giving me error "Error loading media: File could not be played" in IOS.

Here is my JWPlayer code which is currently working.

jwplayer("element").setup({
  file: "/video.cfm?token=4514_129_9B2F727D-5056-A85D-6EBE3E48FC2AB9C6",
  image: "path/to/image",
  width: 450,
  height: 360,
  type: "mp4",
  logo: {
     file: 'path/to/logo',
     link: 'example.com',
     hide : true
  }
});

Here is my video.cfm to server mp4 after verification.

<cfset videoFile = 'path\to\file'>
<cfset fileInfo = GetFileInfo(videoFile)>
<cfset length = fileInfo.size>
<cfset start = 0>
<cfset end = fileInfo.size - 1>
<cfheader name="Content-type" value="video/mp4">
<cfheader name="Accept-Ranges" value="0-#length#">
<cfheader name="Content-Range" value="bytes #start#-#end#/#fileInfo.size#">
<cfheader name="Content-Length" value="#length#">
<cfcontent file="#videoFile#" type="video/mp4">

I have tried some solution by adding some header. But that doesn't work. Can anyone help me to sort out the problem.

Body:
I am able to resolve my problem. iOS uses a partial content header to run videos. Thanks to rickward for this lovely solution: Media Delivery to iPhones and iPads. I have made some little changes and it started working for me.

Here is the final video.cfm file.

<cfset videoPath = 'path\to\mp4\file'>
<cfif FileExists(videoPath)>
    <cfset fileInfoVar = GetFileInfo(videoPath)>
    <cfheader name="Last-Modified" value="#fileInfoVar.Lastmodified#">
    <cfheader name="ETag" value="#hash(videoPath, 'MD5')#">
    <cfheader name="Content-Location" value="http://example.com/video.cfm">

    <cfif structKeyExists(GetHttpRequestData().headers, 'Range')>
        <cfset rangeDownload(videoPath)>
    <cfelse>
        <cffile action="readbinary" file="#videoPath#" variable="theData">
        <cfscript>
            context = getPageContext();
            context.setFlushOutput(false);
            response = context.getResponse().getResponse();
            response.setContentType("video/mp4");
            response.setContentLength(arrayLen(theData));

            out = response.getOutputStream();
            out.write(theData);
            out.flush();
            out.close();
        </cfscript>
    </cfif>
</cfif>

<cffunction name="rangeDownload" returnType="void" output="yes">
    <cfargument name="file" type="string" required="true" hint="path to file">

    <cfset var l = {}>
    <cfset l.request = GetHttpRequestData()>

    <cffile action="readbinary" file="#ARGUMENTS.file#" variable="l.theData">

    <cfset l.size = arrayLen(l.theData)>
    <cfset l.length = l.size>
    <cfset l.start  = 0>
    <cfset l.end = l.size - 1>

    <!--- Now that we've gotten so far without errors we send the accept range header
    /* At the moment we only support single ranges.
     * Multiple ranges requires some more work to ensure it works correctly
     * and comply with the spesifications: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
     *
     * Multirange support annouces itself with:
     * header('Accept-Ranges: bytes');
     *
     * Multirange content must be sent with multipart/byteranges mediatype,
     * (mediatype = mimetype)
     * as well as a boundry header to indicate the various chunks of data.
     */
    --->
    <cfheader name="Accept-Ranges" value="0-#l.length#">
    <!---<cfheader name="Accept-Ranges" value="bytes"> --->
    <!---
      multipart/byteranges
      http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2 --->
    <cfif structKeyExists(l.request.headers, 'Range')>

        <cfset l.c_start = l.start>
        <cfset l.c_end = l.end>

        <!--- Extract the range string --->
        <cfset l.range = ListGetAt(l.request.headers.range, 2, '=')>
        <!--- Make sure the client hasn't sent us a multibyte range --->
        <cflog file="rangeDownload" text="#l.range#" />
        <cfif l.range contains ','>
            <!--- (?) Should this be issued here, or should the first
             range be used? Or should the header be ignored and
             we output the whole content?
            --->
            <cfheader statusCode = "416" statusText = "Requested Range Not Satisfiable">
            <cfheader name="Content-Range" value="bytes #l.start#-#l.end#/#l.size#">
            <!--- (?) Echo some info to the client? --->
            <cfabort>
        </cfif>
        <!--- If the range starts with an '-' we start from the beginning
            If not, we forward the file pointer
            And make sure to get the end byte if specified --->
        <cfif Left(l.range, 1) eq '-'>
        <!--- The n-number of the last bytes is requested --->
            <cfset l.c_start = l.size - Mid(l.range, 2, Len(l.range))>
        <cfelse>
            <cfset l.rangeArray = ListToArray(l.range, '-')>
            <cfset l.c_start = l.rangeArray[1]>
            <cfif ArrayLen(l.rangeArray) eq 2 and val(l.rangeArray[2]) gt 0>
                <cfset l.c_end = l.rangeArray[2]>
            <cfelse>
                <cfset l.c_end = l.size>
            </cfif>
        </cfif>
        <!---
        /* Check the range and make sure it's treated according to the specs.
         * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
         */
        // End bytes can not be larger than l.end. --->
        <cfif l.c_end gt l.end>
            <cfset l.c_end = l.end>
        </cfif>

        <!--- Validate the requested range and return an error if it's not correct. --->
        <cfif l.c_start gt l.c_end || l.c_start gt (l.size - 1) || l.c_end gte l.size>
            <cfheader statusCode = "416" statusText = "Requested Range Not Satisfiable">
            <cfheader name="Content-Range" value="bytes #l.start#-#l.end#/#l.size#">
            <!--- (?) Echo some info to the client? --->
            <cfabort>
        </cfif>

        <cfset l.start = l.c_start>
        <cfset l.end = l.c_end>
        <cfset l.length = l.end - l.start + 1><!--- Calculate new content length --->

        <cfscript>
            context = getPageContext();
            context.setFlushOutput(false);
            response = context.getResponse().getResponse();
            response.setContentType("video/mp4");
            response.setContentLength(l.length);
        </cfscript>
        <cfheader statusCode = "206" statusText = "Partial Content">

    </cfif>

    <!--- Notify the client the byte range we'll be outputting --->
    <cfheader name="Content-Range" value="bytes #l.start#-#l.end#/#l.size#">
    <cfheader name="Content-Length" value="#l.length#">

    <cfscript>
        // Start buffered download
        out = response.getOutputStream();
        // write the portion requested
        out.write(l.theData, javacast('int', l.start), javacast('int', l.length));
        out.flush();
        out.close();
    </cfscript>
</cffunction>


来源: stackexchange

问:
How to pass multiple uniforms efficiently and dynamically to GLSL
I want to pass an array of struct I have in my program, I know there are a few way's to do this but I want to do it efficiently, here is what I know I can do:

I can use simply create a struct with the things I want to pass to the shaders and create an array of how many can be passed:

```<code>struct Light
{
    vec3 Position;
    vec3 diffuse;
    float Intensity;
};

#define NUM_OF_LIGHTS 5
uniform Light lights[NUM_OF_LIGHTS];
</code>```

Pros: Really easy to do.

Cons: It is not dynamic, I need to choose a maximum amount of lights, which I want to avoid doing.

I can use Uniform Blocks Objects (UBO) which I read on opengl.org that I can use array for them from OpenGL 4.0 (Which is my target by the way, (considering 4.1)).

Pros: Cleaner(?) to do. might be faster(?)1

Cons: Still, not dynamic.

Shader Storage Blocks Objects (SSBO) is another option but I can't use them because they are core on version 4.3. bad for me because, as far as I read, they are dynamic and that is what I want.

I couldn't find anything else about how to pass things as I want to do.

If I can't do it, how can game engines create multiple lighting without knowing how much lights the user will enter (considering they using OpenGL and they target 3.X up to 4.0, which seem reasonable to me)?

Thanks in advance.

Footnotes:

I might be wrong here, so if I do let me know and I will delete those.

答:
One option is to render, say first 16 lights, and do another pass for the next 16 lights and continue until all lights are rendered. This would allow arbitrary and dynamic number of lights.

Something like:

```<code>for (int i = 0; i < lights.size(); i += 16) {
    setUniformData(lights, i, i+15);
    render();
}
</code>```

Note that this requires additive blending

```<code>glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_ONE, GL_ONE);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to pass an array of struct I have in my program, I know there are a few way's to do this but I want to do it efficiently, here is what I know I can do:

I can use simply create a struct with the things I want to pass to the shaders and create an array of how many can be passed:

struct Light
{
    vec3 Position;
    vec3 diffuse;
    float Intensity;
};

#define NUM_OF_LIGHTS 5
uniform Light lights[NUM_OF_LIGHTS];

Pros: Really easy to do.

Cons: It is not dynamic, I need to choose a maximum amount of lights, which I want to avoid doing.

I can use Uniform Blocks Objects (UBO) which I read on opengl.org that I can use array for them from OpenGL 4.0 (Which is my target by the way, (considering 4.1)).

Pros: Cleaner(?) to do. might be faster(?)1

Cons: Still, not dynamic.

Shader Storage Blocks Objects (SSBO) is another option but I can't use them because they are core on version 4.3. bad for me because, as far as I read, they are dynamic and that is what I want.

I couldn't find anything else about how to pass things as I want to do.

If I can't do it, how can game engines create multiple lighting without knowing how much lights the user will enter (considering they using OpenGL and they target 3.X up to 4.0, which seem reasonable to me)?

Thanks in advance.

Footnotes:

I might be wrong here, so if I do let me know and I will delete those.

Body:
One option is to render, say first 16 lights, and do another pass for the next 16 lights and continue until all lights are rendered. This would allow arbitrary and dynamic number of lights.

Something like:

for (int i = 0; i < lights.size(); i += 16) {
    setUniformData(lights, i, i+15);
    render();
}

Note that this requires additive blending

glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_ONE, GL_ONE);


问:
Change the text size in tab in android
I've been facing the issue of text size in tab bar. Below is the image,

And here is my code,

MainActivity.java

```<code>public class MainActivity extends Activity implements OnTabChangeListener, OnPageChangeListener{
    private TabHost tabHost;
    private ViewPager pager;

 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   tabHost = (TabHost)findViewById(android.R.id.tabhost);
   pager = (ViewPager) findViewById(R.id.pager);

   tabHost.setup();
   TabWidget tabwidget=tabHost.getTabWidget();

   TabSpec spec = tabHost.newTabSpec("tab1");
   spec.setContent(R.id.tab1);
   spec.setIndicator("Check In");
   tabHost.addTab(spec);

   spec = tabHost.newTabSpec("tab2");
   spec.setContent(R.id.tab2);
   spec.setIndicator("Buddies");
   tabHost.addTab(spec);

   spec = tabHost.newTabSpec("tab3");
   spec.setContent(R.id.tab3);
   spec.setIndicator("Recommendation");
   tabHost.addTab(spec);

   spec = tabHost.newTabSpec("tab4");
   spec.setContent(R.id.tab4);
   spec.setIndicator("Feed");
   tabHost.addTab(spec);

   spec = tabHost.newTabSpec("tab5");
   spec.setContent(R.id.tab5);
   spec.setIndicator("Last");
   tabHost.addTab(spec);

   pager.setAdapter(new MyPagerAdapter(this));
   pager.setOnPageChangeListener(this);
   tabHost.setOnTabChangedListener(this);

 }
    @Override
    public void onTabChanged(String tabId){
         int pageNumber = 0;
         if(tabId.equals("tab1"))
         {
              pageNumber = 0;

         }

         else if(tabId.equals("tab2"))
         {
              pageNumber = 1;

         }

         else if(tabId.equals("tab3"))
         {
              pageNumber = 2;

         }

         else if(tabId.equals("tab4"))
         {
              pageNumber = 3;

         }

         else if(tabId.equals("tab5"))
         {
              pageNumber = 4;

         }
         else
         {
              pageNumber = 0;

         }

         pager.setCurrentItem(pageNumber);
    }

    @Override
    public void onPageSelected(int pageNumber) {
         tabHost.setCurrentTab(pageNumber);

    }
    @Override
    public void onPageScrollStateChanged(int arg0) {

    }
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }
    }
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <FrameLayout
                android:id="@+id/tab1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone" />

            <FrameLayout
                android:id="@+id/tab2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone" />

            <FrameLayout
                android:id="@+id/tab3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone" />

            <FrameLayout
                android:id="@+id/tab4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone" />

            <FrameLayout
                android:id="@+id/tab5"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone" />
        </FrameLayout>

        <android.support.v4.view.ViewPager
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</TabHost>
</code>```

I want whole text to be set in each tab, how can I do that?

I've been trying this code to change the text size and getting this result,

code

```<code> TextView x = (TextView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title);
   x.setTextSize(10);
   tabHost.getTabWidget().getChildAt(0).getLayoutParams().width = 100;

   TextView x1 = (TextView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.title);
   x1.setTextSize(10);
   tabHost.getTabWidget().getChildAt(1).getLayoutParams().width = 90;

   TextView x2 = (TextView) tabHost.getTabWidget().getChildAt(2).findViewById(android.R.id.title);
   x2.setTextSize(10);
   tabHost.getTabWidget().getChildAt(2).getLayoutParams().width = 100;

   TextView x3 = (TextView) tabHost.getTabWidget().getChildAt(3).findViewById(android.R.id.title);
   x3.setTextSize(10);
   tabHost.getTabWidget().getChildAt(3).getLayoutParams().width = 40;

   TextView x4 = (TextView) tabHost.getTabWidget().getChildAt(4).findViewById(android.R.id.title);
   x4.setTextSize(10);
   tabHost.getTabWidget().getChildAt(4).getLayoutParams().width = 40;
</code>```

Image of result

But I want the output as this image

As per above image, my tab widget should be movable, how can I do this?

答:
```<code><TabHost
     android:id="@+id/tabhost"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_alignParentTop="true"
     android:layout_alignParentLeft="true">

     <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="vertical" >

         <TabWidget
             android:id="@android:id/tabs"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             >

         </TabWidget>

         <FrameLayout
             android:id="@android:id/tabcontent"
             android:layout_width="0dp"
             android:layout_height="0dp"
             android:layout_weight="0" />

         <android.support.v4.view.ViewPager
             android:id="@+id/viewpager"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             />
     </LinearLayout>
 </TabHost>
</code>```

Code:

```<code>for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
{
    TextView tv = (TextView) tabhost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
    tv.setTextColor(Color.parseColor(SM.getTheme_colour()));
    tv.setTypeface(font_k);
}
</code>```

This code works for tabhost change text color, type face (font style) and also text size.

Title: Change the text size in tab in android

Body:
I've been facing the issue of text size in tab bar. Below is the image,

And here is my code,

MainActivity.java

public class MainActivity extends Activity implements OnTabChangeListener, OnPageChangeListener{
    private TabHost tabHost;
    private ViewPager pager;

 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   tabHost = (TabHost)findViewById(android.R.id.tabhost);
   pager = (ViewPager) findViewById(R.id.pager);

   tabHost.setup();
   TabWidget tabwidget=tabHost.getTabWidget();

   TabSpec spec = tabHost.newTabSpec("tab1");
   spec.setContent(R.id.tab1);
   spec.setIndicator("Check In");
   tabHost.addTab(spec);

   spec = tabHost.newTabSpec("tab2");
   spec.setContent(R.id.tab2);
   spec.setIndicator("Buddies");
   tabHost.addTab(spec);

   spec = tabHost.newTabSpec("tab3");
   spec.setContent(R.id.tab3);
   spec.setIndicator("Recommendation");
   tabHost.addTab(spec);

   spec = tabHost.newTabSpec("tab4");
   spec.setContent(R.id.tab4);
   spec.setIndicator("Feed");
   tabHost.addTab(spec);

   spec = tabHost.newTabSpec("tab5");
   spec.setContent(R.id.tab5);
   spec.setIndicator("Last");
   tabHost.addTab(spec);

   pager.setAdapter(new MyPagerAdapter(this));
   pager.setOnPageChangeListener(this);
   tabHost.setOnTabChangedListener(this);

 }
    @Override
    public void onTabChanged(String tabId){
         int pageNumber = 0;
         if(tabId.equals("tab1"))
         {
              pageNumber = 0;

         }

         else if(tabId.equals("tab2"))
         {
              pageNumber = 1;

         }

         else if(tabId.equals("tab3"))
         {
              pageNumber = 2;

         }

         else if(tabId.equals("tab4"))
         {
              pageNumber = 3;

         }

         else if(tabId.equals("tab5"))
         {
              pageNumber = 4;

         }
         else
         {
              pageNumber = 0;

         }

         pager.setCurrentItem(pageNumber);
    }

    @Override
    public void onPageSelected(int pageNumber) {
         tabHost.setCurrentTab(pageNumber);

    }
    @Override
    public void onPageScrollStateChanged(int arg0) {

    }
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }
    }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <FrameLayout
                android:id="@+id/tab1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone" />

            <FrameLayout
                android:id="@+id/tab2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone" />

            <FrameLayout
                android:id="@+id/tab3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone" />

            <FrameLayout
                android:id="@+id/tab4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone" />

            <FrameLayout
                android:id="@+id/tab5"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone" />
        </FrameLayout>

        <android.support.v4.view.ViewPager
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</TabHost>

I want whole text to be set in each tab, how can I do that?

I've been trying this code to change the text size and getting this result,

code

 TextView x = (TextView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title);
   x.setTextSize(10);
   tabHost.getTabWidget().getChildAt(0).getLayoutParams().width = 100;

   TextView x1 = (TextView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.title);
   x1.setTextSize(10);
   tabHost.getTabWidget().getChildAt(1).getLayoutParams().width = 90;

   TextView x2 = (TextView) tabHost.getTabWidget().getChildAt(2).findViewById(android.R.id.title);
   x2.setTextSize(10);
   tabHost.getTabWidget().getChildAt(2).getLayoutParams().width = 100;

   TextView x3 = (TextView) tabHost.getTabWidget().getChildAt(3).findViewById(android.R.id.title);
   x3.setTextSize(10);
   tabHost.getTabWidget().getChildAt(3).getLayoutParams().width = 40;

   TextView x4 = (TextView) tabHost.getTabWidget().getChildAt(4).findViewById(android.R.id.title);
   x4.setTextSize(10);
   tabHost.getTabWidget().getChildAt(4).getLayoutParams().width = 40;

Image of result

But I want the output as this image

As per above image, my tab widget should be movable, how can I do this?

Body:
<TabHost
     android:id="@+id/tabhost"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_alignParentTop="true"
     android:layout_alignParentLeft="true">

     <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="vertical" >

         <TabWidget
             android:id="@android:id/tabs"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             >

         </TabWidget>

         <FrameLayout
             android:id="@android:id/tabcontent"
             android:layout_width="0dp"
             android:layout_height="0dp"
             android:layout_weight="0" />

         <android.support.v4.view.ViewPager
             android:id="@+id/viewpager"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             />
     </LinearLayout>
 </TabHost>

Code:

for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
{
    TextView tv = (TextView) tabhost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
    tv.setTextColor(Color.parseColor(SM.getTheme_colour()));
    tv.setTypeface(font_k);
}

This code works for tabhost change text color, type face (font style) and also text size.


问:
How to check if OS is Vista in Python?
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and pywin32 or wxPython?

Essentially, I need a function that called will return True iff current OS is Vista:

```<code>>>> isWindowsVista()
True
</code>```

答:
```<code>import platform
if platform.release() == "Vista":
    # Do something.
</code>```

or

```<code>import platform
if "Vista" in platform.release():
    # Do something.
</code>```

OwnerDisplayName: DzinX

ContentLicense: CC BY-SA 2.5

Title: How to check if OS is Vista in Python?

Body:
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and pywin32 or wxPython?

Essentially, I need a function that called will return True iff current OS is Vista:

>>> isWindowsVista()
True

Body:
import platform
if platform.release() == "Vista":
    # Do something.

or

import platform
if "Vista" in platform.release():
    # Do something.


问:
How to fast reorder child elements in flex 4?
I have a control which contains many child elements (about 1000), and I need to sort them.

Now I doing that like this:

```<code>_elements.sortOn(...);

for (var i: int = 0; i < _elements.length; i++) {
    setItemIndex(_childItems[_elements[i].id], i);
}
</code>```

_childElement - object that contains UI-child elements, which i need to sort (key of the dictionary is an identifier from data-object

_elements - array contains data-objects

But this is too slow!
How to reorder the childs by my criteria as fast as possible?

答:
I don't have enough info to be sure my answer is correct but... if "_elements" is an arraycollection and it's bound to the control as dataprovider

somethink like < ns:mycontrol dataProvider="{_elements}"/>

each time you change "_elements" the binding makes the control parse and render the data in the dataprovider, so, for a list 1000+ long it's going to be painful.

in this case I'd storethe _elements array (the data of the array collection) in a tmp variable and replace it with a new blank array. then do all your sorting stuff on the tmp and set it back again as the _elements data. by doing this you're just forcing parsing and rendering twice...not 1000+ times :)

my 2 cents,
ciao

Body:
I have a control which contains many child elements (about 1000), and I need to sort them.

Now I doing that like this:

_elements.sortOn(...);

for (var i: int = 0; i < _elements.length; i++) {
    setItemIndex(_childItems[_elements[i].id], i);
}

_childElement - object that contains UI-child elements, which i need to sort (key of the dictionary is an identifier from data-object

_elements - array contains data-objects

But this is too slow!
How to reorder the childs by my criteria as fast as possible?


问:
Javascript's setInterval lags the browser
I have a live chat working on. And I have used setInterval to display all messages in realtime every 0.5 seconds. But I noticed that setInterval freezes and sometimes crashes the browser. I heard that setTimeout is the best alternative way to use?</p>

```<code>  setInterval(function(){
        $.ajax({
            url: "display_msg.php",
            method: "POST",
            data: {conn:conn},
            success: function(data) {
                $('#chatarea').html(data);
            }
        });
    },500);
</code>```

答:
The thing is setInterval will call the function every x milliseconds, and, as you are submitting requests, and the server takes some time to respond, it might happen that multiple requests are executing in parallel, causing some trouble to you app.

With setTimeout you could submit a new request only after the completion of the previous one. This will be much better. Don't forget to write some code to treat timeout problems.

Good luck!

Body:
I have a live chat working on. And I have used setInterval to display all messages in realtime every 0.5 seconds. But I noticed that setInterval freezes and sometimes crashes the browser. I heard that setTimeout is the best alternative way to use?

  setInterval(function(){
        $.ajax({
            url: "display_msg.php",
            method: "POST",
            data: {conn:conn},
            success: function(data) {
                $('#chatarea').html(data);
            }
        });
    },500);


问:
php select variable cfrom data base
I am trying to select some variable from database and then insert them. But how to change maybe or idk do something because where i try to insert "VALUES ('m.ID', 'md.ID')" he dont recognize and its not working.</p>

```<code>$sql = "SELECT m.vardas, m.pavarde, m.ID, md.pavadinimas, md.ID FROM  Mokinys m, Mokymodalykas md
where m.vardas='$mokiniovar' and m.pavarde='$mokiniopav' and md.pavadinimas='$dalykas'";

$sql2 = "INSERT INTO Pazymiuregistras (mokinio_ID, dalyko_ID, pazymys, data) VALUES ('$m.ID', '$md.ID', '$pazymys', '$data');"; // in this place he dont recognize m.id and md.id
if ($conn->multi_query($sql2) === TRUE) {
echo "New records created successfully";
} else{
echo "Error";
}
$conn->close();
</code>```

答:
Use a single statement insert . . . select.  Don't do this with a loop!

```<code>INSERT INTO Pazymiuregistras (mokinio_ID, dalyko_ID, pazymys, data)
    SELECT m.ID, md.ID, '$pazymys', '$data'
    FROM  Mokinys m CROSS JOIN
          Mokymodalykas md
    WHERE m.vardas = '$mokiniovar' AND
          m.pavarde = '$mokiniopav' AND
          md.pavadinimas = '$dalykas';
</code>```

In addition, get out of the habit of dumping strings into SQL statements.  Learn to use parameters.  This is important for two reasons:

Putting strings into the statements can cause unexpected syntax errors, and occasionally hard-to-find bugs.

The resulting code is at risk of SQL-injection attacks.

Title: php select variable cfrom data base

Body:
I am trying to select some variable from database and then insert them. But how to change maybe or idk do something because where i try to insert "VALUES ('m.ID', 'md.ID')" he dont recognize and its not working.

$sql = "SELECT m.vardas, m.pavarde, m.ID, md.pavadinimas, md.ID FROM  Mokinys m, Mokymodalykas md
where m.vardas='$mokiniovar' and m.pavarde='$mokiniopav' and md.pavadinimas='$dalykas'";

$sql2 = "INSERT INTO Pazymiuregistras (mokinio_ID, dalyko_ID, pazymys, data) VALUES ('$m.ID', '$md.ID', '$pazymys', '$data');"; // in this place he dont recognize m.id and md.id
if ($conn->multi_query($sql2) === TRUE) {
echo "New records created successfully";
} else{
echo "Error";
}
$conn->close();

Body:
Use a single statement insert . . . select.  Don't do this with a loop!

INSERT INTO Pazymiuregistras (mokinio_ID, dalyko_ID, pazymys, data)
    SELECT m.ID, md.ID, '$pazymys', '$data'
    FROM  Mokinys m CROSS JOIN
          Mokymodalykas md
    WHERE m.vardas = '$mokiniovar' AND
          m.pavarde = '$mokiniopav' AND
          md.pavadinimas = '$dalykas';

In addition, get out of the habit of dumping strings into SQL statements.  Learn to use parameters.  This is important for two reasons:

Putting strings into the statements can cause unexpected syntax errors, and occasionally hard-to-find bugs.

The resulting code is at risk of SQL-injection attacks.


问:
Apply button javascript to an a href
My friend gave me this code that will allow a smooth scroll effect to the page once the user pushes an anchor button:

```<code><form id = "button_design" action="#page2">
     <input type="submit" class="anchor-button" value="Page 2" />
</form>
</code>```

And the javascript:

```<code>$(function() {
$('input.anchor-button').click(function(e) {
e.preventDefault();
var hash = $(this).parent('form').attr('action');
var target = $(hash);
target = target.length ? target : $('[name=' + hash.slice(1) +']');
if (target.length) {
  $('html, body').animate({
   scrollTop: target.offset().top
 }, 1000);
}

});
});
</code>```

It works for input type = "submit" only and I want to try to use this code to my href ="#page3"... which is only a link and not a button. Can anyone help me to convert the code to make it apply to a href too? I tried messing around with it but I get nowhere.

答:
You really have to learn about selectors to work with JS. Here is an example with link. Every link must has class anchor and target in it's href attribute. So you don't need a form to wrap it:

```<code><a class="anchor" href="#page2"> Page 2 </a>
</code>```

And script for this markup

```<code>$(function () {
    $('a.anchor').click(function (e) {
        e.preventDefault();
        var hash = $(this).attr('href');
        var target = $(hash);
        target = target.length ? target : $('[name=' + hash.slice(1) + ']');

        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);
        }
    });
});
</code>```

Title: Apply button javascript to an a href

Body:
My friend gave me this code that will allow a smooth scroll effect to the page once the user pushes an anchor button:

<form id = "button_design" action="#page2">
     <input type="submit" class="anchor-button" value="Page 2" />
</form>

And the javascript:

$(function() {
$('input.anchor-button').click(function(e) {
e.preventDefault();
var hash = $(this).parent('form').attr('action');
var target = $(hash);
target = target.length ? target : $('[name=' + hash.slice(1) +']');
if (target.length) {
  $('html, body').animate({
   scrollTop: target.offset().top
 }, 1000);
}

});
});

It works for input type = "submit" only and I want to try to use this code to my <a href ="#page3"... which is only a link and not a button. Can anyone help me to convert the code to make it apply to a href too? I tried messing around with it but I get nowhere.

Body:
You really have to learn about selectors to work with JS. Here is an example with link. Every link must has class anchor and target in it's href attribute. So you don't need a form to wrap it:

<a class="anchor" href="#page2"> Page 2 </a>

And script for this markup

$(function () {
    $('a.anchor').click(function (e) {
        e.preventDefault();
        var hash = $(this).attr('href');
        var target = $(hash);
        target = target.length ? target : $('[name=' + hash.slice(1) + ']');

        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);
        }
    });
});


问:
multiple comma values in single csv file column
I am not getting multiple , separate values in single column.Thanks for help

```<code>$fname = "vijay";
$mname = "a,b";
$csvData = "";
   $csvData .= "First Name";
    $csvData .= ",Middle Name";
    $csvData .= "\n\r";
    $csvData .= "$fname" . ",";
    $csvData .= "$mname";
    $csvData .= "\n\r";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=student-report-data-" . date("dMY_H:i") . ".csv");
header('Pragma: no-cache');
header('Expires: 0');
echo $csvData;
exit;
</code>```

答:
Try wrapping them inside quotes.  Your second input's ,'s are currently creating a new column rather than behaving how you want them to, stay inline.  I would recommend looking into http://php.net/manual/en/function.fputcsv.php to make this less labor intensive.

```<code>$fname = "vijay";
$mname = "a,b";
$csvData = "";
     $csvData .= "\"First Name\"";
        $csvData .= ",\"Middle Name\"";
        $csvData .= "\n\r";
        $csvData .= "\"$fname\"" . ",";
        $csvData .= "\"$mname\"";
        $csvData .= "\n\r";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=student-report-data-" . date("dMY_H:i") . ".csv");
header('Pragma: no-cache');
header('Expires: 0');
echo $csvData;
exit;
</code>```

If  you ever have a quote in your string you will have to add a \ before the ", just a heads up.

Body:
I am not getting multiple , separate values in single column.Thanks for help

$fname = "vijay";
$mname = "a,b";
$csvData = "";
   $csvData .= "First Name";
    $csvData .= ",Middle Name";
    $csvData .= "\n\r";
    $csvData .= "$fname" . ",";
    $csvData .= "$mname";
    $csvData .= "\n\r";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=student-report-data-" . date("dMY_H:i") . ".csv");
header('Pragma: no-cache');
header('Expires: 0');
echo $csvData;
exit;

Body:
Try wrapping them inside quotes.  Your second input's ,'s are currently creating a new column rather than behaving how you want them to, stay inline.  I would recommend looking into http://php.net/manual/en/function.fputcsv.php to make this less labor intensive.

$fname = "vijay";
$mname = "a,b";
$csvData = "";
     $csvData .= "\"First Name\"";
        $csvData .= ",\"Middle Name\"";
        $csvData .= "\n\r";
        $csvData .= "\"$fname\"" . ",";
        $csvData .= "\"$mname\"";
        $csvData .= "\n\r";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=student-report-data-" . date("dMY_H:i") . ".csv");
header('Pragma: no-cache');
header('Expires: 0');
echo $csvData;
exit;

If  you ever have a quote in your string you will have to add a \ before the ", just a heads up.


问:
laravel5.2 errors not show up in blade
I am trying solve this wired problem for hours, but still the errors message won't show up in template.
I have make sure the web middleware (which contains StartSession and ShareErrorsFromSession) is wrapped all my route.

```<code>Route::group(['namespace'=>'admin','prefix'=>'admin','middleware'=>['web']],function (){
Route::get('index','AdminController@index');
Route::get('addCase','CaseController@create');
Route::any('upload','AdminController@upload');
Route::resource('case', 'CaseController');
</code>```

});

```<code>    public function store(Request $resquest)
{
    //
    $validator = Validator::make($resquest->all(), [
        'title' => 'required',
    ]);
    if($validator->passes()){

    }else{
        return back()->withErrors($validator);
    }

}

   <form method="post" class="form-horizontal" action="{{action('admin\CaseController@store')}}">
            {{ csrf_field() }}
            @if (count($errors) > 0)
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
                <button>submit</button>
        </form>
</code>```

please help!

the validation is worked, but the errors vanished

答:
Please try this

In controller

```<code> $validator = Validator::make($request->all(),[
    'title' => 'required'});
  if($validator->fails()) {
        return Redirect::back()->withErrors($validator);
  }
</code>```

In view page

```<code>   @if ($errors->any())
        <ul class="alert alert-danger">
          @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
          @endforeach
        </ul>
    @endif
</code>```

ContentLicense: CC BY-SA 4.0

Title: laravel5.2 errors not show up in blade

Body:
I am trying solve this wired problem for hours, but still the errors message won't show up in template.
I have make sure the web middleware (which contains StartSession and ShareErrorsFromSession) is wrapped all my route.

Route::group(['namespace'=>'admin','prefix'=>'admin','middleware'=>['web']],function (){
Route::get('index','AdminController@index');
Route::get('addCase','CaseController@create');
Route::any('upload','AdminController@upload');
Route::resource('case', 'CaseController');

});

    public function store(Request $resquest)
{
    //
    $validator = Validator::make($resquest->all(), [
        'title' => 'required',
    ]);
    if($validator->passes()){

    }else{
        return back()->withErrors($validator);
    }

}

   <form method="post" class="form-horizontal" action="{{action('admin\CaseController@store')}}">
            {{ csrf_field() }}
            @if (count($errors) > 0)

                        @foreach ($errors->all() as $error)

{{ $error }}

                        @endforeach

            @endif
                <button>submit</button>
        </form>

please help!

the validation is worked, but the errors vanished

Body:
Please try this

In controller

 $validator = Validator::make($request->all(),[
    'title' => 'required'});
  if($validator->fails()) {
        return Redirect::back()->withErrors($validator);
  }

In view page

   @if ($errors->any())
        <ul class="alert alert-danger">
          @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
          @endforeach
        </ul>
    @endif


问:
Authentication without email and password.
I am trying to have an authentication system for apis. But unlike traditional way, this will be without email and password

The front end is an android app. Initially the app will have empty auth_token in the local storage, now the app requests for
an auth token from the server, by sending the mobile_number, device_id and gcm_id.

Now the server generates a 16 securerandom hex, and sends it as auth token to the front end.

Now the front end has to call all the apis using this auth token.

The server user table will be like this

id || mobile_number || device_id || gcm_id || auth_token

Question 1:

Should I generate my auth token based on the mobile_number, device id or can it be independently generated?

Question 2:

Should the auth token be changed? or can I use the same auth token permanently for the user. If it has to be changed .. can you please guide me in pointing out which strategy to use

Question 3:

What are the pitfalls for this kind of authentication. I don't want the user to type the email and password, but at the same time want to identify the user for personalization calculations.

答: Question 3: One pitfall is not encrypting the key wherever you store it.  If you store it in a database (User table, e.g.) you should encrypt with a method like this: https://saasbook.blogspot.com/2016/08/encrypting-application-level-data-at.html</p>


问:
C++ read from a csv file and then assign the data to class member
I am a C++ beginner. My basic code shown below is able to read csv file and print out data line by line. However, I cannot figure out how to assign all these data to my defined commuter class variables. I have tried alot of online tutorial but it will always show errors that I am not sure how to debug.Could anyone give me a hand or some hints? thank you.

sample data:

```
commuter1;A;7;20
commuter2;B;8;30
commuter3;F;10;10
.....
```

```<code>#include<iostream>
#include<string>
#include<vector>
#include<fstream>//strtok
using namespace std;
class Commuter {
private:
    string name;
    char point;
    int hour;
    int minute;
public:
    Commuter(string name, char point, int hour, int min) {
        this->name = name;
        this->point = point;
        this->hour = hour;
        this->minute = min;
}
void setname(string name);
void setpoint(char point);
void sethour(int hour);
void setmin(int min);
vector<Commuter> commuter;
};

void Commuter::setname(string name) {
this->name = name;
}
void Commuter::setpoint(char point) {
this->point = point;
}
void Commuter::sethour(int hour) {
this->hour = hour;
}
void Commuter::setmin(int min) {
this->minute = min;
}
int main() {
ifstream commuterfile;
string filename;
string str;
cout << "Enter the file path: " << endl;
cin >> filename;
commuterfile.open(filename.c_str());
if (!commuterfile) {
    cerr << "ERROR" << endl;
    exit(1);
}
while (getline(commuterfile, str, ';')) {
    cout << str << endl;
}
commuterfile.close();
return 0;
}
</code>```

答:
You have the line of data in your str variable, so you should be able to take a few more steps and add that to your class.

First, you should figure out how to split the string into components.

The next step is to convert each component from a string to the data type you need. atoi will be a good function for converting string to int.

You need an instance of your class as well. Eg Commuter commuter; Then you can call the functions on the instance like commuter.setXXX(variable);

Body:
I am a C++ beginner. My basic code shown below is able to read csv file and print out data line by line. However, I cannot figure out how to assign all these data to my defined commuter class variables. I have tried alot of online tutorial but it will always show errors that I am not sure how to debug.Could anyone give me a hand or some hints? thank you.

sample data:

commuter1;A;7;20
commuter2;B;8;30
commuter3;F;10;10
.....

#include<iostream>
#include<string>
#include<vector>
#include<fstream>//strtok
using namespace std;
class Commuter {
private:
    string name;
    char point;
    int hour;
    int minute;
public:
    Commuter(string name, char point, int hour, int min) {
        this->name = name;
        this->point = point;
        this->hour = hour;
        this->minute = min;
}
void setname(string name);
void setpoint(char point);
void sethour(int hour);
void setmin(int min);
vector<Commuter> commuter;
};

void Commuter::setname(string name) {
this->name = name;
}
void Commuter::setpoint(char point) {
this->point = point;
}
void Commuter::sethour(int hour) {
this->hour = hour;
}
void Commuter::setmin(int min) {
this->minute = min;
}
int main() {
ifstream commuterfile;
string filename;
string str;
cout << "Enter the file path: " << endl;
cin >> filename;
commuterfile.open(filename.c_str());
if (!commuterfile) {
    cerr << "ERROR" << endl;
    exit(1);
}
while (getline(commuterfile, str, ';')) {
    cout << str << endl;
}
commuterfile.close();
return 0;
}


问:
Unable to get the designer view window back using windows forms with Visual Studio 2010
I am in process of writing a C# Windows Forms application using Visual Studio Express 2010 ENU SP1.  Further VS specifics are at the bottom of this post.  I recently made some changes using the designer view to the layout and then decided that I did not want the changes so I closed the designer window.  The code window was still up when I closed the project and the changes were saved any way.  I don't care about the changes because the layout can be restored easily except for the fact that I cannot find any way to reopen the visual designer window.  To get the window back I have tried the following:

Shift F7

Right click in the designer code window

Double click the designer file under the solution explorer

Select the designer file under the solution explorer and use the context menu to bring up the file

I have an evaluation copy of the VS 2010 Team and it displays exactly the same behavior when utilizing my project

I have tried a backup copy of the project but it displays the same problem in both the Express and Team versions

I have been all over the MSDN, VS forum, and the internet at large and not found any solutions

When I first started the project I did rename the Form1.cs file from within the solution explorer because I wanted to have a different name than Form1 for the application.  When doing this it asked the following:

"You are renaming a file.  Would you like to perform a rename in this project of all references to the code element 'projectname'?

I replied yes.  So now I don't have a Form1.cs file but a file with my "projectname.cs" and the designer file named "projectname.Design.cs.  This is the only change that I made that I can think of that might be relevant.  I did try renaming it back to Form1.cs but that also did not resolve the problem.

I have to say that I am new to using Visual Studio.  So far I like it quite a bit but I am dead in the water right now and unless I can get this resolved I will lose two weeks worth of work.  Any assistance would be greatly appreciated.

Thanks,
-Tom

Additional Details:

Windows 7 Professional SP1 32 bit x86

Microsoft Visual Studio 2010
Version 10.0.40219.1 SP1Rel
Microsoft .NET Framework
Version 4.0.30319 SP1Rel

Installed Version: C# Express

Microsoft Visual C# 2010   01014-169-2560017-70726
Microsoft Visual C# 2010

Microsoft Visual C# 2010 Express - ENU Service Pack 1 (KB983509)   KB983509
This service pack is for Microsoft Visual C# 2010 Express - ENU.
If you later install a more recent service pack, this service pack will be uninstalled automatically.

答:
Although this is quite an old thread, I want to share my case and the solution.

I had the same problem but I used Telerik WinForms component for my Form. I couldn't see the designer until I realize that the design-time capabilities of RadControls for WinForms are implemented in the Telerik.WinControls.UI.Design.dll assembly. Then I add the reference and now the designer shows up.


问:
Only display an inline "add object" field if no objects exist
In my Django application, I have a model, X. It has a related/helper model Y, which contains some extra info about it. Instances of Y are bound to their Xs with a ForeignKey (that is, Y contains a models.ForeignKey(X)).

I also have this code in my admin.py:

```<code>class YInline(admin.TabularInline):
    model = Y
    extra = 1
</code>```

This works fine, but the inline field for adding a new Y is always displayed: when adding a new X, and when editing an existing X which already has some Ys bound to it. I would like to show the field only if X has no Ys bound to it yet (either because it's being created or because no Ys were assigned to it previously). If we're editing an X which already contains some Ys, the inline should not be displayed; the user will use the "Add another Y" button if they wish to add one.

How can I achieve this? I'm using the latest stable version of Django, 1.10 at the time of writing.

答:
You can override the get_extra method of the YInline class, like this:

```<code>class YInline(admin.TabularInline):
    model = Y
    # extra is remove here, is overidden below

    def get_extra(self, request, obj=None, **kwargs):
        # obj is the parent model, for your case X.
        # If X has no Y attribute (thus X is created), return 1 extra inline
        # If X exists, but has null Y's, return 1 extra inline
        if not hasattr(obj, '<related_name_here>') or not obj.<related_name_here>.exists():
            return 1
        # If X exists and has some pre-saved Y's, return 0 extra inlines
        return 0
</code>```

Body:
In my Django application, I have a model, X. It has a related/helper model Y, which contains some extra info about it. Instances of Y are bound to their Xs with a ForeignKey (that is, Y contains a models.ForeignKey(X)).

I also have this code in my admin.py:

class YInline(admin.TabularInline):
    model = Y
    extra = 1

This works fine, but the inline field for adding a new Y is always displayed: when adding a new X, and when editing an existing X which already has some Ys bound to it. I would like to show the field only if X has no Ys bound to it yet (either because it's being created or because no Ys were assigned to it previously). If we're editing an X which already contains some Ys, the inline should not be displayed; the user will use the "Add another Y" button if they wish to add one.

How can I achieve this? I'm using the latest stable version of Django, 1.10 at the time of writing.

Body:
You can override the get_extra method of the YInline class, like this:

class YInline(admin.TabularInline):
    model = Y
    # extra is remove here, is overidden below

    def get_extra(self, request, obj=None, **kwargs):
        # obj is the parent model, for your case X.
        # If X has no Y attribute (thus X is created), return 1 extra inline
        # If X exists, but has null Y's, return 1 extra inline
        if not hasattr(obj, '<related_name_here>') or not obj.<related_name_here>.exists():
            return 1
        # If X exists and has some pre-saved Y's, return 0 extra inlines
        return 0


问:
pass id from angularjs function to codeIgnite controller function
How to pass id from AngularJS function to codeIgniter controller function ??</p>

```<code>$scope.edit = function(id)
    {
        $http({
            method : 'GET',
            url: '',//how to go codeigniter controller function myfuc and send id.
             headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(function(data){
                console.log(data);
        $scope.form = data;
        });
    };

public function myfuc(id)
{
   //here id
}
</code>```

答:
This should work:

```<code>  url: 'example.com/myfuc/id'
</code>```

read more

Body:
How to pass id from AngularJS function to codeIgniter controller function ??

$scope.edit = function(id)
    {
        $http({
            method : 'GET',
            url: '',//how to go codeigniter controller function myfuc and send id.
             headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(function(data){
                console.log(data);
        $scope.form = data;
        });
    };

public function myfuc(id)
{
   //here id
}

Body:
This should work:

  url: 'example.com/myfuc/id'

read more


问:
How to skip case while using String replaceAll
Example my string have :

```<code>text = " Hi {fullname}, wellcome u join my group"
</code>```

this is my code:

```<code>text = text.replaceAll("\\{fullname\\}", user.getMobile() != null ? user.getMobile() : "");
</code>```

but now i have problem if {fullname} is {FULLNAME} or {Fullname} or {fuLLname}, i cant find exactly what i want and replace it.
Anyone have a solution please help me! Thanks

答:
You can use (?i) as a prefix of your token "fullname" which will make it case insensitive so it will work for any Upper and Lower case combination of your token "fullname"
"{FULLname} , {fullNAME} , {FulLName} ,{fuLLname}"

```<code>text = text.replaceAll("\\{(?i)fullname\\}", user.getMobile() != null ? user.getMobile() : "");
</code>```

Body:
Example my string have :

text = " Hi {fullname}, wellcome u join my group"

this is my code:

text = text.replaceAll("\\{fullname\\}", user.getMobile() != null ? user.getMobile() : "");

but now i have problem if {fullname} is {FULLNAME} or {Fullname} or {fuLLname}, i cant find exactly what i want and replace it.
Anyone have a solution please help me! Thanks

Body:
You can use (?i) as a prefix of your token "fullname" which will make it case insensitive so it will work for any Upper and Lower case combination of your token "fullname"
"{FULLname} , {fullNAME} , {FulLName} ,{fuLLname}"

text = text.replaceAll("\\{(?i)fullname\\}", user.getMobile() != null ? user.getMobile() : "");


问:
How to get CMake to add files to MSVC's Solution tree?
Is there a way to get CMake to add files to MSVC's Solution Explorer tree as for example a "Solution item"? I have placed a bunch of CMake macros in a file called "helper_functions.cmake" and would like this file to appear in MSVC's Solution Explorer. This is so that team members can see that the file exists, (as per the CMakeLists.txt files that appear under their projects in the Solution Explorer tree). </p>

答: source_group("Helper Macros" FILES helper_functions.cmake) see more info at http://www.cmake.org/cmake/help/cmake-2-8-docs.html#command:source_group</p>


问:
Creating a text by adding variable data
I have IOS experience on programming, now I am trying to re-do all my apps on Java. (Android Studio). For a little while I was re-searching a way to do that:

```<code>FlightTimeHours.text = NSString(format:"%@:0%.f",Hh , FM) as String
</code>```

So I have 2 Questions:

1) How to format the text as above?

2) I do not want to send the result to a TextView but to a String. (String FlightTimeHours;)

Below it is where I am:

```<code>String AFCR = (String) (FlightTimeHours);
AFCR.setText("0%%:0%.1f", Hh, FM);
</code>```

or

```<code>String AFCR.setText(String.format(Locale.getDefault(),"0%%:0%.1f", Hh, FM));
</code>```

I am lost please help!

Thank you

答:
%@ corresponds to %s and you need to set a precision for float format, e.g. %.6f.

Try this:

// note the Java naming convention:
// variable names should start in lower case.
String flightTimeHours = String.format("%s0:%.6f", Hh, FM);

// a pedantic version, with constant locale and parameter ordering
String flightTimeHours = String.format(Locale.US, "%1$s0:%2$.6f", Hh, FM);
```

Title: Creating a text by adding variable data

Body:
I have IOS experience on programming, now I am trying to re-do all my apps on Java. (Android Studio). For a little while I was re-searching a way to do that:

FlightTimeHours.text = NSString(format:"%@:0%.f",Hh , FM) as String

So I have 2 Questions:

1) How to format the text as above?

2) I do not want to send the result to a TextView but to a String. (String FlightTimeHours;)

Below it is where I am:

String AFCR = (String) (FlightTimeHours);
AFCR.setText("0%%:0%.1f", Hh, FM);

or

String AFCR.setText(String.format(Locale.getDefault(),"0%%:0%.1f", Hh, FM));

I am lost please help!

Thank you


问:
Rails i18n - How to translate enum of a model
I've got the following model:

```<code>class Person < ActiveRecord::Base
  enum gender: [:female, :male]
  ...
end
</code>```

Then I added the selection of the gender to its form, like this:

```<code><%= form_for ([@person]) do |f| %>
  ...
  <div class="form-group">
    <%= f.collection_radio_buttons :gender, Person.genders, :first, :first %>
  </div>
  ...
<% end %>
</code>```

But instead of displaying the constant as a string I want to translate it to Portuguese.

I already tried to add it to the pt.yml file under people but didn't work.

```<code>pt:
 activerecord:
   attributes:
     female: Feminino
     male: Mascúlino
</code>```

I know this question is very similar to How to use i18n with Rails 4 enums but that question is already marked as answered and I'm searching for a better and simpler solution...

Thank you for taking your time to help me :)

答:
After reading How to use i18n with Rails 4 enums answers more carefully I came to this solution:

According rails guides - "In the event you need to access nested attributes within a given model, you should nest these under model/attribute at the model level of your translation file" -

the yml file should look like this:

```<code>pt:
 activerecord:
   attributes:
     person/gender:
       female: Feminino
       male: Mascúlino
</code>```

We need to create a method to return a translated enum since there isn't any method capable of translating an entire enum at once. Rails just has the method to translate a value given a key, i.e People.human_attribute_name("gender.female").

Ok, we'll create a new method but where should we put it?

I think Helpers are the best place to put it because I'm changing the enum values in order to easily attach them to the form collection, although most of the answers suggested to put it in the Models.

Now my person_helper.rb looks like this:

```<code>def human_attribute_genders
  Hash[Person.genders.map { |k,v| [k, Person.human_attribute_name("gender.#{k}")] }]
end
</code>```

And my view:

```<code><%= f.collection_radio_buttons :gender, human_attribute_genders, :first, :second %>
</code>```

Pretty simple and it works just fine!

If anyone has any suggestion to improve my solution I would be happy to hear it from you :)

For example, I could extract the method to application_helper.rb like this:

```<code>def human_attribute_enum(model_name, enum_attr, attr_name)
  Hash[enum_attr.map { |k,v| [k, I18n.t("activerecord.attributes.#{model_name}/#{attr_name}.#{k}")] }]
end
</code>```

But it'd require passing a lot of parameters in the view...

Body:
I've got the following model:

class Person < ActiveRecord::Base
  enum gender: [:female, :male]
  ...
end

Then I added the selection of the gender to its form, like this:

<%= form_for ([@person]) do |f| %>
  ...

    <%= f.collection_radio_buttons :gender, Person.genders, :first, :first %>

  ...
<% end %>

But instead of displaying the constant as a string I want to translate it to Portuguese.

I already tried to add it to the pt.yml file under people but didn't work.

pt:
 activerecord:
   attributes:
     female: Feminino
     male: Mascúlino

I know this question is very similar to How to use i18n with Rails 4 enums but that question is already marked as answered and I'm searching for a better and simpler solution...

Thank you for taking your time to help me :)

Body:
After reading How to use i18n with Rails 4 enums answers more carefully I came to this solution:

According rails guides - "In the event you need to access nested attributes within a given model, you should nest these under model/attribute at the model level of your translation file" -

the yml file should look like this:

pt:
 activerecord:
   attributes:
     person/gender:
       female: Feminino
       male: Mascúlino

We need to create a method to return a translated enum since there isn't any method capable of translating an entire enum at once. Rails just has the method to translate a value given a key, i.e People.human_attribute_name("gender.female").

Ok, we'll create a new method but where should we put it?

I think Helpers are the best place to put it because I'm changing the enum values in order to easily attach them to the form collection, although most of the answers suggested to put it in the Models.

Now my person_helper.rb looks like this:

def human_attribute_genders
  Hash[Person.genders.map { |k,v| [k, Person.human_attribute_name("gender.#{k}")] }]
end

And my view:

<%= f.collection_radio_buttons :gender, human_attribute_genders, :first, :second %>

Pretty simple and it works just fine!

If anyone has any suggestion to improve my solution I would be happy to hear it from you :)

For example, I could extract the method to application_helper.rb like this:

def human_attribute_enum(model_name, enum_attr, attr_name)
  Hash[enum_attr.map { |k,v| [k, I18n.t("activerecord.attributes.#{model_name}/#{attr_name}.#{k}")] }]
end

But it'd require passing a lot of parameters in the view...


问:
How to find the method that is attached to a click event of a button
How can I find out from firebug which method or methods are attached to the click event handler of a button?

This is the code of the button

```<code><button class="rsmg_button_save ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary ui-state-focus" type="button" role="button" aria-disabled="false" style="display: inline-block;"><span class="ui-button-icon-primary ui-icon ui-icon-disk"></span><span class="ui-button-text">Save</span></button>
</code>```

答:
I searched hard with $("desiredSelector").data("events") from above and also with GetEventListeners but in Firebug 2.x there is a very easy new way to find the bound events: If there is a bind-function you will find an "ev" right next to the row:

Cool Thing!

Body:
How can I find out from firebug which method or methods are attached to the click event handler of a button?

This is the code of the button

<button class="rsmg_button_save ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary ui-state-focus" type="button" role="button" aria-disabled="false" style="display: inline-block;">Save</button>


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答: Aside from if statement(which I learned first from Pascal[first language learned]).  The one-to-one correspondence between pointers and arrays in C was what truly hooked me to programming.  It brings my understanding of computer's ability to great heights, including but not limited to, efficient memory traversal, stacks, passing a specific portion(slicing) of an array to a function, treat the pointer to memory-mapped IO(e.g. VGA address) as an array.  In Pascal, the pointer is so opaque that the programmer's understanding of computer memory and its ability is severely hampered.

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

LastEditorDisplayName: Michael Buen


问:
PHP: game loop (threads or the sort)
I am writing PHP code to be a game client. It uses socket; socket_create followed by socket_connect and then socket_read. It works fine, but the issue is that the server can send a packet at any time which means socket_read needs to be happening constantly in a "game loop". So something like this:

```<code><?php
$reply = "";
do {
     $recv = "";
     $recv = socket_read($socket, '1400');
     if($recv != "") {
         $reply .= $recv;
     }
} while($recv != "");

echo($reply);
?>
</code>```

Doesn't work because it's stuck in the loop (server doesn't terminate connection until game is quit by client) and the PHP code needs to handle the packet stuff as it comes in.

So PHP doesn't really have threading. What's the best way of handling this?

答:
If you really want to do this, you have to sleep for some time, check the socket, sleep again, check the socket...

To check the socket without blocking you need to use non-blocking I/O which you can achieve with the socket_set_nonblock() or socket_recv() which has a DONTWAIT flag.

Title: PHP: game loop (threads or the sort)

Body:
I am writing PHP code to be a game client. It uses socket; socket_create followed by socket_connect and then socket_read. It works fine, but the issue is that the server can send a packet at any time which means socket_read needs to be happening constantly in a "game loop". So something like this:

<?php
$reply = "";
do {
     $recv = "";
     $recv = socket_read($socket, '1400');
     if($recv != "") {
         $reply .= $recv;
     }
} while($recv != "");

echo($reply);
?>

Doesn't work because it's stuck in the loop (server doesn't terminate connection until game is quit by client) and the PHP code needs to handle the packet stuff as it comes in.

So PHP doesn't really have threading. What's the best way of handling this?


问:
Class not being autoloaded
I've made a little library for myself and I'm trying to autoload it into my laravel project, it installs fine but whenever I try to use the class it simply says it's not found.

I've checked all the classmap files in vendor/composer and it doesn't seem to be in any of them.

This is my composer.json for my lib:

```<code>{
    "name": "my-user/aspect-parser",
    "version": "1.0.0",
    "type": "package",
    "require": {
        "nesbot/carbon": "^1.22"
    },
    "autoload": {
      "psr-4": {
        "AspectParser\\": "src/"
      }
    }
}
</code>```

My file structure is:

AspectParser

src

Parser.php

答: It was an issue with the type in composer.json. I've changed it to library and it adds to the autoload classmap.

Title: Class not being autoloaded

Body:
I've made a little library for myself and I'm trying to autoload it into my laravel project, it installs fine but whenever I try to use the class it simply says it's not found.

I've checked all the classmap files in vendor/composer and it doesn't seem to be in any of them.

This is my composer.json for my lib:

{
    "name": "my-user/aspect-parser",
    "version": "1.0.0",
    "type": "package",
    "require": {
        "nesbot/carbon": "^1.22"
    },
    "autoload": {
      "psr-4": {
        "AspectParser\\": "src/"
      }
    }
}

My file structure is:

AspectParser

src

Parser.php


问:
Display multiple data into chart.js
I am creating a Chart.js (http://www.chartjs.org/docs/#radar-chart-introduction) from a JSON file.

But I am doing it so with a "checkbox", the idea is click on the element desire and it will display a different data inside de same canvas.

I think I almost have but I have a problem when I want to save the data. As you can see here, with console.log I can see the data through the loop, and its fine but when its trying to keep it into data object, its wrong.

```<code>chart.js:25 CSN08101
chart.js:26 rgba(255, 99, 132, 0.2)
chart.js:27 rgba(255,99,132,1)

chart.js:25 CSN08112
chart.js:26 rgba(54, 162, 235, 0.2)
chart.js:27 rgba(54, 162, 235, 1)

chart.js:47
  Object
    datasets:
      Array[1]
        0:Object
          backgroundColor: "rgba(54, 162, 235, 0.2)"
          borderColor: "rgba(54, 162, 235, 1)"
          data: Array[19]
          label: "CSN08112 module"
          __proto__: Object
          length: 1
          __proto__: Array[0]
          labels: Array[19]
          __proto__: Object

chart.js:47
  Object
    datasets: Array[1]
      0: Object
        backgroundColor: "rgba(54, 162, 235, 0.2)"
        borderColor: "rgba(54, 162, 235, 1)"
        data: Array[19]
        label: "CSN08112 module"
        __proto__: Object
        length: 1
        __proto__: Array[0]
        labels: Array[19]
        __proto__: Object
</code>```

This is my code:

```<code>$(function () {
  $('#go').click(function(){

    var checkbox_value = [];
    $(":checkbox").each(function () {
        var ischecked = $(this).is(":checked");
        if (ischecked) {
            checkbox_value.push($(this).val());
        }
    });

    var background = ["rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)",
                      "rgba(255, 206, 86, 0.2)", "rgba(75, 192, 192, 0.2)",
                      "rgba(153, 102, 255, 0.2)", "rgba(255, 159, 64, 0.2)"];

    var border = ["rgba(255,99,132,1)", "rgba(54, 162, 235, 1)",
                      "rgba(255, 206, 86, 1)", "rgba(75, 192, 192, 1)",
                      "rgba(153, 102, 255, 1)", "rgba(255, 159, 64, 1)"];

    var data = [];
    for (var m = 0; m < checkbox_value.length; m++) {
      var mid = checkbox_value[m];
      var backid = background[m];
      var bordid = border[m];
      console.log(mid);
      console.log(backid);
      console.log(bordid);
      $.ajax({
        url: "output.php",
        data: { MOD_CODE: mid },
        dataType: 'json',
        success: function(d){
          data[m] = {
            labels:[],
            datasets:[{
              label: mid + ' module',
              backgroundColor: backid,
              borderColor: bordid,
              data:[],
            }]
          };

          for (var i = 0; i < d.length; i++) {
            data[m].labels.push(d[i][0]);
            data[m].datasets[0].data.push(parseFloat(d[i][1]));
          }//.for
        console.log(data[m]);
        }//.success
      }); //.ajax
    } //.for

    // Create the chart with the data collected
    var ctx = document.getElementById("myChart");

    var myChart = new Chart(ctx, {
      type: 'radar',
      data: data,
      options:{
        responsive:false,
        scale:{ticks: {beginAtZero: true}}}});

  })//.click
});//.function
</code>```

答:
The only solution I found is with sync which apparently is not good, but if anyone find another solution feel free to post it</p>

```<code>$(function () {
  $('#go').click(function(){

    var checkbox_value = [];
    $(":checkbox").each(function () {
        var ischecked = $(this).is(":checked");
        if (ischecked) {
            checkbox_value.push($(this).val());
        }
    });

    var background = ["rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)",
                      "rgba(255, 206, 86, 0.2)", "rgba(75, 192, 192, 0.2)",
                      "rgba(153, 102, 255, 0.2)", "rgba(255, 159, 64, 0.2)"];

    var border = ["rgba(255,99,132,1)", "rgba(54, 162, 235, 1)",
                  "rgba(255, 206, 86, 1)", "rgba(75, 192, 192, 1)",
                  "rgba(153, 102, 255, 1)", "rgba(255, 159, 64, 1)"];

    var ddm = 0;
    data = {
      labels:[],
      datasets:[]
    };
    for (var m = 0; m < checkbox_value.length; m++) {
      var mid = checkbox_value[m];
      var backid = background[m];
      var bordid = border[m];

      var ajaxResponse = $.ajax({
        url: "output.php",
        data: { MOD_CODE: mid },
        dataType: 'json',
        async: false,
        success: function(d){

          data.labels = [];
          data.datasets[ddm] = {data:[]};
          for (var i = 0; i < d.length; i++) {
            data.labels.push(d[i][0]);
            data.datasets[ddm].data.push(parseFloat(d[i][1]));
            data.datasets[ddm].label = mid;
            data.datasets[ddm].backgroundColor = backid;
            data.datasets[ddm].borderColor = bordid;
          }//.for
          ddm++;

          if (ddm == checkbox_value.length) {
            console.log(data);
            // Create the chart with the data collected
            var ctx = document.getElementById("myChart");
            var myChart = new Chart(ctx, {
              type: 'radar',
              data: data,
              options:{
                responsive:false,
                scale:{ticks: {beginAtZero: true}}}
            });//.new Chart
          }//.if

        }//.success
      }); //.ajax
    }//.for

  })//.click
});//.function
</code>```

Title: Display multiple data into chart.js

Body:
I am creating a Chart.js (http://www.chartjs.org/docs/#radar-chart-introduction) from a JSON file.

But I am doing it so with a "checkbox", the idea is click on the element desire and it will display a different data inside de same canvas.

I think I almost have but I have a problem when I want to save the data. As you can see here, with console.log I can see the data through the loop, and its fine but when its trying to keep it into data object, its wrong.

chart.js:25 CSN08101
chart.js:26 rgba(255, 99, 132, 0.2)
chart.js:27 rgba(255,99,132,1)

chart.js:25 CSN08112
chart.js:26 rgba(54, 162, 235, 0.2)
chart.js:27 rgba(54, 162, 235, 1)

chart.js:47
  Object
    datasets:
      Array[1]
        0:Object
          backgroundColor: "rgba(54, 162, 235, 0.2)"
          borderColor: "rgba(54, 162, 235, 1)"
          data: Array[19]
          label: "CSN08112 module"
          __proto__: Object
          length: 1
          __proto__: Array[0]
          labels: Array[19]
          __proto__: Object

chart.js:47
  Object
    datasets: Array[1]
      0: Object
        backgroundColor: "rgba(54, 162, 235, 0.2)"
        borderColor: "rgba(54, 162, 235, 1)"
        data: Array[19]
        label: "CSN08112 module"
        __proto__: Object
        length: 1
        __proto__: Array[0]
        labels: Array[19]
        __proto__: Object

This is my code:

$(function () {
  $('#go').click(function(){

    var checkbox_value = [];
    $(":checkbox").each(function () {
        var ischecked = $(this).is(":checked");
        if (ischecked) {
            checkbox_value.push($(this).val());
        }
    });

    var background = ["rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)",
                      "rgba(255, 206, 86, 0.2)", "rgba(75, 192, 192, 0.2)",
                      "rgba(153, 102, 255, 0.2)", "rgba(255, 159, 64, 0.2)"];

    var border = ["rgba(255,99,132,1)", "rgba(54, 162, 235, 1)",
                      "rgba(255, 206, 86, 1)", "rgba(75, 192, 192, 1)",
                      "rgba(153, 102, 255, 1)", "rgba(255, 159, 64, 1)"];

    var data = [];
    for (var m = 0; m < checkbox_value.length; m++) {
      var mid = checkbox_value[m];
      var backid = background[m];
      var bordid = border[m];
      console.log(mid);
      console.log(backid);
      console.log(bordid);
      $.ajax({
        url: "output.php",
        data: { MOD_CODE: mid },
        dataType: 'json',
        success: function(d){
          data[m] = {
            labels:[],
            datasets:[{
              label: mid + ' module',
              backgroundColor: backid,
              borderColor: bordid,
              data:[],
            }]
          };

          for (var i = 0; i < d.length; i++) {
            data[m].labels.push(d[i][0]);
            data[m].datasets[0].data.push(parseFloat(d[i][1]));
          }//.for
        console.log(data[m]);
        }//.success
      }); //.ajax
    } //.for

    // Create the chart with the data collected
    var ctx = document.getElementById("myChart");

    var myChart = new Chart(ctx, {
      type: 'radar',
      data: data,
      options:{
        responsive:false,
        scale:{ticks: {beginAtZero: true}}}});

  })//.click
});//.function

Body:
The only solution I found is with sync which apparently is not good, but if anyone find another solution feel free to post it

$(function () {
  $('#go').click(function(){

    var checkbox_value = [];
    $(":checkbox").each(function () {
        var ischecked = $(this).is(":checked");
        if (ischecked) {
            checkbox_value.push($(this).val());
        }
    });

    var background = ["rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)",
                      "rgba(255, 206, 86, 0.2)", "rgba(75, 192, 192, 0.2)",
                      "rgba(153, 102, 255, 0.2)", "rgba(255, 159, 64, 0.2)"];

    var border = ["rgba(255,99,132,1)", "rgba(54, 162, 235, 1)",
                  "rgba(255, 206, 86, 1)", "rgba(75, 192, 192, 1)",
                  "rgba(153, 102, 255, 1)", "rgba(255, 159, 64, 1)"];

    var ddm = 0;
    data = {
      labels:[],
      datasets:[]
    };
    for (var m = 0; m < checkbox_value.length; m++) {
      var mid = checkbox_value[m];
      var backid = background[m];
      var bordid = border[m];

      var ajaxResponse = $.ajax({
        url: "output.php",
        data: { MOD_CODE: mid },
        dataType: 'json',
        async: false,
        success: function(d){

          data.labels = [];
          data.datasets[ddm] = {data:[]};
          for (var i = 0; i < d.length; i++) {
            data.labels.push(d[i][0]);
            data.datasets[ddm].data.push(parseFloat(d[i][1]));
            data.datasets[ddm].label = mid;
            data.datasets[ddm].backgroundColor = backid;
            data.datasets[ddm].borderColor = bordid;
          }//.for
          ddm++;

          if (ddm == checkbox_value.length) {
            console.log(data);
            // Create the chart with the data collected
            var ctx = document.getElementById("myChart");
            var myChart = new Chart(ctx, {
              type: 'radar',
              data: data,
              options:{
                responsive:false,
                scale:{ticks: {beginAtZero: true}}}
            });//.new Chart
          }//.if

        }//.success
      }); //.ajax
    }//.for

  })//.click
});//.function


问:
Running through complex json and match text
I want to run through reddit comments and match the json with a specific text:

I tried the following

```<code>$str = json_decode(file_get_contents('https://www.reddit.com/r/all/comments.json'));
foreach ($str as $comments) {
    //dd($comments->data->children);
    foreach ($comments->data->children as $comment) {
        if ($comment->body_html == 'You') {
            print_r($comment);
        } else {
            print_r($comment);
        }
    }
}
</code>```

However,  I  get the following error message:

```<code>  [ErrorException]
  Trying to get property of non-object

Exception trace:
 () at /home/ubuntu/workspace/app/Console/Commands/reddit.php:58
 Illuminate\Foundation\Bootstrap\HandleExceptions->handleError() at /home/ubuntu/workspace/app/Console/Commands/reddit.php:58
 App\Console\Commands\reddit->handle() at n/a:n/a
 call_user_func_array() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Container/Container.php:507
 Illuminate\Container\Container->call() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:169
 Illuminate\Console\Command->execute() at /home/ubuntu/workspace/vendor/symfony/console/Command/Command.php:256
 Symfony\Component\Console\Command\Command->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:155
 Illuminate\Console\Command->run() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:794
 Symfony\Component\Console\Application->doRunCommand() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:186
 Symfony\Component\Console\Application->doRun() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:117
 Symfony\Component\Console\Application->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:107
 Illuminate\Foundation\Console\Kernel->handle() at /home/ubuntu/workspace/artisan:36
</code>```

I expected to use $comments->data->children to access the body_html tag, but it does not work. Any suggestions why?

答:
Output of json_decode function in this case is an array, not an object. so you can't access it by $comments->data->children. Instead you can access it via: $comments["data"]["children"].

If you want json_decode to produce objects as output, use the second parameter true for it:

```<code>$str = json_decode(file_get_contents('https://www.reddit.com/r/all/comments.json'), true);
</code>```

Body:
I want to run through reddit comments and match the json with a specific text:

I tried the following

$str = json_decode(file_get_contents('https://www.reddit.com/r/all/comments.json'));
foreach ($str as $comments) {
    //dd($comments->data->children);
    foreach ($comments->data->children as $comment) {
        if ($comment->body_html == 'You') {
            print_r($comment);
        } else {
            print_r($comment);
        }
    }
}

However,  I  get the following error message:

  [ErrorException]
  Trying to get property of non-object

Exception trace:
 () at /home/ubuntu/workspace/app/Console/Commands/reddit.php:58
 Illuminate\Foundation\Bootstrap\HandleExceptions->handleError() at /home/ubuntu/workspace/app/Console/Commands/reddit.php:58
 App\Console\Commands\reddit->handle() at n/a:n/a
 call_user_func_array() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Container/Container.php:507
 Illuminate\Container\Container->call() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:169
 Illuminate\Console\Command->execute() at /home/ubuntu/workspace/vendor/symfony/console/Command/Command.php:256
 Symfony\Component\Console\Command\Command->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Console/Command.php:155
 Illuminate\Console\Command->run() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:794
 Symfony\Component\Console\Application->doRunCommand() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:186
 Symfony\Component\Console\Application->doRun() at /home/ubuntu/workspace/vendor/symfony/console/Application.php:117
 Symfony\Component\Console\Application->run() at /home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:107
 Illuminate\Foundation\Console\Kernel->handle() at /home/ubuntu/workspace/artisan:36

I expected to use $comments->data->children to access the body_html tag, but it does not work. Any suggestions why?

Body:
Output of json_decode function in this case is an array, not an object. so you can't access it by $comments->data->children. Instead you can access it via: $comments["data"]["children"].

If you want json_decode to produce objects as output, use the second parameter true for it:

$str = json_decode(file_get_contents('https://www.reddit.com/r/all/comments.json'), true);


问:
how to change the src of an when I know the  id?
I display an array of images in a *ngFor loop.

itemimg.component.html

```<code><div *ngFor="let itemimg of itemimgs" [class.selected]="itemimg === selectedItemimg"
            (click)="onSelect(itemimg)">
    <img id="{{itemimg.index}}" class="thumb" src="{{itemimg.imageUrl}}" width="{{itemimg.width}}" height="{{itemimg.height}}"
        style="float: left; margin-right: 3px; margin-bottom: 3px">
</div>
</code>```

When I click on any of the images I want to replace the first image.

itemimg.components.ts (part)

```<code>  onSelect(itemimg: Itemimg): void{
    this.selectedItemimg = itemimg;
    var newsrc = "../../assets/images/" + itemimg.route + ".jpg";
    //alert (newsrc);
    *what-goes-here* = newsrc;    // the problem
  }
</code>```

I have been googled this for over three hours but cannot find the answer. Thank you for looking.

答:
You want to replace the imageUrl of the first image, in the array itemimgs.

So all you need is

```<code>this.itemimgs[0].imageUrl = newsrc;
</code>```

Title: how to change the src of an< img> when I know the <img> id?

Body:
I display an array of images in a *ngFor loop.

itemimg.component.html

When I click on any of the images I want to replace the first image.

itemimg.components.ts (part)

  onSelect(itemimg: Itemimg): void{
    this.selectedItemimg = itemimg;
    var newsrc = "../../assets/images/" + itemimg.route + ".jpg";
    //alert (newsrc);
    *what-goes-here* = newsrc;    // the problem
  }

I have been googled this for over three hours but cannot find the answer. Thank you for looking.

Body:
You want to replace the imageUrl of the first image, in the array itemimgs.

So all you need is

this.itemimgs[0].imageUrl = newsrc;


问:
Extract individual existing words in domain names
I'm looking for a Ruby gem (preferably) that will cut domain names up into their words.

```<code>whatwomenwant.com => 3 words, "what", "women", "want".
</code>```

If it can ignore things like numbers and gibberish then great.

答:
I don't know gems for this, but if I had to solve this problem, I would download some english words dictionary and read about text searching algorythms.

When you have more than one variant to divide letters (like in sepp2k's expertsexchange), than you can have two hints:

Your dictionary is sorted by... for example, popularity of a word. So dividings with most popular words will be more valuable.

You can go to the main page of site with domain you are anazyling and just read the content, searching your words. I don't think that you'll find sex on a page for some experts. But... hm... experts can be so different ,.)

Body:
I'm looking for a Ruby gem (preferably) that will cut domain names up into their words.

whatwomenwant.com => 3 words, "what", "women", "want".

If it can ignore things like numbers and gibberish then great.


问:
How to Return ajax result in success?
Even though this question has already been answered and I have been through some of them, I still can't find what am I doing wrong.

Basically I have a function which return the success result of ajax:

```<code>var Functioncalling = function(id){
var Infotoreturn=null;
formdata = {
    'id': id
};

$.ajax({
    type: 'POST',
    url: 'http://localhost:20012/pr/servlet',
    data: formdata,
    contentType: "text/html",
    success: function(result){
       console.log("1="+result);
       Infotoreturn = result;
    }
});
console.log("2="+Infotoreturn);
return Infotoreturn;
}
</code>```

Calling the function:

```<code>var idreturned = Functioncalling(idvalue);
console.log("3="+idreturned);
</code>```

Now in my first console output I'm getting exactly the data as I'm suppose to. But the second and third output both is null.

答:
Adding to what @Utkanos has said, your return statement at the end is premature.

The variable Infotoreturn will be null, because the Ajax call is performed asynchronously, that is, in parallel. The main function will return before its operation has been completed. The console will log the result, but it will be too late for the variable.

Effectively, and Ajax call is delayed in the background, so the return statement still has the original value.

You can either work with more advanced features such as Promises & deferred objects, or you can write your next step as a callback.

Here is an example of using a callback:

```<code>var Functioncalling = function(id,callback) {
    var Infotoreturn=null;
    formdata = {
        'id': id
    };

    $.ajax({
        //  existing code
        success: function(result){
           console.log("1="+result);
            //  Modification
           callback(result);
        }
    });
    //  nothing to report yet
}
function where_I_need_the_result(result) {
    console.log('I got: '+result);
}

Functioncalling(id,where_I_need_the_result);
</code>```

Title: How to Return ajax result in success?

Body:
Even though this question has already been answered and I have been through some of them, I still can't find what am I doing wrong.

Basically I have a function which return the success result of ajax:

var Functioncalling = function(id){
var Infotoreturn=null;
formdata = {
    'id': id
};

$.ajax({
    type: 'POST',
    url: 'http://localhost:20012/pr/servlet',
    data: formdata,
    contentType: "text/html",
    success: function(result){
       console.log("1="+result);
       Infotoreturn = result;
    }
});
console.log("2="+Infotoreturn);
return Infotoreturn;
}

Calling the function:

var idreturned = Functioncalling(idvalue);
console.log("3="+idreturned);

Now in my first console output I'm getting exactly the data as I'm suppose to. But the second and third output both is null.

Body:
Adding to what @Utkanos has said, your return statement at the end is premature.

The variable Infotoreturn will be null, because the Ajax call is performed asynchronously, that is, in parallel. The main function will return before its operation has been completed. The console will log the result, but it will be too late for the variable.

Effectively, and Ajax call is delayed in the background, so the return statement still has the original value.

You can either work with more advanced features such as Promises & deferred objects, or you can write your next step as a callback.

Here is an example of using a callback:

var Functioncalling = function(id,callback) {
    var Infotoreturn=null;
    formdata = {
        'id': id
    };

    $.ajax({
        //  existing code
        success: function(result){
           console.log("1="+result);
            //  Modification
           callback(result);
        }
    });
    //  nothing to report yet
}
function where_I_need_the_result(result) {
    console.log('I got: '+result);
}

Functioncalling(id,where_I_need_the_result);