text:
Q: Oracle WebLogic Server is "Stopped" and yet I can't start it in Eclipse When I open the Servers view in Eclipse (Galileo), I have a localhost instance of WLS with a "[Stopped]" indicator on it.  When I attempt to start the supposedly stopped instance, I get these errors:
ERROR: transport error 202: bind failed: Address already in use
ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510)
JDWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [../../../src/share/back/debugInit.c:690]

The "Address already in use" part clued me in that WLS was already running.
How can I stop/view the output of the currently running instance?
I normally run WLS through the command line (Windows) separately but I'm starting to fiddle around with running WLS right inside of Eclipse.
I've been searching for a good guide on setting Eclipse up to interact with WLS but haven't found one yet.  If any of you can recommend one I would appreciate that as well.

A: the message you see means that java debugger cannot bind to the specified port, and not (yet) that weblogic cannot bind to its listen address.
This, can be due to an existing running weblogic instance (running with debugger enabled and on the same port) as you say, but may also mean that another Java program has been started with JDWP enabled on the same port.
So in the second case, please search if there is such a process (netstat -a will help) or just change debugger port you are trying to start weblogic with
If instead you really have a running weblogic instance, there are three cases:
1) it is a windows service (strange that you run weblogic as a service with JDWP activated), thus you can search and stop it through windows services ui
2) you started it through the command line, but in this case you would easily find the command line window you used to start it.
3) it is started by eclipse and you cannot see it for any reason, which is quite strange since it means that eclipse would have started two weblogic instances and one is failing. You can search in eclipse console view if you find a running instance (many consoles can be used at the same time). IF you don't find it just try to quit eclipse, WLS must die together with eclipse and you will see it in weblogic logs or through WLS process disappearing from task manager.
Are you using Oracle Enterprise Pack for Eclipse for running weblogic there? If yes I think this is a good introduction:
http://www.oracle.com/webfolder/technetwork/tutorials/obe/jdev/obe11jdev/11/oepe11g/introeclipseide.htm


text:
Q: space before li items in ol list I have a problem with the ol list : before each li item there is a space, I don't need it but I want to keep the number before items.
I tried to deal with it by setting margin and padding to 0 on ol and li elements but it didn't work.
The code looks like this:

item

item

item

Do you have any idea using only css and html languages?

A: By default ol and ul list have some margin and padding. It's may gonna fix your problem.
This is what by default ol and ul tag have, doc
ol {
  display: block;
  list-style-type: decimal;
  margin-top: 1em;
  margin-bottom: 1em;
  margin-left: 0;
  margin-right: 0;
  padding-left: 40px;
}

ol{
  margin-top: 0;
  margin-bottom: 0;
  padding-left: 10px; //by default 40px, it's up to you
}

item

item

item

A: Try to set padding on your ol
ol {
    padding-left: 0;
}

A: Unordered and ordered lists have a default left padding. You can remove that padding by writing a style rule. Like this:
ol {
  padding-left:0;
}

More info on styling lists here

A: Just add padding on the ol element, but keep the list style.
ol {
  padding: 0;
  list-style: inside decimal;
}

A: You can do something like.

It is a cheat code but it works.

ol {
  counter-reset: number;
}
li {
  list-style: none;
  counter-increment: number;
}
li::before {
  content:counter(number)".";
  position: relative;
  left:0px;
}

item

item

item

redpajama_set_name: RedPajamaStackExchange


text:
Q: I can't understand difference between quote/quoteitems and order/order Items Magento 2.3 I can't Understand the difference between Order And Quote or Order Items And Quote Items please explain what is it and how it works

A: I believe this is very basic question. Though I will explain it in detail.
Quote/Quote Items :
When you click on "Addtocart" button from that time your session starts. Magento quote saves all your session data until you place the order successfully. Quote keeps all data related cart like all types of totals including subtotal, grandtotal, shipping, etc and customer details like firstname,lastname, email id, etc. While quote items table keeps record of individual items added into cart. Quote items table has data like product id, sku, name, price, qty, etc.
Order/Order Items :
Whatever the data available in quote and quote items table those data transferred into order and order items table when you place the order successfully.
So the basic difference is that quote/quote items table keeps customer cart data till customer places the order. Once order is placed those data is transferred into order and order items table and customer's respective quote becomes inactive.
I hope to have explained properly. Let me know if you have any more queries.
Thanks,


text:
Q: Change the language from app? How can I change the language for phone from an android app? Can you give me some example?
Thanks in advance.

A: Phone-level language control is typically done using restricted interfaces: as far as I am aware there is no direct control from an app as part of the public Android interface.
Your best bet would be to use an Intent to open up the language picker. The Intent filter is:
<intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <action android:name="android.settings.LOCALE_SETTINGS" />
                 <category android:name="android.intent.category.DEFAULT" />
                 <category android:name="android.intent.category.VOICE_LAUNCH" />
             </intent-filter>

So something like this should work:
Intent i = new Intent();
i.setAction(android.provider.Settings.ACTION_LOCALE_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.startActivity();

And then the user can pick their language from there.


text:
Q: Is it possible to purchase hardware using my Apple ID credit? I know that I can purchase apps, music, movies etc. using the credit that's on my Apple ID. But is it also possible to purchase hardware from the online Apple Store, using that same credit on my Apple ID?

A: No. The credit shown in the Mac App Store or iTunes App Stores is not spendable from the retail stores or the online store.
There is a physical gift card that can be bought for online store or retail store use, but it's not the same bucket of funds as the iTunes store gift cards. See http://store.apple.com/us/browse/home/giftcards for more details...


text:
Q: Azure cosmos db stored procedure not work I'm looking to MSDN how to write a stored procedure in CosmoDB.
I find the following simple example :
var helloWorldStoredProc = {
    id: "helloWorld",
    serverScript: function () {
        var context = getContext();
        var response = context.getResponse();

        response.setBody("Hello, World");
    }
}

but if i try to execute it in cosmos db I get the following error message:
Failed to execute stored procedure helloWorldId for container Measure: {"code":400,"body":{"code":"BadRequest","message":"Message: {\"Errors\":[\"Encountered exception while compiling Javascript. Exception = SyntaxError: Syntax error\\r\\nSource information: line: 1, column: 36, source line:\\r\\n(function __docDbMain() { var fn = var helloWorldStoredProc = {\"]}\r\nActivityId: 21c41459-2e6b-407b-af9b-80c81ef54746, Request URI: /apps/a6f25760-7394-4bfb-bafc-7ea08f3f3f13/services/6574355c-d55b-43fa-b388-b270ebbd4403/partitions/409dd415-cb4d-49f0-9d16-11c07c880ee2/replicas/132070570012201722p/, RequestStats: \r\nRequestStartTime: 2019-07-08T12:28:32.6776283Z, RequestEndTime: 2019-07-08T12:28:32.7176085Z, Number of regions attempted: 1\r\nResponseTime: 2019-07-08T12:28:32.7176085Z, StoreResult: StorePhysicalAddress: rntbd://cdb-ms-prod-australiaeast1-fd3.documents.azure.com:14032/apps/a6f25760-7394-4bfb-bafc-7ea08f3f3f13/services/6574355c-d55b-43fa-b388-b270ebbd4403/partitions/409dd415-cb4d-49f0-9d16-11c07c880ee2/replicas/132070570012201722p/, LSN: 7, GlobalCommittedLsn: 7, PartitionKeyRangeId: 0, IsValid: True, StatusCode: 400, SubStatusCode: 65535, RequestCharge: 1.7, ItemLSN: -1, SessionToken: -1#7, UsingLocalLSN: False, TransportException: null, ResourceType: StoredProcedure, OperationType: ExecuteJavaScript\r\n, SDK: Microsoft.Azure.Documents.Common/2.4.0.0"},"headers":{"access-control-allow-credentials":"true","access-control-allow-origin":"https://cosmos.azure.com","content-type":"application/json","lsn":"7","strict-transport-security":"max-age=31536000","x-ms-activity-id":"21c41459-2e6b-407b-af9b-80c81ef54746","x-ms-cosmos-llsn":"7","x-ms-cosmos-quorum-acked-llsn":"7","x-ms-current-replica-set-size":"4","x-ms-current-write-quorum":"3","x-ms-gatewayversion":"version=2.4.0.0","x-ms-global-committed-lsn":"7","x-ms-last-state-change-utc":"Mon, 08 Jul 2019 10:56:52.631 GMT","x-ms-number-of-read-regions":"0","x-ms-quorum-acked-lsn":"7","x-ms-request-charge":"1.7","x-ms-schemaversion":"1.8","x-ms-serviceversion":"version=2.4.0.0","x-ms-session-token":"0:-1#7","x-ms-substatus":"65535","x-ms-transport-request-id":"1","x-ms-xp-role":"1","x-ms-throttle-retry-count":0,"x-ms-throttle-retry-wait-time-ms":0},"activityId":"21c41459-2e6b-407b-af9b-80c81ef54746","substatus":65535}

Can anyone help me?
Thanks in advance,
Simone

A: This format is not a valid Cosmos DB stored procedure format.
It should look like this:
function helloWorldStoredProc() {
    var context = getContext();
    var response = context.getResponse();

    response.setBody("Hello, World");
}

Here is the executed sample code:


text:
Q: (OctoKit.ObjC) `.a` libraries for OctoKit, AFNetworking, and ISO8601DateFormatter I am attempting to use, as well as update the extremely outdated (XCode 4!) documentation for, the Objective-C OctoKit library.
In the instructions for importing into a project, step 4 states:

On iOS, add the .a libraries for OctoKit, AFNetworking, and ISO8601DateFormatter.

I started with XCode 6, so much of the information in the Readme.md is Greek to me. I've worked through all of it, though, and updated the instructions appropriately, except for this line.
In the "Choose Frameworks and Libraries to add" dialog box in XCode, none of the OctoKit .framework or .a archives are present. Even looking through the repository in Finder with Hidden Files shown, and using the Finder search bar (which worked for a previous step that called for AWOL files out of their place) returns nil for any frameworks or archives in any of the project files.
Does anyone have an answer for this? I'm not sure if this step was obsoleted, or perhaps I'm not understanding how to search for / locate these types of files.
Any information is greatly appreciated,
Cheers!
EDIT: By adding all the OctoKit .xcodeproj files to the workspace in XCode directly, the .framework files are now selectable from the Frameworks and Libraries menus, however still nothing for the .a files.


text:
Q: How to focus the nth-child in *ngFor with a mutating array I have a list of items that are displayed it in my template with an *ngFor directive. An item in the array will be replaced, so it will be rerendered. I am trying to select a specific element in the *ngFor after this rerendering.
My first try
The code below works until an element is replaced from the array and the reference I used disappears.
my.component.html
<div *ngFor='let item of array'>
  <input #input type='text' [value]='item.name' \>
  <button (click)='select_function( input )'></button>
</div>

my.component.ts
@Component({
  // ...
})
export class MyComponent {
  public array: [] = [{name: 'Peter'}, {name: 'John'}]
  public select_function( element ) {
    element.focus();
  }
}

An incomplete solution
So I figured I should use the index somehow.
my.component.html
<div *ngFor='let item of array; let index = index;'>
  <input #input type='text' [value]='item.name' \>
  <button (click)='select_function(index)'>Modify</button>
</div>

my.component.ts
@Component({
  // ...
})
export class MyComponent {
  public array: [] = [{name: 'Peter'}, {name: 'John'}]
  public select_function( index) {
    // the array is mutated ( with ngrx in the actual situation )
    this.array.splice( index, 1, {name: 'Mary'} );
    // how do I get the nth element that was replaced from my template?
    // ???
    element.focus();
  }
}

How can I use the index to select a reference of the element in the view?

A: use ViewChildren and focus the last Element of the QueryList. Be carefull, It's possible you need "wait" Angular display the new data (for this use setTimeout)
//it's 'input' because your reference variable is #input
@ViewChildren('input',{read:ElementRef}) inputs:QueryList<ElementRef>

public select_function( index) {
    this.array.splice( index, 1, {name: 'Mary'} );
    setTimeout(()=>{
        //if you want the last element
        //inputs.last.nativeElement.focus()
        //if you want the nth
        inputs.find((x,i)=>i==index).nativeElement.focus()
    })
  }


text:
Q: Tidy up - put things in order According to English WordNet, tidy up has a meaning:

put (things or places) in order: "Tidy up your room!"

I feel comfortable with the use of "Tidy up your room!"
However, what is the exact meaning of putting things in order? Is it rather like in

*

*"Tidy up your shoes!" = put all the shoes to their proper place in the shelf, do not leave any under the furniture
or

*"Tidy up your guitar!" = take the guitar and move it to the place where it is usually kept
In other words, can you use tidy up as an instruction to put one single thing to its usual place? If not, what is the best word for such a situation then?

A: "Tidy up" suggests that there is a state of perceived organizational disorder among some set of objects relative to a broader context, but not necessarily in relation to the objects themselves.  In the classic example of tidying up one's room, the judgment is that objects in the room are in some perceived state of disarray relative to the perceiver's expectation for the state and purpose of the room.  Rarely, if ever, would one hear of a need to "tidy up" a junkyard.  This is because the perceived purpose of that place does not include an expectation that the objects be in order to serve the place's purpose or meet the typical person's expectations for it.
All that said, one cannot "tidy up" a single object in a given context since it has no other objects in its given context.  For example, if a room (the context) has one object in it, the room can't be "tidied up" because in order for it to be in organizational disarray, there has to be other objects in it to create a state of measurable organization.
But as one commenter has written, one can refer to a non-atomic object (such as a guitar with strings) as the context in the phrase that includes the verb "to tidy up" in some way.  The strings on the guitar need to be tidied up, for example, but it's in relation to the guitar and its perceived purpose, not to the other strings on it.  So while a guitar is not a room, it might still need "tidying up" in some way by someone's standards.
Hope this helps!

A: In the quoted definition of tidy up,
order is used in the following sense:

The state of being well arranged. [eg]  The house is in order; the machinery is out of order.

Another sense of order is closely related:

Conformity with law or decorum; freedom from disturbance; general tranquillity; public quiet. [eg] to preserve order in a community or an assembly

The sense of order suggested in the question – that of placing things into sequence according to some rule of precedence – is not relevant to order as used in the quoted definition of tidy up.


text:
Q: 'propertyName' cannot be used as a property on entity type 'typeName' because it is configured as a navigation I have an entity user with the following:
public class User
{
    [Key, Required]
    public int Id { get; set; }
    public int GenderId { get; set; }
    public virtual Gender Gender { get; set; }
}

In gender:
public class Gender
{
    [Key, Required]
    public int Id { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

Then, inside my DbContext, I have:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>(user =>
    {
        user
        .HasOne(x => x.Gender)
        .WithMany(x => x.Users)
        .HasForeignKey(x => x.GenderId);
    }

    user.HasIndex(x => x.Gender);
}

When I run dotnet ef add migration User, I am getting the error:

'Gender' cannot be used as a property on entity type 'User' because it
  is configured as a navigation.

A: I was trying to create an index on a navigation property. Instead, create the index on the foreign key.
Change user.HasIndex(x => x.Gender) to user.HasIndex(x => x.GenderId).

A: Use [ForeignKey("GenderId")] on your public virtual  Gender Gender { get; set; } property . Thus GenderId would be identified as a foreign key for Associated User.
See below updated code:
public class User
{
    public int GenderId { get; set; }
    [ForeignKey("Id")]//Gender Primary key
    public virtual Gender Gender { get; set; }
}

Hope it will fix your issue.
Thanks,

A: I had a similar error:

'Product' cannot be used as a property on entity type 'OrderLine'
  because it is configured as a navigation.

The cause of the error was that in the fluent api I also used the entity as a property:
modelBuilder.Entity<OrderLine>().Property(ol => ol.Product).IsRequired(true)

A: I had the same problem for a complex hierarchy model with nested complex classes in it.
Apparently, the IsRequired() method conflicts with OnDelete(...). I removed the IsRequired() and everything got back to normal.
public class MyComplexClassConfig : IEntityTypeConfiguration<MyComplexClass>
{
    public void Configure(EntityTypeBuilder<MyComplexClass> builder)
    {
        builder
            .HasOne(col => col.ChildClass)
            .WithOne(col => col.ParentClass)
            .OnDelete(DeleteBehavior.Cascade);

        // The following line of code needs to be deleted.
        builder.Property(col => col.Customer).IsRequired();
    }
}

A: An update due to a similar problem:
I had same problem when I was stablishing a relation between Product Entity and Warranti Entity as below:
public class Product
{
    public long Id { get; set; }
    public string Images { get; set; }
    public string Brand { get; set; }
    public Warranti Warranti { get; set; }
}

public class Warranti
{
    public Product Product { get; set; }
    public long ProductId { get; set; }
    public int WarrantyPeriod { get; set; }
}

and on my DatabaseContext Class I had this config:
  protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
        modelBuilder.Entity<Product>()
            .HasOne(p => p.Warranti)
            .WithOne(p => p.Product)
            .HasForeignKey<Warranti>(p => p.Product);
    }

And I got Same error. But, What was The problem?
According to Microsoft Official EFCore Doc The ForeignKey Should be something like this:
.HasForeignKey(p => p.BlogForeignKey); // single prop such as string or int,...

Or
 .HasForeignKey("BlogForeignKey"); // Hardcoded favorite string

But I was Using a class(Product) instead of a property In HasForeignKey method. likewise, you were using a class(Gender) instead of a property In HasIndex method. Changing these classes to an Id property solves the problem.
As a conclusion: Try to use an Id property on HasForeignKey() and HasIndex();


text:
Q: Wordpress deploy pages, post and menus to live server I design wordpress sites locally then when the time comes to deploy it to a hosted server  I transer all the database and I edit the config table for the new url, but I dont think this is a good practice.
What are you thoughts on the best way to do this?
My question is : How do I publish a wordpress site from my computer to a live server constantly?

A: I take it you are referring to the site url settings. You can override these from the config file instead of manually editing the db values. This is a supported and probably safest way to do it.
http://codex.wordpress.org/Editing_wp-config.php#WordPress_address_.28URL.29
Once you have the site up and running you can save the settings from the WP interface and remove the lines from the config file.
define('WP_SITEURL', 'http://example.com/wordpress');
define('WP_HOME', 'http://example.com/wordpress');


text:
Q: Div Tags are showing vertically instead of Horizontally? I have 3 div elements each with width of 4 i want to align them all of 4 in a row i am also using a toggle button to show these div because by default these div display are none but when i user click the toggle button div will show to him the problem is that div are showing but they are vertically showing in three rows i want to show them horizontally in a single row.

   @Html.CheckBox("Select Raw Targets", new { @class = "custom-control-input", id = "rawTargetSelection" })
   Select Raw Targets

                                        Select Real Tag Targets
                                        @Html.DropDownList("Raw Tag Targets", (IEnumerable<SelectListItem>)ViewBag.rawTagTargetValue, new { @class = "form-control add_item", @multiple = true, id = "Raw_Tag_Target_List" })

                                        Select Real Tag Min Targets
                                        @Html.DropDownList("Raw Tag Min Targets", (IEnumerable<SelectListItem>)ViewBag.rawTagTargetMin, new { @class = "form-control add_item", @multiple = true, id = "Raw_Tag_Min_Target_List" })

                                        Select Real Tag Max Targets
                                        @Html.DropDownList("Raw Tag Max Targets", (IEnumerable<SelectListItem>)ViewBag.rawTagTargetMax, new { @class = "form-control add_item", @multiple = true, id = "Raw_Tag_Max_Target_List" })

 $("#rawTargetSelection").change(function () {
             var x = document.getElementById("Real_Tag_Targets");
            if (x.style.display === "none") {
              x.style.display = "block";
            }
            else
            {
               x.style.display = "none";
            }
        });

A: You're starting a row after a col, without the complete code its hard to tell. Better example code recommended. Also try it without the server code, and just the html output since this is obviously a markup-problem.
You can tell from the example below, the markup col-md-4 works as expected (if screensize allows it).
Also: you're setting the row (which uses display:flex)  to display:block;

$("#rawTargetSelection").change(function() {
  var x = document.getElementById("Real_Tag_Targets");
  if (x.style.display === "none") {
    //x.style.display = "block";
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    Select Raw Targets

      Select Real Tag Targets -input-

      Select Real Tag Min Targets -input-

      Select Real Tag Min Targets -input-

      Select Real Tag Targets -input-

      Select Real Tag Min Targets -input-

      Select Real Tag Min Targets -input-

A: try:
x.style.display = "inline";

in your function

A: I think the problem might be with your @html checkbox style property, please check that. because without that it works.


text:
Q: How to create tiger textbox in silverlight I want to add the tiger textbox for message conversation in my project, I dont know how to apply styles or controls to get the tiger textbox in silverlight.

Is any way to get the above image in silverlight code / styles

A: Short of creating your own custom control in silverlight, there is no way you can have a textbox shaped like that.
However, there are 2 ways you can get what you want.
1) Either add a simple Border to your textbox. Change the opacity setting according to your needs.
For example:
`<Border BorderBrush="Black" BorderThickness="3" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="49,33,0,0">
            <TextBox Height="72" TextAlignment="Center"  Name="textBox1" Text="TextBox"  Width="270" Background="White" />
 </Border>`

2) Place the Image of the bubble, and place a textbox inside it. You would have to change a few opacity settings, but here is an example:
<Grid HorizontalAlignment="Left" Height="96" Width="316"  Margin="99,265,0,0" VerticalAlignment="Top">
            <Image    Name="image1" Stretch="Fill"   Source="bubble.png" />
            <TextBox   Name="textBox2" Text="TextBox"  SelectionBackground="#001BA1E2" SelectionForeground="Black" BorderBrush="Transparent" Background="Transparent" Margin="0,0,0,30" />
        </Grid>

You would have to made a few adjustments with the margins based on the image you use. But basically, this is how the above 2 textboxes would look:

If You wish to create your own Control for the Tiger Textbox, you could follow these steps:
1) Open the Project in Expression Blend
2) In the position where you wish to add the textbox, Draw an image which is in the Tiger Textbox format.
3) Right Click on this Image and Select "Make into Control..."
4) Choose the TextBox.


text:
Q: Android Volley Cache on LastModified The server returns a "Last Modified" header based on when the data changes. Need to use this to cache the response in volley.
My Volley request looks something like this:
StringRequest req = new StringRequest(Request.Method.GET, requestUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONArray result = new JSONArray(response);
                    callback.onSuccess(result);
                } catch (JSONException je) {
                    callback.onSuccess(new JSONArray());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("Error: " + error.getMessage());
            }
        });

Can find examples to cache based on a fixed time - say cache for 5 mins:
Android Setup Volley to use from Cache
But this doesnt solve my purpose. The server response has to be invalidated based on the "Last Modified" header. So I'm expecting volley to make the request and get a 304 Not Modified response and hence serve the content from the cache.
Even tried a custom header parser something like this:
https://github.com/mcxiaoke/android-volley/blob/master/src/main/java/com/android/volley/toolbox/HttpHeaderParser.java
But this doesnt seem to do the trick either.


text:
Q: Downloading file from server stops after 2 minutes Some of our users are having problems downloading .pdf files from our site. When the file takes more than ~2 minutes to download, it suddenly stops, causing the downloaded file to be unopenable. This is a huge problem for users on slow connections who are trying to download large documents.
We are using a slightly modified version of this asp code to handle the downloads. The browser will automatically download other file types like .zip, but this script is used to download .pdfs so they don't just open in the browser.
Does anyone have any ideas as to what could be causing this?

A: The default value of Server.ScriptTimeout is 90 (seconds). If you find that your downloads are interrupted after a minute or two, try increasing the value of this property.
<%
    ' Bump the default timeout from 90 seconds to 5 minutes...
    Server.ScriptTimeout = 300
%>


text:
Q: How to pass music Service from one Activity to another I'm starting my Music Service in my Main Activity where I display a list of songs. On clicking a song, it takes me to another activity where I do the basic controls. How do I continue with this same service in my second class?
Main Activity:
open class MainActivity : AppCompatActivity() {
private var musicSrv: MusicService? = null
private var playIntent: Intent? = null
private var musicBound = false

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

override fun onStart() {
    super.onStart()
    if (playIntent == null) {
        playIntent = Intent(this, MusicService::class.java)
        bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE)
        startService(playIntent)
    }
}

override fun onDestroy() {
    stopService(playIntent)
    musicSrv = null
    super.onDestroy()
}

fun songPicked(view: View) {
    musicSrv!!.setSong(view.tag.toString().toInt())
    musicSrv!!.playSong()
    val intent = Intent(this@MainActivity, SmartPlayerActivity::class.java)
    intent.putExtra("title", songList[view.tag.toString().toInt()].title)
    intent.putExtra("artist", songList[view.tag.toString().toInt()].artist)
    intent.putExtra("duration", songList[view.tag.toString().toInt()].seconds)
    startActivity(intent)
}

private val musicConnection: ServiceConnection = object : ServiceConnection {
    override fun onServiceConnected(name: ComponentName, service: IBinder) {
        val binder = service as MusicBinder
        musicSrv = binder.service
        musicSrv!!.setList(songList)
        musicBound = true
    }

    override fun onServiceDisconnected(name: ComponentName) {
        musicBound = false
    }
}
}


text:
Q: архивация логов есть каталог /var/log.
как с помощью с скрипта заархивировать логи старше, чем вчера, в папку /var/log/archive?
логи имеют формат yyyy_mm_dd_name.log

A: главные трудности, видимо, следующие:

*

*отобрать только те файлы в текущем каталоге, имена которых соответствуют шаблону yyyy_mm_dd_name.log, где name — произвольный набор символов, не содержащий символа _

*исключить из отобранных те файлы, в именах которых часть yyyy_mm_dd соответствует сегодняшней или вчерашней дате

*что-то сделать с найденными файлами (например, переместить куда-нибудь)

решение:

*

*отобрать в текущем каталоге такие файлы можно, например, так:
$ find -maxdepth 1 -regextype posix-basic -regex "\./[0-9]\{4\}_[0-9]\{2\}_[0-9]\{2\}_[^_]\+\.log"

проверим, создав тестовые файлы (один содержит сегодняшнюю дату, один — вчерашнюю, один — позавчерашнюю, и один, контрольный, не содержит даты в имени):
$ touch 2016_07_04_some.log 2016_07_03_some.log 2016_07_02_some.log some.file
$ find -maxdepth 1 -regextype posix-basic -regex "\./[0-9]\{4\}_[0-9]\{2\}_[0-9]\{2\}_[^_]\+\.log"
./2016_07_03_some.log
./2016_07_04_some.log
./2016_07_02_some.log

вроде, правильно.

*чтобы исключить файлы, в имени которых содержится сегодняшняя или вчерашняя дата, надо добавить к опциям программы find такую примерно конструкцию:
\! -regex "\./2016_07_04_[^_]\+\.log" \! -regex "\./2016_07_03_[^_]\+\.log"

тогда в вывод попадает только позавчерашний файл:
./2016_07_02_some.log

но завтра ведь даты будут другие. как привязаться к текущему дню?
с помощью программы date, например. сегодняшняя дата:
$ date +'%Y_%m_%d'
2016_07_04

и вчерашняя:
$ date -d 'day ago' +'%Y_%m_%d'
2016_07_03

заключаем вызовы date в «операторные скобки» $(...), подставляем в нужные места, и получаем длинную команду:
$ find -maxdepth 1 -regextype posix-basic -regex "\./[0-9]\{4\}_[0-9]\{2\}_[0-9]\{2\}_[^_]\+\.log" \! -regex "\./$(date +'%Y_%m_%d')_[^_]\+\.log" \! -regex "\./$(date -d 'day ago' +'%Y_%m_%d')_[^_]\+\.log"
./2016_07_02_some.log

*для того, чтобы переместить найденные программой find файлы в каталог, например, /var/log/archive, можно добавить к опциям той же программы такую, например, конструкцию:
-exec mv {} /var/log/archive \;

итого полный текст команды будет таким:
$ find -maxdepth 1 -regextype posix-basic \
 -regex "\./[0-9]\{4\}_[0-9]\{2\}_[0-9]\{2\}_[^_]\+\.log" \
 \! -regex "\./$(date +'%Y_%m_%d')_[^_]\+\.log" \
 \! -regex "\./$(date -d 'day ago' +'%Y_%m_%d')_[^_]\+\.log" \
 -exec mv {} /var/log/archive \;

он разбит на строки исключительно для удобства обзора. если вставлять этот текст в одну строку, то последний в каждой строке символ \ надо удалить.

A:
Не нужно писать собственное решение, когда уже есть различные готовые.

Автоматическая ротация и архивация логов
Решение называется logrotate.
Предположим, вы хотите ротировать и архивировать логи приложения name
Конфигурация в файле /etc/logrotate.d/name:
/var/log/*name.log {
    daily # ежедневно
    olddir /var/log/archive # перемещать в другую папку
    missingok # не создавать сообщение об ошибке, если лог пустой
}

Logrotate исключает необходимость приложению самостоятельно записывать дату в имя файла. Приложение может писать логи в один и тот же файл, который в момент ротации будет заменяться на новый. Если приложение самостоятельно не переоткрывает файл при записи каждой новой строки, то будет полезна опция copytruncate. С ней logrotate не пересоздает файлы логов, а вырезает содержимое и пишет его в новый файл.
/var/log/*name.log {
    ...
    copytruncate
}

   copytruncate
          Truncate  the  original log file in place after creating a copy,
          instead of moving the old log file and optionally creating a new
          one,  It  can be used when some program can not be told to close
          its logfile and thus might continue writing (appending)  to  the
          previous log file forever.

Если по соображениям места на диске или полезности вы хотите хранить логи за последние N периодов ротации, то добавьте опцию rotate N. Например, за последнюю неделю:
/var/log/*name.log {
    ...
    daily
    rotate 7
}

Централизованное хранение логов.
Хранить важные логи прямо на хосте - это плохо, и вот почему:

*

*Там может быть недостаточно места. У меня был случай, когда логи заняли всё место и парализовали хост (к счастью, тестовый).

*Если всё совсем сломается, то логи будут очень нужны, а вы на них не посмотрите.

*Читать логи в текстовом редакторе или анализировать grep'ом - неэффективно.

*У этого способа масштабируемость хуже линейной. То есть чтобы следить за логами на вдвое большем количестве хостов вам понадобится более чем вдвое больше ресурсов (человекочасов и т.п.).

Логи должны храниться централизованно и в базе данных. Тогда:

*

*Вы можете получать оперативную аналитику

*Вы можете легко сравнивать логи между разными хостами, приложениями, периодами времени

*В случае поломки все или почти все логи будут вам доступны

*Масштабируемость примерно логарифмическая.

Есть ряд решений, одно из них - стек ELK (Elasticsearch, Logstash, Kibana).
Возможно, в данный момент для ваших задач достаточно простой ротации. Но, пожалуйста, ориентируйтесь на централизованное хранение.


text:
Q: Random character at the beginning of serial.readline() in python and arduino I get random characters when I perform a serial.readline(), sometimes it is other  umbers and sometimes it is whole messages. The output should be "1,2" or "2,2"
Here are a couple of screenshots of the output of serial.readline().
I have tried to put a delay at before serial.readline() but it did not make a difference.
There is usually a strange character at the beginning:

I have also received strange messages:

There is a problem later on in the program that causes the program to hand because sometimes I just receive a blank line.
Is there a way to get consistent output from serial?
Here is the arduino code:
void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
   Serial.println("1,2");
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
    Serial.println("2,2");
  }

}

And here is the python code:
ser = serial.Serial('/dev/ttyUSB0', 9600)

line=ser.readline()
coord= line.strip()

print coord

EDIT:
I tried putting ser.flushInput() after the ser.open() and I get the same output.

A: Have you flushed the serial buffer
ser.flushInput()

A: I've been having the same issue when interfacing between pyserial and Arduino. This may be an old post, but in case someone else is having the same trouble, I remedied my problem by inserting:
ser.flushInput()

...right before my ser.readline() call.

A: How to Read serial data from an Arduino in Linux

Nothing fancy here. I'm getting the current port configuration, setting the input/output speed to 9600 baud, setting the data expectations to be 8 bits per word, with no parity bit and no stop bit, setting canonical mode, and then committing those changes back to the serial port.

If I am not mistaken you have to change the mentioned settings when connecting through serial port.
You do not mention it, but I guess you are using the pySerial library. Regardless you can use it with the correct settings to connect through serial. The constructor of the API allows all the parameters which are noted below:
Pyserial Library
I have not tested this approach as I have had a similar problem in C not Python.

A: What happens if you break it down to something simpler?
On the Arduino:
void setup()
{
  Serial.begin(9600);
}

int i = 0;
void loop()
{
  delay(1000);
  Serial.print("Hello World ");
  Serial.println(i);
  i++;
}

And in the Python REPL...
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
while(1):
    ser.readline()

The first behavior you should observe is that when you initiate the serial connection, the Arduino reboots. This takes a few seconds.
The second behavior you should observe is that (if you're typing this in the REPL slowly) when the while(1) loop begins, you get all of the serial data that had accumulated since you initiated the serial connection. It takes me a few seconds to type all that out, so when I hit Enter after ser.readline() I see:
'Hello World 1\r\n'
'Hello World 2\r\n'
'Hello World 3\r\n'

I only mention this to make sure you're familiar with two things that burned me a bit the last time I messed with serial communication to an Arduino: it needs time to reboot after connecting, and the serial data buffers. readline() will only give you one line in the buffer - not everything that's in the buffer.
Is it possible you're trying to sent/receive data before it's done rebooting? What about button bounce - could a dozen high/low state detections be messing something up?


text:
Q: CSS: Creating textured backgrounds I'm currently struggling with setting an image background for my site that will load fast enough.
I have used data url image and even optomized images but it's taking to long when loading the page since the backgournd-image is still very large.
Is it possible with CSS to create a textured background color like the one in the picture below?
I tried and couldn't match this:

A: with latest CSS3 technology, it is possible to create textured background. Check this out: http://lea.verou.me/css3patterns/#
but it still limited on so many aspect. And browser support is also not so ready.
your best bet is using small texture image and make repeat to that background. you could get some nice ready to use texture image here:
http://subtlepatterns.com

A: It's also possible to add texture using only CSS with repeating-linear-gradient()
Try the following example:

div {
    margin:10px;
    width:200px;
    height:200px;
    background-color: #67686b;
}

.pattern1{
    background-image: repeating-linear-gradient(36deg, rgba(255,255,255, 0.1), rgba(255,255,255, 0.1) 1px, transparent 0px, transparent 2px);
}

.pattern2 {
    background-image: repeating-linear-gradient(-45deg, rgba(255,255,255, 0.1), rgba(255,255,255, 0.1) 1px, transparent 1px, transparent 6px);
    background-size: 4px 4px;
}

Bonus: in this link you can find different types of patterns which you can customize to fit your needs.

A: You should try slicing the image if possible into a smaller piece which could be repeated. I have sliced that image to a 101x101px image.

CSS:
body{
  background-image: url(SO_texture_bg.jpg);
  background-repeat:repeat;
}

But in some cases, we wouldn't be able to slice the image to a smaller one. In that case, I would use the whole image. But you could also use the CSS3 methods like what Mustafa Kamal had mentioned.
Wish you good luck.

A: If you search for an image base-64 converter, you can embed some small image texture files as code into your @import url('') section of code.  It will look like a lot of code; but at least all your data is now stored locally - rather than having to call a separate resource to load the image.
Example link: http://www.base64-image.de/
When I take a file from my own inventory of a simple icon in PNG format, and convert it to base-64, it looks like this in my CSS:
url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAm0SURBVHjaRFdLrF1lFf72++xzzj33nMPt7QuhxNJCY4smGomKCQlWxMSJgQ4dyEATE3FCSDRxjnHiwMTUAdHowIGJOqBEg0RDCCESKIgCWtqCfd33eeyz39vvW/vcctvz2nv/61/rW9/61vqd7CIewMT5VlnChf059t40QBwB7io+vjx3kczb++D9Tof3x1xWNu39hP9nHhxH62t0u7zWb9rFtl73G1veXamrs98rf+5Pbjnnnv5p+IPNiQvXreF7AZ914bgOv/PBOIDH767HH/DgO4F9d7hLHPkYrIRw+d1x2/sufBRViboCgkCvBmmWcw2v5zWStABv4+iBOe49enXqb2x4a79+wYfidx2XRgP4vm8QBLTgBx4CLva4QRjyO+9FUUjndD1ATJjkgNaEoW/R6ZmyqgxFvU3nCTzaqLhzURSoGWJ82cN9d3r3+Z5TV6srni30fAdNXSP0a3ToiCHvVuh1mQsua+gl98Zqz0PNEIOAv4OidZToNU1OG8TAbUC7qGirdV6bV0SGa3gvISKrPUcoFj5xt/S4xDtktFVZMRrXItDiKAxRFiVh9HH2y+s05OHVizvod+mJ4yEnebSOROCzAfJ5ZgRxGHmXzwQ+U+aKFJ5oQ8fllGfp0XM+f0OsaaoaHnPq8U4YtFAqz0rL+riDR7+4guPrGaK4i8+dWMdotYdBf8CIPaatgzCKEHdi7hPRTg9uvIoLL76DC39+DcN+F4s8ZaAOCkYfEOmCQenPl3ftho4xmxcYfcmcCZGAMALjUYBvf2WM3//pDcwZoVKSzyNUowHGa2Pc0R9iOFjFcMSHhwxtQHNjDye+8Bht1Hj+wpsCy3i0N19gY3sPZ+5ty8uXVyFh8jyXm7EW+RkwZ47jmjNFJXKEGJ06g8ebDi5vptjYnWJvj68iR87vO2R3b0bHtmck4jYOjVYQuR8gHr2L73z3NN68eBm3NqbGo7gTMoAu6qatbV8wi70iiCL2/ZaQIfPZYf59eiBYcfdXMbj7NJ55+Cf4x1sfYkUiYSZ3jbie267LyKFPfXKI809/BjsfXMPpPMPjZ4/g2fNvg5mywEaDFa5JSNpGDihSMZU64Dlkr2uElCqVJFhJV4UEsMLXacTdIY4cSCwNYrdSKEOeZ1Q2Qv7n6iZ+99IlPHCwwot/3cDxU/dynWdk3v9ToJVs101lP1zWrgzJjGwpFULBzWs0t6WwINNd3HnwgPHGZbUIpZIIqFpqcqcbx2R4jJcv3sLdD6Z4+587JG6Fg+MAl6+1xAZajShLiR/Z4Wszwh9zw7gTWemYoFgZtvxgUsyJcOl5oOtcW0uwpHKMTrbmSYLVfoyk6OLUqZM4uNbF1asf4cBKTkHKuGll61MqYl0JXXrU68ao5RjRUNk5vpQtMkmuyQ1Yrb7H15qRJwj2hUvpkxPUfTpeSX+ZljTNMZmXOHLsJJ48t4KbWzso329w4ZUNOuuaGrpMiVBw95uPR0csWhrsdTv2aSXK+vYIPfK/86m/8VpDKe7cblAtOjClExpCQtfSJMVOcBL+I9/A0bMP4cFP32NaoHQrCD2vunddzwTbUqA8Rp2gLUEJDKOS5ktmceMScP1dNpQCi6Tk3gGBabBIMxmhdtS2eV21FRGFEa5f36Ht+4HRw7jnzEOMlmsXKbI8NxQkAf5w6FD3QyNU20Rqay5Mj5GwMS9ZDTf/S+MhTnyiD9w1RK/XwTvv7xqRxKG8rFoSEzUJmch2a3PXCtVY3+tzuwZ50d7LGYhs+8qnOlrJHRtGpM3F8IqkUDRMLzepceNGQjHZxFPfHGJ1MKMTx/DMDz1c/rCy3NdNc1u+hYQSu8gFc2R9Qn8qaVF5v71rhV+r+ZA46myN8iiPJcl+YAQTS8TByZ6Dm9cb7O7usgNu4+T2BJvbazQxREG9EHo5YVUqFWmWMx3FhPc3IG3O0tIqQMaLggZj64aQ5toEo1w7hDLJarBCrBv2SUb1gpSOTCYNtjYqE5QgcrC7UxtitfX/wHIqIs+ThTnuqP8vrvPu83wdxtbNErMkp050DLGcPNCw4jtUuR7FQ4YWWYlzjw5wZJSwZoXEzEpuPkvRFBk0FtQFiZext6eOkdV1GBFTFAStFoiA83RBljfoRZzR/vdvDhA7eOftGerSMfbnRMcjlWwCExOlhjVFZJIU+PqXYqyevAJc2cJ8K8KlzRDFSoXd6RCDO2GbiS83FyusdTJewxP7ha7LeJoVbU/gJr6zg/zyFYRHZnj9YorabTki5CRGxgFYvgoSMVBxYpYGWB0dZ+ncg9d/VeKRJ1/FGtuxmF4pHyp7Qd9McezoHTh8IG51QE6oFMtWB+KY82J3gX+9N8MJ9xZeeSNDh2gusgwpn8mLZXUIxsDGk8aYmU83We8sn/EYvf4Yp08cZvPpGbzyuVr2CxMvEyENpLCB0+Y93q8KDbcVIke8qXGpW+Kt9xc2U+oZIZCXRTsRzea+abgm2YybTKc587YH8LNOGoyHKrvISrGNHuaIUNPoXTF9FYlbL0tRk9WMLD60RpImFCmOYn95rcH2XoW1VXc5Z/LVOK0QZWllRhSWCDWdpsg/ShAOK+xMBtie5lailSlcKzgWad1+qnekWWojuSon10heB3jqCYpYlmD98AjPPbdLojsMsK0UNSH9k5KqB1tX23dCjeTGjRzhdoED4QTff2Idh8YhK8CxuVgGoDLT6KZzAk8navN1vocimZCYKdaHCe5f2+AGfTz7h5zzAW2NQrKfaRJqFZYtXkLEN83tIcdwTbJXthwMj64jM/hdPPZZ1rWXstY9SjbTxTyio5ZI/uocEPF3OCIAh0kEcifZQbO7wT4Q4Jd/3MbPfnuNLbnHlFXYP1KpAjTsiEu+8uiYmHh2FPvx+Q8NSqFScEaUUtoMQQLoWXmuKbu2SmjssKH7MqrkNstzXcnjWsXX0YN944/WFrJlnbO2IWY5lMIOEMkiMxk9cdchu6nGUi6xUr4ko4I9YxmpWozNS/0vjBeVafx+dNZofHdZ722FqOKKsp2GHBNspaCq/e0pdSByLRKeifhZW3cET0U6SIg03ZglqgEV7TGMMxQluzQnijLntdCMS2Z1DlyQS1nRmGhlWeu8KsRxWjscF3itcfz+ILv5tc9vYGui+a6FUP0ey8OymF812qD1WPOATkeSUxMgpklqaNMQS6soVSGu1Xpp3ZTNLsBSQ9oUSIPuO9aQsKj8H/2i+M14cIVV5UZZThrWikhQtOdEhxOqH1ZQI6PysyQdO93q/KdeHbC/hp2P+aG3PG1aiCVahDWIm49p77RHf/LHfeFlvPR/AQYAyMIq/fJRUogAAAAASUVORK5CYII=')

With your texture images, you'll want to employ a similar process.

A: Use an image editor to cut out a portion of the background, then apply CSS's background-repeat property to make the small image fill the area where it is used.
In some cases, background-repeat creates seams where the image repeats.  A solution is to use an image editor as follows: starting with the background image, copy the image, flip (mirror, not rotate) the copy left-to-right, and paste it to the right edge of the original, overlapping 1 pixel.  Crop to remove 1 pixel from the right edge of the combined image.  Now repeat for the vertical: copy the combined image, flip the copy top-to-bottom, paste it to the bottom of the combined, overlapping one pixel.  Crop to remove 1 pixel from the bottom.  The resulting image should be seam-free.


text:
Q: Beautiful section styles with polyglossia I would like to use polyglossia to be able to write in arabic and english on the following code beautiful section styles
It compiles without errors, but the output doesn't show any Arabic language.

\documentclass{article}
\usepackage[margin=1in]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{xcolor}
\usepackage[explicit]{titlesec}
\usepackage{soul}

\definecolor{titleblue}{HTML}{4a7aa4}

\title{Probability}
\author{Educ}
\date{\today}

\newbox\TitleUnderlineTestBox
\newcommand*\TitleUnderline[1]
  {%
    \bgroup
    \setbox\TitleUnderlineTestBox\hbox{\colorbox{titleblue}\strut}%
    \setul{\dimexpr\dp\TitleUnderlineTestBox-.3ex\relax}{.3ex}%
    \ul{#1}%
    \egroup
  }
\newcommand*\SectionNumberBox[1]
  {%
    \colorbox{titleblue}
      {%
        \makebox[2.5em][c]
          {%
            \color{white}%
            \strut
            \csname the#1\endcsname
          }%
      }%
    \TitleUnderline{\ \ \ }%
  }
\titleformat{\section}
  {\Large\bfseries\sffamily\color{titleblue}}
  {\SectionNumberBox{section}}
  {0pt}
  {\TitleUnderline{#1}}
\titleformat{\subsection}
  {\large\bfseries\sffamily\color{titleblue}}
  {\SectionNumberBox{subsection}}
  {0pt}
  {\TitleUnderline{#1}}

\usepackage{polyglossia}
\setmainlanguage[numerals=maghrib]{arabic}
\setotherlanguage{english}
\newfontfamily\arabicfont[Script=Arabic,Scale=1.2,AutoFakeSlant=-0.02]{Traditional Arabic}
\setsansfont[Script=Arabic,Scale=1.5]{Traditional Arabic}

\begin{document}

\maketitle

\newpage
\chapter{الاحتمالات}
\section{الاحتمالات الحزء الاول }
\subsection{الاحتمالات الحزء الاول}
\subsection{الاحتمالات الحزء الاول}
\section{الاحتمالات الحزء الاول الاحتمالات الحزء الاول}

\section
  {الاحتمالات الحزء الاول and text in English }

\end{document}

A: The incompatibility was with the soul package, which switches the font to a legacy 8-bit typewriter-style font.  It also does not support Unicode.  Here is an example that replaces it with ulem:
\documentclass{article}
% To fit within the allowed image size on TeX.SX:
\usepackage[margin=1in]{geometry}
\usepackage{xcolor}
\usepackage[explicit]{titlesec}
\usepackage{ulem}

\definecolor{titleblue}{HTML}{4a7aa4}

\title{\textenglish{Probability}}
\author{\textenglish{Educ}}
\date{\today}

\newbox\TitleUnderlineTestBox
\newcommand\TitleUnderline{\bgroup\markoverwith{%
  \textcolor{titleblue}{\rule[-1.3ex]{2pt}{1.0pt}}}\ULon}
\newcommand*\SectionNumberBox[1]
  {%
    \colorbox{titleblue}
      {%
        \makebox[2.5em][c]
          {%
            \color{white}%
            \strut
            \csname the#1\endcsname
          }%
      }%
    \TitleUnderline{\ \ \ }%
  }
\titleformat{\section}
  {\Large\bfseries\sffamily\color{titleblue}}
  {\SectionNumberBox{section}}
  {0pt}
  {\TitleUnderline{#1}}
\titleformat{\subsection}
  {\large\bfseries\sffamily\color{titleblue}}
  {\SectionNumberBox{subsection}}
  {0pt}
  {\TitleUnderline{#1}}

\usepackage{polyglossia}
\setmainlanguage[numerals=maghrib]{arabic}
\setotherlanguage{english}
\setmainfont{Latin Modern Roman}
\setsansfont{Latin Modern Sans}
\newfontfamily\arabicfont[Script=Arabic]{Noto Naskh Arabic}
\newfontfamily\arabicfontsf[Script=Arabic]{Noto Sans Arabic}

\begin{document}

\maketitle

\newpage
\chapter{الاحتمالات}
\section{الاحتمالات الحزء الاول }
\subsection{الاحتمالات الحزء الاول}
\subsection{الاحتمالات الحزء الاول}
\section{الاحتمالات الحزء الاول الاحتمالات الحزء الاول}

\section
الاحتمالات الحزء الاول \\
\textenglish{and text in English}

\end{document}


text:
Q: Replacing NA with a value - R Is there a way that I can replace missing values in a vector by randomly sampling from the rest of the data?
e.g
age<-c(4.2,5.6,NA,8.4,9.8,NA,10.4,15.3)

age[is.na(age)]<-sample(age,length(age[is.na(age)]),replace=TRUE)  ## trying to replace NA values with a random value from age.

I don't understand why this does not work?  Ideally I would like each NA value to be replaced by a different value.

A: age[is.na(age)] <- sample(age[!is.na(age)], sum(is.na(age)), replace=F)

sum(is.na(age)) suggested by @Ananda Mahto

A: In cases where random sampling is undesirable you might replace them with means, medians, or even a model fit:
library(e1071)
?impute
impute(as.matrix(age),what="mean") # replaces with mean 8.95

or
library(randomForest)
?na.roughfix
na.roughfix(age) # replaces with median 9.1

If age is a predictor and you have responses you could use random forest to impute
library(randomForest)
?rfImpute


text:
Q: Removing letter code gone wrong (C++) I was writing this code below that is suppose to take in information from the user ( a sentence ) and remove the desired letter. However, it only works if that sentence is one word. If the information contains a space, it will terminate at the space.Any advice as how I can get the program to read the entire sentence?
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {
string sentence;
char letterRemoved;

//Entering in Information
cout <<"Enter a sentence here!";
cin >> sentence;

cout <<"Enter letter to remove";
cin>>letterRemoved;

//Removing Occurence of letter
sentence.erase(remove(sentence.begin(), sentence.end(),letterRemoved), sentence.end());

//Print out
cout<<sentence << "\n";

return 0;
}

A: Reading input using cin >> sentence only reads until whitespace is encountered, and then stops. If you want to read an entire line (until the user presses enter), you want to use std::getline:
getline(cin, sentence);

Alternately, if you want to read up until a full stop character or a newline is found, you can use the delimeter argument to getline:
getline(cin, sentence, '.');


text:
Q: Looking for an alternative for WITH SQL statement, having interdependent temporary tables I am working on a huge DB with many tables. I have a kind of working version with the ";WITH" statement but it have side effects on the whole database (it sometimes stops or slows down the ETL job)so I am looking for an alternative.
I tried to rewrite the query but then I get the

multi-part identifier x could not be bound

because the tables build upon each other.
The kind of working version is:
USE[database]
;WITH[table1] AS
(
  SELECT [RegionList].[Cluster]
         ,[RegionList].[Region]
         ,[Customer]
         ,[Key1]
         ,[Key2]
         ,MAX(..[TimeK].) AS [Time]
  FROM [table3]
  JOIN [RegionList] ON [RegionList].[Region] = [DRegion].[Region]
  JOIN [DTime] ON [table3].[TimeK] = [DTime].[TimeK]
  JOIN [PKey]  ON [table3].[Key2] = [PKey].[Key2]

  GROUP BY [RegionList].[Cluster]
         ,[RegionList].[Region]
         ,[Customer]
         ,[Key1]
         ,[Key2]

)
,[table2] AS
(
 SELECT [table3].[Name]
        ,[DProduct].[Product]
        ,[PKey].[Key2]
        ,CASE
             WHEN [table1].[time] IS NULL THEN [DProduct].[Product]
             WHEN ...
             ELSE NULL
        END AS [NotActive]
 FROM [table1]
 JOIN [DProduct] ON [table1].[Key1] = [DProduct].[Key1]
 JOIN [PKey]  ON [table3].[Key2] = [PKey].[Key2]
 JOIN [Name] ON [table3].[Name] = [DName].[Name]

)
SELECT [table2].[NotActive]
       ,[table2].[Name]
       ,[tabel1].[Time]
       ,[table1].[Region]
FROM [table2]
JOIN [table1] ON [table1].[Key2] = [table2].[Key2]
WHERE [NotActive] IS NOT NULL

(needed to alter the names from the data, so if there is an error it is because of the transcript)
I wanted to rewrite it so I have:
USE[database]

SELECT [table2].[NotActive]
       ,[table2].[Name]
       ,[tabel1].[Time]
       ,[table1].[Region]
FROM (
      SELECT [RegionList].[Cluster]
         ,[RegionList].[Region]
         ,[Customer]
         ,[Key1]
         ,[Key2]
         ,MAX(..[TimeK].) AS [Time]
      FROM [table3]
      JOIN [RegionList] ON [RegionList].[Region] = [DRegion].[Region]
      JOIN [DTime] ON [table3].[TimeK] = [DTime].[TimeK]
      JOIN [PKey]  ON [table3].[Key2] = [PKey].[Key2]

      GROUP BY [RegionList].[Cluster]
         ,[RegionList].[Region]
         ,[Customer]
         ,[Key1]
         ,[Key2]
      ) AS [table1],
    (
      SELECT [table3].[Name]
        ,[DProduct].[Product]
        ,[PKey].[Key2]
        ,CASE
             WHEN [table1].[time] IS NULL THEN [DProduct].[Product]
             WHEN ...
             ELSE NULL
        END AS [NotActive]
      FROM [table1]
      JOIN [DProduct] ON [table1].[Key1] = [DProduct].[Key1]
      JOIN [PKey]  ON [table3].[Key2] = [PKey].[Key2]
      JOIN [Name] ON [table3].[Name] = [DName].[Name]
    ) AS [table2]

WHERE [NotActive] IS NOT NULL

But now in the second part of the statement there is the "multi-part identifier [table1] could not be bound" error. I know that at this part it doesn't "see" [table1] but what do I do? Is there an easy fix? Or am I on the wrong way?


text:
Q: Google map : can any one help me to set below location in my code?

View Larger Map

i want to set this location https://www.google.co.in/maps/place/Railway+Basketball+Court/@23.338003,75.046929,16z/data=!4m2!3m1!1s0x0:0xdc7e2bda17b6799e
in above code

A: Try using this:

for further info click on the settings icon on the maps on the down left corner and click on share or embed map

A: this will set both your maps to point to the basketball court

    View Larger Map

you can also go on the google map when its opened to the gear in the bottom right open the dropup menu go to share and embed map and click embed map and it will generate the iframe for you.


text:
Q: Can we define an object in a predicative and also in an impredicative way? I wonder if there are some objects that one could define in a predicative way and also in an impredicative way. I mean, two defenitions for the same object.
Thanks.
Edit: although I did get an answer for my question from Derek Elkins. I am editing for future googlers because I recieved some comments about the topic not being cleared.
Examples for objects:

*

*R = {S | S ∉ S} (Russell's paradox) - Impredicative, because R is a set (in the naive sense)
and S is ranging over all possible sets

*Let x be the smallest element in S" - Impredicative, because x is a member of S

*Let π be the ratio between the circumference and diameter of a circle" - predicative

I wanted to find a predicative defenition and an impredicative defenition for the same object.

A: As briefly covered on the nLab for Grothendieck toposes, it turns out you can't prove that a Grothendieck topos (by one definition) is cocomplete in a finitist, predicative foundation.  Given either W-types, including natural numbers, or impredicativity you can.  The core problem is the notion of transitive closure.  In a finitist, predicative mathematics, you can't define the transitive closure of an arbitrary relation.  In more traditional mathematics, there are two equivalent ways of defining the transitive closure of a relation.
The first is to say the transitive closure of a relation, $R$, is the smallest transitive relation that contains $R$.  The definition doesn't require any infinite sets to exist, but it does require that you can quantify over "all transitive relations containing $R$" which is impredicative in general.
The second is to say the transitive closure of a relation, $R \subseteq X\times X$, is the relation $R^*$ where $R^*(x,y)$ if and only if there exists a list of elements of $X$, $(x_i)_{i=0}^n$ such that $x = x_0$ and $x_n = y$ and $R(x_{i-1},x_i)$ for $i \in \{1,\dots, n\}$.  This definition is predicative but not finitist since it's based on lists.
The nLab page on pretoposes gives a brief but decent break-down of what kinds of math you get as you assume different structure. (Of course, you don't need to start at a pretopos.)  This provides one way of interpreting what "finitist" or "predicative" mathematics is.


text:
Q: Using Date VBA Function, but need to add four hours on to it before formatting it. I'm accessing a file that name changes based on of the date of UTC. I'm on USE. So using the Date VBA function, sometimes it won't grab the file because its the next day on UTC, and I'm on USE.
Dim dttDate As Date
dttDate = Date

Set LMData = Workbooks.Open("C:\...\PRIVATENAME" & Format(dttDate, "yyyy-mm-dd") & ".csv")

I've considered Now + 4 (because now deals in time as well), but the issue is I seen on VBA that single integers are read as months and I cannot determine how to read it as hours. In excel functions dates are # values so + 4 would add 4 hours to it.

A: Reference: Date and Time Functions in VBA

Time represents the decimal part of the double that Access stores for
  date and time. Since adding 1 to a stored date/time represents 1 day
  or 24 hours, each hour is stored as .041666, or 1/24 of a day. In
  Access all times are stored as a fraction of a day. Each hour is 1/24
  of a day, each minute 1/1440, each second 1/86400. So 3:00 is stored
  as .125 (or 1/8 of a day), and 16:00 is stored as 0.666, (or 2/3 of a
  day). Conversely, 0.2 represents 4:48 hours (1/5 of a day), and so on.

dttDate = int(Now + 4/24)


text:
Q: javascript - center div (position:absolute) vertically and horizontally to screen view I am trying to make a usercript that overlays text boxes over images: It uses a draggable menu using interactjs with fixed position. The menu has a button and I need it to create a div of 20px*60px and show it at the center of the screen view (so not to scroll to the bottom of the page and drag it from there). I can do it (somewhat) by using:
var div = document.getElementById("inserted_div_2");
div.style.position = 'fixed';
div.style.top = '50%'; //relative to screen
div.style.left = '50%';

From there I can drag/resize it to where I want over the image (also using interactjs) but then, how can I change it to position:absolute so it scrolls with the content keeping the same position over the images (eg: in the top left corner of img2)? something like:
var posX = div.getPosX(); //relative to page; in %, px or em
var posY = div.getPosY();
// when I change it from fixed to absolute the div goes back to the bottom of the page
div.style.position = 'absolute';
div.style.left = posX;
div.style.top = posY;

The HTML structure looks something like this:

    ...

        ...
         // size and number of imgs is variable.
         // are in a strip format.

        ...

    ...

         //eg: div1 was dragged from the center of screen
         //into in between img1 and img2

Text

         //now I need to do the same for div2,
         //dragging it to the top left corner of img2

Text

I would prefer not using jQuery or another library, but if it is too difficult then I will use it.
Thanks!

A: You can use offsetTop and offsetLeft to get the element's position (in px) relative to the page.
var posX = div.offsetLeft;
var posY = div.offsetTop;
div.style.position = 'absolute';
div.style.left = posX;
div.style.top = posY;

UPDATE
The values returned by offsetTop and offsetLeft do not include the transform:translate styles applied. I created a test case - its not dragable but it shows you how to calculate the relative positions by adding the offset and the translate values:
var div = document.getElementById("inserted_div_2");
var content = document.getElementById("content");

function testpos(){
    var ol = div.offsetLeft,
        ot = div.offsetTop,
        cs = window.getComputedStyle(div, null),
        tr = cs.getPropertyValue("-webkit-transform") ||
             cs.getPropertyValue("-moz-transform") ||
             cs.getPropertyValue("-ms-transform") ||
             cs.getPropertyValue("-o-transform") ||
             cs.getPropertyValue("transform") ||
             false;
        //outputs something like 'matrix(1, 0, 0, 1, 80, 90)'
        var values = tr.replace(/[^0-9\.\,]/g,'').split(','),//split into array
            tx = values[4] || 0,//take the x value (else 0)
            ty = values[5] || 0;//take the y value (else 0)
    //
    content.innerHTML+=("
position: "+div.style.position+"
");
    content.innerHTML+=("offsetLeft:"+ol+", offsetTop:"+ot+"
");
    content.innerHTML+=("translate-x:"+tx+", translate-y:"+ty+"
");
    //so the actual position is the offset + the translate ==
    var x = parseInt(ol) + parseInt(tx),
        y = parseInt(ot) + parseInt(ty);
    content.innerHTML+=("x:"+x+" y:"+y+"
");
}

/* TEST */
//1 set to fixed
div.style.position = 'fixed';
testpos();//test position
//2 move using transfor:translate
div.style.transform = 'translate(80px,90px)';
testpos();//test position (note the offset does not include the transform)
/3 set to absolute and get the position
div.style.position = 'absolute';
testpos();

http://jsfiddle.net/u3ay74bs/

A: you can use css for center div vertically and horizontally
for example
#content{
     position:absolute;
     width:100px;
     height:100px;
     left:50%;
     top:50%;
     margin-left:-50px; /*half width*/
     margin-top:-50px; /*half height*/
}

     ...

if width equal 100px margin-left equal -50px
if width equal 200px margin-left equal -100px
and so on
margin-left half width
and
margin-top half height


text:
Q: Pointer and use of it: *&p and &*p? are they legal? Hi I am new to C programming. I try to figure out what do *&p and &*p pointer mean ? Does it ever come to help?
q=*&p

A: They are no-ops, except that they can produce compile-time errors. Therefore, they could be useful in a macro as an assertion. *&l ensures that l is an lvalue, and &*p ensures that p is (implicitly convertible to) a pointer.
#define ASSERT_LVALUE(l)  (void)(*&(l))
#define ASSERT_POINTER(p) (void)(&*(p))

int main(void) {
    int* p;
    int i;

    ASSERT_LVALUE(i);
    ASSERT_LVALUE(3);   /* error: lvalue required as unary '&' operand */

    ASSERT_POINTER(p);
    ASSERT_POINTER(i);  /* error: invalid type argument of unary '*' (have 'int') */
    ASSERT_POINTER(3);  /* error: invalid type argument of unary '*' (have 'int') */

    return 0;
}


text:
Q: onDataChange is getting called twice in android Firebase Here is My simple query for firebase data using timestamp in android app
Query recentStaticJobQuery = reference.child(AppConstants.WORKINDIA_JOBS)
                        .child(AppConstants.WORKINDIA_STATIC_JOBS)
                        .orderByChild(AppConstants.TIMESTAMP)
                        .startAt(lastStaticJobSyncTime);
recentStaticJobQuery.addListenerForSingleValueEvent
(staticJobDownloadListener);

 ValueEventListener staticJobDownloadListener = new ValueEventListener() {
    @Override
    public void onDataChange(final DataSnapshot dataSnapshot) {
        Log.i("Firebase", "Called")
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.i("Firebase", "onCancelled")
    }
};

How to avoid onDataChange to get called twice in android Firebase?

A: There are 2 scenarios where this may happen:

*

*onDataChange is called twice in case you have enabled offline persistence. Once with the stale offline value and again with the updated value in case it has changed.

*onDataChange is called multiple times in case you have not removed the listener properly and are creating a new instance of your listener in your activity every time you open it.
Scenario 2 is easy to fix. You can maintain local references of your firebase reference and listener, than you can do a ref.removeListener(listener) in onDestroy of your Activity. Scenario 2 is difficult to fix and you have 2 possible remedies:

*

*Disable offline persistence in case you always want the updated latest value.

*Do a runnable.postDelayed(callbackRunnable, 3000); to wait for the latest value for 3 seconds before updating the views or whatever you want to update.

A: Use SingleEventListener instead of ValueEventListener Like this
Firebase ref = new Firebase("YOUR-URL-HERE/PATH/TO/YOUR/STUFF");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
       String value = (String) dataSnapshot.getValue();
       // do your stuff here with value
   }
   @Override
   public void onCancelled(FirebaseError firebaseError) {
   }
});

A: Replace your query by adding endAt() like below. It will help you.
Query recentStaticJobQuery = reference.child(AppConstants.WORKINDIA_JOBS)
                        .child(AppConstants.WORKINDIA_STATIC_JOBS)
                        .orderByChild(AppConstants.TIMESTAMP)
                        .startAt(lastStaticJobSyncTime).endAt(lastStaticJobSyncTime+"\uf8ff");

A: I found out the reason for this issue.
Attaching and detaching the listeners were fine. Add listener getting called only once. But still child changes and value changes were getting called twice.
I noticed that the 2nd trigger was always about 320ms after the first one. The data was same in both the callbacks, except for the fields with ServerValue.TIMESTAMP. These fields also had about 320ms increase in the 2nd trigger.
The data I was writing to the firebase database was containing the ServerValue.TIMESTAMP as it stores the server's current timestamp in that field, and I was using it to filter the data.
On removing this field from the object I'm writing to database; the listeners are getting called only once.
Here is my code that caused 2 triggers:
My class
@Entity
class Route {
    @PrimaryKey
    var id: String = ""
        @Exclude
        get() {
            return field
        }
        @Exclude
        set(value) {
            field = value
        }
    ....
    ....
    @Ignore
    var z: Any? = null
}

In the viewModel
fun addRoute(routeName: String){
        viewModelScope.launch(Dispatchers.IO) {
            if(!repository.isRouteExists(routeName)){
                val route = Route()
                route.name = routeName
                route.addedBy = uid
                route.z = ServerValue.TIMESTAMP
                repository.insertRouteToFirebase(route)
            }
        }
    }

In the repository
fun insertRouteToFirebase(route: Route){
        val database = Firebase.database
        val myRef = database.getReference("routes")
        val routeId = myRef.push().key
        if(routeId != null){
            route.id = routeId
            myRef.child(routeId).setValue(route)
        }
    }

Logs when using ServerValue.TIMESTAMP (Notice the 300ms difference in log time and field z in data):
2022-09-11 11:38:05.880 23911-23911/com.slvt.vikku.sharadhamohotsav D/MY_FIREBASE: onDataChange: DataSnapshot { key = routes, value = {-NBf9NKGpmwWZDfp9uLp={addedBy=VLdrj1JbJhb1T9GXBm9WONhs5l03, name=new route , z=1662876484946}} }
2022-09-11 11:38:06.173 23911-23911/com.slvt.vikku.sharadhamohotsav D/MY_FIREBASE: onDataChange: DataSnapshot { key = routes, value = {-NBf9NKGpmwWZDfp9uLp={addedBy=VLdrj1JbJhb1T9GXBm9WONhs5l03, name=new route , z=1662876485282}} }

So the solution to this must be found out. This is just the cause of the issue.
On changing
route.z = ServerValue.TIMESTAMP

to some other number like
 route.z = 791456

the listeners were getting called only once.


text:
Q: HTML5 Video tag suddenly stopped working on Safari desktop I have read through and tried suggested solutions on many other similar questions to this one, but nothing is working. When I initially deployed this code a few months ago, it was working on all browsers, mobile and desktop. Now, suddenly, there's no video rendering on Safari (desktop only—it still works on mobile).
<video muted
       playsinline
       disablepictureinpicture
       loop
       class="video"
       preload="metadata">
  <source src="assets/videos/cl.mp4" type="video/mp4"/>
  <source src="assets/videos/cl.mov" type="video/mov"/>

Your browser does not support HTML5 video.

</video>

The unsupported message doesn't render, but no video renders either. Did something change with Safari recently? What else do I need to get this working again?
I have tried:

*

*re-encoding the mp4 file with:

ffmpeg -i cl.mp4 -vcodec libx264 -acodec aac -movflags faststart cl-encoded.mp4

*adding the controls attribute

*adding multiple source types

A: <video class="video-background" autoplay loop muted playsinline>

It works when you include a playinline word and add the source file


text:
Q: Sort Table Client Side with Plain JavaScript and without any library I searched in the website a lot but I couldn't find my answer. They are either too complex or they require JQuery, an external library or I couldn't manage to make them work.
I am looking for a JavaScript to have the following condition.

*

*Run on client Side from bookmark

*Easy to understand

*No Libraries

*Sort an html table and high-light related titles

The project is for a Helpdesk software where multiple tickets are created because of replies/forward/conversations. It becomes like the following (i.e):

*

*first ticket title: Cannot login

*Second ticket title: Re: Cannot login

*Third ticket title: Fw: R: Cannot login
Finding those in the middle of like 30 or more tickets and merging them can sometime contain mistakes and annoyance especially if I am busy. So I wanted a way to sort and highlight them with a click without affecting any formatting.
The html table does note have a head, but have the first two rows for head and filtering function. So there should be a way to skip them.
Please suggest a code to do it.

A: Please note that I am a complete beginner with Java-scripting but was able to build this solution one part at a time.
The solution is to go through the table row by row and extracting the "textContent" from the required cell (column in the row). and making an array where the first level is the cleaned out cell then the second level is the row itself.
cleaning to detects same tickets titles by removing "Re:" and "Fw:" from the textContent
var key = rows[i].cells[col].textContent.replace(/[^a-zA-Z0-9: ]/g, '').trim();
key = key.replace(/Fw:/gi, '').replace(/Re:/gi, '').trim();

creating the array while deducting the startRow so it starts at 0.
arr[i - startRow] = [key, rows[i]];

It will become something like this arr[index] = [key,row]
arr[0] = ['Cannot login','....	']
arr[1] = ['next subject','....	']

then we can use the simple array sort function.
arr.sort();

after that we can delete the current table rows while keeping the first 2 rows.
    while (tbody.rows.length > startRow) {
        tbody.deleteRow(startRow);
    };

then we can regenerate the table while checking for any duplicates and changing the background table to "yellow" to duplicates.
The complete code is as follows:
javascript :
sortandclean();
function sortandclean() {
    var col = 6; /* title row */
    var startRow = 2; /* to skip the first two rows */
    var arr = []; /* main array which will contains the rows */
    var tbody = document.getElementById('RequestsView_TABLE').tBodies[0];
    var rows = tbody.rows;
    for (i = startRow; i < rows.length; i++) {
        var key = rows[i].cells[col].textContent.replace(/[^a-zA-Z0-9: ]/g, '').trim();
        key = key .replace(/Fw:/gi, '').replace(/Re:/gi, '').trim();
        arr[i - startRow] = [key, rows[i]];
    };
    console.log('rows: ' + rows.length);
    arr.sort(); /* sorting the easy way. works with both texts and numbers */
    while (tbody.rows.length > startRow) {
        tbody.deleteRow(startRow);
    };
    for (i = 0; i < arr.length; i++) {
        rowToInsert = arr[i][1]; /* arr[i][0] has the key and arr[i][1] has the row */
        if (arr[i][0] == lastrow) {
            rowToInsert.cells[col].style.backgroundColor = "yellow";
            tbody.rows[tbody.rows.length - 1].cells[col].style.backgroundColor = "yellow";
        }; /* if the current row have the same clean title highlight both current and previous rows title cell */
        tbody.appendChild(rowToInsert);
        var lastrow = arr[i][0];
        totalRows = i;
    };
    console.log('rows reinserted: ' + (totalRows + 1));
} void(0);

Use block commenting for commenting the code so it will work normally in the bookmark. (i.e. /* some comment */)


text:
Q: PrimeFaces autocomplete="off" didn't work for username and password I'm using jsf 2.2 and PrimeFaces 5.0. problem is I have the system login page that is done
by spring security, and also to add new user im using another page
which is shown below.

the problem is that in chrome I just put the remember password to my system login page after that whenever I tried to use the username and password text in any form. it keeps getting fill by that user name and password. I tried to put the "autocomplete="off" in my register new user page. but it didn't work.

A: I believe you can't do anything about it JSF-wise as its remembered by the browser, but you can go to
chrome://settings/personal

and select "Show advanced settings" and manage the passwords under "Passwords and forms".


text:
Q: google maps v3 markers not showing ie 8 and 9 I am trying to get Google Maps markers to appear in IE 8 and 9.  Here's where I believe the problem lies:
var addresses = mapAddresses;
//alert(addresses);
if (addresses != null)
{
    var marker, x;
    var infowindow = new google.maps.InfoWindow();

    for (x = 0; x < addresses.length; x++) {
        //alert(addresses.length);
        //alert('http://maps.googleapis.com/maps/api/geocode/json?address=' + addresses[x]);
        $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=' + addresses[x] + '&sensor=false', null, function (data) {

            var p = data.results[0].geometry.location
            //alert(data.results[0].formatted_address);  // This will alert the individual addresses.

            var latlng = new google.maps.LatLng(p.lat, p.lng);
            var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                title: data.results[0].formatted_address
            });

            // Add the markers to the gmarkers array.
            gmarkers.push(marker);  //<-------- No markers appear to be getting in here.
        });
    }

    geoCodeAddress(map);
}

I can see the markers in IE 10+, FF, and Chrome.  I do not see any js errors in the debugger indicating something wrong.  I verified that the $.getJSON() call returns results.  Any help is appreciated.  Thanks!

A: After trying it on a windows XP.. it turns out that is is not the Google Maps, I mean I can add marker statically. In stead, I realized that it is actually the problem of the CORS on IE 8 + 9.
As you can see in the caniuse.com, IE 8 and IE 9 has only a partial support on CORS. Also it is said in the wiki that:

Internet Explorer did not implement CORS until version 10. The two previous versions (8 and 9) offered similar functionality through the XDomainRequest API. It is now supported by all modern browsers (desktop and mobile)

There are discussions saying that using jQuery.support.cors = true; would make it works, but sadly no luck for my Windows XP + IE 8.
Some more helpful readings:
'jQuery.getJSON' not working in Internet Explorer 8
jQuery issue in Internet Explorer 8


text:
Q: Running a program with segmentation fault works well with gdb I implemented the program that uses mmap() system call, but Segmentation Fault occurs during process runtime.
So, I ran this program with gdb, but when I did it, it worked well without segment fault.
I wonder if it is possible that running with gdb can affect segment fault.
Could you tell me about it?

A:
if it is possible that running with gdb can affect segment fault.

One possibility: GDB disables address randomization (so as to make reproducing the bug easier). You can re-enable it with:
(gdb) set disable-randomization off

GDB may also affect timing of threads, but you didn't mention threads, so that's less likely.

A: You are probably invoking Undefined Behavior somewhere in your code that is breaking C or C++ rules. Try to run the program under Valgrind. It should give you more information if this is the case.


text:
Q: How to change the type of transitions between slides in this jquery slider? Can someone help me to change the type of transitions between slides in this jquery slider ?
I am using a slider called blueberry made by Mark Tyrrell , but wanted the deslizacem slides to the left .

(function($){
 $.fn.extend({
  blueberry: function(options) {

   //default values for plugin options
   var defaults = {
    interval: 5000,
    duration: 500,

    lineheight: 1,
    height: 'auto', //reserved
    hoverpause: false,
    pager: true,
    nav: true, //reserved
    keynav: true
   }
   var options =  $.extend(defaults, options);

   return this.each(function() {
    var o = options;
    var obj = $(this);

    //store the slide and pager li
    var slides = $('.slides li', obj);
    var pager = $('.pager li', obj);

    //set initial current and next slide index values
    var current = 0;
    var next = current+1;

    //get height and width of initial slide image and calculate size ratio
    var imgHeight = slides.eq(current).find('img').height();
    var imgWidth = slides.eq(current).find('img').width();
    var imgRatio = imgWidth/imgHeight;

    //define vars for setsize function
    var sliderWidth = 0;
    var cropHeight = 0;

    //hide all slides, fade in the first, add active class to first slide
    slides.hide().eq(current).fadeIn(o.duration).addClass('active');

    //build pager if it doesn't already exist and if enabled
    if(pager.length) {
     pager.eq(current).addClass('active');
    } else if(o.pager){
     obj.append('

');
     slides.each(function(index) {
      $('.pager', obj).append('
'+index+'
')
     });
     pager = $('.pager li', obj);
     pager.eq(current).addClass('active');
    }

    //rotate to selected slide on pager click
    if(pager){
     $('a', pager).click(function() {
      //stop the timer
      clearTimeout(obj.play);
      //set the slide index based on pager index
      next = $(this).parent().index();
      //rotate the slides
      rotate();
      return false;
     });
    }

    //primary function to change slides
    var rotate = function(){
     //fade out current slide and remove active class,
     //fade in next slide and add active class
     slides.eq(current).fadeOut(o.duration).removeClass('active')
      .end().eq(next).fadeIn(o.duration).addClass('active').queue(function(){
       //add rotateTimer function to end of animation queue
       //this prevents animation buildup caused by requestAnimationFrame
       //rotateTimer starts a timer for the next rotate
       rotateTimer();
       $(this).dequeue()
     });

     //update pager to reflect slide change
     if(pager){
      pager.eq(current).removeClass('active')
       .end().eq(next).addClass('active');
     }

     //update current and next vars to reflect slide change
     //set next as first slide if current is the last
     current = next;
     next = current >= slides.length-1 ? 0 : current+1;
    };
    //create a timer to control slide rotation interval
    var rotateTimer = function(){
     obj.play = setTimeout(function(){
      //trigger slide rotate function at end of timer
      rotate();
     }, o.interval);
    };
    //start the timer for the first time
    rotateTimer();

    //pause the slider on hover
    //disabled by default due to bug
    if(o.hoverpause){
     slides.hover(function(){
      //stop the timer in mousein
      clearTimeout(obj.play);
     }, function(){
      //start the timer on mouseout
      rotateTimer();
     });
    }

    //calculate and set height based on image width/height ratio and specified line height
    var setsize = function(){
     sliderWidth = $('.slides', obj).width();
     cropHeight = Math.floor(((sliderWidth/imgRatio)/o.lineheight))*o.lineheight;

     $('.slides', obj).css({height: cropHeight});
    };
    setsize();

    //bind setsize function to window resize event
    $(window).resize(function(){
     setsize();
    });

    //Add keyboard navigation

    if(o.keynav){
     $(document).keyup(function(e){

      switch (e.which) {

       case 39: case 32: //right arrow & space

        clearTimeout(obj.play);

        rotate();

        break;

       case 37: // left arrow
        clearTimeout(obj.play);
        next = current - 1;
        rotate();

        break;
      }

     });
    }

   });
  }
 });
})(jQuery);
.blueberry { margin: 0 auto; }
.blueberry .slides {
 display: block;
 position: relative;
 overflow: hidden;
}
.blueberry .slides li {
 position: absolute;
 top: 0;
 left: 0;
 overflow: hidden;
}
.blueberry .slides li img {
 display: block;
 width: 100%;
 max-width: none;
}
.blueberry .slides li.active { display: block; position: relative; }
.blueberry .crop li img { width: auto; }

.blueberry .pager {
 height: 40px;
 text-align: center;
}
.blueberry .pager li { display: inline-block; }
.blueberry .pager li a,
.blueberry .pager li a span {
 display: block;
 height: 4px;
 width: 4px;
}
.blueberry .pager li a {
 padding: 18px 8px;
-webkit-border-radius: 6px;
   -moz-border-radius: 6px;
 border-radius: 6px;
}
.blueberry .pager li a span {
 overflow: hidden;
 background: #c0c0c0;
 text-indent: -9999px;
-webkit-border-radius: 2px;
   -moz-border-radius: 2px;
 border-radius: 2px;
}
.blueberry .pager li.active a span { background: #404040; }
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, maximum-scale=1.0, minimum-scale=1.0, initial-scale=1" />

<Title>Slides</title>


text:
Q: create groupbox in new panel dynamically I want to create groupbox in my new panel dynamically. How i do this in vb.net? thank you.......................
Dim Groups As New Dictionary(Of String, GroupBox)
Dim Panels As New Dictionary(Of String, Panel)
Dim jmlpnl As Integer = 1
Dim jmlgrp As Integer = 10

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim pnl As New Panel
    For i As Integer = 1 To jmlpnl
        Me.Controls.Add(pnl)
        pnl.Width = 883
        pnl.Height = 744
        pnl.Top = 5
        pnl.Left = 439
        pnl.BackColor = Color.White
        Panels.Add("Panel" & i, pnl)
        pnl.Tag = "Panel" & i
        For j As Integer = 1 To jmlgrp
           'create groupbox in my new panel
        Next
    Next

End Sub

A: That's a not very difficult task. You just have to create the new groupboxes and add them to the Panel. The only thing you must have in mind is the distribution, this code just puts them one right to the other, if you want something different you'll need to play with the top and left variables:
Dim top As Integer = 0
Dim left As Integer = 0
For j As Integer = 1 To jmlgrp
    'create groupbox in my new panel
    Dim grp As New GroupBox
    grp.Width = 50
    grp.Height = 50
    grp.Top = top
    grp.Left = left

    pnl.Controls.Add(grp)
    left += 60
Next


text:
Q: checking if something is a prime python?
def prime_check(num):
    if num>1:
        if num == 2:
                return True
        for i in range(2, num+1):
            if ((num%i) == 0):
                print(i)
                return False
            else:
                return True
    else:
        return False
prime_check(99)

returns true (as in is prime) when it should be false when i use value 99. WHY?

A: In the loop, you're returning true whenever the input is not divisible by the current number in the loop. So, in the first iteration, when if condition checks whether 99%2 == 0, if so then return false else return true. That's why it returns True as 99%2 != 0.
Just change your code a bit, as you are using for....else:
if (num >1):
    for i in range(2, num):
        if ((num%i) == 0):
            print(i)
            return False
    else:
        return True

You can improve the program by decreasing the range of the loop using range(2,math.floor(math.sqrt(num))):
for i in range(2,math.floor(math.sqrt(num))):
    //do the same

A: When 99 enters into the for loop It checks whether 99%2==0, as it finds 99%2!=0 else block is executed, returns true and comes out of the loop without doing further iterations. You need to change the code.
To reduce the complexity you can further use sqrt functions. You can refer to this
def prime(num):
if num==1:
    return False
else:
    for i in range(2,num):
        if num%i==0:
            return False
return True

print(prime(17))


text:
Q: Can't perform a request on Laravel with 3 tables I began laravel one week ago, and today I decided to properly use eloquent.
So I will explain you my problem, and if you are wondering, yes I already looked for a solution on topics, google ..
I'm on this problem for about 8 hours .. Start to get tired.
Well, I created 3 databases (using mgrations, and creating relations)

*

*Tags [id; name]

*Users [id, its not important]

*TagsRelationUsers [id, user_id, tag_id]

So, I just want to make a request that gives me the all the tags name related with a user, in the tagsRelationUsers table, by just having the user_id.
In my case, a user can have an infinite amount of tags, and a tag can have an infinitee amount of users, that's why I created a table called TagsRelationUsers.
class User extends Authenticatable

public function tagsRelationsUsers()
{
    return $this->belongsTo('App\TagRelationUser');
}

.
class Tag extends Model

public function tagsRelationsUsers()
{
    return $this->belongsTo('App\TagRelationUser');
}

If you can help me, this will be super cool :). Thanks !

A: You are doing things a bit wrong here,

*

*The relation method is called incorrectly. (for many to many relationships).

*Laravel guesses the pivot table name from the related tables. Sorting them in alphabetical order using the singular form of the table name and joining them up using '_' (so in your case tag_user). But you are using TagsRelationUsers as the pivot table so you need to specify that explicitly.

Guessing your pivot table name is TagsRelationUsers.
Try this.
class User extends Authenticatable

public function tagsRelationsUsers()
{
    return $this->belongsToMany('App\Tag', 'TagsRelationUsers', 'tag_id', 'user_id');
}

class Tag extends Model

public function tagsRelationsUsers()
{
    return $this->belongsToMany('App\User', 'TagsRelationUsers', 'user_id', 'tag_id');
}


text:
Q: SQL Server join or Pentaho Spoon lookup? What provides higher performance?

*

*Writing a query using T-SQL, joining tables, then inserting the result into another table

*Using Pentaho Spoon's table insert, then using database lookup to "join" each table at a time, then inserting the result into another table
The objective is to take a denormalized table, join it with 5 dimension tables by their text, and retrieve dimensions' PKs, and then insert the result into a fact table.

A: probably better suited for dba.stackexchange.com. But I guess a database engine is going to perform this task much faster, because a) it can optimize access to all tables involved using indexes and table statistics and b) you get rid of the overhead an ETL tool and multiple database queries introduce. Pentaho PDI processes rows individually, so for each row coming from your table input step you will have an SQL query for every lookup step.

A: It is conventional wisdom to think that SQL outperforms Pentaho PDI on complex queries. The truthiness comes from the blind believe that the SQL optimizer gives a real optimum.
I have a number of counter examples in which we have reduced the query time of more than one hour to a few minutes by extracting the SQL query complexity out into a series of lookups and filters.
We were better because:

*

*The lookup expects one matching record per entry, while the SQL optimizer must take the assumption that the join is not unique. And it is the case of unfolding a star/snowflake schema like here.

*The lookup step is really smart, reading just the data needed and keeping it in memory, making provision with internal sorted hashtables to speed up forthcoming queries.

*The above is especially efficient when the flow is known to be sorted. And while a select from oneTable order by is quick especially when the table is suitably indexed , the same select from manyJoinedTables where LotsOfConditions order by may be pretty inefficient because the SQL cannot count on indexes.
In facts, I guess the above conditions are exactly the ones which the SQL optimizer wish to find and rely, but cannot because of generality.
As a rule of thumb be confident in the efficiency of PDI. Matt Casters and Jens Bleuel made a very good software which was tested under volume conditions you cannot even imagine.
So use the solution which is the easier to maintain (most the time PDI lookups) and if it is really, really to slow, then move it into Input Tables but do not expect to be systematically better.
Notes:

*

*Avoid the Database Lookup (prepared statement uses cache, but we are in precisely the case in which we look for a different key each time).

*Avoid Joins, i.e.: explicitly tell kettle it can count on a unique match, if you know it is the case. The Join Rows and Merge Join are efficient steps, but only when the incoming flows are sorted.

*Use Filters (reduce the number of rows) as soon as possible. Even, every rule has its exception, in the SQL.

*Don't bother to reduce the number of columns with Select values. It has almost no impact on the speed! You do not thing Kettle is naively  rewriting the values from step to step, instead of using a clever system of pointers, don't you?.

*Computations with a JavaScript is not so inefficient as the legend says, and in facts the PDI is usually much more busy in sorting and lookups.

*Do not spread the aggregates in many Memory Group by steps. Each of these steps needs to read all the incoming flow before to know it is finished, so it is a blocking factor the next steps.

*Usually the Sorted Group by does not improve the Memory Group by. The one exception is when the memory reach its quota and java starts to launch a garbage collector over garbage collector. In that case, a sort can be used to store data on temporary disk.

*Avoid intermediary tables. Instead build the flow by adding columns and when the data is ready, throw it in a Output Table with a large commit size.


text:
Q: How do Xeon processors differ from regular processors? Yes I know that Xeons are meant for server use, require different motherboards and you can have more than one of them in a box.
But technically how is a Xeon processor itself different from a regular core 2 processor?

A: *

*Bigger L3 cache

*Multiprocessor support

*Generally adjusted for server usage (heavy load, long runtimes)

A: The key thing about Xeons is that they are geared towards the server/workstation market and thus are designed to be more reliable and always-on, and for MP enviroments.
They work in different motherboards (different chipsets) - usually alongside FB-DIMMs, which are slower but more reliable than their consumer equivalents.
In general, there is a Xeon equivalent for each Core 2 CPU; for example a Q6600 is almost identical to the X3220, though there are some variations.

A: The answer is that it's not very different.  It has a larger cache and is not explicitly crippled to prevent it working in multiprocessor systems.  Xeons also have support for ECC memory, which is not normally supported on consumer CPU chips.  Otherwise the basic processor core is much the same.
On older 32 bit systems the Xeon's MMU was slightly more clever in that it could support multiple 4GB process spaces in up to 64GB of physical RAM.  SPARC v8 chips had a similar feature in the MMU.  This feature worked because of the difference in the number of bits needed to address an offset within a page (12 for a 4KB page) and the number of bits needed to record a page's status (RWX, dirty etc.).  The extra bits could be used for a slightly wider physical page reference (24 bits vs. 20 to specify the page number) allowing a 36-bit physical address.  However a single process could only see a contiguous 4GB address space at any given time.
Some systems (e.g. Datacentre versions of Windows Server) had an API that allowed a process to control the MMU to overlay chunks of this physical address space into its virtual space.
This feature was used in enterprise versions of SQL Server to support larger disk caches.
Most if not all modern CPUs support feature this when running in 32 bit mode, and there are probably plenty of shops still running legacy 32 bit applications in this mode, either on VMs (where the MMU is emulated with a greater or lesser amount of hardware support) or physical tin.  However, 64 bit builds are much more prevalent on modern large-memory server builds these days, which allow larger contiguous memory images within a process.

A: Xeon is optimized for multiprocessor architecture

*

*Supports the QuickPath Interconnect, the Intel InterBand offering high bandwidth and low latency

*Provides more cache (35MB vs. 6MB for i7 Core)

*Provides higher memory bandwidth (102GB/s vs 25.6GM/s for i7 Core)

*Supports ECC memory

*Possible coupling with Xeon-Phi coprocessors ("accelerators") in a many-core architecture


text:
Q: how to draw a looping rectangle in a for statement in java i have been trying to make a program in java that makes a rectangle that gets bigger and bigger using a for loop. ive been getting stuck on this problem for like 2 hours and i really need help.
public void paintComponent (Graphics g) {
super.paintComponent(g);
for( int i = 20; i <= 26; i++ ) {
            g.drawRect(200 - 2 * i, 200 - 2 * i, 40, 40)}

This is what i want it to look like:

A: You have to increase the width and the height
g.drawRect(200 - 2 * i, 200 - 2 * i, 40, 40)
//drawRect(x, y, width, height)
//you can see your width and height are constant

You can increase it doing something like this:
g.drawRect(200 - 2 * i, 200 - 2 * i, 40 + (i + 10), 40 + (i + 10))

A: You need to increase the width too:
for( int i = 20; i <= 26; i++ ) {
    g.drawRect(200 - 2*i, 200 - 2*i, 40 + 4*i, 40 + 4*i)
}


text:
Q: Reverse vertical one of the subplots in python I have two data frames to plot. One of bar chart, another one is a line chart.
I want to plot the barchart upside to down. (vertically reversed.)
How can i handle this?
fig, ax1 = plt.subplots(figsize=(10, 5))
tidy = results.melt(id_vars='Day').rename(columns=str.title)
ax1 = sns.lineplot(x='Day', y='Value', hue='Variable', data=tidy, ax=ax1)
tidy2 = drugs.melt(id_vars='Day').rename(columns=str.title)
ax1 = sns.barplot(x='Day', y='Value', hue='Variable', data=tidy2, ax=ax1)
ax1.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax1.legend(loc=1)
ax1.tick_params(axis='x', labelrotation=45)


text:
Q: Looking for a reliable way to test CSS transition performance on mobile devices I'm building a feature-rich mobile website with jquery mobile. Accross all views there is some css transitions, box-shadows, gradients...
What I'm concerned about is users with lower-grade phones browsing my website. Plenty of phones support transitions but will display them at a terrible framerate: I'm thinking older Androids, first iPad, etc. So for this kind of hardware, I want to disable them (as well as box shadow which is very expensive).
Right now what I'm doing is apply this rule depending on user agent:
* {
      box-shadow: none !important;
      -webkit-box-shadow: none !important;
      transition: none !important;
      -webkit-transition: none !important;
      moz-transition: none !important;
      -ms-transition: none important;
      -o-transition: none !important;
   }

However this is totally unreliable: a phone with Android 4 will pass the user agent test yet might perform terribly. Not to mention users can upgrade their version of Android or even use custom roms on old hardware. And finally, they can always change their user agent.
Another test I've been suggested is starting a width/height transition on an empty page, then check if it completed in time. Altough I can see this working, I'm not sure how reliable that would be since general use involves much more elements in the DOM.
I would like to add that I don't make heavy use of CSS3 effects and I've built this website with optimisation in mind, so please don't suggest optimisation or hacks like backface-visibility, I know of that.

A: There are several solutions but I would presume you need a solution that runs only on a client device.
If this is the case then use this:
First you will need to download/use Modernizer: http://modernizr.com/
You can use it to detect which devices have support for newer HTML5/CSS3 options.
What you need to check is: Inline SVG support, you will find it detectable in an official documentation here: http://modernizr.com/docs/#features-html5
Older versions of Android (pre 3.0) and iOS (pre 5.0) don't have a support for it, find it
here: http://caniuse.com/#feat=svg-html5
This is only reliable client side solution I know. If you need much more specific detection you will need to use server side detection. Currently best one is WURFL but it will cost you.
Read more about it in my other answer.


text:
Q: How to connect to an already existing database in python I made a database using mongoose on express js. Then when I try to access that database in python using pymongo it creates a new database with same name on same connection and new collections. Below is my connection code in python
import pymongo
connection = pymongo.MongoClient('mongodb://localhost:27017/fileUpoadStats')
file1 = connection.fileStats
cursor = file1.find()
for doc in cursor:
    print doc

I want to access the same database in python. Can anyone help?